[8572] Add active repeatable non-daily quest in quest book at character loading also.
[getmangos.git] / src / game / Player.cpp
blob2436278ad2185734bc4a06006803856fea3486ca
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Language.h"
21 #include "Database/DatabaseEnv.h"
22 #include "Log.h"
23 #include "Opcodes.h"
24 #include "SpellMgr.h"
25 #include "World.h"
26 #include "WorldPacket.h"
27 #include "WorldSession.h"
28 #include "UpdateMask.h"
29 #include "Player.h"
30 #include "Vehicle.h"
31 #include "SkillDiscovery.h"
32 #include "QuestDef.h"
33 #include "GossipDef.h"
34 #include "UpdateData.h"
35 #include "Channel.h"
36 #include "ChannelMgr.h"
37 #include "MapManager.h"
38 #include "MapInstanced.h"
39 #include "InstanceSaveMgr.h"
40 #include "GridNotifiers.h"
41 #include "GridNotifiersImpl.h"
42 #include "CellImpl.h"
43 #include "ObjectMgr.h"
44 #include "ObjectAccessor.h"
45 #include "CreatureAI.h"
46 #include "Formulas.h"
47 #include "Group.h"
48 #include "Guild.h"
49 #include "Pet.h"
50 #include "Util.h"
51 #include "Transports.h"
52 #include "Weather.h"
53 #include "BattleGround.h"
54 #include "BattleGroundMgr.h"
55 #include "ArenaTeam.h"
56 #include "Chat.h"
57 #include "Database/DatabaseImpl.h"
58 #include "Spell.h"
59 #include "SocialMgr.h"
60 #include "AchievementMgr.h"
62 #include <cmath>
64 #define ZONE_UPDATE_INTERVAL (1*IN_MILISECONDS)
66 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
67 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
68 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
70 #define SKILL_VALUE(x) PAIR32_LOPART(x)
71 #define SKILL_MAX(x) PAIR32_HIPART(x)
72 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
74 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
75 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
76 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
78 enum CharacterFlags
80 CHARACTER_FLAG_NONE = 0x00000000,
81 CHARACTER_FLAG_UNK1 = 0x00000001,
82 CHARACTER_FLAG_UNK2 = 0x00000002,
83 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
84 CHARACTER_FLAG_UNK4 = 0x00000008,
85 CHARACTER_FLAG_UNK5 = 0x00000010,
86 CHARACTER_FLAG_UNK6 = 0x00000020,
87 CHARACTER_FLAG_UNK7 = 0x00000040,
88 CHARACTER_FLAG_UNK8 = 0x00000080,
89 CHARACTER_FLAG_UNK9 = 0x00000100,
90 CHARACTER_FLAG_UNK10 = 0x00000200,
91 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
92 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
93 CHARACTER_FLAG_UNK13 = 0x00001000,
94 CHARACTER_FLAG_GHOST = 0x00002000,
95 CHARACTER_FLAG_RENAME = 0x00004000,
96 CHARACTER_FLAG_UNK16 = 0x00008000,
97 CHARACTER_FLAG_UNK17 = 0x00010000,
98 CHARACTER_FLAG_UNK18 = 0x00020000,
99 CHARACTER_FLAG_UNK19 = 0x00040000,
100 CHARACTER_FLAG_UNK20 = 0x00080000,
101 CHARACTER_FLAG_UNK21 = 0x00100000,
102 CHARACTER_FLAG_UNK22 = 0x00200000,
103 CHARACTER_FLAG_UNK23 = 0x00400000,
104 CHARACTER_FLAG_UNK24 = 0x00800000,
105 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
106 CHARACTER_FLAG_DECLINED = 0x02000000,
107 CHARACTER_FLAG_UNK27 = 0x04000000,
108 CHARACTER_FLAG_UNK28 = 0x08000000,
109 CHARACTER_FLAG_UNK29 = 0x10000000,
110 CHARACTER_FLAG_UNK30 = 0x20000000,
111 CHARACTER_FLAG_UNK31 = 0x40000000,
112 CHARACTER_FLAG_UNK32 = 0x80000000
115 // corpse reclaim times
116 #define DEATH_EXPIRE_STEP (5*MINUTE)
117 #define MAX_DEATH_COUNT 3
119 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
121 //== PlayerTaxi ================================================
123 PlayerTaxi::PlayerTaxi()
125 // Taxi nodes
126 memset(m_taximask, 0, sizeof(m_taximask));
129 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
131 // class specific initial known nodes
132 switch(chrClass)
134 case CLASS_DEATH_KNIGHT:
136 for(int i = 0; i < TaxiMaskSize; ++i)
137 m_taximask[i] |= sOldContinentsNodesMask[i];
138 break;
142 // race specific initial known nodes: capital and taxi hub masks
143 switch(race)
145 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
146 case RACE_ORC: SetTaximaskNode(23); break; // Orc
147 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
148 case RACE_NIGHTELF: SetTaximaskNode(26);
149 SetTaximaskNode(27); break; // Night Elf
150 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
151 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
152 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
153 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
154 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
155 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
158 // new continent starting masks (It will be accessible only at new map)
159 switch(Player::TeamForRace(race))
161 case ALLIANCE: SetTaximaskNode(100); break;
162 case HORDE: SetTaximaskNode(99); break;
164 // level dependent taxi hubs
165 if(level>=68)
166 SetTaximaskNode(213); //Shattered Sun Staging Area
169 void PlayerTaxi::LoadTaxiMask(const char* data)
171 Tokens tokens = StrSplit(data, " ");
173 int index;
174 Tokens::iterator iter;
175 for (iter = tokens.begin(), index = 0;
176 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
178 // load and set bits only for existed taxi nodes
179 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
183 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
185 if(all)
187 for (uint8 i=0; i<TaxiMaskSize; ++i)
188 data << uint32(sTaxiNodesMask[i]); // all existed nodes
190 else
192 for (uint8 i=0; i<TaxiMaskSize; ++i)
193 data << uint32(m_taximask[i]); // known nodes
197 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team )
199 ClearTaxiDestinations();
201 Tokens tokens = StrSplit(values," ");
203 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
205 uint32 node = uint32(atol(iter->c_str()));
206 AddTaxiDestination(node);
209 if(m_TaxiDestinations.empty())
210 return true;
212 // Check integrity
213 if(m_TaxiDestinations.size() < 2)
214 return false;
216 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
218 uint32 cost;
219 uint32 path;
220 objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
221 if(!path)
222 return false;
225 // can't load taxi path without mount set (quest taxi path?)
226 if(!objmgr.GetTaxiMountDisplayId(GetTaxiSource(),team,true))
227 return false;
229 return true;
232 std::string PlayerTaxi::SaveTaxiDestinationsToString()
234 if(m_TaxiDestinations.empty())
235 return "";
237 std::ostringstream ss;
239 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
240 ss << m_TaxiDestinations[i] << " ";
242 return ss.str();
245 uint32 PlayerTaxi::GetCurrentTaxiPath() const
247 if(m_TaxiDestinations.size() < 2)
248 return 0;
250 uint32 path;
251 uint32 cost;
253 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
255 return path;
258 std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
260 ss << "'";
261 for(int i = 0; i < TaxiMaskSize; ++i)
262 ss << taxi.m_taximask[i] << " ";
263 ss << "'";
264 return ss;
267 //== Player ====================================================
269 UpdateMask Player::updateVisualBits;
271 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this), m_reputationMgr(this)
273 m_transport = 0;
275 m_speakTime = 0;
276 m_speakCount = 0;
278 m_objectType |= TYPEMASK_PLAYER;
279 m_objectTypeId = TYPEID_PLAYER;
281 m_valuesCount = PLAYER_END;
283 m_session = session;
285 m_divider = 0;
287 m_ExtraFlags = 0;
288 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
289 SetAcceptTicket(true);
291 // players always accept
292 if(GetSession()->GetSecurity() == SEC_PLAYER)
293 SetAcceptWhispers(true);
295 m_curSelection = 0;
296 m_lootGuid = 0;
298 m_comboTarget = 0;
299 m_comboPoints = 0;
301 m_usedTalentCount = 0;
302 m_questRewardTalentCount = 0;
304 m_regenTimer = 0;
305 m_weaponChangeTimer = 0;
307 m_zoneUpdateId = 0;
308 m_zoneUpdateTimer = 0;
310 m_areaUpdateId = 0;
312 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
314 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
315 // this must help in case next save after mass player load after server startup
316 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
318 clearResurrectRequestData();
320 m_SpellModRemoveCount = 0;
322 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
324 m_social = NULL;
326 // group is initialized in the reference constructor
327 SetGroupInvite(NULL);
328 m_groupUpdateMask = 0;
329 m_auraUpdateMask = 0;
331 duel = NULL;
333 m_GuildIdInvited = 0;
334 m_ArenaTeamIdInvited = 0;
336 m_atLoginFlags = AT_LOGIN_NONE;
338 mSemaphoreTeleport_Near = false;
339 mSemaphoreTeleport_Far = false;
341 m_DelayedOperations = 0;
342 m_bCanDelayTeleport = false;
343 m_bHasDelayedTeleport = false;
344 m_teleport_options = 0;
346 pTrader = 0;
347 ClearTrade();
349 m_cinematic = 0;
351 PlayerTalkClass = new PlayerMenu( GetSession() );
352 m_currentBuybackSlot = BUYBACK_SLOT_START;
354 m_DailyQuestChanged = false;
355 m_lastDailyQuestTime = 0;
357 for (int i=0; i<MAX_TIMERS; ++i)
358 m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
360 m_MirrorTimerFlags = UNDERWATER_NONE;
361 m_MirrorTimerFlagsLast = UNDERWATER_NONE;
362 m_isInWater = false;
363 m_drunkTimer = 0;
364 m_drunk = 0;
365 m_restTime = 0;
366 m_deathTimer = 0;
367 m_deathExpireTime = 0;
369 m_swingErrorMsg = 0;
371 m_DetectInvTimer = 1*IN_MILISECONDS;
373 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
375 m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
376 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
379 m_logintime = time(NULL);
380 m_Last_tick = m_logintime;
381 m_WeaponProficiency = 0;
382 m_ArmorProficiency = 0;
383 m_canParry = false;
384 m_canBlock = false;
385 m_canDualWield = false;
386 m_canTitanGrip = false;
387 m_ammoDPS = 0.0f;
389 m_temporaryUnsummonedPetNumber = 0;
390 //cache for UNIT_CREATED_BY_SPELL to allow
391 //returning reagents for temporarily removed pets
392 //when dying/logging out
393 m_oldpetspell = 0;
395 ////////////////////Rest System/////////////////////
396 time_inn_enter=0;
397 inn_pos_mapid=0;
398 inn_pos_x=0;
399 inn_pos_y=0;
400 inn_pos_z=0;
401 m_rest_bonus=0;
402 rest_type=REST_TYPE_NO;
403 ////////////////////Rest System/////////////////////
405 m_mailsLoaded = false;
406 m_mailsUpdated = false;
407 unReadMails = 0;
408 m_nextMailDelivereTime = 0;
410 m_resetTalentsCost = 0;
411 m_resetTalentsTime = 0;
412 m_itemUpdateQueueBlocked = false;
414 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
415 m_forced_speed_changes[i] = 0;
417 m_stableSlots = 0;
419 /////////////////// Instance System /////////////////////
421 m_HomebindTimer = 0;
422 m_InstanceValid = true;
423 m_dungeonDifficulty = DIFFICULTY_NORMAL;
425 m_lastPotionId = 0;
427 m_activeSpec = 0;
428 m_specsCount = 1;
430 for (int i = 0; i < BASEMOD_END; ++i)
432 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
433 m_auraBaseMod[i][PCT_MOD] = 1.0f;
436 for (int i = 0; i < MAX_COMBAT_RATING; ++i)
437 m_baseRatingValue[i] = 0;
439 m_baseSpellPower = 0;
440 m_baseFeralAP = 0;
441 m_baseManaRegen = 0;
442 m_armorPenetrationPct = 0.0f;
444 // Honor System
445 m_lastHonorUpdateTime = time(NULL);
447 // Player summoning
448 m_summon_expire = 0;
449 m_summon_mapid = 0;
450 m_summon_x = 0.0f;
451 m_summon_y = 0.0f;
452 m_summon_z = 0.0f;
454 m_mover = this;
456 m_miniPet = 0;
457 m_contestedPvPTimer = 0;
459 m_declinedname = NULL;
460 m_runes = NULL;
462 m_lastFallTime = 0;
463 m_lastFallZ = 0;
466 Player::~Player ()
468 CleanupsBeforeDelete();
470 // it must be unloaded already in PlayerLogout and accessed only for loggined player
471 //m_social = NULL;
473 // Note: buy back item already deleted from DB when player was saved
474 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
476 if(m_items[i])
477 delete m_items[i];
479 CleanupChannels();
481 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
482 delete itr->second;
484 //all mailed items should be deleted, also all mail should be deallocated
485 for (PlayerMails::const_iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
486 delete *itr;
488 for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
489 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
491 delete PlayerTalkClass;
493 if (m_transport)
495 m_transport->RemovePassenger(this);
498 for(size_t x = 0; x < ItemSetEff.size(); x++)
499 if(ItemSetEff[x])
500 delete ItemSetEff[x];
502 // clean up player-instance binds, may unload some instance saves
503 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
504 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
505 itr->second.save->RemovePlayer(this);
507 delete m_declinedname;
508 delete m_runes;
511 void Player::CleanupsBeforeDelete()
513 if(m_uint32Values) // only for fully created Object
515 TradeCancel(false);
516 DuelComplete(DUEL_INTERUPTED);
518 Unit::CleanupsBeforeDelete();
521 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 )
523 //FIXME: outfitId not used in player creating
525 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
527 m_name = name;
529 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
530 if(!info)
532 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
533 return false;
536 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
537 m_items[i] = NULL;
539 SetLocationMapId(info->mapId);
540 Relocate(info->positionX,info->positionY,info->positionZ);
542 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
543 if(!cEntry)
545 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
546 return false;
549 SetMap(MapManager::Instance().CreateMap(info->mapId, this));
551 uint8 powertype = cEntry->powerType;
553 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
554 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
556 setFactionForRace(race);
558 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
560 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
561 InitDisplayIds();
562 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
563 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
564 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
565 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
566 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
568 // -1 is default value
569 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
571 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
572 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
573 SetByteValue(PLAYER_BYTES_3, 0, gender);
575 SetUInt32Value( PLAYER_GUILDID, 0 );
576 SetUInt32Value( PLAYER_GUILDRANK, 0 );
577 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
579 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
580 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
581 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES2, 0 ); // 0=disabled
582 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
583 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
584 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
585 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
586 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
588 // set starting level
589 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
590 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
591 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
593 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
595 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
596 if(gm_level > start_level)
597 start_level = gm_level;
600 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
602 InitRunes();
604 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
605 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
606 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
608 // Played time
609 m_Last_tick = time(NULL);
610 m_Played_time[PLAYED_TIME_TOTAL] = 0;
611 m_Played_time[PLAYED_TIME_LEVEL] = 0;
613 // base stats and related field values
614 InitStatsForLevel();
615 InitTaxiNodesForLevel();
616 InitGlyphsForLevel();
617 InitTalentForLevel();
618 InitPrimaryProfessions(); // to max set before any spell added
620 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
621 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
622 SetHealth(GetMaxHealth());
623 if (getPowerType()==POWER_MANA)
625 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
626 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
629 if(getPowerType() == POWER_RUNIC_POWER)
631 SetPower(POWER_RUNE, 8);
632 SetMaxPower(POWER_RUNE, 8);
633 SetPower(POWER_RUNIC_POWER, 0);
634 SetMaxPower(POWER_RUNIC_POWER, 1000);
637 // original spells
638 learnDefaultSpells();
640 // original action bar
641 for (PlayerCreateInfoActions::const_iterator action_itr = info->action.begin(); action_itr != info->action.end(); ++action_itr)
642 addActionButton(action_itr->button,action_itr->action,action_itr->type);
644 // original items
645 CharStartOutfitEntry const* oEntry = NULL;
646 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
648 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
650 if(entry->RaceClassGender == RaceClassGender)
652 oEntry = entry;
653 break;
658 if(oEntry)
660 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
662 if(oEntry->ItemId[j] <= 0)
663 continue;
665 uint32 item_id = oEntry->ItemId[j];
667 // Hack for not existed item id in dbc 3.0.3
668 if(item_id==40582)
669 continue;
671 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
672 if(!iProto)
674 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
675 continue;
678 // BuyCount by default
679 uint32 count = iProto->BuyCount;
681 // special amount for foor/drink
682 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
684 switch(iProto->Spells[0].SpellCategory)
686 case 11: // food
687 count = getClass()==CLASS_DEATH_KNIGHT ? 10 : 4;
688 break;
689 case 59: // drink
690 count = 2;
691 break;
693 if(iProto->Stackable < count)
694 count = iProto->Stackable;
697 StoreNewItemInBestSlots(item_id, count);
701 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
702 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
704 // bags and main-hand weapon must equipped at this moment
705 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
706 // or ammo not equipped in special bag
707 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
709 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
711 uint16 eDest;
712 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
713 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
714 if( msg == EQUIP_ERR_OK )
716 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
717 EquipItem( eDest, pItem, true);
719 // move other items to more appropriate slots (ammo not equipped in special bag)
720 else
722 ItemPosCountVec sDest;
723 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
724 if( msg == EQUIP_ERR_OK )
726 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
727 pItem = StoreItem( sDest, pItem, true);
730 // if this is ammo then use it
731 msg = CanUseAmmo( pItem->GetEntry() );
732 if( msg == EQUIP_ERR_OK )
733 SetAmmo( pItem->GetEntry() );
737 // all item positions resolved
739 return true;
742 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
744 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
746 // attempt equip by one
747 while(titem_amount > 0)
749 uint16 eDest;
750 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
751 if( msg != EQUIP_ERR_OK )
752 break;
754 EquipNewItem( eDest, titem_id, true);
755 AutoUnequipOffhandIfNeed();
756 --titem_amount;
759 if(titem_amount == 0)
760 return true; // equipped
762 // attempt store
763 ItemPosCountVec sDest;
764 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
765 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
766 if( msg == EQUIP_ERR_OK )
768 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
769 return true; // stored
772 // item can't be added
773 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
774 return false;
777 void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
779 if (int(MaxValue) == DISABLED_MIRROR_TIMER)
781 if (int(CurrentValue) != DISABLED_MIRROR_TIMER)
782 StopMirrorTimer(Type);
783 return;
785 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
786 data << (uint32)Type;
787 data << CurrentValue;
788 data << MaxValue;
789 data << Regen;
790 data << (uint8)0;
791 data << (uint32)0; // spell id
792 GetSession()->SendPacket( &data );
795 void Player::StopMirrorTimer(MirrorTimerType Type)
797 m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
798 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
799 data << (uint32)Type;
800 GetSession()->SendPacket( &data );
803 uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
805 if(!isAlive() || isGameMaster())
806 return 0;
808 // Absorb, resist some environmental damage type
809 uint32 absorb = 0;
810 uint32 resist = 0;
811 if (type == DAMAGE_LAVA)
812 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
813 else if (type == DAMAGE_SLIME)
814 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
816 damage-=absorb+resist;
818 DealDamageMods(this,damage,&absorb);
820 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
821 data << uint64(GetGUID());
822 data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
823 data << uint32(damage);
824 data << uint32(absorb);
825 data << uint32(resist);
826 SendMessageToSet(&data, true);
828 uint32 final_damage = DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
830 if(!isAlive())
832 if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
834 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
835 DurabilityLossAll(0.10f,false);
836 // durability lost message
837 WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
838 GetSession()->SendPacket(&data2);
841 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
844 return final_damage;
847 int32 Player::getMaxTimer(MirrorTimerType timer)
849 switch (timer)
851 case FATIGUE_TIMER:
852 return MINUTE*IN_MILISECONDS;
853 case BREATH_TIMER:
855 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
856 return DISABLED_MIRROR_TIMER;
857 int32 UnderWaterTime = 3*MINUTE*IN_MILISECONDS;
858 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
859 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
860 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
861 return UnderWaterTime;
863 case FIRE_TIMER:
865 if (!isAlive())
866 return DISABLED_MIRROR_TIMER;
867 return 1*IN_MILISECONDS;
869 default:
870 return 0;
872 return 0;
875 void Player::UpdateMirrorTimers()
877 // Desync flags for update on next HandleDrowning
878 if (m_MirrorTimerFlags)
879 m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
882 void Player::HandleDrowning(uint32 time_diff)
884 if (!m_MirrorTimerFlags)
885 return;
887 // In water
888 if (m_MirrorTimerFlags & UNDERWATER_INWATER)
890 // Breath timer not activated - activate it
891 if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
893 m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
894 SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
896 else // If activated - do tick
898 m_MirrorTimer[BREATH_TIMER]-=time_diff;
899 // Timer limit - need deal damage
900 if (m_MirrorTimer[BREATH_TIMER] < 0)
902 m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILISECONDS;
903 // Calculate and deal damage
904 // TODO: Check this formula
905 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
906 EnvironmentalDamage(DAMAGE_DROWNING, damage);
908 else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
909 SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
912 else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
914 int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
915 // Need breath regen
916 m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
917 if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
918 StopMirrorTimer(BREATH_TIMER);
919 else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
920 SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
923 // In dark water
924 if (m_MirrorTimerFlags & UNDERWARER_INDARKWATER)
926 // Fatigue timer not activated - activate it
927 if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
929 m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
930 SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
932 else
934 m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
935 // Timer limit - need deal damage or teleport ghost to graveyard
936 if (m_MirrorTimer[FATIGUE_TIMER] < 0)
938 m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILISECONDS;
939 if (isAlive()) // Calculate and deal damage
941 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
942 EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
944 else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
945 RepopAtGraveyard();
947 else if (!(m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER))
948 SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
951 else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
953 int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
954 m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
955 if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
956 StopMirrorTimer(FATIGUE_TIMER);
957 else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER)
958 SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
961 if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
963 // Breath timer not activated - activate it
964 if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
965 m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
966 else
968 m_MirrorTimer[FIRE_TIMER]-=time_diff;
969 if (m_MirrorTimer[FIRE_TIMER] < 0)
971 m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILISECONDS;
972 // Calculate and deal damage
973 // TODO: Check this formula
974 uint32 damage = urand(600, 700);
975 if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
976 EnvironmentalDamage(DAMAGE_LAVA, damage);
977 else
978 EnvironmentalDamage(DAMAGE_SLIME, damage);
982 else
983 m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
985 // Recheck timers flag
986 m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
987 for (int i = 0; i< MAX_TIMERS; ++i)
988 if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
990 m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
991 break;
993 m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
996 ///The player sobers by 256 every 10 seconds
997 void Player::HandleSobering()
999 m_drunkTimer = 0;
1001 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
1002 SetDrunkValue(drunk);
1005 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
1007 if(value >= 23000)
1008 return DRUNKEN_SMASHED;
1009 if(value >= 12800)
1010 return DRUNKEN_DRUNK;
1011 if(value & 0xFFFE)
1012 return DRUNKEN_TIPSY;
1013 return DRUNKEN_SOBER;
1016 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
1018 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1020 m_drunk = newDrunkenValue;
1021 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
1023 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1025 // special drunk invisibility detection
1026 if(newDrunkenState >= DRUNKEN_DRUNK)
1027 m_detectInvisibilityMask |= (1<<6);
1028 else
1029 m_detectInvisibilityMask &= ~(1<<6);
1031 if(newDrunkenState == oldDrunkenState)
1032 return;
1034 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1035 data << uint64(GetGUID());
1036 data << uint32(newDrunkenState);
1037 data << uint32(itemId);
1039 SendMessageToSet(&data, true);
1042 void Player::Update( uint32 p_time )
1044 if(!IsInWorld())
1045 return;
1047 // undelivered mail
1048 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1050 SendNewMail();
1051 ++unReadMails;
1053 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1054 m_nextMailDelivereTime = 0;
1057 //used to implement delayed far teleports
1058 SetCanDelayTeleport(true);
1059 Unit::Update( p_time );
1060 SetCanDelayTeleport(false);
1062 // update player only attacks
1063 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1065 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1068 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1070 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1073 time_t now = time (NULL);
1075 UpdatePvPFlag(now);
1077 UpdateContestedPvP(p_time);
1079 UpdateDuelFlag(now);
1081 CheckDuelDistance(now);
1083 UpdateAfkReport(now);
1085 // Update items that have just a limited lifetime
1086 if (now>m_Last_tick)
1087 UpdateItemDuration(uint32(now- m_Last_tick));
1089 if (!m_timedquests.empty())
1091 std::set<uint32>::iterator iter = m_timedquests.begin();
1092 while (iter != m_timedquests.end())
1094 QuestStatusData& q_status = mQuestStatus[*iter];
1095 if( q_status.m_timer <= p_time )
1097 uint32 quest_id = *iter;
1098 ++iter; // current iter will be removed in FailQuest
1099 FailQuest(quest_id);
1101 else
1103 q_status.m_timer -= p_time;
1104 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1105 ++iter;
1110 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1112 Unit *pVictim = getVictim();
1113 if (pVictim && !IsNonMeleeSpellCasted(false))
1115 // default combat reach 10
1116 // TODO add weapon,skill check
1118 float pldistance = ATTACK_DISTANCE;
1120 if (isAttackReady(BASE_ATTACK))
1122 if(!IsWithinDistInMap(pVictim, pldistance))
1124 setAttackTimer(BASE_ATTACK,100);
1125 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1127 SendAttackSwingNotInRange();
1128 m_swingErrorMsg = 1;
1131 //120 degrees of radiant range
1132 else if( !HasInArc( 2*M_PI/3, pVictim ))
1134 setAttackTimer(BASE_ATTACK,100);
1135 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1137 SendAttackSwingBadFacingAttack();
1138 m_swingErrorMsg = 2;
1141 else
1143 m_swingErrorMsg = 0; // reset swing error state
1145 // prevent base and off attack in same time, delay attack at 0.2 sec
1146 if(haveOffhandWeapon())
1148 uint32 off_att = getAttackTimer(OFF_ATTACK);
1149 if(off_att < ATTACK_DISPLAY_DELAY)
1150 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1152 AttackerStateUpdate(pVictim, BASE_ATTACK);
1153 resetAttackTimer(BASE_ATTACK);
1157 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1159 if(!IsWithinDistInMap(pVictim, pldistance))
1161 setAttackTimer(OFF_ATTACK,100);
1163 else if( !HasInArc( 2*M_PI/3, pVictim ))
1165 setAttackTimer(OFF_ATTACK,100);
1167 else
1169 // prevent base and off attack in same time, delay attack at 0.2 sec
1170 uint32 base_att = getAttackTimer(BASE_ATTACK);
1171 if(base_att < ATTACK_DISPLAY_DELAY)
1172 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1173 // do attack
1174 AttackerStateUpdate(pVictim, OFF_ATTACK);
1175 resetAttackTimer(OFF_ATTACK);
1179 Unit *owner = pVictim->GetOwner();
1180 Unit *u = owner ? owner : pVictim;
1181 if(u->IsPvP() && (!duel || duel->opponent != u))
1183 UpdatePvP(true);
1184 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1189 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1191 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1193 int time_inn = time(NULL)-GetTimeInnEnter();
1194 if (time_inn >= 10) //freeze update
1196 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1197 //speed collect rest bonus (section/in hour)
1198 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1199 UpdateInnerTime(time(NULL));
1204 if (m_regenTimer)
1206 if(p_time >= m_regenTimer)
1207 m_regenTimer = 0;
1208 else
1209 m_regenTimer -= p_time;
1212 if (m_weaponChangeTimer > 0)
1214 if(p_time >= m_weaponChangeTimer)
1215 m_weaponChangeTimer = 0;
1216 else
1217 m_weaponChangeTimer -= p_time;
1220 if (m_zoneUpdateTimer > 0)
1222 if(p_time >= m_zoneUpdateTimer)
1224 uint32 newzone, newarea;
1225 GetZoneAndAreaId(newzone,newarea);
1227 if( m_zoneUpdateId != newzone )
1228 UpdateZone(newzone,newarea); // also update area
1229 else
1231 // use area updates as well
1232 // needed for free far all arenas for example
1233 if( m_areaUpdateId != newarea )
1234 UpdateArea(newarea);
1236 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1239 else
1240 m_zoneUpdateTimer -= p_time;
1243 if (isAlive())
1245 // if no longer casting, set regen power as soon as it is up.
1246 if (!IsUnderLastManaUseEffect())
1247 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
1249 if (!m_regenTimer)
1250 RegenerateAll();
1253 if (m_deathState == JUST_DIED)
1255 KillPlayer();
1258 if(m_nextSave > 0)
1260 if(p_time >= m_nextSave)
1262 // m_nextSave reseted in SaveToDB call
1263 SaveToDB();
1264 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1266 else
1268 m_nextSave -= p_time;
1272 //Handle Water/drowning
1273 HandleDrowning(p_time);
1275 //Handle detect stealth players
1276 if (m_DetectInvTimer > 0)
1278 if (p_time >= m_DetectInvTimer)
1280 HandleStealthedUnitsDetection();
1281 m_DetectInvTimer = 3000;
1283 else
1284 m_DetectInvTimer -= p_time;
1287 // Played time
1288 if (now > m_Last_tick)
1290 uint32 elapsed = uint32(now - m_Last_tick);
1291 m_Played_time[PLAYED_TIME_TOTAL] += elapsed; // Total played time
1292 m_Played_time[PLAYED_TIME_LEVEL] += elapsed; // Level played time
1293 m_Last_tick = now;
1296 if (m_drunk)
1298 m_drunkTimer += p_time;
1300 if (m_drunkTimer > 10*IN_MILISECONDS)
1301 HandleSobering();
1304 // not auto-free ghost from body in instances
1305 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1307 if(p_time >= m_deathTimer)
1309 m_deathTimer = 0;
1310 BuildPlayerRepop();
1311 RepopAtGraveyard();
1313 else
1314 m_deathTimer -= p_time;
1317 UpdateEnchantTime(p_time);
1318 UpdateHomebindTime(p_time);
1320 // group update
1321 SendUpdateToOutOfRangeGroupMembers();
1323 Pet* pet = GetPet();
1324 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1326 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1329 //we should execute delayed teleports only for alive(!) players
1330 //because we don't want player's ghost teleported from graveyard
1331 if(IsHasDelayedTeleport() && isAlive())
1332 TeleportTo(m_teleport_dest, m_teleport_options);
1335 void Player::setDeathState(DeathState s)
1337 uint32 ressSpellId = 0;
1339 bool cur = isAlive();
1341 if(s == JUST_DIED && cur)
1343 // drunken state is cleared on death
1344 SetDrunkValue(0);
1345 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1346 ClearComboPoints();
1348 clearResurrectRequestData();
1350 // remove form before other mods to prevent incorrect stats calculation
1351 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1353 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1354 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1356 // remove uncontrolled pets
1357 RemoveMiniPet();
1359 // save value before aura remove in Unit::setDeathState
1360 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1362 // passive spell
1363 if(!ressSpellId)
1364 ressSpellId = GetResurrectionSpellId();
1365 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1366 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
1367 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
1369 Unit::setDeathState(s);
1371 // restore resurrection spell id for player after aura remove
1372 if(s == JUST_DIED && cur && ressSpellId)
1373 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1375 if(isAlive() && !cur)
1377 //clear aura case after resurrection by another way (spells will be applied before next death)
1378 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1380 // restore default warrior stance
1381 if(getClass()== CLASS_WARRIOR)
1382 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1386 bool Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1388 // 0 1 2 3 4 5 6 7
1389 // "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.playerBytes, characters.playerBytes2, characters.level, "
1390 // 8 9 10 11 12 13 14
1391 // "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, "
1392 // 15 16 17 18 19 20
1393 // "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.data, character_declinedname.genitive "
1395 Field *fields = result->Fetch();
1397 uint32 guid = fields[0].GetUInt32();
1398 uint8 pRace = fields[2].GetUInt8();
1399 uint8 pClass = fields[3].GetUInt8();
1401 PlayerInfo const *info = objmgr.GetPlayerInfo(pRace, pClass);
1402 if(!info)
1404 sLog.outError("Player %u has incorrect race/class pair. Don't build enum.", guid);
1405 return false;
1408 *p_data << uint64(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
1409 *p_data << fields[1].GetString(); // name
1410 *p_data << uint8(pRace); // race
1411 *p_data << uint8(pClass); // class
1412 *p_data << uint8(fields[4].GetUInt8()); // gender
1414 uint32 playerBytes = fields[5].GetUInt32();
1415 *p_data << uint8(playerBytes); // skin
1416 *p_data << uint8(playerBytes >> 8); // face
1417 *p_data << uint8(playerBytes >> 16); // hair style
1418 *p_data << uint8(playerBytes >> 24); // hair color
1420 uint32 playerBytes2 = fields[6].GetUInt32();
1421 *p_data << uint8(playerBytes2 & 0xFF); // facial hair
1423 *p_data << uint8(fields[7].GetUInt8()); // level
1424 *p_data << uint32(fields[8].GetUInt32()); // zone
1425 *p_data << uint32(fields[9].GetUInt32()); // map
1427 *p_data << fields[10].GetFloat(); // x
1428 *p_data << fields[11].GetFloat(); // y
1429 *p_data << fields[12].GetFloat(); // z
1431 *p_data << uint32(fields[13].GetUInt32()); // guild id
1433 uint32 char_flags = 0;
1434 uint32 playerFlags = fields[14].GetUInt32();
1435 uint32 atLoginFlags = fields[15].GetUInt32();
1436 if(playerFlags & PLAYER_FLAGS_HIDE_HELM)
1437 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1438 if(playerFlags & PLAYER_FLAGS_HIDE_CLOAK)
1439 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1440 if(playerFlags & PLAYER_FLAGS_GHOST)
1441 char_flags |= CHARACTER_FLAG_GHOST;
1442 if(atLoginFlags & AT_LOGIN_RENAME)
1443 char_flags |= CHARACTER_FLAG_RENAME;
1444 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED))
1446 if(!fields[20].GetCppString().empty())
1447 char_flags |= CHARACTER_FLAG_DECLINED;
1449 else
1450 char_flags |= CHARACTER_FLAG_DECLINED;
1452 *p_data << uint32(char_flags); // character flags
1453 // character customize (flags?)
1454 *p_data << uint32(atLoginFlags & AT_LOGIN_CUSTOMIZE ? 1 : 0);
1455 *p_data << uint8(1); // unknown
1457 // Pets info
1459 uint32 petDisplayId = 0;
1460 uint32 petLevel = 0;
1461 uint32 petFamily = 0;
1463 // show pet at selection character in character list only for non-ghost character
1464 if (result && !(playerFlags & PLAYER_FLAGS_GHOST) && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER || pClass == CLASS_DEATH_KNIGHT))
1466 uint32 entry = fields[16].GetUInt32();
1467 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1468 if(cInfo)
1470 petDisplayId = fields[17].GetUInt32();
1471 petLevel = fields[18].GetUInt32();
1472 petFamily = cInfo->family;
1476 *p_data << uint32(petDisplayId);
1477 *p_data << uint32(petLevel);
1478 *p_data << uint32(petFamily);
1481 // TODO: do not access data field here
1482 Tokens data = StrSplit(fields[19].GetCppString(), " ");
1484 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1486 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2);
1487 uint32 item_id = GetUInt32ValueFromArray(data, visualbase);
1488 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1489 if(!proto)
1491 *p_data << uint32(0);
1492 *p_data << uint8(0);
1493 *p_data << uint32(0);
1494 continue;
1497 SpellItemEnchantmentEntry const *enchant = NULL;
1499 uint32 enchants = GetUInt32ValueFromArray(data, visualbase + 1);
1500 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot)
1502 // values stored in 2 uint16
1503 uint32 enchantId = 0x0000FFFF & (enchants >> enchantSlot*16);
1504 if(!enchantId)
1505 continue;
1507 if ((enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId)))
1508 break;
1511 *p_data << uint32(proto->DisplayInfoID);
1512 *p_data << uint8(proto->InventoryType);
1513 *p_data << uint32(enchant ? enchant->aura_id : 0);
1515 *p_data << uint32(0); // first bag display id
1516 *p_data << uint8(0); // first bag inventory type
1517 *p_data << uint32(0); // enchant?
1519 return true;
1522 bool Player::ToggleAFK()
1524 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1526 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1528 // afk player not allowed in battleground
1529 if(state && InBattleGround())
1530 LeaveBattleground();
1532 return state;
1535 bool Player::ToggleDND()
1537 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1539 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1542 uint8 Player::chatTag() const
1544 // it's bitmask
1545 // 0x8 - ??
1546 // 0x4 - gm
1547 // 0x2 - dnd
1548 // 0x1 - afk
1549 if(isGMChat())
1550 return 4;
1551 else if(isDND())
1552 return 3;
1553 if(isAFK())
1554 return 1;
1555 else
1556 return 0;
1559 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1561 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1563 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1564 return false;
1567 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1568 Pet* pet = GetPet();
1570 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1572 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1573 // don't let gm level > 1 either
1574 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1575 return false;
1577 // client without expansion support
1578 if(GetSession()->Expansion() < mEntry->Expansion())
1580 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1582 if(GetTransport())
1583 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1585 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1587 return false; // normal client can't teleport to this map...
1589 else
1591 sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
1594 // if we were on a transport, leave
1595 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1597 m_transport->RemovePassenger(this);
1598 m_transport = NULL;
1599 m_movementInfo.t_x = 0.0f;
1600 m_movementInfo.t_y = 0.0f;
1601 m_movementInfo.t_z = 0.0f;
1602 m_movementInfo.t_o = 0.0f;
1603 m_movementInfo.t_time = 0;
1606 // The player was ported to another map and looses the duel immediately.
1607 // We have to perform this check before the teleport, otherwise the
1608 // ObjectAccessor won't find the flag.
1609 if (duel && GetMapId()!=mapid)
1611 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
1612 if (obj)
1613 DuelComplete(DUEL_FLED);
1616 // reset movement flags at teleport, because player will continue move with these flags after teleport
1617 m_movementInfo.SetMovementFlags(MOVEMENTFLAG_NONE);
1619 if ((GetMapId() == mapid) && (!m_transport))
1621 //lets reset far teleport flag if it wasn't reset during chained teleports
1622 SetSemaphoreTeleportFar(false);
1623 //setup delayed teleport flag
1624 SetDelayedTeleportFlag(IsCanDelayTeleport());
1625 //if teleport spell is casted in Unit::Update() func
1626 //then we need to delay it until update process will be finished
1627 if(IsHasDelayedTeleport())
1629 SetSemaphoreTeleportNear(true);
1630 //lets save teleport destination for player
1631 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1632 m_teleport_options = options;
1633 return true;
1636 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1638 //same map, only remove pet if out of range for new position
1639 if(pet && !pet->IsWithinDist3d(x,y,z, OWNER_MAX_DISTANCE))
1640 UnsummonPetTemporaryIfAny();
1643 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1644 CombatStop();
1646 // this will be used instead of the current location in SaveToDB
1647 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1648 SetFallInformation(0, z);
1650 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1651 // at client packet MSG_MOVE_TELEPORT_ACK
1652 SetSemaphoreTeleportNear(true);
1653 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1654 if(!GetSession()->PlayerLogout())
1656 WorldPacket data;
1657 BuildTeleportAckMsg(&data, x, y, z, orientation);
1658 GetSession()->SendPacket(&data);
1661 else
1663 // far teleport to another map
1664 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1665 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1667 // Check enter rights before map getting to avoid creating instance copy for player
1668 // this check not dependent from map instance copy and same for all instance copies of selected map
1669 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1670 return false;
1672 // If the map is not created, assume it is possible to enter it.
1673 // It will be created in the WorldPortAck.
1674 Map *map = MapManager::Instance().FindMap(mapid);
1675 if (!map || map->CanEnter(this))
1677 //lets reset near teleport flag if it wasn't reset during chained teleports
1678 SetSemaphoreTeleportNear(false);
1679 //setup delayed teleport flag
1680 SetDelayedTeleportFlag(IsCanDelayTeleport());
1681 //if teleport spell is casted in Unit::Update() func
1682 //then we need to delay it until update process will be finished
1683 if(IsHasDelayedTeleport())
1685 SetSemaphoreTeleportFar(true);
1686 //lets save teleport destination for player
1687 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1688 m_teleport_options = options;
1689 return true;
1692 SetSelection(0);
1694 CombatStop();
1696 ResetContestedPvP();
1698 // remove player from battleground on far teleport (when changing maps)
1699 if(BattleGround const* bg = GetBattleGround())
1701 // Note: at battleground join battleground id set before teleport
1702 // and we already will found "current" battleground
1703 // just need check that this is targeted map or leave
1704 if(bg->GetMapId() != mapid)
1705 LeaveBattleground(false); // don't teleport to entry point
1708 // remove pet on map change
1709 if (pet)
1710 UnsummonPetTemporaryIfAny();
1712 // remove all dyn objects
1713 RemoveAllDynObjects();
1715 // stop spellcasting
1716 // not attempt interrupt teleportation spell at caster teleport
1717 if(!(options & TELE_TO_SPELL))
1718 if(IsNonMeleeSpellCasted(true))
1719 InterruptNonMeleeSpells(true);
1721 //remove auras before removing from map...
1722 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
1724 if(!GetSession()->PlayerLogout())
1726 // send transfer packets
1727 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1728 data << uint32(mapid);
1729 if (m_transport)
1731 data << m_transport->GetEntry() << GetMapId();
1733 GetSession()->SendPacket(&data);
1735 data.Initialize(SMSG_NEW_WORLD, (20));
1736 if (m_transport)
1738 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1740 else
1742 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1744 GetSession()->SendPacket( &data );
1745 SendSavedInstances();
1747 // remove from old map now
1748 if(oldmap) oldmap->Remove(this, false);
1751 // new final coordinates
1752 float final_x = x;
1753 float final_y = y;
1754 float final_z = z;
1755 float final_o = orientation;
1757 if(m_transport)
1759 final_x += m_movementInfo.t_x;
1760 final_y += m_movementInfo.t_y;
1761 final_z += m_movementInfo.t_z;
1762 final_o += m_movementInfo.t_o;
1765 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1766 SetFallInformation(0, final_z);
1767 // if the player is saved before worldportack (at logout for example)
1768 // this will be used instead of the current location in SaveToDB
1770 // move packet sent by client always after far teleport
1771 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1772 SetSemaphoreTeleportFar(true);
1774 else
1775 return false;
1777 return true;
1780 bool Player::TeleportToBGEntryPoint()
1782 ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE);
1783 ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE);
1784 return TeleportTo(m_bgData.joinPos);
1787 void Player::ProcessDelayedOperations()
1789 if(m_DelayedOperations == 0)
1790 return;
1792 if(m_DelayedOperations & DELAYED_RESURRECT_PLAYER)
1794 ResurrectPlayer(0.0f, false);
1796 if(GetMaxHealth() > m_resurrectHealth)
1797 SetHealth( m_resurrectHealth );
1798 else
1799 SetHealth( GetMaxHealth() );
1801 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
1802 SetPower(POWER_MANA, m_resurrectMana );
1803 else
1804 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
1806 SetPower(POWER_RAGE, 0 );
1807 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
1809 SpawnCorpseBones();
1812 if(m_DelayedOperations & DELAYED_SAVE_PLAYER)
1814 SaveToDB();
1817 if(m_DelayedOperations & DELAYED_SPELL_CAST_DESERTER)
1819 CastSpell(this, 26013, true); // Deserter
1822 if (m_DelayedOperations & DELAYED_BG_MOUNT_RESTORE)
1824 if (m_bgData.mountSpell)
1826 CastSpell(this, m_bgData.mountSpell, true);
1827 m_bgData.mountSpell = 0;
1831 if (m_DelayedOperations & DELAYED_BG_TAXI_RESTORE)
1833 if (m_bgData.HasTaxiPath())
1835 m_taxi.AddTaxiDestination(m_bgData.taxiPath[0]);
1836 m_taxi.AddTaxiDestination(m_bgData.taxiPath[1]);
1837 m_bgData.ClearTaxiPath();
1839 ContinueTaxiFlight();
1843 //we have executed ALL delayed ops, so clear the flag
1844 m_DelayedOperations = 0;
1847 void Player::AddToWorld()
1849 ///- Do not add/remove the player from the object storage
1850 ///- It will crash when updating the ObjectAccessor
1851 ///- The player should only be added when logging in
1852 Unit::AddToWorld();
1854 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1856 if(m_items[i])
1857 m_items[i]->AddToWorld();
1861 void Player::RemoveFromWorld()
1863 // cleanup
1864 if(IsInWorld())
1866 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1867 Uncharm();
1868 UnsummonAllTotems();
1869 RemoveMiniPet();
1872 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1874 if(m_items[i])
1875 m_items[i]->RemoveFromWorld();
1878 ///- Do not add/remove the player from the object storage
1879 ///- It will crash when updating the ObjectAccessor
1880 ///- The player should only be removed when logging out
1881 Unit::RemoveFromWorld();
1884 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1886 float addRage;
1888 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1890 if(attacker)
1892 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1894 // talent who gave more rage on attack
1895 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1897 else
1899 addRage = damage/rageconversion*2.5;
1901 // Berserker Rage effect
1902 if(HasAura(18499,0))
1903 addRage *= 1.3;
1906 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1908 ModifyPower(POWER_RAGE, uint32(addRage*10));
1911 void Player::RegenerateAll(uint32 diff)
1913 // Not in combat or they have regeneration
1914 if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1915 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1917 RegenerateHealth(diff);
1918 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1920 Regenerate(POWER_RAGE, diff);
1921 if(getClass() == CLASS_DEATH_KNIGHT)
1922 Regenerate(POWER_RUNIC_POWER, diff);
1926 Regenerate(POWER_ENERGY, diff);
1928 Regenerate(POWER_MANA, diff);
1930 if (getClass() == CLASS_DEATH_KNIGHT)
1931 Regenerate(POWER_RUNE, diff);
1933 m_regenTimer = REGEN_TIME_FULL;
1936 // diff contains the time in milliseconds since last regen.
1937 void Player::Regenerate(Powers power, uint32 diff)
1939 uint32 curValue = GetPower(power);
1940 uint32 maxValue = GetMaxPower(power);
1942 float addvalue = 0.0f;
1944 switch (power)
1946 case POWER_MANA:
1948 bool recentCast = IsUnderLastManaUseEffect();
1949 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1950 if (recentCast)
1952 // Mangos Updates Mana in intervals of 2s, which is correct
1953 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1955 else
1957 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1959 } break;
1960 case POWER_RAGE: // Regenerate rage
1962 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1963 addvalue = 20 * RageDecreaseRate; // 2 rage by tick (= 2 seconds => 1 rage/sec)
1964 } break;
1965 case POWER_ENERGY: // Regenerate energy (rogue)
1966 addvalue = 20;
1967 break;
1968 case POWER_RUNIC_POWER:
1970 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1971 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1972 } break;
1973 case POWER_RUNE:
1975 for(uint32 i = 0; i < MAX_RUNES; ++i)
1977 if(uint16 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1978 SetRuneCooldown(i, (cd < diff) ? 0 : cd - diff);
1980 } break;
1981 case POWER_FOCUS:
1982 case POWER_HAPPINESS:
1983 case POWER_HEALTH:
1984 break;
1987 // Mana regen calculated in Player::UpdateManaRegen()
1988 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1989 if(power != POWER_MANA)
1991 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1992 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1993 if ((*i)->GetModifier()->m_miscvalue == power)
1994 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1997 // addvalue computed on a 2sec basis. => update to diff time
1998 addvalue *= float(diff) / REGEN_TIME_FULL;
2000 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
2002 curValue += uint32(addvalue);
2003 if (curValue > maxValue)
2004 curValue = maxValue;
2006 else
2008 if(curValue <= uint32(addvalue))
2009 curValue = 0;
2010 else
2011 curValue -= uint32(addvalue);
2013 SetPower(power, curValue);
2016 void Player::RegenerateHealth(uint32 diff)
2018 uint32 curValue = GetHealth();
2019 uint32 maxValue = GetMaxHealth();
2021 if (curValue >= maxValue) return;
2023 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
2025 float addvalue = 0.0f;
2027 // polymorphed case
2028 if ( IsPolymorphed() )
2029 addvalue = GetMaxHealth()/3;
2030 // normal regen case (maybe partly in combat case)
2031 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
2033 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
2034 if (!isInCombat())
2036 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
2037 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
2038 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
2040 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
2041 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
2043 if(!IsStandState())
2044 addvalue *= 1.5;
2047 // always regeneration bonus (including combat)
2048 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
2050 if(addvalue < 0)
2051 addvalue = 0;
2053 addvalue *= (float)diff / REGEN_TIME_FULL;
2055 ModifyHealth(int32(addvalue));
2058 bool Player::CanInteractWithNPCs(bool alive) const
2060 if(alive && !isAlive())
2061 return false;
2062 if(isInFlight())
2063 return false;
2065 return true;
2068 Creature*
2069 Player::GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask)
2071 // unit checks
2072 if (!guid)
2073 return NULL;
2075 if(!IsInWorld())
2076 return NULL;
2078 // exist (we need look pets also for some interaction (quest/etc)
2079 Creature *unit = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
2080 if (!unit)
2081 return NULL;
2083 // player check
2084 if(!CanInteractWithNPCs(!unit->isSpiritService()))
2085 return NULL;
2087 // appropriate npc type
2088 if(npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
2089 return NULL;
2091 // alive or spirit healer
2092 if(!unit->isAlive() && (!unit->isSpiritService() || isAlive() ))
2093 return NULL;
2095 // not allow interaction under control, but allow with own pets
2096 if(unit->GetCharmerGUID())
2097 return NULL;
2099 // not enemy
2100 if( unit->IsHostileTo(this))
2101 return NULL;
2103 // not unfriendly
2104 if(FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction()))
2105 if(factionTemplate->faction)
2106 if(FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
2107 if(faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
2108 return NULL;
2110 // not too far
2111 if(!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE))
2112 return NULL;
2114 return unit;
2117 GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const
2119 if(GameObject *go = GetMap()->GetGameObject(guid))
2121 if(go->GetGoType() == type)
2123 float maxdist;
2124 switch(type)
2126 // TODO: find out how the client calculates the maximal usage distance to spellless working
2127 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2128 case GAMEOBJECT_TYPE_GUILD_BANK:
2129 case GAMEOBJECT_TYPE_MAILBOX:
2130 maxdist = 10.0f;
2131 break;
2132 case GAMEOBJECT_TYPE_FISHINGHOLE:
2133 maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
2134 break;
2135 default:
2136 maxdist = INTERACTION_DISTANCE;
2137 break;
2140 if (go->IsWithinDistInMap(this, maxdist))
2141 return go;
2143 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,
2144 go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
2147 return NULL;
2150 bool Player::IsUnderWater() const
2152 return IsInWater() &&
2153 GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2156 void Player::SetInWater(bool apply)
2158 if(m_isInWater==apply)
2159 return;
2161 //define player in water by opcodes
2162 //move player's guid into HateOfflineList of those mobs
2163 //which can't swim and move guid back into ThreatList when
2164 //on surface.
2165 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2166 m_isInWater = apply;
2168 // remove auras that need water/land
2169 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
2171 getHostilRefManager().updateThreatTables();
2174 void Player::SetGameMaster(bool on)
2176 if(on)
2178 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
2179 setFaction(35);
2180 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2182 if (Pet* pet = GetPet())
2184 pet->setFaction(35);
2185 pet->getHostilRefManager().setOnlineOfflineState(false);
2188 for (int8 i = 0; i < MAX_TOTEM; ++i)
2189 if(m_TotemSlot[i])
2190 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
2191 totem->setFaction(35);
2193 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2194 ResetContestedPvP();
2196 getHostilRefManager().setOnlineOfflineState(false);
2197 CombatStopWithPets();
2199 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
2201 else
2203 // restore phase
2204 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
2205 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2207 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2208 setFactionForRace(getRace());
2209 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2211 if (Pet* pet = GetPet())
2213 pet->setFaction(getFaction());
2214 pet->getHostilRefManager().setOnlineOfflineState(true);
2217 for (int8 i = 0; i < MAX_TOTEM; ++i)
2218 if(m_TotemSlot[i])
2219 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
2220 totem->setFaction(getFaction());
2222 // restore FFA PvP Server state
2223 if(sWorld.IsFFAPvPRealm())
2224 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2226 // restore FFA PvP area state, remove not allowed for GM mounts
2227 UpdateArea(m_areaUpdateId);
2229 getHostilRefManager().setOnlineOfflineState(true);
2232 ObjectAccessor::UpdateVisibilityForPlayer(this);
2235 void Player::SetGMVisible(bool on)
2237 if(on)
2239 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2241 // Reapply stealth/invisibility if active or show if not any
2242 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2243 SetVisibility(VISIBILITY_GROUP_STEALTH);
2244 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2245 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2246 else
2247 SetVisibility(VISIBILITY_ON);
2249 else
2251 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2253 SetAcceptWhispers(false);
2254 SetGameMaster(true);
2256 SetVisibility(VISIBILITY_OFF);
2260 bool Player::IsGroupVisibleFor(Player* p) const
2262 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2264 default: return IsInSameGroupWith(p);
2265 case 1: return IsInSameRaidWith(p);
2266 case 2: return GetTeam()==p->GetTeam();
2270 bool Player::IsInSameGroupWith(Player const* p) const
2272 return (p==this || (GetGroup() != NULL &&
2273 GetGroup()->SameSubGroup((Player*)this, (Player*)p)));
2276 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2277 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2278 void Player::UninviteFromGroup()
2280 Group* group = GetGroupInvite();
2281 if(!group)
2282 return;
2284 group->RemoveInvite(this);
2286 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2288 if(group->IsCreated())
2290 group->Disband(true);
2291 objmgr.RemoveGroup(group);
2293 else
2294 group->RemoveAllInvites();
2296 delete group;
2300 void Player::RemoveFromGroup(Group* group, uint64 guid)
2302 if(group)
2304 if (group->RemoveMember(guid, 0) <= 1)
2306 // group->Disband(); already disbanded in RemoveMember
2307 objmgr.RemoveGroup(group);
2308 delete group;
2309 // removemember sets the player's group pointer to NULL
2314 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2316 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2317 data << uint64(victim ? victim->GetGUID() : 0); // guid
2318 data << uint32(GivenXP+RestXP); // given experience
2319 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2320 if(victim)
2322 data << uint32(GivenXP); // experience without rested bonus
2323 data << float(1); // 1 - none 0 - 100% group bonus output
2325 data << uint8(0); // new 2.4.0
2326 GetSession()->SendPacket(&data);
2329 void Player::GiveXP(uint32 xp, Unit* victim)
2331 if ( xp < 1 )
2332 return;
2334 if(!isAlive())
2335 return;
2337 uint32 level = getLevel();
2339 // XP to money conversion processed in Player::RewardQuest
2340 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2341 return;
2343 // handle SPELL_AURA_MOD_XP_PCT auras
2344 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2345 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2346 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2348 // XP resting bonus for kill
2349 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2351 SendLogXPGain(xp,victim,rested_bonus_xp);
2353 uint32 curXP = GetUInt32Value(PLAYER_XP);
2354 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2355 uint32 newXP = curXP + xp + rested_bonus_xp;
2357 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2359 newXP -= nextLvlXP;
2361 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2362 GiveLevel(level + 1);
2364 level = getLevel();
2365 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2368 SetUInt32Value(PLAYER_XP, newXP);
2371 // Update player to next level
2372 // Current player experience not update (must be update by caller)
2373 void Player::GiveLevel(uint32 level)
2375 if ( level == getLevel() )
2376 return;
2378 PlayerLevelInfo info;
2379 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2381 PlayerClassLevelInfo classInfo;
2382 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2384 // send levelup info to client
2385 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2386 data << uint32(level);
2387 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2388 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2389 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2390 data << uint32(0);
2391 data << uint32(0);
2392 data << uint32(0);
2393 data << uint32(0);
2394 data << uint32(0);
2395 data << uint32(0);
2396 // end for
2397 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2398 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2400 GetSession()->SendPacket(&data);
2402 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level));
2404 //update level, max level of skills
2405 m_Played_time[PLAYED_TIME_LEVEL] = 0; // Level Played Time reset
2407 _ApplyAllLevelScaleItemMods(false);
2409 SetLevel(level);
2411 UpdateSkillsForLevel ();
2413 // save base values (bonuses already included in stored stats
2414 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2415 SetCreateStat(Stats(i), info.stats[i]);
2417 SetCreateHealth(classInfo.basehealth);
2418 SetCreateMana(classInfo.basemana);
2420 InitTalentForLevel();
2421 InitTaxiNodesForLevel();
2422 InitGlyphsForLevel();
2424 UpdateAllStats();
2426 // set current level health and mana/energy to maximum after applying all mods.
2427 SetHealth(GetMaxHealth());
2428 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2429 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2430 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2431 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2432 SetPower(POWER_FOCUS, 0);
2433 SetPower(POWER_HAPPINESS, 0);
2435 _ApplyAllLevelScaleItemMods(true);
2437 // update level to hunter/summon pet
2438 if (Pet* pet = GetPet())
2439 pet->SynchronizeLevelWithOwner();
2441 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2444 void Player::InitTalentForLevel()
2446 uint32 level = getLevel();
2447 // talents base at level diff ( talents = level - 9 but some can be used already)
2448 if(level < 10)
2450 // Remove all talent points
2451 if(m_usedTalentCount > 0) // Free any used talents
2453 resetTalents(true);
2454 SetFreeTalentPoints(0);
2457 else
2459 uint32 talentPointsForLevel = CalculateTalentsPoints();
2461 // if used more that have then reset
2462 if(m_usedTalentCount > talentPointsForLevel)
2464 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2465 resetTalents(true);
2466 else
2467 SetFreeTalentPoints(0);
2469 // else update amount of free points
2470 else
2471 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2474 if(!GetSession()->PlayerLoading())
2475 SendTalentsInfoData(false); // update at client
2478 void Player::InitStatsForLevel(bool reapplyMods)
2480 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2481 _RemoveAllStatBonuses();
2483 PlayerClassLevelInfo classInfo;
2484 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2486 PlayerLevelInfo info;
2487 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2489 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2490 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel()));
2492 UpdateSkillsForLevel ();
2494 // set default cast time multiplier
2495 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2497 // reset size before reapply auras
2498 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2500 // save base values (bonuses already included in stored stats
2501 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2502 SetCreateStat(Stats(i), info.stats[i]);
2504 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2505 SetStat(Stats(i), info.stats[i]);
2507 SetCreateHealth(classInfo.basehealth);
2509 //set create powers
2510 SetCreateMana(classInfo.basemana);
2512 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2514 InitStatBuffMods();
2516 //reset rating fields values
2517 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2518 SetUInt32Value(index, 0);
2520 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2521 for (int i = 0; i < 7; ++i)
2523 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2524 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2525 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2528 //reset attack power, damage and attack speed fields
2529 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2530 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2531 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2533 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2534 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2535 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2536 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2537 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2538 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2540 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2541 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2542 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2543 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2544 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2545 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2547 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2548 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2549 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2550 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2552 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2553 for (uint8 i = 0; i < 7; ++i)
2554 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2556 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2557 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2558 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2560 // Dodge percentage
2561 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2563 // set armor (resistance 0) to original value (create_agility*2)
2564 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2565 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2566 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2567 // set other resistance to original value (0)
2568 for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
2570 SetResistance(SpellSchools(i), 0);
2571 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2572 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2575 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2576 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2577 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2579 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
2580 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2582 // Reset no reagent cost field
2583 for(int i = 0; i < 3; ++i)
2584 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2585 // Init data for form but skip reapply item mods for form
2586 InitDataForForm(reapplyMods);
2588 // save new stats
2589 for (int i = POWER_MANA; i < MAX_POWERS; ++i)
2590 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2592 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2594 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2595 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2597 // cleanup unit flags (will be re-applied if need at aura load).
2598 RemoveFlag( UNIT_FIELD_FLAGS,
2599 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2600 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2601 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2602 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2603 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2604 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2606 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2608 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2609 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2611 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2612 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2614 // restore if need some important flags
2615 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2617 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2618 _ApplyAllStatBonuses();
2620 // set current level health and mana/energy to maximum after applying all mods.
2621 SetHealth(GetMaxHealth());
2622 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2623 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2624 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2625 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2626 SetPower(POWER_FOCUS, 0);
2627 SetPower(POWER_HAPPINESS, 0);
2628 SetPower(POWER_RUNIC_POWER, 0);
2630 // update level to hunter/summon pet
2631 if (Pet* pet = GetPet())
2632 pet->SynchronizeLevelWithOwner();
2635 void Player::SendInitialSpells()
2637 time_t curTime = time(NULL);
2638 time_t infTime = curTime + infinityCooldownDelayCheck;
2640 uint16 spellCount = 0;
2642 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2643 data << uint8(0);
2645 size_t countPos = data.wpos();
2646 data << uint16(spellCount); // spell count placeholder
2648 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2650 if(itr->second->state == PLAYERSPELL_REMOVED)
2651 continue;
2653 if(!itr->second->active || itr->second->disabled)
2654 continue;
2656 data << uint32(itr->first);
2657 data << uint16(0); // it's not slot id
2659 spellCount +=1;
2662 data.put<uint16>(countPos,spellCount); // write real count value
2664 uint16 spellCooldowns = m_spellCooldowns.size();
2665 data << uint16(spellCooldowns);
2666 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2668 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2669 if(!sEntry)
2670 continue;
2672 data << uint32(itr->first);
2674 data << uint16(itr->second.itemid); // cast item id
2675 data << uint16(sEntry->Category); // spell category
2677 // send infinity cooldown in special format
2678 if(itr->second.end >= infTime)
2680 data << uint32(1); // cooldown
2681 data << uint32(0x80000000); // category cooldown
2682 continue;
2685 time_t cooldown = itr->second.end > curTime ? (itr->second.end-curTime)*IN_MILISECONDS : 0;
2687 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2689 data << uint32(0); // cooldown
2690 data << uint32(cooldown); // category cooldown
2692 else
2694 data << uint32(cooldown); // cooldown
2695 data << uint32(0); // category cooldown
2699 GetSession()->SendPacket(&data);
2701 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2704 void Player::RemoveMail(uint32 id)
2706 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2708 if ((*itr)->messageID == id)
2710 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2711 m_mail.erase(itr);
2712 return;
2717 void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2719 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2720 data << (uint32) mailId;
2721 data << (uint32) mailAction;
2722 data << (uint32) mailError;
2723 if ( mailError == MAIL_ERR_EQUIP_ERROR )
2724 data << (uint32) equipError;
2725 else if( mailAction == MAIL_ITEM_TAKEN )
2727 data << (uint32) item_guid; // item guid low?
2728 data << (uint32) item_count; // item count?
2730 GetSession()->SendPacket(&data);
2733 void Player::SendNewMail()
2735 // deliver undelivered mail
2736 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2737 data << (uint32) 0;
2738 GetSession()->SendPacket(&data);
2741 void Player::UpdateNextMailTimeAndUnreads()
2743 // calculate next delivery time (min. from non-delivered mails
2744 // and recalculate unReadMail
2745 time_t cTime = time(NULL);
2746 m_nextMailDelivereTime = 0;
2747 unReadMails = 0;
2748 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2750 if((*itr)->deliver_time > cTime)
2752 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2753 m_nextMailDelivereTime = (*itr)->deliver_time;
2755 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2756 ++unReadMails;
2760 void Player::AddNewMailDeliverTime(time_t deliver_time)
2762 if(deliver_time <= time(NULL)) // ready now
2764 ++unReadMails;
2765 SendNewMail();
2767 else // not ready and no have ready mails
2769 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2770 m_nextMailDelivereTime = deliver_time;
2774 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2776 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2777 if (!spellInfo)
2779 // do character spell book cleanup (all characters)
2780 if(!IsInWorld() && !learning) // spell load case
2782 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2783 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2785 else
2786 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2788 return false;
2791 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2793 // do character spell book cleanup (all characters)
2794 if(!IsInWorld() && !learning) // spell load case
2796 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2797 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2799 else
2800 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2802 return false;
2805 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2807 bool dependent_set = false;
2808 bool disabled_case = false;
2809 bool superceded_old = false;
2811 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2812 if (itr != m_spells.end())
2814 uint32 next_active_spell_id = 0;
2815 // fix activate state for non-stackable low rank (and find next spell for !active case)
2816 if(!SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2818 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2819 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2821 if(HasSpell(next_itr->second))
2823 // high rank already known so this must !active
2824 active = false;
2825 next_active_spell_id = next_itr->second;
2826 break;
2831 // not do anything if already known in expected state
2832 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2833 itr->second->dependent == dependent && itr->second->disabled == disabled)
2835 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2836 itr->second->state = PLAYERSPELL_UNCHANGED;
2838 return false;
2841 // dependent spell known as not dependent, overwrite state
2842 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2844 itr->second->dependent = dependent;
2845 if (itr->second->state != PLAYERSPELL_NEW)
2846 itr->second->state = PLAYERSPELL_CHANGED;
2847 dependent_set = true;
2850 // update active state for known spell
2851 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2853 itr->second->active = active;
2855 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2856 itr->second->state = PLAYERSPELL_UNCHANGED;
2857 else if(itr->second->state != PLAYERSPELL_NEW)
2858 itr->second->state = PLAYERSPELL_CHANGED;
2860 if(active)
2862 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2863 CastSpell (this,spell_id,true);
2865 else if(IsInWorld())
2867 if(next_active_spell_id)
2869 // update spell ranks in spellbook and action bar
2870 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2871 data << uint32(spell_id);
2872 data << uint32(next_active_spell_id);
2873 GetSession()->SendPacket( &data );
2875 else
2877 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2878 data << uint32(spell_id);
2879 GetSession()->SendPacket(&data);
2883 return active; // learn (show in spell book if active now)
2886 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2888 if(itr->second->state != PLAYERSPELL_NEW)
2889 itr->second->state = PLAYERSPELL_CHANGED;
2890 itr->second->disabled = disabled;
2892 if(disabled)
2893 return false;
2895 disabled_case = true;
2897 else switch(itr->second->state)
2899 case PLAYERSPELL_UNCHANGED: // known saved spell
2900 return false;
2901 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2903 delete itr->second;
2904 m_spells.erase(itr);
2905 state = PLAYERSPELL_CHANGED;
2906 break; // need re-add
2908 default: // known not saved yet spell (new or modified)
2910 // can be in case spell loading but learned at some previous spell loading
2911 if(!IsInWorld() && !learning && !dependent_set)
2912 itr->second->state = PLAYERSPELL_UNCHANGED;
2914 return false;
2919 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2921 // talent: unlearn all other talent ranks (high and low)
2922 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2924 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2926 for(int i=0; i < MAX_TALENT_RANK; ++i)
2928 // skip learning spell and no rank spell case
2929 uint32 rankSpellId = talentInfo->RankID[i];
2930 if(!rankSpellId || rankSpellId==spell_id)
2931 continue;
2933 removeSpell(rankSpellId,false,false);
2937 // non talent spell: learn low ranks (recursive call)
2938 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2940 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
2941 addSpell(prev_spell,active,true,true,disabled);
2942 else // at normal learning
2943 learnSpell(prev_spell,true);
2946 PlayerSpell *newspell = new PlayerSpell;
2947 newspell->state = state;
2948 newspell->active = active;
2949 newspell->dependent = dependent;
2950 newspell->disabled = disabled;
2952 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2953 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2955 for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
2957 if(itr2->second->state == PLAYERSPELL_REMOVED) continue;
2958 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
2959 if(!i_spellInfo) continue;
2961 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
2963 if(itr2->second->active)
2965 if(spellmgr.IsHighRankOfSpell(spell_id,itr2->first))
2967 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2969 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2970 data << uint32(itr2->first);
2971 data << uint32(spell_id);
2972 GetSession()->SendPacket( &data );
2975 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2976 itr2->second->active = false;
2977 if(itr2->second->state != PLAYERSPELL_NEW)
2978 itr2->second->state = PLAYERSPELL_CHANGED;
2979 superceded_old = true; // new spell replace old in action bars and spell book.
2981 else if(spellmgr.IsHighRankOfSpell(itr2->first,spell_id))
2983 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2985 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2986 data << uint32(spell_id);
2987 data << uint32(itr2->first);
2988 GetSession()->SendPacket( &data );
2991 // mark new spell as disable (not learned yet for client and will not learned)
2992 newspell->active = false;
2993 if(newspell->state != PLAYERSPELL_NEW)
2994 newspell->state = PLAYERSPELL_CHANGED;
3001 m_spells[spell_id] = newspell;
3003 // return false if spell disabled
3004 if (newspell->disabled)
3005 return false;
3008 uint32 talentCost = GetTalentSpellCost(spell_id);
3010 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
3011 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
3012 if (talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL))
3014 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
3015 CastSpell(this, spell_id, true);
3017 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
3018 else if (IsPassiveSpell(spell_id))
3020 if (IsNeedCastPassiveSpellAtLearn(spellInfo))
3021 CastSpell(this, spell_id, true);
3023 else if (IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP))
3025 CastSpell(this, spell_id, true);
3026 return false;
3029 // update used talent points count
3030 m_usedTalentCount += talentCost;
3032 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
3033 if (uint32 freeProfs = GetFreePrimaryProfessionPoints())
3035 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3036 SetFreePrimaryProfessions(freeProfs-1);
3039 // add dependent skills
3040 uint16 maxskill = GetMaxSkillValueForLevel();
3042 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
3044 SkillLineAbilityMapBounds skill_bounds = spellmgr.GetSkillLineAbilityMapBounds(spell_id);
3046 if (spellLearnSkill)
3048 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
3049 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
3051 if (skill_value < spellLearnSkill->value)
3052 skill_value = spellLearnSkill->value;
3054 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
3056 if (skill_max_value < new_skill_max_value)
3057 skill_max_value = new_skill_max_value;
3059 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
3061 else
3063 // not ranked skills
3064 for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
3066 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3067 if (!pSkill)
3068 continue;
3070 if (HasSkill(pSkill->id))
3071 continue;
3073 if (_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3074 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3075 ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
3077 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
3079 case SKILL_RANGE_LANGUAGE:
3080 SetSkill(pSkill->id, 300, 300 );
3081 break;
3082 case SKILL_RANGE_LEVEL:
3083 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
3084 break;
3085 case SKILL_RANGE_MONO:
3086 SetSkill(pSkill->id, 1, 1 );
3087 break;
3088 default:
3089 break;
3095 // learn dependent spells
3096 SpellLearnSpellMapBounds spell_bounds = spellmgr.GetSpellLearnSpellMapBounds(spell_id);
3098 for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
3100 if (!itr2->second.autoLearned)
3102 if (!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
3103 addSpell(itr2->second.spell,itr2->second.active,true,true,false);
3104 else // at normal learning
3105 learnSpell(itr2->second.spell,true);
3109 if (!GetSession()->PlayerLoading())
3111 // not ranked skills
3112 for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
3114 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
3115 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
3118 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
3121 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
3122 return active && !disabled && !superceded_old;
3125 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
3127 // note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell
3128 // talent dependent passives activated at form apply have proper stance data
3129 bool need_cast = (!spellInfo->Stances || (m_form != 0 && (spellInfo->Stances & (1<<(m_form-1)))));
3131 //Check CasterAuraStates
3132 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
3135 void Player::learnSpell(uint32 spell_id, bool dependent)
3137 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3139 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
3140 bool active = disabled ? itr->second->active : true;
3142 bool learning = addSpell(spell_id,active,true,dependent,false);
3144 // learn all disabled higher ranks (recursive)
3145 if(disabled)
3147 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3148 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
3150 PlayerSpellMap::iterator iter = m_spells.find(i->second);
3151 if (iter != m_spells.end() && iter->second->disabled)
3152 learnSpell(i->second,false);
3156 // prevent duplicated entires in spell book, also not send if not in world (loading)
3157 if(!learning || !IsInWorld ())
3158 return;
3160 WorldPacket data(SMSG_LEARNED_SPELL, 4);
3161 data << uint32(spell_id);
3162 GetSession()->SendPacket(&data);
3165 void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank)
3167 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3168 if (itr == m_spells.end())
3169 return;
3171 if (itr->second->state == PLAYERSPELL_REMOVED || (disabled && itr->second->disabled))
3172 return;
3174 // unlearn non talent higher ranks (recursive)
3175 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3176 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
3177 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
3178 removeSpell(itr2->second,disabled,false);
3180 // re-search, it can be corrupted in prev loop
3181 itr = m_spells.find(spell_id);
3182 if (itr == m_spells.end())
3183 return; // already unleared
3185 bool cur_active = itr->second->active;
3186 bool cur_dependent = itr->second->dependent;
3188 if (disabled)
3190 itr->second->disabled = disabled;
3191 if(itr->second->state != PLAYERSPELL_NEW)
3192 itr->second->state = PLAYERSPELL_CHANGED;
3194 else
3196 if(itr->second->state == PLAYERSPELL_NEW)
3198 delete itr->second;
3199 m_spells.erase(itr);
3201 else
3202 itr->second->state = PLAYERSPELL_REMOVED;
3205 RemoveAurasDueToSpell(spell_id);
3207 // remove pet auras
3208 for(int i = 0; i < 3; ++i)
3209 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id, i))
3210 RemovePetAura(petSpell);
3212 // free talent points
3213 uint32 talentCosts = GetTalentSpellCost(spell_id);
3214 if(talentCosts > 0)
3216 if(talentCosts < m_usedTalentCount)
3217 m_usedTalentCount -= talentCosts;
3218 else
3219 m_usedTalentCount = 0;
3222 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3223 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3225 uint32 freeProfs = GetFreePrimaryProfessionPoints()+1;
3226 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
3227 SetFreePrimaryProfessions(freeProfs);
3230 // remove dependent skill
3231 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
3232 if(spellLearnSkill)
3234 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
3235 if(!prev_spell) // first rank, remove skill
3236 SetSkill(spellLearnSkill->skill,0,0);
3237 else
3239 // search prev. skill setting by spell ranks chain
3240 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
3241 while(!prevSkill && prev_spell)
3243 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
3244 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
3247 if (!prevSkill) // not found prev skill setting, remove skill
3248 SetSkill(spellLearnSkill->skill,0,0);
3249 else // set to prev. skill setting values
3251 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3252 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3254 if (skill_value > prevSkill->value)
3255 skill_value = prevSkill->value;
3257 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3259 if (skill_max_value > new_skill_max_value)
3260 skill_max_value = new_skill_max_value;
3262 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3267 else
3269 // not ranked skills
3270 SkillLineAbilityMapBounds bounds = spellmgr.GetSkillLineAbilityMapBounds(spell_id);
3272 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
3274 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3275 if (!pSkill)
3276 continue;
3278 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL &&
3279 pSkill->categoryId != SKILL_CATEGORY_CLASS ||// not unlearn class skills (spellbook/talent pages)
3280 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3281 ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
3283 // not reset skills for professions and racial abilities
3284 if ((pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3285 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0))
3286 continue;
3288 SetSkill(pSkill->id, 0, 0 );
3293 // remove dependent spells
3294 SpellLearnSpellMapBounds spell_bounds = spellmgr.GetSpellLearnSpellMapBounds(spell_id);
3296 for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
3297 removeSpell(itr2->second.spell, disabled);
3299 // activate lesser rank in spellbook/action bar, and cast it if need
3300 bool prev_activate = false;
3302 if (uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id))
3304 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3306 // if talent then lesser rank also talent and need learn
3307 if (talentCosts)
3309 if(learn_low_rank)
3310 learnSpell (prev_id,false);
3312 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3313 else if (cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
3315 // need manually update dependence state (learn spell ignore like attempts)
3316 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3317 if (prev_itr != m_spells.end())
3319 if (prev_itr->second->dependent != cur_dependent)
3321 prev_itr->second->dependent = cur_dependent;
3322 if (prev_itr->second->state != PLAYERSPELL_NEW)
3323 prev_itr->second->state = PLAYERSPELL_CHANGED;
3326 // now re-learn if need re-activate
3327 if (cur_active && !prev_itr->second->active && learn_low_rank)
3329 if (addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3331 // downgrade spell ranks in spellbook and action bar
3332 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3333 data << uint32(spell_id);
3334 data << uint32(prev_id);
3335 GetSession()->SendPacket( &data );
3336 prev_activate = true;
3343 // remove from spell book if not replaced by lesser rank
3344 if(!prev_activate)
3346 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3347 data << uint32(spell_id);
3348 GetSession()->SendPacket(&data);
3352 void Player::RemoveSpellCooldown( uint32 spell_id, bool update /* = false */ )
3354 m_spellCooldowns.erase(spell_id);
3356 if(update)
3357 SendClearCooldown(spell_id, this);
3360 void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */)
3362 SpellCategoryStore::const_iterator ct = sSpellCategoryStore.find(cat);
3363 if (ct == sSpellCategoryStore.end())
3364 return;
3366 const SpellCategorySet& ct_set = ct->second;
3367 for (SpellCooldowns::const_iterator i = m_spellCooldowns.begin(); i != m_spellCooldowns.end();)
3369 if (ct_set.find(i->first) != ct_set.end())
3370 RemoveSpellCooldown((i++)->first, update);
3371 else
3372 ++i;
3376 void Player::RemoveArenaSpellCooldowns()
3378 // remove cooldowns on spells that has < 15 min CD
3379 SpellCooldowns::iterator itr, next;
3380 // iterate spell cooldowns
3381 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3383 next = itr;
3384 ++next;
3385 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3386 // check if spellentry is present and if the cooldown is less than 15 mins
3387 if( entry &&
3388 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3389 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3391 // remove & notify
3392 RemoveSpellCooldown(itr->first, true);
3397 void Player::RemoveAllSpellCooldown()
3399 if(!m_spellCooldowns.empty())
3401 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3402 SendClearCooldown(itr->first, this);
3404 m_spellCooldowns.clear();
3408 void Player::_LoadSpellCooldowns(QueryResult *result)
3410 // some cooldowns can be already set at aura loading...
3412 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3414 if(result)
3416 time_t curTime = time(NULL);
3420 Field *fields = result->Fetch();
3422 uint32 spell_id = fields[0].GetUInt32();
3423 uint32 item_id = fields[1].GetUInt32();
3424 time_t db_time = (time_t)fields[2].GetUInt64();
3426 if(!sSpellStore.LookupEntry(spell_id))
3428 sLog.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3429 continue;
3432 // skip outdated cooldown
3433 if(db_time <= curTime)
3434 continue;
3436 AddSpellCooldown(spell_id, item_id, db_time);
3438 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3440 while( result->NextRow() );
3442 delete result;
3446 void Player::_SaveSpellCooldowns()
3448 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3450 time_t curTime = time(NULL);
3451 time_t infTime = curTime + infinityCooldownDelayCheck;
3453 // remove outdated and save active
3454 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3456 if(itr->second.end <= curTime)
3457 m_spellCooldowns.erase(itr++);
3458 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3460 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));
3461 ++itr;
3463 else
3464 ++itr;
3468 uint32 Player::resetTalentsCost() const
3470 // The first time reset costs 1 gold
3471 if(m_resetTalentsCost < 1*GOLD)
3472 return 1*GOLD;
3473 // then 5 gold
3474 else if(m_resetTalentsCost < 5*GOLD)
3475 return 5*GOLD;
3476 // After that it increases in increments of 5 gold
3477 else if(m_resetTalentsCost < 10*GOLD)
3478 return 10*GOLD;
3479 else
3481 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3482 if(months > 0)
3484 // This cost will be reduced by a rate of 5 gold per month
3485 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3486 // to a minimum of 10 gold.
3487 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3489 else
3491 // After that it increases in increments of 5 gold
3492 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3493 // until it hits a cap of 50 gold.
3494 if(new_cost > 50*GOLD)
3495 new_cost = 50*GOLD;
3496 return new_cost;
3501 bool Player::resetTalents(bool no_cost)
3503 // not need after this call
3504 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3505 RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS,true);
3507 uint32 talentPointsForLevel = CalculateTalentsPoints();
3509 if (m_usedTalentCount == 0)
3511 SetFreeTalentPoints(talentPointsForLevel);
3512 return false;
3515 uint32 cost = 0;
3517 if(!no_cost)
3519 cost = resetTalentsCost();
3521 if (GetMoney() < cost)
3523 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3524 return false;
3528 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
3530 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3532 if (!talentInfo) continue;
3534 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3536 if(!talentTabInfo)
3537 continue;
3539 // unlearn only talents for character class
3540 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3541 // to prevent unexpected lost normal learned spell skip another class talents
3542 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3543 continue;
3545 for (int j = 0; j < MAX_TALENT_RANK; ++j)
3547 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3549 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3551 ++itr;
3552 continue;
3555 // remove learned spells (all ranks)
3556 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3558 // unlearn if first rank is talent or learned by talent
3559 if (itrFirstId == talentInfo->RankID[j])
3561 removeSpell(itr->first,!IsPassiveSpell(itr->first),false);
3562 itr = GetSpellMap().begin();
3563 continue;
3565 else if (spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3567 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3568 itr = GetSpellMap().begin();
3569 continue;
3571 else
3572 ++itr;
3577 SetFreeTalentPoints(talentPointsForLevel);
3579 if(!no_cost)
3581 ModifyMoney(-(int32)cost);
3582 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3583 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
3585 m_resetTalentsCost = cost;
3586 m_resetTalentsTime = time(NULL);
3589 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3590 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3591 /* when prev line will dropped use next line
3592 if(Pet* pet = GetPet())
3594 if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
3595 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3600 if(m_canTitanGrip)
3602 m_canTitanGrip = false;
3603 if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET))
3604 AutoUnequipOffhandIfNeed();
3607 return true;
3610 Mail* Player::GetMail(uint32 id)
3612 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3614 if ((*itr)->messageID == id)
3616 return (*itr);
3619 return NULL;
3622 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3624 if(target == this)
3626 Object::_SetCreateBits(updateMask, target);
3628 else
3630 for(uint16 index = 0; index < m_valuesCount; index++)
3632 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3633 updateMask->SetBit(index);
3638 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3640 if(target == this)
3642 Object::_SetUpdateBits(updateMask, target);
3644 else
3646 Object::_SetUpdateBits(updateMask, target);
3647 *updateMask &= updateVisualBits;
3651 void Player::InitVisibleBits()
3653 updateVisualBits.SetCount(PLAYER_END);
3655 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3656 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3657 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3658 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3659 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3660 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3661 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3662 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3663 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3664 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3665 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3666 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3667 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3668 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3669 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3670 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3671 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3672 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3673 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3674 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3675 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3676 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3677 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3678 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3679 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3680 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3681 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3682 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3683 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3684 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3685 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3686 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3687 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3688 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3689 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3690 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3691 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3692 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3693 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3694 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3695 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3696 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3697 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3698 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3699 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3700 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3701 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3702 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3703 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3704 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3705 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3706 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3707 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3708 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3709 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3711 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3712 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3713 updateVisualBits.SetBit(PLAYER_FLAGS);
3714 updateVisualBits.SetBit(PLAYER_GUILDID);
3715 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3716 updateVisualBits.SetBit(PLAYER_BYTES);
3717 updateVisualBits.SetBit(PLAYER_BYTES_2);
3718 updateVisualBits.SetBit(PLAYER_BYTES_3);
3719 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3720 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3722 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3723 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3724 updateVisualBits.SetBit(i);
3726 // Players visible items are not inventory stuff
3727 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3729 uint32 offset = i * 2;
3731 // item entry
3732 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset);
3733 // enchant
3734 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset);
3737 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3740 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3742 for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
3744 if(m_items[i] == NULL)
3745 continue;
3747 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3750 if(target == this)
3752 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3754 if(m_items[i] == NULL)
3755 continue;
3757 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3759 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3761 if(m_items[i] == NULL)
3762 continue;
3764 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3768 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3771 void Player::DestroyForPlayer( Player *target, bool anim ) const
3773 Unit::DestroyForPlayer( target, anim );
3775 for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
3777 if(m_items[i] == NULL)
3778 continue;
3780 m_items[i]->DestroyForPlayer( target );
3783 if(target == this)
3785 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3787 if(m_items[i] == NULL)
3788 continue;
3790 m_items[i]->DestroyForPlayer( target );
3792 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3794 if(m_items[i] == NULL)
3795 continue;
3797 m_items[i]->DestroyForPlayer( target );
3802 bool Player::HasSpell(uint32 spell) const
3804 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3805 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3806 !itr->second->disabled);
3809 bool Player::HasActiveSpell(uint32 spell) const
3811 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3812 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3813 itr->second->active && !itr->second->disabled);
3816 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3818 if (!trainer_spell)
3819 return TRAINER_SPELL_RED;
3821 if (!trainer_spell->learnedSpell)
3822 return TRAINER_SPELL_RED;
3824 // known spell
3825 if(HasSpell(trainer_spell->learnedSpell))
3826 return TRAINER_SPELL_GRAY;
3828 // check race/class requirement
3829 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3830 return TRAINER_SPELL_RED;
3832 // check level requirement
3833 if(getLevel() < trainer_spell->reqLevel)
3834 return TRAINER_SPELL_RED;
3836 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learnedSpell))
3838 // check prev.rank requirement
3839 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3840 return TRAINER_SPELL_RED;
3842 // check additional spell requirement
3843 if(spell_chain->req && !HasSpell(spell_chain->req))
3844 return TRAINER_SPELL_RED;
3847 // check skill requirement
3848 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3849 return TRAINER_SPELL_RED;
3851 // exist, already checked at loading
3852 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3854 // secondary prof. or not prof. spell
3855 uint32 skill = spell->EffectMiscValue[1];
3857 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3858 return TRAINER_SPELL_GREEN;
3860 // check primary prof. limit
3861 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProfessionPoints() == 0)
3862 return TRAINER_SPELL_GREEN_DISABLED;
3864 return TRAINER_SPELL_GREEN;
3867 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3869 uint32 guid = GUID_LOPART(playerguid);
3871 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3872 // bones will be deleted by corpse/bones deleting thread shortly
3873 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3875 // remove from guild
3876 uint32 guildId = GetGuildIdFromDB(playerguid);
3877 if(guildId != 0)
3879 Guild* guild = objmgr.GetGuildById(guildId);
3880 if(guild)
3881 guild->DelMember(guid);
3884 // remove from arena teams
3885 LeaveAllArenaTeams(playerguid);
3887 // the player was uninvited already on logout so just remove from group
3888 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3889 if(resultGroup)
3891 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3892 delete resultGroup;
3893 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3894 if(group)
3896 RemoveFromGroup(group, playerguid);
3900 // remove signs from petitions (also remove petitions if owner);
3901 RemovePetitionsAndSigns(playerguid, 10);
3903 // return back all mails with COD and Item 0 1 2 3 4 5 6
3904 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);
3905 if(resultMail)
3909 Field *fields = resultMail->Fetch();
3911 uint32 mail_id = fields[0].GetUInt32();
3912 uint16 mailTemplateId= fields[1].GetUInt16();
3913 uint32 sender = fields[2].GetUInt32();
3914 std::string subject = fields[3].GetCppString();
3915 uint32 itemTextId = fields[4].GetUInt32();
3916 uint32 money = fields[5].GetUInt32();
3917 bool has_items = fields[6].GetBool();
3919 //we can return mail now
3920 //so firstly delete the old one
3921 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3923 MailItemsInfo mi;
3924 if(has_items)
3926 // data needs to be at first place for Item::LoadFromDB
3927 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);
3928 if(resultItems)
3932 Field *fields2 = resultItems->Fetch();
3934 uint32 item_guidlow = fields2[1].GetUInt32();
3935 uint32 item_template = fields2[2].GetUInt32();
3937 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3938 if(!itemProto)
3940 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3941 continue;
3944 Item *pItem = NewItemOrBag(itemProto);
3945 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3947 pItem->FSetState(ITEM_REMOVED);
3948 pItem->SaveToDB(); // it also deletes item object !
3949 continue;
3952 mi.AddItem(item_guidlow, item_template, pItem);
3954 while (resultItems->NextRow());
3956 delete resultItems;
3960 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3962 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3964 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3966 while (resultMail->NextRow());
3968 delete resultMail;
3971 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3972 // Get guids of character's pets, will deleted in transaction
3973 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3975 // NOW we can finally clear other DB data related to character
3976 CharacterDatabase.BeginTransaction();
3977 if (resultPets)
3981 Field *fields3 = resultPets->Fetch();
3982 uint32 petguidlow = fields3[0].GetUInt32();
3983 Pet::DeleteFromDB(petguidlow);
3984 } while (resultPets->NextRow());
3985 delete resultPets;
3988 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3989 CharacterDatabase.PExecute("DELETE FROM character_account_data WHERE guid = '%u'",guid);
3990 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3991 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3992 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3993 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3994 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3995 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3996 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3997 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3998 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3999 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
4000 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
4001 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
4002 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
4003 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
4004 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
4005 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
4006 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
4007 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
4008 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
4009 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
4010 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
4011 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid);
4012 CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid1 = '%u'",guid);
4013 CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid2 = '%u'",guid);
4014 CharacterDatabase.PExecute("DELETE FROM guild_bank_eventlog WHERE PlayerGuid = '%u'",guid);
4015 CharacterDatabase.CommitTransaction();
4017 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
4018 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
4021 void Player::SetMovement(PlayerMovementType pType)
4023 WorldPacket data;
4024 switch(pType)
4026 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
4027 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
4028 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
4029 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
4030 default:
4031 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
4032 return;
4034 data.append(GetPackGUID());
4035 data << uint32(0);
4036 GetSession()->SendPacket( &data );
4039 /* Preconditions:
4040 - a resurrectable corpse must not be loaded for the player (only bones)
4041 - the player must be in world
4043 void Player::BuildPlayerRepop()
4045 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
4046 data.append(GetPackGUID());
4047 GetSession()->SendPacket(&data);
4049 if(getRace() == RACE_NIGHTELF)
4050 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)
4051 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
4053 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
4054 // there must be SMSG.STOP_MIRROR_TIMER
4055 // there we must send 888 opcode
4057 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
4058 if(GetCorpse())
4060 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
4061 assert(false);
4064 // create a corpse and place it at the player's location
4065 CreateCorpse();
4066 Corpse *corpse = GetCorpse();
4067 if(!corpse)
4069 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
4070 return;
4072 GetMap()->Add(corpse);
4074 // convert player body to ghost
4075 SetHealth( 1 );
4077 SetMovement(MOVE_WATER_WALK);
4078 if(!GetSession()->isLogingOut())
4079 SetMovement(MOVE_UNROOT);
4081 // BG - remove insignia related
4082 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
4084 SendCorpseReclaimDelay();
4086 // to prevent cheating
4087 corpse->ResetGhostTime();
4089 StopMirrorTimers(); //disable timers(bars)
4091 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
4093 // set and clear other
4094 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
4097 void Player::SendDelayResponse(const uint32 ml_seconds)
4099 //FIXME: is this delay time arg really need? 50msec by default in code
4100 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
4101 data << (uint32)time(NULL);
4102 data << (uint32)0;
4103 GetSession()->SendPacket( &data );
4106 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
4108 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
4109 data << uint32(-1);
4110 data << float(0);
4111 data << float(0);
4112 data << float(0);
4113 GetSession()->SendPacket(&data);
4115 // speed change, land walk
4117 // remove death flag + set aura
4118 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
4119 if(getRace() == RACE_NIGHTELF)
4120 RemoveAurasDueToSpell(20584); // speed bonuses
4121 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
4123 setDeathState(ALIVE);
4125 SetMovement(MOVE_LAND_WALK);
4126 SetMovement(MOVE_UNROOT);
4128 m_deathTimer = 0;
4130 // set health/powers (0- will be set in caller)
4131 if(restore_percent>0.0f)
4133 SetHealth(uint32(GetMaxHealth()*restore_percent));
4134 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
4135 SetPower(POWER_RAGE, 0);
4136 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
4139 // trigger update zone for alive state zone updates
4140 uint32 newzone, newarea;
4141 GetZoneAndAreaId(newzone,newarea);
4142 UpdateZone(newzone,newarea);
4144 // update visibility
4145 ObjectAccessor::UpdateVisibilityForPlayer(this);
4147 if(!applySickness)
4148 return;
4150 //Characters from level 1-10 are not affected by resurrection sickness.
4151 //Characters from level 11-19 will suffer from one minute of sickness
4152 //for each level they are above 10.
4153 //Characters level 20 and up suffer from ten minutes of sickness.
4154 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
4156 if(int32(getLevel()) >= startLevel)
4158 // set resurrection sickness
4159 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
4161 // not full duration
4162 if(int32(getLevel()) < startLevel+9)
4164 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
4166 for(int i =0; i < 3; ++i)
4168 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
4170 Aur->SetAuraDuration(delta*IN_MILISECONDS);
4171 Aur->SendAuraUpdate(false);
4178 void Player::KillPlayer()
4180 SetMovement(MOVE_ROOT);
4182 StopMirrorTimers(); //disable timers(bars)
4184 setDeathState(CORPSE);
4185 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4187 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
4188 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
4190 // 6 minutes until repop at graveyard
4191 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
4193 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4195 // don't create corpse at this moment, player might be falling
4197 // update visibility
4198 ObjectAccessor::UpdateObjectVisibility(this);
4201 void Player::CreateCorpse()
4203 // prevent existence 2 corpse for player
4204 SpawnCorpseBones();
4206 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
4208 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
4209 SetPvPDeath(false);
4211 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
4213 delete corpse;
4214 return;
4217 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
4218 _pb = GetUInt32Value(PLAYER_BYTES);
4219 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
4221 uint8 race = (uint8)(_uf);
4222 uint8 skin = (uint8)(_pb);
4223 uint8 face = (uint8)(_pb >> 8);
4224 uint8 hairstyle = (uint8)(_pb >> 16);
4225 uint8 haircolor = (uint8)(_pb >> 24);
4226 uint8 facialhair = (uint8)(_pb2);
4228 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
4229 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
4231 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
4232 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
4234 uint32 flags = CORPSE_FLAG_UNK2;
4235 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
4236 flags |= CORPSE_FLAG_HIDE_HELM;
4237 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
4238 flags |= CORPSE_FLAG_HIDE_CLOAK;
4239 if(InBattleGround() && !InArena())
4240 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
4241 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4243 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4245 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4247 uint32 iDisplayID;
4248 uint16 iIventoryType;
4249 uint32 _cfi;
4250 for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
4252 if(m_items[i])
4254 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4255 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
4257 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
4258 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
4262 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4263 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4264 assert(entry);
4265 if(entry->map_type != MAP_BATTLEGROUND)
4266 corpse->SaveToDB();
4268 // register for player, but not show
4269 ObjectAccessor::Instance().AddCorpse(corpse);
4272 void Player::SpawnCorpseBones()
4274 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4275 SaveToDB(); // prevent loading as ghost without corpse
4278 Corpse* Player::GetCorpse() const
4280 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4283 void Player::DurabilityLossAll(double percent, bool inventory)
4285 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4286 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4287 DurabilityLoss(pItem,percent);
4289 if(inventory)
4291 // bags not have durability
4292 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4294 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4295 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4296 DurabilityLoss(pItem,percent);
4298 // keys not have durability
4299 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4301 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4302 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4303 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4304 if(Item* pItem = GetItemByPos( i, j ))
4305 DurabilityLoss(pItem,percent);
4309 void Player::DurabilityLoss(Item* item, double percent)
4311 if(!item )
4312 return;
4314 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4316 if(!pMaxDurability)
4317 return;
4319 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4321 if(pDurabilityLoss < 1 )
4322 pDurabilityLoss = 1;
4324 DurabilityPointsLoss(item,pDurabilityLoss);
4327 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4329 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4330 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4331 DurabilityPointsLoss(pItem,points);
4333 if(inventory)
4335 // bags not have durability
4336 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4338 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4339 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4340 DurabilityPointsLoss(pItem,points);
4342 // keys not have durability
4343 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4345 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4346 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4347 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4348 if(Item* pItem = GetItemByPos( i, j ))
4349 DurabilityPointsLoss(pItem,points);
4353 void Player::DurabilityPointsLoss(Item* item, int32 points)
4355 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4356 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4357 int32 pNewDurability = pOldDurability - points;
4359 if (pNewDurability < 0)
4360 pNewDurability = 0;
4361 else if (pNewDurability > pMaxDurability)
4362 pNewDurability = pMaxDurability;
4364 if (pOldDurability != pNewDurability)
4366 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4367 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4368 _ApplyItemMods(item,item->GetSlot(), false);
4370 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4372 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4373 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4374 _ApplyItemMods(item,item->GetSlot(), true);
4376 item->SetState(ITEM_CHANGED, this);
4380 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4382 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4383 DurabilityPointsLoss(pItem,1);
4386 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4388 uint32 TotalCost = 0;
4389 // equipped, backpack, bags itself
4390 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4391 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4393 // bank, buyback and keys not repaired
4395 // items in inventory bags
4396 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
4397 for(int i = 0; i < MAX_BAG_SIZE; ++i)
4398 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4399 return TotalCost;
4402 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4404 Item* item = GetItemByPos(pos);
4406 uint32 TotalCost = 0;
4407 if(!item)
4408 return TotalCost;
4410 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4411 if(!maxDurability)
4412 return TotalCost;
4414 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4416 if(cost)
4418 uint32 LostDurability = maxDurability - curDurability;
4419 if(LostDurability>0)
4421 ItemPrototype const *ditemProto = item->GetProto();
4423 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4424 if(!dcost)
4426 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4427 return TotalCost;
4430 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4431 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4432 if(!dQualitymodEntry)
4434 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4435 return TotalCost;
4438 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4439 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4441 costs = uint32(costs * discountMod);
4443 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4444 costs = 1;
4446 if (guildBank)
4448 if (GetGuildId()==0)
4450 DEBUG_LOG("You are not member of a guild");
4451 return TotalCost;
4454 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4455 if (!pGuild)
4456 return TotalCost;
4458 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4460 DEBUG_LOG("You do not have rights to withdraw for repairs");
4461 return TotalCost;
4464 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4466 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4467 return TotalCost;
4470 if (pGuild->GetGuildBankMoney() < costs)
4472 DEBUG_LOG("There is not enough money in bank");
4473 return TotalCost;
4476 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4477 TotalCost = costs;
4479 else if (GetMoney() < costs)
4481 DEBUG_LOG("You do not have enough money");
4482 return TotalCost;
4484 else
4485 ModifyMoney( -int32(costs) );
4489 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4490 item->SetState(ITEM_CHANGED, this);
4492 // reapply mods for total broken and repaired item if equipped
4493 if(IsEquipmentPos(pos) && !curDurability)
4494 _ApplyItemMods(item,pos & 255, true);
4495 return TotalCost;
4498 void Player::RepopAtGraveyard()
4500 // note: this can be called also when the player is alive
4501 // for example from WorldSession::HandleMovementOpcodes
4503 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4505 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4506 if ((!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY) || GetTransport())
4508 ResurrectPlayer(0.5f);
4509 SpawnCorpseBones();
4512 WorldSafeLocsEntry const *ClosestGrave = NULL;
4514 // Special handle for battleground maps
4515 if( BattleGround *bg = GetBattleGround() )
4516 ClosestGrave = bg->GetClosestGraveYard(this);
4517 else
4518 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4520 // stop countdown until repop
4521 m_deathTimer = 0;
4523 // if no grave found, stay at the current location
4524 // and don't show spirit healer location
4525 if(ClosestGrave)
4527 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4528 if(isDead()) // not send if alive, because it used in TeleportTo()
4530 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4531 data << ClosestGrave->map_id;
4532 data << ClosestGrave->x;
4533 data << ClosestGrave->y;
4534 data << ClosestGrave->z;
4535 GetSession()->SendPacket(&data);
4540 void Player::JoinedChannel(Channel *c)
4542 m_channels.push_back(c);
4545 void Player::LeftChannel(Channel *c)
4547 m_channels.remove(c);
4550 void Player::CleanupChannels()
4552 while(!m_channels.empty())
4554 Channel* ch = *m_channels.begin();
4555 m_channels.erase(m_channels.begin()); // remove from player's channel list
4556 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4557 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4558 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4561 sLog.outDebug("Player: channels cleaned up!");
4564 void Player::UpdateLocalChannels(uint32 newZone )
4566 if(m_channels.empty())
4567 return;
4569 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4570 if(!current_zone)
4571 return;
4573 ChannelMgr* cMgr = channelMgr(GetTeam());
4574 if(!cMgr)
4575 return;
4577 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4579 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4581 next = i; ++next;
4583 // skip non built-in channels
4584 if(!(*i)->IsConstant())
4585 continue;
4587 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4588 if(!ch)
4589 continue;
4591 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4592 continue;
4594 // new channel
4595 char new_channel_name_buf[100];
4596 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4597 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4599 if((*i)!=new_channel)
4601 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4603 // leave old channel
4604 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4605 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4606 LeftChannel(*i); // remove from player's channel list
4607 cMgr->LeftChannel(name); // delete if empty
4610 sLog.outDebug("Player: channels cleaned up!");
4613 void Player::LeaveLFGChannel()
4615 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4617 if((*i)->IsLFG())
4619 (*i)->Leave(GetGUID());
4620 break;
4625 void Player::UpdateDefense()
4627 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4629 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4631 // update dependent from defense skill part
4632 UpdateDefenseBonusesMod();
4636 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4638 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4640 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4641 return;
4644 float val = 1.0f;
4646 switch(modType)
4648 case FLAT_MOD:
4649 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4650 break;
4651 case PCT_MOD:
4652 if(amount <= -100.0f)
4653 amount = -200.0f;
4655 val = (100.0f + amount) / 100.0f;
4656 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4657 break;
4660 if(!CanModifyStats())
4661 return;
4663 switch(modGroup)
4665 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4666 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4667 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4668 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4669 default: break;
4673 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4675 if(modGroup >= BASEMOD_END || modType > MOD_END)
4677 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4678 return 0.0f;
4681 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4682 return 0.0f;
4684 return m_auraBaseMod[modGroup][modType];
4687 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4689 if(modGroup >= BASEMOD_END)
4691 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4692 return 0.0f;
4695 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4696 return 0.0f;
4698 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4701 uint32 Player::GetShieldBlockValue() const
4703 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4705 value = (value < 0) ? 0 : value;
4707 return uint32(value);
4710 float Player::GetMeleeCritFromAgility()
4712 uint32 level = getLevel();
4713 uint32 pclass = getClass();
4715 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4717 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4718 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4719 if (critBase==NULL || critRatio==NULL)
4720 return 0.0f;
4722 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4723 return crit*100.0f;
4726 float Player::GetDodgeFromAgility()
4728 // Table for base dodge values
4729 float dodge_base[MAX_CLASSES] = {
4730 0.0075f, // Warrior
4731 0.00652f, // Paladin
4732 -0.0545f, // Hunter
4733 -0.0059f, // Rogue
4734 0.03183f, // Priest
4735 0.0114f, // DK
4736 0.0167f, // Shaman
4737 0.034575f, // Mage
4738 0.02011f, // Warlock
4739 0.0f, // ??
4740 -0.0187f // Druid
4742 // Crit/agility to dodge/agility coefficient multipliers
4743 float crit_to_dodge[MAX_CLASSES] = {
4744 1.1f, // Warrior
4745 1.0f, // Paladin
4746 1.6f, // Hunter
4747 2.0f, // Rogue
4748 1.0f, // Priest
4749 1.0f, // DK?
4750 1.0f, // Shaman
4751 1.0f, // Mage
4752 1.0f, // Warlock
4753 0.0f, // ??
4754 1.7f // Druid
4757 uint32 level = getLevel();
4758 uint32 pclass = getClass();
4760 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4762 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4763 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4764 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4765 return 0.0f;
4767 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4768 return dodge*100.0f;
4771 float Player::GetSpellCritFromIntellect()
4773 uint32 level = getLevel();
4774 uint32 pclass = getClass();
4776 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4778 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4779 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4780 if (critBase==NULL || critRatio==NULL)
4781 return 0.0f;
4783 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4784 return crit*100.0f;
4787 float Player::GetRatingCoefficient(CombatRating cr) const
4789 uint32 level = getLevel();
4791 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4793 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4794 if (Rating == NULL)
4795 return 1.0f; // By default use minimum coefficient (not must be called)
4797 return Rating->ratio;
4800 float Player::GetRatingBonusValue(CombatRating cr) const
4802 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4805 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4807 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.2f;
4808 if (melee>33.0f) melee = 33.0f;
4809 return uint32 (melee * damage /100.0f);
4812 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4814 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.2f;
4815 if (ranged>33.0f) ranged=33.0f;
4816 return uint32 (ranged * damage /100.0f);
4819 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4821 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.2f;
4822 // In wow script resilience limited to 33%
4823 if (spell>33.0f)
4824 spell = 33.0f;
4825 return uint32 (spell * damage / 100.0f);
4828 uint32 Player::GetDotDamageReduction(uint32 damage) const
4830 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4831 // Dot resilience not limited (limit it by 100%)
4832 if (spellDot > 100.0f)
4833 spellDot = 100.0f;
4834 return uint32 (spellDot * damage / 100.0f);
4837 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4839 switch (attType)
4841 case BASE_ATTACK:
4842 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4843 case OFF_ATTACK:
4844 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4845 default:
4846 break;
4848 return 0.0f;
4851 float Player::OCTRegenHPPerSpirit()
4853 uint32 level = getLevel();
4854 uint32 pclass = getClass();
4856 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4858 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4859 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4860 if (baseRatio==NULL || moreRatio==NULL)
4861 return 0.0f;
4863 // Formula from PaperDollFrame script
4864 float spirit = GetStat(STAT_SPIRIT);
4865 float baseSpirit = spirit;
4866 if (baseSpirit>50) baseSpirit = 50;
4867 float moreSpirit = spirit - baseSpirit;
4868 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4869 return regen;
4872 float Player::OCTRegenMPPerSpirit()
4874 uint32 level = getLevel();
4875 uint32 pclass = getClass();
4877 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4879 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4880 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4881 if (moreRatio==NULL)
4882 return 0.0f;
4884 // Formula get from PaperDollFrame script
4885 float spirit = GetStat(STAT_SPIRIT);
4886 float regen = spirit * moreRatio->ratio;
4887 return regen;
4890 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4892 m_baseRatingValue[cr]+=(apply ? value : -value);
4894 int32 amount = uint32(m_baseRatingValue[cr]);
4895 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4896 // stat used stored in miscValueB for this aura
4897 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4898 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4899 if ((*i)->GetMiscValue() & (1<<cr))
4900 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4901 if (amount < 0)
4902 amount = 0;
4903 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4905 float RatingCoeffecient = GetRatingCoefficient(cr);
4906 float RatingChange = 0.0f;
4908 bool affectStats = CanModifyStats();
4910 switch (cr)
4912 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4913 case CR_DEFENSE_SKILL:
4914 UpdateDefenseBonusesMod();
4915 break;
4916 case CR_DODGE:
4917 UpdateDodgePercentage();
4918 break;
4919 case CR_PARRY:
4920 UpdateParryPercentage();
4921 break;
4922 case CR_BLOCK:
4923 UpdateBlockPercentage();
4924 break;
4925 case CR_HIT_MELEE:
4926 UpdateMeleeHitChances();
4927 break;
4928 case CR_HIT_RANGED:
4929 UpdateRangedHitChances();
4930 break;
4931 case CR_HIT_SPELL:
4932 UpdateSpellHitChances();
4933 break;
4934 case CR_CRIT_MELEE:
4935 if(affectStats)
4937 UpdateCritPercentage(BASE_ATTACK);
4938 UpdateCritPercentage(OFF_ATTACK);
4940 break;
4941 case CR_CRIT_RANGED:
4942 if(affectStats)
4943 UpdateCritPercentage(RANGED_ATTACK);
4944 break;
4945 case CR_CRIT_SPELL:
4946 if(affectStats)
4947 UpdateAllSpellCritChances();
4948 break;
4949 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4950 case CR_HIT_TAKEN_RANGED:
4951 break;
4952 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4953 break;
4954 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4955 case CR_CRIT_TAKEN_RANGED:
4956 break;
4957 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4958 break;
4959 case CR_HASTE_MELEE:
4960 RatingChange = value / RatingCoeffecient;
4961 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4962 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4963 break;
4964 case CR_HASTE_RANGED:
4965 RatingChange = value / RatingCoeffecient;
4966 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4967 break;
4968 case CR_HASTE_SPELL:
4969 RatingChange = value / RatingCoeffecient;
4970 ApplyCastTimePercentMod(RatingChange,apply);
4971 break;
4972 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4973 case CR_WEAPON_SKILL_OFFHAND:
4974 case CR_WEAPON_SKILL_RANGED:
4975 break;
4976 case CR_EXPERTISE:
4977 if(affectStats)
4979 UpdateExpertise(BASE_ATTACK);
4980 UpdateExpertise(OFF_ATTACK);
4982 break;
4983 case CR_ARMOR_PENETRATION:
4984 if(affectStats)
4985 UpdateArmorPenetration();
4986 break;
4990 void Player::SetRegularAttackTime()
4992 for(int i = 0; i < MAX_ATTACK; ++i)
4994 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4995 if(tmpitem && !tmpitem->IsBroken())
4997 ItemPrototype const *proto = tmpitem->GetProto();
4998 if(proto->Delay)
4999 SetAttackTime(WeaponAttackType(i), proto->Delay);
5000 else
5001 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
5006 //skill+step, checking for max value
5007 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
5009 if(!skill_id)
5010 return false;
5012 uint16 i=0;
5013 for (; i < PLAYER_MAX_SKILLS; ++i)
5014 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
5015 break;
5017 if(i>=PLAYER_MAX_SKILLS)
5018 return false;
5020 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5021 uint32 value = SKILL_VALUE(data);
5022 uint32 max = SKILL_MAX(data);
5024 if ((!max) || (!value) || (value >= max))
5025 return false;
5027 if (value*512 < max*urand(0,512))
5029 uint32 new_value = value+step;
5030 if(new_value > max)
5031 new_value = max;
5033 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
5034 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
5035 return true;
5038 return false;
5041 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
5043 if ( SkillValue >= GrayLevel )
5044 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
5045 if ( SkillValue >= GreenLevel )
5046 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
5047 if ( SkillValue >= YellowLevel )
5048 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
5049 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
5052 bool Player::UpdateCraftSkill(uint32 spellid)
5054 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
5056 SkillLineAbilityMapBounds bounds = spellmgr.GetSkillLineAbilityMapBounds(spellid);
5058 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
5060 if (_spell_idx->second->skillId)
5062 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
5064 // Alchemy Discoveries here
5065 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
5066 if (spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
5068 if (uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
5069 learnSpell(discoveredSpell,false);
5072 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
5074 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
5075 _spell_idx->second->max_value,
5076 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
5077 _spell_idx->second->min_value),
5078 craft_skill_gain);
5081 return false;
5084 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
5086 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
5088 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
5090 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
5091 switch (SkillId)
5093 case SKILL_HERBALISM:
5094 case SKILL_LOCKPICKING:
5095 case SKILL_JEWELCRAFTING:
5096 case SKILL_INSCRIPTION:
5097 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5098 case SKILL_SKINNING:
5099 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
5100 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5101 else
5102 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
5103 case SKILL_MINING:
5104 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
5105 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5106 else
5107 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
5109 return false;
5112 bool Player::UpdateFishingSkill()
5114 sLog.outDebug("UpdateFishingSkill");
5116 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
5118 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
5120 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
5122 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
5125 // levels sync. with spell requirement for skill levels to learn
5126 // bonus abilities in sSkillLineAbilityStore
5127 // Used only to avoid scan DBC at each skill grow
5128 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
5130 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
5132 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
5133 if ( !SkillId )
5134 return false;
5136 if(Chance <= 0) // speedup in 0 chance case
5138 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5139 return false;
5142 uint16 i=0;
5143 for (; i < PLAYER_MAX_SKILLS; ++i)
5144 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
5145 if ( i >= PLAYER_MAX_SKILLS )
5146 return false;
5148 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5149 uint16 SkillValue = SKILL_VALUE(data);
5150 uint16 MaxValue = SKILL_MAX(data);
5152 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
5153 return false;
5155 int32 Roll = irand(1,1000);
5157 if ( Roll <= Chance )
5159 uint32 new_value = SkillValue+step;
5160 if(new_value > MaxValue)
5161 new_value = MaxValue;
5163 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
5164 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
5166 if((SkillValue < *bsl && new_value >= *bsl))
5168 learnSkillRewardedSpells( SkillId, new_value);
5169 break;
5172 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
5173 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
5174 return true;
5177 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5178 return false;
5181 void Player::UpdateWeaponSkill (WeaponAttackType attType)
5183 // no skill gain in pvp
5184 Unit *pVictim = getVictim();
5185 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
5186 return;
5188 if(IsInFeralForm())
5189 return; // always maximized SKILL_FERAL_COMBAT in fact
5191 if(m_form == FORM_TREE)
5192 return; // use weapon but not skill up
5194 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
5196 switch(attType)
5198 case BASE_ATTACK:
5200 Item *tmpitem = GetWeaponForAttack(attType,true);
5202 if (!tmpitem)
5203 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
5204 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
5205 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5206 break;
5208 case OFF_ATTACK:
5209 case RANGED_ATTACK:
5211 Item *tmpitem = GetWeaponForAttack(attType,true);
5212 if (tmpitem)
5213 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5214 break;
5217 UpdateAllCritPercentages();
5220 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
5222 uint32 plevel = getLevel(); // if defense than pVictim == attacker
5223 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
5224 uint32 moblevel = pVictim->getLevelForTarget(this);
5225 if(moblevel < greylevel)
5226 return;
5228 if (moblevel > plevel + 5)
5229 moblevel = plevel + 5;
5231 uint32 lvldif = moblevel - greylevel;
5232 if(lvldif < 3)
5233 lvldif = 3;
5235 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
5236 if(skilldif <= 0)
5237 return;
5239 float chance = float(3 * lvldif * skilldif) / plevel;
5240 if(!defence)
5242 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5243 chance *= 0.1f * GetStat(STAT_INTELLECT);
5246 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5248 if(roll_chance_f(chance))
5250 if(defence)
5251 UpdateDefense();
5252 else
5253 UpdateWeaponSkill(attType);
5255 else
5256 return;
5259 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5261 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5262 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
5264 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5265 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5266 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5268 if(talent) // permanent bonus stored in high part
5269 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5270 else // temporary/item bonus stored in low part
5271 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5272 return;
5276 void Player::UpdateSkillsForLevel()
5278 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5279 uint32 maxSkill = GetMaxSkillValueForLevel();
5281 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5283 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5284 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5286 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5288 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5289 if(!pSkill)
5290 continue;
5292 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5293 continue;
5295 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5296 uint32 max = SKILL_MAX(data);
5297 uint32 val = SKILL_VALUE(data);
5299 /// update only level dependent max skill values
5300 if(max!=1)
5302 /// miximize skill always
5303 if(alwaysMaxSkill)
5304 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
5305 /// update max skill value if current max skill not maximized
5306 else if(max != maxconfskill)
5307 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
5312 void Player::UpdateSkillsToMaxSkillsForLevel()
5314 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5315 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5317 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5318 if( IsProfessionOrRidingSkill(pskill))
5319 continue;
5320 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5322 uint32 max = SKILL_MAX(data);
5324 if(max > 1)
5325 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
5327 if(pskill == SKILL_DEFENSE)
5328 UpdateDefenseBonusesMod();
5332 // This functions sets a skill line value (and adds if doesn't exist yet)
5333 // To "remove" a skill line, set it's values to zero
5334 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5336 if(!id)
5337 return;
5339 uint16 i=0;
5340 for (; i < PLAYER_MAX_SKILLS; ++i)
5341 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
5343 if(i<PLAYER_MAX_SKILLS) //has skill
5345 if(currVal)
5347 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5348 learnSkillRewardedSpells(id, currVal);
5349 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5350 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5352 else //remove
5354 // clear skill fields
5355 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
5356 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
5357 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5359 // remove all spells that related to this skill
5360 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5361 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5362 if (pAbility->skillId==id)
5363 removeSpell(spellmgr.GetFirstSpellInChain(pAbility->spellId));
5366 else if(currVal) //add
5368 for (i=0; i < PLAYER_MAX_SKILLS; ++i)
5369 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5371 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5372 if(!pSkill)
5374 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5375 return;
5377 // enable unlearn button for primary professions only
5378 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5379 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5380 else
5381 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5382 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5383 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5384 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5386 // apply skill bonuses
5387 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5389 // temporary bonuses
5390 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5391 for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
5392 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5393 (*j)->ApplyModifier(true);
5395 // permanent bonuses
5396 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5397 for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
5398 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5399 (*j)->ApplyModifier(true);
5401 // Learn all spells for skill
5402 learnSkillRewardedSpells(id, currVal);
5403 return;
5408 bool Player::HasSkill(uint32 skill) const
5410 if(!skill)return false;
5411 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5413 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5415 return true;
5418 return false;
5421 uint16 Player::GetSkillValue(uint32 skill) const
5423 if(!skill)
5424 return 0;
5426 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5428 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5430 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5432 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5433 result += SKILL_TEMP_BONUS(bonus);
5434 result += SKILL_PERM_BONUS(bonus);
5435 return result < 0 ? 0 : result;
5438 return 0;
5441 uint16 Player::GetMaxSkillValue(uint32 skill) const
5443 if(!skill)return 0;
5444 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5446 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5448 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5450 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5451 result += SKILL_TEMP_BONUS(bonus);
5452 result += SKILL_PERM_BONUS(bonus);
5453 return result < 0 ? 0 : result;
5456 return 0;
5459 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5461 if(!skill)return 0;
5462 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5464 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5466 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5469 return 0;
5472 uint16 Player::GetBaseSkillValue(uint32 skill) const
5474 if(!skill)return 0;
5475 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5477 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5479 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5480 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5481 return result < 0 ? 0 : result;
5484 return 0;
5487 uint16 Player::GetPureSkillValue(uint32 skill) const
5489 if(!skill)return 0;
5490 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5492 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5494 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5497 return 0;
5500 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5502 if(!skill)
5503 return 0;
5505 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5507 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5509 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5513 return 0;
5516 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5518 if(!skill)
5519 return 0;
5521 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5523 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5525 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5529 return 0;
5532 void Player::SendInitialActionButtons() const
5534 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5536 WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
5537 data << uint8(0); // can be 0, 1, 2 (talent spec)
5538 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5540 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5541 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5542 data << uint32(itr->second.packedData);
5543 else
5544 data << uint32(0);
5547 GetSession()->SendPacket( &data );
5548 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5551 ActionButton* Player::addActionButton(uint8 button, uint32 action, uint8 type)
5553 if(button >= MAX_ACTION_BUTTONS)
5555 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5556 return NULL;
5559 if(action >= MAX_ACTION_BUTTON_ACTION_VALUE)
5561 sLog.outError( "Action %u not added into button %u for player %s: action must be < %u", action, button, GetName(), MAX_ACTION_BUTTON_ACTION_VALUE );
5562 return NULL;
5565 switch(type)
5567 case ACTION_BUTTON_SPELL:
5568 if(!sSpellStore.LookupEntry(action))
5570 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5571 return NULL;
5574 if(!HasSpell(action))
5576 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5577 return NULL;
5579 break;
5580 case ACTION_BUTTON_ITEM:
5581 if(!objmgr.GetItemPrototype(action))
5583 sLog.outError( "Action %u not added into button %u for player %s: item not exist", action, button, GetName() );
5584 return NULL;
5586 break;
5587 default:
5588 break; // pther cases not checked at this moment
5592 // it create new button (NEW state) if need or return existed
5593 ActionButton& ab = m_actionButtons[button];
5595 // set data and update to CHANGED if not NEW
5596 ab.SetActionAndType(action,ActionButtonType(type));
5598 sLog.outDetail( "Player '%u' Added Action '%u' (type %u) to Button '%u'", GetGUIDLow(), action, uint32(type), button );
5599 return &ab;
5602 void Player::removeActionButton(uint8 button)
5604 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5605 if (buttonItr==m_actionButtons.end())
5606 return;
5608 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5609 m_actionButtons.erase(buttonItr); // new and not saved
5610 else
5611 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5613 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5616 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5618 // prevent crash when a bad coord is sent by the client
5619 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5621 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5622 return false;
5625 Map *m = GetMap();
5627 const float old_x = GetPositionX();
5628 const float old_y = GetPositionY();
5629 const float old_z = GetPositionZ();
5630 const float old_r = GetOrientation();
5632 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5634 if (teleport || old_x != x || old_y != y || old_z != z)
5635 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5636 else
5637 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5639 // move and update visible state if need
5640 m->PlayerRelocation(this, x, y, z, orientation);
5642 // reread after Map::Relocation
5643 m = GetMap();
5644 x = GetPositionX();
5645 y = GetPositionY();
5646 z = GetPositionZ();
5648 // group update
5649 if(GetGroup() && (old_x != x || old_y != y))
5650 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5653 // code block for underwater state update
5654 UpdateUnderwaterState(m, x, y, z);
5656 CheckExploreSystem();
5658 return true;
5661 void Player::SaveRecallPosition()
5663 m_recallMap = GetMapId();
5664 m_recallX = GetPositionX();
5665 m_recallY = GetPositionY();
5666 m_recallZ = GetPositionZ();
5667 m_recallO = GetOrientation();
5670 void Player::SendMessageToSet(WorldPacket *data, bool self)
5672 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5673 if(_map)
5675 _map->MessageBroadcast(this, data, self);
5676 return;
5679 //if player is not in world and map in not created/already destroyed
5680 //no need to create one, just send packet for itself!
5681 if(self)
5682 GetSession()->SendPacket(data);
5685 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5687 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5688 if(_map)
5690 _map->MessageDistBroadcast(this, data, dist, self);
5691 return;
5694 if(self)
5695 GetSession()->SendPacket(data);
5698 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5700 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5701 if(_map)
5703 _map->MessageDistBroadcast(this, data, dist, self, own_team_only);
5704 return;
5707 if(self)
5708 GetSession()->SendPacket(data);
5711 void Player::SendDirectMessage(WorldPacket *data)
5713 GetSession()->SendPacket(data);
5716 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5718 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5719 data << uint32(CinematicSequenceId);
5720 SendDirectMessage(&data);
5723 void Player::SendMovieStart(uint32 MovieId)
5725 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5726 data << uint32(MovieId);
5727 SendDirectMessage(&data);
5730 void Player::CheckExploreSystem()
5732 if (!isAlive())
5733 return;
5735 if (isInFlight())
5736 return;
5738 uint16 areaFlag = GetBaseMap()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5739 if(areaFlag==0xffff)
5740 return;
5741 int offset = areaFlag / 32;
5743 if(offset >= 128)
5745 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);
5746 return;
5749 uint32 val = (uint32)(1 << (areaFlag % 32));
5750 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5752 if( !(currFields & val) )
5754 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5756 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5758 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5759 if(!p)
5761 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5763 else if(p->area_level > 0)
5765 uint32 area = p->ID;
5766 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5768 SendExplorationExperience(area,0);
5770 else
5772 int32 diff = int32(getLevel()) - p->area_level;
5773 uint32 XP = 0;
5774 if (diff < -5)
5776 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5778 else if (diff > 5)
5780 int32 exploration_percent = (100-((diff-5)*5));
5781 if (exploration_percent > 100)
5782 exploration_percent = 100;
5783 else if (exploration_percent < 0)
5784 exploration_percent = 0;
5786 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5788 else
5790 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5793 GiveXP( XP, NULL );
5794 SendExplorationExperience(area,XP);
5796 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5801 uint32 Player::TeamForRace(uint8 race)
5803 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5804 if(!rEntry)
5806 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5807 return ALLIANCE;
5810 switch(rEntry->TeamID)
5812 case 7: return ALLIANCE;
5813 case 1: return HORDE;
5816 sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5817 return ALLIANCE;
5820 uint32 Player::getFactionForRace(uint8 race)
5822 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5823 if(!rEntry)
5825 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5826 return 0;
5829 return rEntry->FactionID;
5832 void Player::setFactionForRace(uint8 race)
5834 m_team = TeamForRace(race);
5835 setFaction( getFactionForRace(race) );
5838 ReputationRank Player::GetReputationRank(uint32 faction) const
5840 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
5841 return GetReputationMgr().GetRank(factionEntry);
5844 //Calculate total reputation percent player gain with quest/creature level
5845 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest)
5847 float percent = 100.0f;
5849 float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL);
5851 if (rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
5852 percent *= rate;
5854 float repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5856 if (!for_quest)
5857 repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);
5859 percent += rep > 0 ? repMod : -repMod;
5861 if (percent <= 0.0f)
5862 return 0;
5864 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100.0f);
5867 //Calculates how many reputation points player gains in victim's enemy factions
5868 void Player::RewardReputation(Unit *pVictim, float rate)
5870 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5871 return;
5873 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5875 if(!Rep)
5876 return;
5878 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5880 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue1, Rep->repfaction1, false);
5881 donerep1 = int32(donerep1*rate);
5882 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5883 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
5884 if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5885 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
5887 // Wiki: Team factions value divided by 2
5888 if (factionEntry1 && Rep->is_teamaward1)
5890 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5891 if(team1_factionEntry)
5892 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
5896 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5898 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue2, Rep->repfaction2, false);
5899 donerep2 = int32(donerep2*rate);
5900 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5901 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
5902 if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5903 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
5905 // Wiki: Team factions value divided by 2
5906 if (factionEntry2 && Rep->is_teamaward2)
5908 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5909 if(team2_factionEntry)
5910 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
5915 //Calculate how many reputation points player gain with the quest
5916 void Player::RewardReputation(Quest const *pQuest)
5918 // quest reputation reward/loss
5919 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5921 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5923 int32 rep = CalculateReputationGain(GetQuestLevel(pQuest), pQuest->RewRepValue[i], pQuest->RewRepFaction[i], true);
5924 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5925 if(factionEntry)
5926 GetReputationMgr().ModifyReputation(factionEntry, rep);
5930 // TODO: implement reputation spillover
5933 void Player::UpdateArenaFields(void)
5935 /* arena calcs go here */
5938 void Player::UpdateHonorFields()
5940 /// called when rewarding honor and at each save
5941 uint64 now = time(NULL);
5942 uint64 today = uint64(time(NULL) / DAY) * DAY;
5944 if(m_lastHonorUpdateTime < today)
5946 uint64 yesterday = today - DAY;
5948 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5950 // update yesterday's contribution
5951 if(m_lastHonorUpdateTime >= yesterday )
5953 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5955 // this is the first update today, reset today's contribution
5956 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5957 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5959 else
5961 // no honor/kills yesterday or today, reset
5962 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5963 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5967 m_lastHonorUpdateTime = now;
5970 ///Calculate the amount of honor gained based on the victim
5971 ///and the size of the group for which the honor is divided
5972 ///An exact honor value can also be given (overriding the calcs)
5973 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5975 // do not reward honor in arenas, but enable onkill spellproc
5976 if(InArena())
5978 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
5979 return false;
5981 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
5982 return false;
5984 return true;
5987 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5988 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5989 return false;
5991 uint64 victim_guid = 0;
5992 uint32 victim_rank = 0;
5994 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5995 UpdateHonorFields();
5997 if(honor <= 0)
5999 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
6000 return false;
6002 victim_guid = uVictim->GetGUID();
6004 if( uVictim->GetTypeId() == TYPEID_PLAYER )
6006 Player *pVictim = (Player *)uVictim;
6008 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
6009 return false;
6011 float f = 1; //need for total kills (?? need more info)
6012 uint32 k_grey = 0;
6013 uint32 k_level = getLevel();
6014 uint32 v_level = pVictim->getLevel();
6017 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6018 // [0] Just name
6019 // [1..14] Alliance honor titles and player name
6020 // [15..28] Horde honor titles and player name
6021 // [29..38] Other title and player name
6022 // [39+] Nothing
6023 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
6024 // Get Killer titles, CharTitlesEntry::bit_index
6025 // Ranks:
6026 // title[1..14] -> rank[5..18]
6027 // title[15..28] -> rank[5..18]
6028 // title[other] -> 0
6029 if (victim_title == 0)
6030 victim_guid = 0; // Don't show HK: <rank> message, only log.
6031 else if (victim_title < 15)
6032 victim_rank = victim_title + 4;
6033 else if (victim_title < 29)
6034 victim_rank = victim_title - 14 + 4;
6035 else
6036 victim_guid = 0; // Don't show HK: <rank> message, only log.
6039 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
6041 if(v_level<=k_grey)
6042 return false;
6044 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
6046 int32 v_rank =1; //need more info
6048 honor = ((f * diff_level * (190 + v_rank*10))/6);
6049 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
6051 // count the number of playerkills in one day
6052 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
6053 // and those in a lifetime
6054 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
6055 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
6056 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
6057 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
6059 else
6061 Creature *cVictim = (Creature *)uVictim;
6063 if (!cVictim->isRacialLeader())
6064 return false;
6066 honor = 100; // ??? need more info
6067 victim_rank = 19; // HK: Leader
6071 if (uVictim != NULL)
6073 honor *= sWorld.getRate(RATE_HONOR);
6075 if(groupsize > 1)
6076 honor /= groupsize;
6078 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6081 // honor - for show honor points in log
6082 // victim_guid - for show victim name in log
6083 // victim_rank [1..4] HK: <dishonored rank>
6084 // victim_rank [5..19] HK: <alliance\horde rank>
6085 // victim_rank [0,20+] HK: <>
6086 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
6087 data << (uint32) honor;
6088 data << (uint64) victim_guid;
6089 data << (uint32) victim_rank;
6091 GetSession()->SendPacket(&data);
6093 // add honor points
6094 ModifyHonorPoints(int32(honor));
6096 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
6097 return true;
6100 void Player::ModifyHonorPoints( int32 value )
6102 if(value < 0)
6104 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
6105 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
6106 else
6107 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6109 else
6110 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6113 void Player::ModifyArenaPoints( int32 value )
6115 if(value < 0)
6117 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6118 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6119 else
6120 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6122 else
6123 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6126 uint32 Player::GetGuildIdFromDB(uint64 guid)
6128 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
6129 if(!result)
6130 return 0;
6132 uint32 id = result->Fetch()[0].GetUInt32();
6133 delete result;
6134 return id;
6137 uint32 Player::GetRankFromDB(uint64 guid)
6139 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6140 if( result )
6142 uint32 v = result->Fetch()[0].GetUInt32();
6143 delete result;
6144 return v;
6146 else
6147 return 0;
6150 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6152 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);
6153 if(!result)
6154 return 0;
6156 uint32 id = (*result)[0].GetUInt32();
6157 delete result;
6158 return id;
6161 uint32 Player::GetZoneIdFromDB(uint64 guid)
6163 uint32 guidLow = GUID_LOPART(guid);
6164 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6165 if (!result)
6166 return 0;
6167 Field* fields = result->Fetch();
6168 uint32 zone = fields[0].GetUInt32();
6169 delete result;
6171 if (!zone)
6173 // stored zone is zero, use generic and slow zone detection
6174 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6175 if( !result )
6176 return 0;
6177 fields = result->Fetch();
6178 uint32 map = fields[0].GetUInt32();
6179 float posx = fields[1].GetFloat();
6180 float posy = fields[2].GetFloat();
6181 float posz = fields[3].GetFloat();
6182 delete result;
6184 zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
6186 if (zone > 0)
6187 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6190 return zone;
6193 uint32 Player::GetLevelFromDB(uint64 guid)
6195 QueryResult *result = CharacterDatabase.PQuery( "SELECT level FROM characters WHERE guid='%u'", GUID_LOPART(guid) );
6196 if (!result)
6197 return 0;
6199 Field* fields = result->Fetch();
6200 uint32 level = fields[0].GetUInt32();
6201 delete result;
6203 return level;
6206 void Player::UpdateArea(uint32 newArea)
6208 // FFA_PVP flags are area and not zone id dependent
6209 // so apply them accordingly
6210 m_areaUpdateId = newArea;
6212 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6214 if(area && (area->flags & AREA_FLAG_ARENA))
6216 if(!isGameMaster())
6217 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6219 else
6221 // remove ffa flag only if not ffapvp realm
6222 // removal in sanctuaries and capitals is handled in zone update
6223 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6224 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6227 UpdateAreaDependentAuras(newArea);
6230 void Player::UpdateZone(uint32 newZone, uint32 newArea)
6232 if(m_zoneUpdateId != newZone)
6233 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
6235 m_zoneUpdateId = newZone;
6236 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6238 // zone changed, so area changed as well, update it
6239 UpdateArea(newArea);
6241 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6242 if(!zone)
6243 return;
6245 if (sWorld.getConfig(CONFIG_WEATHER))
6247 Weather *wth = sWorld.FindWeather(zone->ID);
6248 if(wth)
6250 wth->SendWeatherUpdateToPlayer(this);
6252 else
6254 if(!sWorld.AddWeather(zone->ID))
6256 // send fine weather packet to remove old zone's weather
6257 Weather::SendFineWeatherUpdateToPlayer(this);
6262 // in PvP, any not controlled zone (except zone->team == 6, default case)
6263 // in PvE, only opposition team capital
6264 switch(zone->team)
6266 case AREATEAM_ALLY:
6267 pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6268 break;
6269 case AREATEAM_HORDE:
6270 pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6271 break;
6272 case AREATEAM_NONE:
6273 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6274 pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround();
6275 break;
6276 default: // 6 in fact
6277 pvpInfo.inHostileArea = false;
6278 break;
6281 if(pvpInfo.inHostileArea) // in hostile area
6283 if(!IsPvP() || pvpInfo.endTimer != 0)
6284 UpdatePvP(true, true);
6286 else // in friendly area
6288 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6289 pvpInfo.endTimer = time(0); // start toggle-off
6292 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6294 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6295 if(sWorld.IsFFAPvPRealm())
6296 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6298 else
6300 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6303 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6305 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6306 SetRestType(REST_TYPE_IN_CITY);
6307 InnEnter(time(0),GetMapId(),0,0,0);
6309 if(sWorld.IsFFAPvPRealm())
6310 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6312 else // anywhere else
6314 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6316 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6318 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6320 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6321 SetRestType(REST_TYPE_NO);
6323 if(sWorld.IsFFAPvPRealm())
6324 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6327 else // not in tavern (leave city then)
6329 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6330 SetRestType(REST_TYPE_NO);
6332 // Set player to FFA PVP when not in rested environment.
6333 if(sWorld.IsFFAPvPRealm())
6334 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6339 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6340 // if player resurrected at teleport this will be applied in resurrect code
6341 if(isAlive())
6342 DestroyZoneLimitedItem( true, newZone );
6344 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6345 AutoUnequipOffhandIfNeed();
6347 // recent client version not send leave/join channel packets for built-in local channels
6348 UpdateLocalChannels( newZone );
6350 // group update
6351 if(GetGroup())
6352 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6354 UpdateZoneDependentAuras(newZone);
6357 //If players are too far way of duel flag... then player loose the duel
6358 void Player::CheckDuelDistance(time_t currTime)
6360 if(!duel)
6361 return;
6363 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6364 GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
6365 if(!obj)
6366 return;
6368 if(duel->outOfBound == 0)
6370 if(!IsWithinDistInMap(obj, 50))
6372 duel->outOfBound = currTime;
6374 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6375 GetSession()->SendPacket(&data);
6378 else
6380 if(IsWithinDistInMap(obj, 40))
6382 duel->outOfBound = 0;
6384 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6385 GetSession()->SendPacket(&data);
6387 else if(currTime >= (duel->outOfBound+10))
6389 DuelComplete(DUEL_FLED);
6394 void Player::DuelComplete(DuelCompleteType type)
6396 // duel not requested
6397 if(!duel)
6398 return;
6400 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6401 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6402 GetSession()->SendPacket(&data);
6403 duel->opponent->GetSession()->SendPacket(&data);
6405 if(type != DUEL_INTERUPTED)
6407 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6408 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6409 data << duel->opponent->GetName();
6410 data << GetName();
6411 SendMessageToSet(&data,true);
6414 if (type == DUEL_WON)
6416 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
6417 if (duel->opponent)
6418 duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
6421 //Remove Duel Flag object
6422 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
6423 if(obj)
6424 duel->initiator->RemoveGameObject(obj,true);
6426 /* remove auras */
6427 std::vector<uint32> auras2remove;
6428 AuraMap const& vAuras = duel->opponent->GetAuras();
6429 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6431 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6432 auras2remove.push_back(i->second->GetId());
6435 for(size_t i=0; i<auras2remove.size(); ++i)
6436 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6438 auras2remove.clear();
6439 AuraMap const& auras = GetAuras();
6440 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6442 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6443 auras2remove.push_back(i->second->GetId());
6445 for(size_t i=0; i<auras2remove.size(); ++i)
6446 RemoveAurasDueToSpell(auras2remove[i]);
6448 // cleanup combo points
6449 if(GetComboTarget()==duel->opponent->GetGUID())
6450 ClearComboPoints();
6451 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6452 ClearComboPoints();
6454 if(duel->opponent->GetComboTarget()==GetGUID())
6455 duel->opponent->ClearComboPoints();
6456 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6457 duel->opponent->ClearComboPoints();
6459 //cleanups
6460 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6461 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6462 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6463 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6465 delete duel->opponent->duel;
6466 duel->opponent->duel = NULL;
6467 delete duel;
6468 duel = NULL;
6471 //---------------------------------------------------------//
6473 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6475 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6476 return;
6478 // not apply/remove mods for broken item
6479 if(item->IsBroken())
6480 return;
6482 ItemPrototype const *proto = item->GetProto();
6484 if(!proto)
6485 return;
6487 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6489 uint32 attacktype = Player::GetAttackBySlot(slot);
6490 if(attacktype < MAX_ATTACK)
6491 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6493 _ApplyItemBonuses(proto,slot,apply);
6495 if( slot==EQUIPMENT_SLOT_RANGED )
6496 _ApplyAmmoBonuses();
6498 ApplyItemEquipSpell(item,apply);
6499 ApplyEnchantment(item, apply);
6501 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6502 CorrectMetaGemEnchants(slot, apply);
6504 sLog.outDebug("_ApplyItemMods complete.");
6507 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply, bool only_level_scale /*= false*/)
6509 if (slot >= INVENTORY_SLOT_BAG_END || !proto)
6510 return;
6512 ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : NULL;
6513 if (only_level_scale && !ssd)
6514 return;
6516 // req. check at equip, but allow use for extended range if range limit max level, set proper level
6517 uint32 ssd_level = getLevel();
6518 if (ssd && ssd_level > ssd->MaxLevel)
6519 ssd_level = ssd->MaxLevel;
6521 ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(ssd_level) : NULL;
6522 if (only_level_scale && !ssv)
6523 return;
6525 for (int i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6527 uint32 statType = 0;
6528 int32 val = 0;
6529 // If set ScalingStatDistribution need get stats and values from it
6530 if (ssd && ssv)
6532 if (ssd->StatMod[i] < 0)
6533 continue;
6534 statType = ssd->StatMod[i];
6535 val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[i]) / 10000;
6537 else
6539 if (i >= proto->StatsCount)
6540 continue;
6541 statType = proto->ItemStat[i].ItemStatType;
6542 val = proto->ItemStat[i].ItemStatValue;
6545 if(val == 0)
6546 continue;
6548 switch (statType)
6550 case ITEM_MOD_MANA:
6551 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6552 break;
6553 case ITEM_MOD_HEALTH: // modify HP
6554 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6555 break;
6556 case ITEM_MOD_AGILITY: // modify agility
6557 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6558 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6559 break;
6560 case ITEM_MOD_STRENGTH: //modify strength
6561 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6562 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6563 break;
6564 case ITEM_MOD_INTELLECT: //modify intellect
6565 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6566 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6567 break;
6568 case ITEM_MOD_SPIRIT: //modify spirit
6569 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6570 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6571 break;
6572 case ITEM_MOD_STAMINA: //modify stamina
6573 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6574 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6575 break;
6576 case ITEM_MOD_DEFENSE_SKILL_RATING:
6577 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6578 break;
6579 case ITEM_MOD_DODGE_RATING:
6580 ApplyRatingMod(CR_DODGE, int32(val), apply);
6581 break;
6582 case ITEM_MOD_PARRY_RATING:
6583 ApplyRatingMod(CR_PARRY, int32(val), apply);
6584 break;
6585 case ITEM_MOD_BLOCK_RATING:
6586 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6587 break;
6588 case ITEM_MOD_HIT_MELEE_RATING:
6589 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6590 break;
6591 case ITEM_MOD_HIT_RANGED_RATING:
6592 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6593 break;
6594 case ITEM_MOD_HIT_SPELL_RATING:
6595 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6596 break;
6597 case ITEM_MOD_CRIT_MELEE_RATING:
6598 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6599 break;
6600 case ITEM_MOD_CRIT_RANGED_RATING:
6601 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6602 break;
6603 case ITEM_MOD_CRIT_SPELL_RATING:
6604 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6605 break;
6606 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6607 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6608 break;
6609 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6610 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6611 break;
6612 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6613 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6614 break;
6615 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6616 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6617 break;
6618 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6619 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6620 break;
6621 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6622 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6623 break;
6624 case ITEM_MOD_HASTE_MELEE_RATING:
6625 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6626 break;
6627 case ITEM_MOD_HASTE_RANGED_RATING:
6628 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6629 break;
6630 case ITEM_MOD_HASTE_SPELL_RATING:
6631 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6632 break;
6633 case ITEM_MOD_HIT_RATING:
6634 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6635 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6636 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6637 break;
6638 case ITEM_MOD_CRIT_RATING:
6639 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6640 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6641 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6642 break;
6643 case ITEM_MOD_HIT_TAKEN_RATING:
6644 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6645 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6646 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6647 break;
6648 case ITEM_MOD_CRIT_TAKEN_RATING:
6649 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6650 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6651 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6652 break;
6653 case ITEM_MOD_RESILIENCE_RATING:
6654 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6655 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6656 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6657 break;
6658 case ITEM_MOD_HASTE_RATING:
6659 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6660 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6661 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6662 break;
6663 case ITEM_MOD_EXPERTISE_RATING:
6664 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6665 break;
6666 case ITEM_MOD_ATTACK_POWER:
6667 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6668 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6669 break;
6670 case ITEM_MOD_RANGED_ATTACK_POWER:
6671 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6672 break;
6673 case ITEM_MOD_FERAL_ATTACK_POWER:
6674 ApplyFeralAPBonus(int32(val), apply);
6675 break;
6676 case ITEM_MOD_MANA_REGENERATION:
6677 ApplyManaRegenBonus(int32(val), apply);
6678 break;
6679 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6680 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6681 break;
6682 case ITEM_MOD_SPELL_POWER:
6683 ApplySpellPowerBonus(int32(val), apply);
6684 break;
6685 // depricated item mods
6686 case ITEM_MOD_SPELL_HEALING_DONE:
6687 case ITEM_MOD_SPELL_DAMAGE_DONE:
6688 break;
6692 // Apply Spell Power from ScalingStatValue if set
6693 if(ssv)
6695 if (int32 spellbonus = ssv->getSpellBonus(proto->ScalingStatValue))
6696 ApplySpellPowerBonus(spellbonus, apply);
6699 // If set ScalingStatValue armor get it or use item armor
6700 uint32 armor = proto->Armor;
6701 if (ssv)
6703 if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue))
6704 armor = ssvarmor;
6706 // Add armor bonus from ArmorDamageModifier if > 0
6707 if (proto->ArmorDamageModifier > 0)
6708 armor += uint32(proto->ArmorDamageModifier);
6710 if (armor)
6711 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(armor), apply);
6713 if (proto->Block)
6714 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6716 if (proto->HolyRes)
6717 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6719 if (proto->FireRes)
6720 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6722 if (proto->NatureRes)
6723 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6725 if (proto->FrostRes)
6726 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6728 if (proto->ShadowRes)
6729 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6731 if (proto->ArcaneRes)
6732 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6734 WeaponAttackType attType = BASE_ATTACK;
6735 float damage = 0.0f;
6737 if( slot == EQUIPMENT_SLOT_RANGED && (
6738 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6739 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6741 attType = RANGED_ATTACK;
6743 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6745 attType = OFF_ATTACK;
6748 float minDamage = proto->Damage[0].DamageMin;
6749 float maxDamage = proto->Damage[0].DamageMax;
6750 int32 extraDPS = 0;
6751 // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
6752 if (ssv)
6754 if ((extraDPS = ssv->getDPSMod(proto->ScalingStatValue)))
6756 float average = extraDPS * proto->Delay / 1000.0f;
6757 minDamage = 0.7f * average;
6758 maxDamage = 1.3f * average;
6761 if (minDamage > 0 )
6763 damage = apply ? minDamage : BASE_MINDAMAGE;
6764 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6765 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6768 if (maxDamage > 0 )
6770 damage = apply ? maxDamage : BASE_MAXDAMAGE;
6771 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6774 // Apply feral bonus from ScalingStatValue if set
6775 if (ssv)
6777 if (int32 feral_bonus = ssv->getFeralBonus(proto->ScalingStatValue))
6778 ApplyFeralAPBonus(feral_bonus, apply);
6780 // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
6781 if(getClass() == CLASS_DRUID)
6783 int32 feral_bonus = proto->getFeralBonus(extraDPS);
6784 if (feral_bonus > 0)
6785 ApplyFeralAPBonus(feral_bonus, apply);
6788 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6789 return;
6791 if (proto->Delay)
6793 if(slot == EQUIPMENT_SLOT_RANGED)
6794 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6795 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6796 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6797 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6798 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6801 if(CanModifyStats() && (damage || proto->Delay))
6802 UpdateDamagePhysical(attType);
6805 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6807 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6808 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6809 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6811 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6812 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6813 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6815 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6816 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6817 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6820 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6822 // generic not weapon specific case processes in aura code
6823 if(aura->GetSpellProto()->EquippedItemClass == -1)
6824 return;
6826 BaseModGroup mod = BASEMOD_END;
6827 switch(attackType)
6829 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6830 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6831 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6832 default: return;
6835 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6837 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6841 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6843 // ignore spell mods for not wands
6844 Modifier const* modifier = aura->GetModifier();
6845 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6846 return;
6848 // generic not weapon specific case processes in aura code
6849 if(aura->GetSpellProto()->EquippedItemClass == -1)
6850 return;
6852 UnitMods unitMod = UNIT_MOD_END;
6853 switch(attackType)
6855 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6856 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6857 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6858 default: return;
6861 UnitModifierType unitModType = TOTAL_VALUE;
6862 switch(modifier->m_auraname)
6864 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6865 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6866 default: return;
6869 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6871 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6875 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6877 if(!item)
6878 return;
6880 ItemPrototype const *proto = item->GetProto();
6881 if(!proto)
6882 return;
6884 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6886 _Spell const& spellData = proto->Spells[i];
6888 // no spell
6889 if(!spellData.SpellId )
6890 continue;
6892 // wrong triggering type
6893 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6894 continue;
6896 // check if it is valid spell
6897 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6898 if(!spellproto)
6899 continue;
6901 ApplyEquipSpell(spellproto,item,apply,form_change);
6905 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6907 if(apply)
6909 // Cannot be used in this stance/form
6910 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
6911 return;
6913 if(form_change) // check aura active state from other form
6915 bool found = false;
6916 for (int k=0; k < 3; ++k)
6918 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6919 for (AuraMap::const_iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6921 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6923 found = true;
6924 break;
6927 if(found)
6928 break;
6931 if(found) // and skip re-cast already active aura at form change
6932 return;
6935 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6937 CastSpell(this,spellInfo,true,item);
6939 else
6941 if(form_change) // check aura compatibility
6943 // Cannot be used in this stance/form
6944 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
6945 return; // and remove only not compatible at form change
6948 if(item)
6949 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6950 else
6951 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6955 void Player::UpdateEquipSpellsAtFormChange()
6957 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6959 if(m_items[i] && !m_items[i]->IsBroken())
6961 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6962 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6966 // item set bonuses not dependent from item broken state
6967 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6969 ItemSetEffect* eff = ItemSetEff[setindex];
6970 if(!eff)
6971 continue;
6973 for(uint32 y=0;y<8; ++y)
6975 SpellEntry const* spellInfo = eff->spells[y];
6976 if(!spellInfo)
6977 continue;
6979 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6980 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6985 void Player::CastItemCombatSpell(Unit* Target, WeaponAttackType attType)
6987 Item *item = GetWeaponForAttack(attType, true);
6988 if(!item || item->IsBroken())
6989 return;
6991 ItemPrototype const *proto = item->GetProto();
6992 if(!proto)
6993 return;
6995 if (!Target || Target == this )
6996 return;
6998 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7000 _Spell const& spellData = proto->Spells[i];
7002 // no spell
7003 if(!spellData.SpellId )
7004 continue;
7006 // wrong triggering type
7007 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
7008 continue;
7010 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7011 if(!spellInfo)
7013 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
7014 continue;
7017 // not allow proc extra attack spell at extra attack
7018 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
7019 return;
7021 float chance = spellInfo->procChance;
7023 if(spellData.SpellPPMRate)
7025 uint32 WeaponSpeed = proto->Delay;
7026 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
7028 else if(chance > 100.0f)
7030 chance = GetWeaponProcChance();
7033 if (roll_chance_f(chance))
7034 CastSpell(Target, spellInfo->Id, true, item);
7037 // item combat enchantments
7038 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7040 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7041 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7042 if(!pEnchant) continue;
7043 for (int s=0;s<3;s++)
7045 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
7046 continue;
7048 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7049 if (!spellInfo)
7051 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7052 continue;
7055 // Use first rank to access spell item enchant procs
7056 float ppmRate = spellmgr.GetItemEnchantProcChance(spellInfo->Id);
7058 float chance = ppmRate
7059 ? GetPPMProcChance(proto->Delay, ppmRate)
7060 : pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
7063 ApplySpellMod(spellInfo->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
7064 ApplySpellMod(spellInfo->Id,SPELLMOD_FREQUENCY_OF_SUCCESS,chance);
7066 if (roll_chance_f(chance))
7068 if(IsPositiveSpell(pEnchant->spellid[s]))
7069 CastSpell(this, pEnchant->spellid[s], true, item);
7070 else
7071 CastSpell(Target, pEnchant->spellid[s], true, item);
7077 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
7079 ItemPrototype const* proto = item->GetProto();
7080 // special learning case
7081 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
7083 uint32 learn_spell_id = proto->Spells[0].SpellId;
7084 uint32 learning_spell_id = proto->Spells[1].SpellId;
7086 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
7087 if(!spellInfo)
7089 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
7090 SendEquipError(EQUIP_ERR_NONE,item,NULL);
7091 return;
7094 Spell *spell = new Spell(this, spellInfo, false);
7095 spell->m_CastItem = item;
7096 spell->m_cast_count = cast_count; //set count of casts
7097 spell->m_currentBasePoints[0] = learning_spell_id;
7098 spell->prepare(&targets);
7099 return;
7102 // use triggered flag only for items with many spell casts and for not first cast
7103 int count = 0;
7105 // item spells casted at use
7106 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7108 _Spell const& spellData = proto->Spells[i];
7110 // no spell
7111 if(!spellData.SpellId)
7112 continue;
7114 // wrong triggering type
7115 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
7116 continue;
7118 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7119 if(!spellInfo)
7121 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
7122 continue;
7125 Spell *spell = new Spell(this, spellInfo, (count > 0));
7126 spell->m_CastItem = item;
7127 spell->m_cast_count = cast_count; // set count of casts
7128 spell->m_glyphIndex = glyphIndex; // glyph index
7129 spell->prepare(&targets);
7131 ++count;
7134 // Item enchantments spells casted at use
7135 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7137 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7138 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7139 if(!pEnchant) continue;
7140 for (int s=0;s<3;s++)
7142 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
7143 continue;
7145 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7146 if (!spellInfo)
7148 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7149 continue;
7152 Spell *spell = new Spell(this, spellInfo, (count > 0));
7153 spell->m_CastItem = item;
7154 spell->m_cast_count = cast_count; // set count of casts
7155 spell->m_glyphIndex = glyphIndex; // glyph index
7156 spell->prepare(&targets);
7158 ++count;
7163 void Player::_RemoveAllItemMods()
7165 sLog.outDebug("_RemoveAllItemMods start.");
7167 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7169 if(m_items[i])
7171 ItemPrototype const *proto = m_items[i]->GetProto();
7172 if(!proto)
7173 continue;
7175 // item set bonuses not dependent from item broken state
7176 if(proto->ItemSet)
7177 RemoveItemsSetItem(this,proto);
7179 if(m_items[i]->IsBroken())
7180 continue;
7182 ApplyItemEquipSpell(m_items[i],false);
7183 ApplyEnchantment(m_items[i], false);
7187 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7189 if(m_items[i])
7191 if(m_items[i]->IsBroken())
7192 continue;
7193 ItemPrototype const *proto = m_items[i]->GetProto();
7194 if(!proto)
7195 continue;
7197 uint32 attacktype = Player::GetAttackBySlot(i);
7198 if(attacktype < MAX_ATTACK)
7199 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7201 _ApplyItemBonuses(proto,i, false);
7203 if( i == EQUIPMENT_SLOT_RANGED )
7204 _ApplyAmmoBonuses();
7208 sLog.outDebug("_RemoveAllItemMods complete.");
7211 void Player::_ApplyAllItemMods()
7213 sLog.outDebug("_ApplyAllItemMods start.");
7215 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7217 if(m_items[i])
7219 if(m_items[i]->IsBroken())
7220 continue;
7222 ItemPrototype const *proto = m_items[i]->GetProto();
7223 if(!proto)
7224 continue;
7226 uint32 attacktype = Player::GetAttackBySlot(i);
7227 if(attacktype < MAX_ATTACK)
7228 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7230 _ApplyItemBonuses(proto,i, true);
7232 if( i == EQUIPMENT_SLOT_RANGED )
7233 _ApplyAmmoBonuses();
7237 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7239 if(m_items[i])
7241 ItemPrototype const *proto = m_items[i]->GetProto();
7242 if(!proto)
7243 continue;
7245 // item set bonuses not dependent from item broken state
7246 if(proto->ItemSet)
7247 AddItemsSetItem(this,m_items[i]);
7249 if(m_items[i]->IsBroken())
7250 continue;
7252 ApplyItemEquipSpell(m_items[i],true);
7253 ApplyEnchantment(m_items[i], true);
7257 sLog.outDebug("_ApplyAllItemMods complete.");
7260 void Player::_ApplyAllLevelScaleItemMods(bool apply)
7262 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7264 if(m_items[i])
7266 if(m_items[i]->IsBroken())
7267 continue;
7269 ItemPrototype const *proto = m_items[i]->GetProto();
7270 if(!proto)
7271 continue;
7273 _ApplyItemBonuses(proto,i, apply, true);
7278 void Player::_ApplyAmmoBonuses()
7280 // check ammo
7281 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7282 if(!ammo_id)
7283 return;
7285 float currentAmmoDPS;
7287 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
7288 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7289 currentAmmoDPS = 0.0f;
7290 else
7291 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7293 if(currentAmmoDPS == GetAmmoDPS())
7294 return;
7296 m_ammoDPS = currentAmmoDPS;
7298 if(CanModifyStats())
7299 UpdateDamagePhysical(RANGED_ATTACK);
7302 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7304 if(!ammo_proto)
7305 return false;
7307 // check ranged weapon
7308 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7309 if(!weapon || weapon->IsBroken() )
7310 return false;
7312 ItemPrototype const* weapon_proto = weapon->GetProto();
7313 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7314 return false;
7316 // check ammo ws. weapon compatibility
7317 switch(weapon_proto->SubClass)
7319 case ITEM_SUBCLASS_WEAPON_BOW:
7320 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7321 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7322 return false;
7323 break;
7324 case ITEM_SUBCLASS_WEAPON_GUN:
7325 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7326 return false;
7327 break;
7328 default:
7329 return false;
7332 return true;
7335 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7336 Called by remove insignia spell effect */
7337 void Player::RemovedInsignia(Player* looterPlr)
7339 if (!GetBattleGroundId())
7340 return;
7342 // If not released spirit, do it !
7343 if(m_deathTimer > 0)
7345 m_deathTimer = 0;
7346 BuildPlayerRepop();
7347 RepopAtGraveyard();
7350 Corpse *corpse = GetCorpse();
7351 if (!corpse)
7352 return;
7354 // We have to convert player corpse to bones, not to be able to resurrect there
7355 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7356 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7357 if (!bones)
7358 return;
7360 // Now we must make bones lootable, and send player loot
7361 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7363 // We store the level of our player in the gold field
7364 // We retrieve this information at Player::SendLoot()
7365 bones->loot.gold = getLevel();
7366 bones->lootRecipient = looterPlr;
7367 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7370 void Player::SendLootRelease( uint64 guid )
7372 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7373 data << uint64(guid) << uint8(1);
7374 SendDirectMessage( &data );
7377 void Player::SendLoot(uint64 guid, LootType loot_type)
7379 if (uint64 lguid = GetLootGUID())
7380 m_session->DoLootRelease(lguid);
7382 Loot *loot = 0;
7383 PermissionTypes permission = ALL_PERMISSION;
7385 sLog.outDebug("Player::SendLoot");
7386 if (IS_GAMEOBJECT_GUID(guid))
7388 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7389 GameObject *go = GetMap()->GetGameObject(guid);
7391 // not check distance for GO in case owned GO (fishing bobber case, for example)
7392 // And permit out of range GO with no owner in case fishing hole
7393 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7395 SendLootRelease(guid);
7396 return;
7399 loot = &go->loot;
7401 if (go->getLootState() == GO_READY)
7403 uint32 lootid = go->GetGOInfo()->GetLootId();
7405 if (lootid)
7407 sLog.outDebug(" if(lootid)");
7408 loot->clear();
7409 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7412 if (loot_type == LOOT_FISHING)
7413 go->getFishLoot(loot,this);
7415 go->SetLootState(GO_ACTIVATED);
7418 else if (IS_ITEM_GUID(guid))
7420 Item *item = GetItemByGuid( guid );
7422 if (!item)
7424 SendLootRelease(guid);
7425 return;
7428 loot = &item->loot;
7430 if (!item->m_lootGenerated)
7432 item->m_lootGenerated = true;
7433 loot->clear();
7435 switch(loot_type)
7437 case LOOT_DISENCHANTING:
7438 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7439 break;
7440 case LOOT_PROSPECTING:
7441 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7442 break;
7443 case LOOT_MILLING:
7444 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7445 break;
7446 default:
7447 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7448 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7449 break;
7453 else if (IS_CORPSE_GUID(guid)) // remove insignia
7455 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7457 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7459 SendLootRelease(guid);
7460 return;
7463 loot = &bones->loot;
7465 if (!bones->lootForBody)
7467 bones->lootForBody = true;
7468 uint32 pLevel = bones->loot.gold;
7469 bones->loot.clear();
7470 // It may need a better formula
7471 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7472 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7475 if (bones->lootRecipient != this)
7476 permission = NONE_PERMISSION;
7478 else
7480 Creature *creature = GetMap()->GetCreature(guid);
7482 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7483 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7485 SendLootRelease(guid);
7486 return;
7489 if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7491 SendLootRelease(guid);
7492 return;
7495 loot = &creature->loot;
7497 if (loot_type == LOOT_PICKPOCKETING)
7499 if (!creature->lootForPickPocketed)
7501 creature->lootForPickPocketed = true;
7502 loot->clear();
7504 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7505 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7507 // Generate extra money for pick pocket loot
7508 const uint32 a = urand(0, creature->getLevel()/2);
7509 const uint32 b = urand(0, getLevel()/2);
7510 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7513 else
7515 // the player whose group may loot the corpse
7516 Player *recipient = creature->GetLootRecipient();
7517 if (!recipient)
7519 creature->SetLootRecipient(this);
7520 recipient = this;
7523 if (creature->lootForPickPocketed)
7525 creature->lootForPickPocketed = false;
7526 loot->clear();
7529 if (!creature->lootForBody)
7531 creature->lootForBody = true;
7532 loot->clear();
7534 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7535 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7537 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7539 if (Group* group = recipient->GetGroup())
7541 group->UpdateLooterGuid(creature,true);
7543 switch (group->GetLootMethod())
7545 case GROUP_LOOT:
7546 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7547 group->GroupLoot(recipient->GetGUID(), loot, creature);
7548 break;
7549 case NEED_BEFORE_GREED:
7550 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7551 break;
7552 case MASTER_LOOT:
7553 group->MasterLoot(recipient->GetGUID(), loot, creature);
7554 break;
7555 default:
7556 break;
7561 // possible only if creature->lootForBody && loot->empty() at spell cast check
7562 if (loot_type == LOOT_SKINNING)
7564 loot->clear();
7565 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7567 // set group rights only for loot_type != LOOT_SKINNING
7568 else
7570 if(Group* group = GetGroup())
7572 if (group == recipient->GetGroup())
7574 if (group->GetLootMethod() == FREE_FOR_ALL)
7575 permission = ALL_PERMISSION;
7576 else if (group->GetLooterGuid() == GetGUID())
7578 if (group->GetLootMethod() == MASTER_LOOT)
7579 permission = MASTER_PERMISSION;
7580 else
7581 permission = ALL_PERMISSION;
7583 else
7584 permission = GROUP_PERMISSION;
7586 else
7587 permission = NONE_PERMISSION;
7589 else if (recipient == this)
7590 permission = ALL_PERMISSION;
7591 else
7592 permission = NONE_PERMISSION;
7597 SetLootGUID(guid);
7599 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7600 switch(loot_type)
7602 case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
7603 case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
7604 default: break;
7607 // need know merged fishing/corpse loot type for achievements
7608 loot->loot_type = loot_type;
7610 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7612 data << uint64(guid);
7613 data << uint8(loot_type);
7614 data << LootView(*loot, this, permission);
7616 SendDirectMessage(&data);
7618 // add 'this' player as one of the players that are looting 'loot'
7619 if (permission != NONE_PERMISSION)
7620 loot->AddLooter(GetGUID());
7622 if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
7623 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7626 void Player::SendNotifyLootMoneyRemoved()
7628 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7629 GetSession()->SendPacket( &data );
7632 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7634 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7635 data << uint8(lootSlot);
7636 GetSession()->SendPacket( &data );
7639 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7641 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7642 data << Field;
7643 data << Value;
7644 GetSession()->SendPacket(&data);
7647 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7649 // data depends on zoneid/mapid...
7650 BattleGround* bg = GetBattleGround();
7651 uint16 NumberOfFields = 0;
7652 uint32 mapid = GetMapId();
7654 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7656 // may be exist better way to do this...
7657 switch(zoneid)
7659 case 0:
7660 case 1:
7661 case 4:
7662 case 8:
7663 case 10:
7664 case 11:
7665 case 12:
7666 case 36:
7667 case 38:
7668 case 40:
7669 case 41:
7670 case 51:
7671 case 267:
7672 case 1519:
7673 case 1537:
7674 case 2257:
7675 case 2918:
7676 NumberOfFields = 8;
7677 break;
7678 case 139:
7679 NumberOfFields = 41;
7680 break;
7681 case 1377:
7682 NumberOfFields = 15;
7683 break;
7684 case 2597:
7685 NumberOfFields = 83;
7686 break;
7687 case 3277:
7688 NumberOfFields = 16;
7689 break;
7690 case 3358:
7691 case 3820:
7692 NumberOfFields = 40;
7693 break;
7694 case 3483:
7695 NumberOfFields = 27;
7696 break;
7697 case 3518:
7698 NumberOfFields = 39;
7699 break;
7700 case 3519:
7701 NumberOfFields = 38;
7702 break;
7703 case 3521:
7704 NumberOfFields = 37;
7705 break;
7706 case 3698:
7707 case 3702:
7708 case 3968:
7709 NumberOfFields = 11;
7710 break;
7711 case 3703:
7712 NumberOfFields = 11;
7713 break;
7714 default:
7715 NumberOfFields = 12;
7716 break;
7719 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7720 data << uint32(mapid); // mapid
7721 data << uint32(zoneid); // zone id
7722 data << uint32(areaid); // area id, new 2.1.0
7723 data << uint16(NumberOfFields); // count of uint64 blocks
7724 data << uint32(0x8d8) << uint32(0x0); // 1
7725 data << uint32(0x8d7) << uint32(0x0); // 2
7726 data << uint32(0x8d6) << uint32(0x0); // 3
7727 data << uint32(0x8d5) << uint32(0x0); // 4
7728 data << uint32(0x8d4) << uint32(0x0); // 5
7729 data << uint32(0x8d3) << uint32(0x0); // 6
7730 // 7 1 - Arena season in progress, 0 - end of season
7731 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7732 // 8 Arena season id
7733 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7734 if(mapid == 530) // Outland
7736 data << uint32(0x9bf) << uint32(0x0); // 7
7737 data << uint32(0x9bd) << uint32(0xF); // 8
7738 data << uint32(0x9bb) << uint32(0xF); // 9
7740 switch(zoneid)
7742 case 1:
7743 case 11:
7744 case 12:
7745 case 38:
7746 case 40:
7747 case 51:
7748 case 1519:
7749 case 1537:
7750 case 2257:
7751 break;
7752 case 2597: // AV
7753 data << uint32(0x7ae) << uint32(0x1); // 7
7754 data << uint32(0x532) << uint32(0x1); // 8
7755 data << uint32(0x531) << uint32(0x0); // 9
7756 data << uint32(0x52e) << uint32(0x0); // 10
7757 data << uint32(0x571) << uint32(0x0); // 11
7758 data << uint32(0x570) << uint32(0x0); // 12
7759 data << uint32(0x567) << uint32(0x1); // 13
7760 data << uint32(0x566) << uint32(0x1); // 14
7761 data << uint32(0x550) << uint32(0x1); // 15
7762 data << uint32(0x544) << uint32(0x0); // 16
7763 data << uint32(0x536) << uint32(0x0); // 17
7764 data << uint32(0x535) << uint32(0x1); // 18
7765 data << uint32(0x518) << uint32(0x0); // 19
7766 data << uint32(0x517) << uint32(0x0); // 20
7767 data << uint32(0x574) << uint32(0x0); // 21
7768 data << uint32(0x573) << uint32(0x0); // 22
7769 data << uint32(0x572) << uint32(0x0); // 23
7770 data << uint32(0x56f) << uint32(0x0); // 24
7771 data << uint32(0x56e) << uint32(0x0); // 25
7772 data << uint32(0x56d) << uint32(0x0); // 26
7773 data << uint32(0x56c) << uint32(0x0); // 27
7774 data << uint32(0x56b) << uint32(0x0); // 28
7775 data << uint32(0x56a) << uint32(0x1); // 29
7776 data << uint32(0x569) << uint32(0x1); // 30
7777 data << uint32(0x568) << uint32(0x1); // 13
7778 data << uint32(0x565) << uint32(0x0); // 32
7779 data << uint32(0x564) << uint32(0x0); // 33
7780 data << uint32(0x563) << uint32(0x0); // 34
7781 data << uint32(0x562) << uint32(0x0); // 35
7782 data << uint32(0x561) << uint32(0x0); // 36
7783 data << uint32(0x560) << uint32(0x0); // 37
7784 data << uint32(0x55f) << uint32(0x0); // 38
7785 data << uint32(0x55e) << uint32(0x0); // 39
7786 data << uint32(0x55d) << uint32(0x0); // 40
7787 data << uint32(0x3c6) << uint32(0x4); // 41
7788 data << uint32(0x3c4) << uint32(0x6); // 42
7789 data << uint32(0x3c2) << uint32(0x4); // 43
7790 data << uint32(0x516) << uint32(0x1); // 44
7791 data << uint32(0x515) << uint32(0x0); // 45
7792 data << uint32(0x3b6) << uint32(0x6); // 46
7793 data << uint32(0x55c) << uint32(0x0); // 47
7794 data << uint32(0x55b) << uint32(0x0); // 48
7795 data << uint32(0x55a) << uint32(0x0); // 49
7796 data << uint32(0x559) << uint32(0x0); // 50
7797 data << uint32(0x558) << uint32(0x0); // 51
7798 data << uint32(0x557) << uint32(0x0); // 52
7799 data << uint32(0x556) << uint32(0x0); // 53
7800 data << uint32(0x555) << uint32(0x0); // 54
7801 data << uint32(0x554) << uint32(0x1); // 55
7802 data << uint32(0x553) << uint32(0x1); // 56
7803 data << uint32(0x552) << uint32(0x1); // 57
7804 data << uint32(0x551) << uint32(0x1); // 58
7805 data << uint32(0x54f) << uint32(0x0); // 59
7806 data << uint32(0x54e) << uint32(0x0); // 60
7807 data << uint32(0x54d) << uint32(0x1); // 61
7808 data << uint32(0x54c) << uint32(0x0); // 62
7809 data << uint32(0x54b) << uint32(0x0); // 63
7810 data << uint32(0x545) << uint32(0x0); // 64
7811 data << uint32(0x543) << uint32(0x1); // 65
7812 data << uint32(0x542) << uint32(0x0); // 66
7813 data << uint32(0x540) << uint32(0x0); // 67
7814 data << uint32(0x53f) << uint32(0x0); // 68
7815 data << uint32(0x53e) << uint32(0x0); // 69
7816 data << uint32(0x53d) << uint32(0x0); // 70
7817 data << uint32(0x53c) << uint32(0x0); // 71
7818 data << uint32(0x53b) << uint32(0x0); // 72
7819 data << uint32(0x53a) << uint32(0x1); // 73
7820 data << uint32(0x539) << uint32(0x0); // 74
7821 data << uint32(0x538) << uint32(0x0); // 75
7822 data << uint32(0x537) << uint32(0x0); // 76
7823 data << uint32(0x534) << uint32(0x0); // 77
7824 data << uint32(0x533) << uint32(0x0); // 78
7825 data << uint32(0x530) << uint32(0x0); // 79
7826 data << uint32(0x52f) << uint32(0x0); // 80
7827 data << uint32(0x52d) << uint32(0x1); // 81
7828 break;
7829 case 3277: // WS
7830 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7831 bg->FillInitialWorldStates(data);
7832 else
7834 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7835 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7836 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7837 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7838 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7839 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7840 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7841 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7843 break;
7844 case 3358: // AB
7845 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7846 bg->FillInitialWorldStates(data);
7847 else
7849 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7850 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7851 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7852 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7853 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7854 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7855 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7856 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7857 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7858 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7859 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7860 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7861 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7862 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7863 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7864 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7865 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7866 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7867 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7868 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7869 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7870 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7871 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7872 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7873 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7874 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7875 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7876 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7877 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7878 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7879 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7880 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7882 break;
7883 case 3820: // EY
7884 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7885 bg->FillInitialWorldStates(data);
7886 else
7888 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7889 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7890 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7891 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7892 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7893 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7894 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7895 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7896 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7897 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7898 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7899 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7900 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7901 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7902 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7903 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7904 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7905 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7906 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7907 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7908 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7909 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7910 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7911 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7912 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7913 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7914 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7915 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7916 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7917 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7918 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7919 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7920 // and some more ... unknown
7922 break;
7923 case 3483: // Hellfire Peninsula
7924 data << uint32(0x9ba) << uint32(0x1); // 10
7925 data << uint32(0x9b9) << uint32(0x1); // 11
7926 data << uint32(0x9b5) << uint32(0x0); // 12
7927 data << uint32(0x9b4) << uint32(0x1); // 13
7928 data << uint32(0x9b3) << uint32(0x0); // 14
7929 data << uint32(0x9b2) << uint32(0x0); // 15
7930 data << uint32(0x9b1) << uint32(0x1); // 16
7931 data << uint32(0x9b0) << uint32(0x0); // 17
7932 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7933 data << uint32(0x9ac) << uint32(0x0); // 19
7934 data << uint32(0x9a8) << uint32(0x0); // 20
7935 data << uint32(0x9a7) << uint32(0x0); // 21
7936 data << uint32(0x9a6) << uint32(0x1); // 22
7937 break;
7938 case 3519: // Terokkar Forest
7939 data << uint32(0xa41) << uint32(0x0); // 10
7940 data << uint32(0xa40) << uint32(0x14); // 11
7941 data << uint32(0xa3f) << uint32(0x0); // 12
7942 data << uint32(0xa3e) << uint32(0x0); // 13
7943 data << uint32(0xa3d) << uint32(0x5); // 14
7944 data << uint32(0xa3c) << uint32(0x0); // 15
7945 data << uint32(0xa87) << uint32(0x0); // 16
7946 data << uint32(0xa86) << uint32(0x0); // 17
7947 data << uint32(0xa85) << uint32(0x0); // 18
7948 data << uint32(0xa84) << uint32(0x0); // 19
7949 data << uint32(0xa83) << uint32(0x0); // 20
7950 data << uint32(0xa82) << uint32(0x0); // 21
7951 data << uint32(0xa81) << uint32(0x0); // 22
7952 data << uint32(0xa80) << uint32(0x0); // 23
7953 data << uint32(0xa7e) << uint32(0x0); // 24
7954 data << uint32(0xa7d) << uint32(0x0); // 25
7955 data << uint32(0xa7c) << uint32(0x0); // 26
7956 data << uint32(0xa7b) << uint32(0x0); // 27
7957 data << uint32(0xa7a) << uint32(0x0); // 28
7958 data << uint32(0xa79) << uint32(0x0); // 29
7959 data << uint32(0x9d0) << uint32(0x5); // 30
7960 data << uint32(0x9ce) << uint32(0x0); // 31
7961 data << uint32(0x9cd) << uint32(0x0); // 32
7962 data << uint32(0x9cc) << uint32(0x0); // 33
7963 data << uint32(0xa88) << uint32(0x0); // 34
7964 data << uint32(0xad0) << uint32(0x0); // 35
7965 data << uint32(0xacf) << uint32(0x1); // 36
7966 break;
7967 case 3521: // Zangarmarsh
7968 data << uint32(0x9e1) << uint32(0x0); // 10
7969 data << uint32(0x9e0) << uint32(0x0); // 11
7970 data << uint32(0x9df) << uint32(0x0); // 12
7971 data << uint32(0xa5d) << uint32(0x1); // 13
7972 data << uint32(0xa5c) << uint32(0x0); // 14
7973 data << uint32(0xa5b) << uint32(0x1); // 15
7974 data << uint32(0xa5a) << uint32(0x0); // 16
7975 data << uint32(0xa59) << uint32(0x1); // 17
7976 data << uint32(0xa58) << uint32(0x0); // 18
7977 data << uint32(0xa57) << uint32(0x0); // 19
7978 data << uint32(0xa56) << uint32(0x0); // 20
7979 data << uint32(0xa55) << uint32(0x1); // 21
7980 data << uint32(0xa54) << uint32(0x0); // 22
7981 data << uint32(0x9e7) << uint32(0x0); // 23
7982 data << uint32(0x9e6) << uint32(0x0); // 24
7983 data << uint32(0x9e5) << uint32(0x0); // 25
7984 data << uint32(0xa00) << uint32(0x0); // 26
7985 data << uint32(0x9ff) << uint32(0x1); // 27
7986 data << uint32(0x9fe) << uint32(0x0); // 28
7987 data << uint32(0x9fd) << uint32(0x0); // 29
7988 data << uint32(0x9fc) << uint32(0x1); // 30
7989 data << uint32(0x9fb) << uint32(0x0); // 31
7990 data << uint32(0xa62) << uint32(0x0); // 32
7991 data << uint32(0xa61) << uint32(0x1); // 33
7992 data << uint32(0xa60) << uint32(0x1); // 34
7993 data << uint32(0xa5f) << uint32(0x0); // 35
7994 break;
7995 case 3698: // Nagrand Arena
7996 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
7997 bg->FillInitialWorldStates(data);
7998 else
8000 data << uint32(0xa0f) << uint32(0x0); // 7
8001 data << uint32(0xa10) << uint32(0x0); // 8
8002 data << uint32(0xa11) << uint32(0x0); // 9 show
8004 break;
8005 case 3702: // Blade's Edge Arena
8006 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
8007 bg->FillInitialWorldStates(data);
8008 else
8010 data << uint32(0x9f0) << uint32(0x0); // 7 gold
8011 data << uint32(0x9f1) << uint32(0x0); // 8 green
8012 data << uint32(0x9f3) << uint32(0x0); // 9 show
8014 break;
8015 case 3968: // Ruins of Lordaeron
8016 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
8017 bg->FillInitialWorldStates(data);
8018 else
8020 data << uint32(0xbb8) << uint32(0x0); // 7 gold
8021 data << uint32(0xbb9) << uint32(0x0); // 8 green
8022 data << uint32(0xbba) << uint32(0x0); // 9 show
8024 break;
8025 case 3703: // Shattrath City
8026 break;
8027 default:
8028 data << uint32(0x914) << uint32(0x0); // 7
8029 data << uint32(0x913) << uint32(0x0); // 8
8030 data << uint32(0x912) << uint32(0x0); // 9
8031 data << uint32(0x915) << uint32(0x0); // 10
8032 break;
8034 GetSession()->SendPacket(&data);
8037 uint32 Player::GetXPRestBonus(uint32 xp)
8039 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
8041 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
8042 rested_bonus = xp;
8044 SetRestBonus( GetRestBonus() - rested_bonus);
8046 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
8047 return rested_bonus;
8050 void Player::SetBindPoint(uint64 guid)
8052 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
8053 data << uint64(guid);
8054 GetSession()->SendPacket( &data );
8057 void Player::SendTalentWipeConfirm(uint64 guid)
8059 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
8060 data << uint64(guid);
8061 data << uint32(resetTalentsCost());
8062 GetSession()->SendPacket( &data );
8065 void Player::SendPetSkillWipeConfirm()
8067 Pet* pet = GetPet();
8068 if(!pet)
8069 return;
8070 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
8071 data << pet->GetGUID();
8072 data << uint32(pet->resetTalentsCost());
8073 GetSession()->SendPacket( &data );
8076 /*********************************************************/
8077 /*** STORAGE SYSTEM ***/
8078 /*********************************************************/
8080 void Player::SetVirtualItemSlot( uint8 i, Item* item)
8082 assert(i < 3);
8083 if(i < 2 && item)
8085 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
8086 return;
8087 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
8088 if(charges == 0)
8089 return;
8090 if(charges > 1)
8091 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
8092 else if(charges <= 1)
8094 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
8095 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
8100 void Player::SetSheath( SheathState sheathed )
8102 switch (sheathed)
8104 case SHEATH_STATE_UNARMED: // no prepared weapon
8105 SetVirtualItemSlot(0,NULL);
8106 SetVirtualItemSlot(1,NULL);
8107 SetVirtualItemSlot(2,NULL);
8108 break;
8109 case SHEATH_STATE_MELEE: // prepared melee weapon
8111 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
8112 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
8113 SetVirtualItemSlot(2,NULL);
8114 }; break;
8115 case SHEATH_STATE_RANGED: // prepared ranged weapon
8116 SetVirtualItemSlot(0,NULL);
8117 SetVirtualItemSlot(1,NULL);
8118 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
8119 break;
8120 default:
8121 SetVirtualItemSlot(0,NULL);
8122 SetVirtualItemSlot(1,NULL);
8123 SetVirtualItemSlot(2,NULL);
8124 break;
8126 Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
8129 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
8131 uint8 pClass = getClass();
8133 uint8 slots[4];
8134 slots[0] = NULL_SLOT;
8135 slots[1] = NULL_SLOT;
8136 slots[2] = NULL_SLOT;
8137 slots[3] = NULL_SLOT;
8138 switch( proto->InventoryType )
8140 case INVTYPE_HEAD:
8141 slots[0] = EQUIPMENT_SLOT_HEAD;
8142 break;
8143 case INVTYPE_NECK:
8144 slots[0] = EQUIPMENT_SLOT_NECK;
8145 break;
8146 case INVTYPE_SHOULDERS:
8147 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
8148 break;
8149 case INVTYPE_BODY:
8150 slots[0] = EQUIPMENT_SLOT_BODY;
8151 break;
8152 case INVTYPE_CHEST:
8153 slots[0] = EQUIPMENT_SLOT_CHEST;
8154 break;
8155 case INVTYPE_ROBE:
8156 slots[0] = EQUIPMENT_SLOT_CHEST;
8157 break;
8158 case INVTYPE_WAIST:
8159 slots[0] = EQUIPMENT_SLOT_WAIST;
8160 break;
8161 case INVTYPE_LEGS:
8162 slots[0] = EQUIPMENT_SLOT_LEGS;
8163 break;
8164 case INVTYPE_FEET:
8165 slots[0] = EQUIPMENT_SLOT_FEET;
8166 break;
8167 case INVTYPE_WRISTS:
8168 slots[0] = EQUIPMENT_SLOT_WRISTS;
8169 break;
8170 case INVTYPE_HANDS:
8171 slots[0] = EQUIPMENT_SLOT_HANDS;
8172 break;
8173 case INVTYPE_FINGER:
8174 slots[0] = EQUIPMENT_SLOT_FINGER1;
8175 slots[1] = EQUIPMENT_SLOT_FINGER2;
8176 break;
8177 case INVTYPE_TRINKET:
8178 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8179 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8180 break;
8181 case INVTYPE_CLOAK:
8182 slots[0] = EQUIPMENT_SLOT_BACK;
8183 break;
8184 case INVTYPE_WEAPON:
8186 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8188 // suggest offhand slot only if know dual wielding
8189 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8190 if(CanDualWield())
8191 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8192 break;
8194 case INVTYPE_SHIELD:
8195 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8196 break;
8197 case INVTYPE_RANGED:
8198 slots[0] = EQUIPMENT_SLOT_RANGED;
8199 break;
8200 case INVTYPE_2HWEAPON:
8201 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8202 if (CanDualWield() && CanTitanGrip())
8203 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8204 break;
8205 case INVTYPE_TABARD:
8206 slots[0] = EQUIPMENT_SLOT_TABARD;
8207 break;
8208 case INVTYPE_WEAPONMAINHAND:
8209 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8210 break;
8211 case INVTYPE_WEAPONOFFHAND:
8212 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8213 break;
8214 case INVTYPE_HOLDABLE:
8215 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8216 break;
8217 case INVTYPE_THROWN:
8218 slots[0] = EQUIPMENT_SLOT_RANGED;
8219 break;
8220 case INVTYPE_RANGEDRIGHT:
8221 slots[0] = EQUIPMENT_SLOT_RANGED;
8222 break;
8223 case INVTYPE_BAG:
8224 slots[0] = INVENTORY_SLOT_BAG_START + 0;
8225 slots[1] = INVENTORY_SLOT_BAG_START + 1;
8226 slots[2] = INVENTORY_SLOT_BAG_START + 2;
8227 slots[3] = INVENTORY_SLOT_BAG_START + 3;
8228 break;
8229 case INVTYPE_RELIC:
8231 switch(proto->SubClass)
8233 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8234 if (pClass == CLASS_PALADIN)
8235 slots[0] = EQUIPMENT_SLOT_RANGED;
8236 break;
8237 case ITEM_SUBCLASS_ARMOR_IDOL:
8238 if (pClass == CLASS_DRUID)
8239 slots[0] = EQUIPMENT_SLOT_RANGED;
8240 break;
8241 case ITEM_SUBCLASS_ARMOR_TOTEM:
8242 if (pClass == CLASS_SHAMAN)
8243 slots[0] = EQUIPMENT_SLOT_RANGED;
8244 break;
8245 case ITEM_SUBCLASS_ARMOR_MISC:
8246 if (pClass == CLASS_WARLOCK)
8247 slots[0] = EQUIPMENT_SLOT_RANGED;
8248 break;
8249 case ITEM_SUBCLASS_ARMOR_SIGIL:
8250 if (pClass == CLASS_DEATH_KNIGHT)
8251 slots[0] = EQUIPMENT_SLOT_RANGED;
8252 break;
8254 break;
8256 default :
8257 return NULL_SLOT;
8260 if( slot != NULL_SLOT )
8262 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8264 for (int i = 0; i < 4; ++i)
8266 if ( slots[i] == slot )
8267 return slot;
8271 else
8273 // search free slot at first
8274 for (int i = 0; i < 4; ++i)
8276 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8278 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8279 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8280 return slots[i];
8284 // if not found free and can swap return first appropriate from used
8285 for (int i = 0; i < 4; ++i)
8287 if ( slots[i] != NULL_SLOT && swap )
8288 return slots[i];
8292 // no free position
8293 return NULL_SLOT;
8296 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8298 Item *pItem;
8299 uint32 tempcount = 0;
8301 uint8 res = EQUIP_ERR_OK;
8303 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
8305 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8306 if( pItem && pItem->GetEntry() == item )
8308 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8309 if(ires==EQUIP_ERR_OK)
8311 tempcount += pItem->GetCount();
8312 if( tempcount >= count )
8313 return EQUIP_ERR_OK;
8315 else
8316 res = ires;
8319 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8321 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8322 if( pItem && pItem->GetEntry() == item )
8324 tempcount += pItem->GetCount();
8325 if( tempcount >= count )
8326 return EQUIP_ERR_OK;
8329 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8331 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8332 if( pItem && pItem->GetEntry() == item )
8334 tempcount += pItem->GetCount();
8335 if( tempcount >= count )
8336 return EQUIP_ERR_OK;
8339 Bag *pBag;
8340 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8342 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8343 if( pBag )
8345 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8347 pItem = GetItemByPos( i, j );
8348 if( pItem && pItem->GetEntry() == item )
8350 tempcount += pItem->GetCount();
8351 if( tempcount >= count )
8352 return EQUIP_ERR_OK;
8358 // not found req. item count and have unequippable items
8359 return res;
8362 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8364 uint32 count = 0;
8365 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8367 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8368 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8369 count += pItem->GetCount();
8371 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8373 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8374 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8375 count += pItem->GetCount();
8377 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8379 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8380 if( pBag )
8381 count += pBag->GetItemCount(item,skipItem);
8384 if(skipItem && skipItem->GetProto()->GemProperties)
8386 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8388 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8389 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8390 count += pItem->GetGemCountWithID(item);
8394 if(inBankAlso)
8396 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8398 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8399 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8400 count += pItem->GetCount();
8402 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8404 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8405 if( pBag )
8406 count += pBag->GetItemCount(item,skipItem);
8409 if(skipItem && skipItem->GetProto()->GemProperties)
8411 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8413 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8414 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8415 count += pItem->GetGemCountWithID(item);
8420 return count;
8423 Item* Player::GetItemByGuid( uint64 guid ) const
8425 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8427 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8428 if( pItem && pItem->GetGUID() == guid )
8429 return pItem;
8431 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8433 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8434 if( pItem && pItem->GetGUID() == guid )
8435 return pItem;
8438 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8440 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8441 if( pBag )
8443 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8445 Item* pItem = pBag->GetItemByPos( j );
8446 if( pItem && pItem->GetGUID() == guid )
8447 return pItem;
8451 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8453 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8454 if( pBag )
8456 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8458 Item* pItem = pBag->GetItemByPos( j );
8459 if( pItem && pItem->GetGUID() == guid )
8460 return pItem;
8465 return NULL;
8468 Item* Player::GetItemByPos( uint16 pos ) const
8470 uint8 bag = pos >> 8;
8471 uint8 slot = pos & 255;
8472 return GetItemByPos( bag, slot );
8475 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8477 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || (slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END )) )
8478 return m_items[slot];
8479 else if ((bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8480 || (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END) )
8482 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8483 if ( pBag )
8484 return pBag->GetItemByPos(slot);
8486 return NULL;
8489 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8491 uint16 slot;
8492 switch (attackType)
8494 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8495 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8496 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8497 default: return NULL;
8500 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8501 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8502 return NULL;
8504 if(!useable)
8505 return item;
8507 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8508 return NULL;
8510 return item;
8513 Item* Player::GetShield(bool useable) const
8515 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8516 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8517 return NULL;
8519 if(!useable)
8520 return item;
8522 if( item->IsBroken())
8523 return NULL;
8525 return item;
8528 uint32 Player::GetAttackBySlot( uint8 slot )
8530 switch(slot)
8532 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8533 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8534 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8535 default: return MAX_ATTACK;
8539 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8541 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8542 return true;
8543 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8544 return true;
8545 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8546 return true;
8547 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8548 return true;
8549 return false;
8552 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8554 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8555 return true;
8556 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8557 return true;
8558 return false;
8561 bool Player::IsBankPos( uint8 bag, uint8 slot )
8563 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8564 return true;
8565 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8566 return true;
8567 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8568 return true;
8569 return false;
8572 bool Player::IsBagPos( uint16 pos )
8574 uint8 bag = pos >> 8;
8575 uint8 slot = pos & 255;
8576 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8577 return true;
8578 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8579 return true;
8580 return false;
8583 bool Player::IsValidPos( uint8 bag, uint8 slot )
8585 // post selected
8586 if(bag == NULL_BAG)
8587 return true;
8589 if (bag == INVENTORY_SLOT_BAG_0)
8591 // any post selected
8592 if (slot == NULL_SLOT)
8593 return true;
8595 // equipment
8596 if (slot < EQUIPMENT_SLOT_END)
8597 return true;
8599 // bag equip slots
8600 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8601 return true;
8603 // backpack slots
8604 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8605 return true;
8607 // keyring slots
8608 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8609 return true;
8611 // bank main slots
8612 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8613 return true;
8615 // bank bag slots
8616 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8617 return true;
8619 return false;
8622 // bag content slots
8623 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8625 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8626 if(!pBag)
8627 return false;
8629 // any post selected
8630 if (slot == NULL_SLOT)
8631 return true;
8633 return slot < pBag->GetBagSize();
8636 // bank bag content slots
8637 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8639 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8640 if(!pBag)
8641 return false;
8643 // any post selected
8644 if (slot == NULL_SLOT)
8645 return true;
8647 return slot < pBag->GetBagSize();
8650 // where this?
8651 return false;
8655 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8657 uint32 tempcount = 0;
8658 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8660 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8661 if( pItem && pItem->GetEntry() == item )
8663 tempcount += pItem->GetCount();
8664 if( tempcount >= count )
8665 return true;
8668 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8670 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8671 if( pItem && pItem->GetEntry() == item )
8673 tempcount += pItem->GetCount();
8674 if( tempcount >= count )
8675 return true;
8678 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8680 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8682 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8684 Item* pItem = GetItemByPos( i, j );
8685 if( pItem && pItem->GetEntry() == item )
8687 tempcount += pItem->GetCount();
8688 if( tempcount >= count )
8689 return true;
8695 if(inBankAlso)
8697 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8699 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8700 if( pItem && pItem->GetEntry() == item )
8702 tempcount += pItem->GetCount();
8703 if( tempcount >= count )
8704 return true;
8707 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8709 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8711 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8713 Item* pItem = GetItemByPos( i, j );
8714 if( pItem && pItem->GetEntry() == item )
8716 tempcount += pItem->GetCount();
8717 if( tempcount >= count )
8718 return true;
8725 return false;
8728 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8730 uint32 tempcount = 0;
8731 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8733 if(i==int(except_slot))
8734 continue;
8736 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8737 if( pItem && pItem->GetEntry() == item)
8739 tempcount += pItem->GetCount();
8740 if( tempcount >= count )
8741 return true;
8745 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8746 if (pProto && pProto->GemProperties)
8748 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8750 if(i==int(except_slot))
8751 continue;
8753 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8754 if( pItem && pItem->GetProto()->Socket[0].Color)
8756 tempcount += pItem->GetGemCountWithID(item);
8757 if( tempcount >= count )
8758 return true;
8763 return false;
8766 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8768 uint32 tempcount = 0;
8769 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8771 if(i==int(except_slot))
8772 continue;
8774 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8775 if (!pItem)
8776 continue;
8778 ItemPrototype const *pProto = pItem->GetProto();
8779 if (!pProto)
8780 continue;
8782 if (pProto->ItemLimitCategory == limitCategory)
8784 tempcount += pItem->GetCount();
8785 if( tempcount >= count )
8786 return true;
8789 if( pProto->Socket[0].Color)
8791 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8792 if( tempcount >= count )
8793 return true;
8797 return false;
8800 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8802 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8803 if( !pProto )
8805 if(no_space_count)
8806 *no_space_count = count;
8807 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8810 // no maximum
8811 if(pProto->MaxCount <= 0)
8812 return EQUIP_ERR_OK;
8814 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8816 if (curcount + count > uint32(pProto->MaxCount))
8818 if(no_space_count)
8819 *no_space_count = count +curcount - pProto->MaxCount;
8820 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8823 return EQUIP_ERR_OK;
8826 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8828 Item *pItem;
8829 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8831 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8832 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8833 return true;
8835 for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8837 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8838 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8839 return true;
8841 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8843 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8845 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8847 pItem = GetItemByPos( i, j );
8848 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8849 return true;
8853 return false;
8856 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8858 Item* pItem2 = GetItemByPos( bag, slot );
8860 // ignore move item (this slot will be empty at move)
8861 if (pItem2==pSrcItem)
8862 pItem2 = NULL;
8864 uint32 need_space;
8866 // empty specific slot - check item fit to slot
8867 if (!pItem2 || swap)
8869 if (bag == INVENTORY_SLOT_BAG_0)
8871 // keyring case
8872 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8873 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8875 // currencytoken case
8876 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8877 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8879 // prevent cheating
8880 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8881 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8883 else
8885 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8886 if (!pBag)
8887 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8889 ItemPrototype const* pBagProto = pBag->GetProto();
8890 if (!pBagProto)
8891 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8893 if (slot >= pBagProto->ContainerSlots)
8894 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8896 if (!ItemCanGoIntoBag(pProto,pBagProto))
8897 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8900 // non empty stack with space
8901 need_space = pProto->GetMaxStackSize();
8903 // non empty slot, check item type
8904 else
8906 // check item type
8907 if (pItem2->GetEntry() != pProto->ItemId)
8908 return EQUIP_ERR_ITEM_CANT_STACK;
8910 // check free space
8911 if (pItem2->GetCount() >= pProto->GetMaxStackSize())
8912 return EQUIP_ERR_ITEM_CANT_STACK;
8914 // free stack space or infinity
8915 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8918 if (need_space > count)
8919 need_space = count;
8921 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8922 if (!newPosition.isContainedIn(dest))
8924 dest.push_back(newPosition);
8925 count -= need_space;
8927 return EQUIP_ERR_OK;
8930 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
8932 // skip specific bag already processed in first called _CanStoreItem_InBag
8933 if (bag==skip_bag)
8934 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8936 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8937 if (!pBag)
8938 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8940 ItemPrototype const* pBagProto = pBag->GetProto();
8941 if (!pBagProto)
8942 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8944 // specialized bag mode or non-specilized
8945 if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER))
8946 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8948 if (!ItemCanGoIntoBag(pProto,pBagProto))
8949 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8951 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8953 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8954 if (j==skip_slot)
8955 continue;
8957 Item* pItem2 = GetItemByPos( bag, j );
8959 // ignore move item (this slot will be empty at move)
8960 if (pItem2==pSrcItem)
8961 pItem2 = NULL;
8963 // if merge skip empty, if !merge skip non-empty
8964 if ((pItem2!=NULL)!=merge)
8965 continue;
8967 if (pItem2)
8969 if (pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8971 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8972 if(need_space > count)
8973 need_space = count;
8975 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8976 if (!newPosition.isContainedIn(dest))
8978 dest.push_back(newPosition);
8979 count -= need_space;
8981 if (count==0)
8982 return EQUIP_ERR_OK;
8986 else
8988 uint32 need_space = pProto->GetMaxStackSize();
8989 if (need_space > count)
8990 need_space = count;
8992 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8993 if (!newPosition.isContainedIn(dest))
8995 dest.push_back(newPosition);
8996 count -= need_space;
8998 if (count==0)
8999 return EQUIP_ERR_OK;
9003 return EQUIP_ERR_OK;
9006 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
9008 for(uint32 j = slot_begin; j < slot_end; ++j)
9010 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9011 if (INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
9012 continue;
9014 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
9016 // ignore move item (this slot will be empty at move)
9017 if (pItem2==pSrcItem)
9018 pItem2 = NULL;
9020 // if merge skip empty, if !merge skip non-empty
9021 if ((pItem2!=NULL)!=merge)
9022 continue;
9024 if (pItem2)
9026 if (pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
9028 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9029 if (need_space > count)
9030 need_space = count;
9031 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9032 if (!newPosition.isContainedIn(dest))
9034 dest.push_back(newPosition);
9035 count -= need_space;
9037 if (count==0)
9038 return EQUIP_ERR_OK;
9042 else
9044 uint32 need_space = pProto->GetMaxStackSize();
9045 if (need_space > count)
9046 need_space = count;
9048 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9049 if (!newPosition.isContainedIn(dest))
9051 dest.push_back(newPosition);
9052 count -= need_space;
9054 if (count==0)
9055 return EQUIP_ERR_OK;
9059 return EQUIP_ERR_OK;
9062 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
9064 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
9066 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
9067 if (!pProto)
9069 if (no_space_count)
9070 *no_space_count = count;
9071 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
9074 if (pItem && pItem->IsBindedNotWith(this))
9076 if (no_space_count)
9077 *no_space_count = count;
9078 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9081 // check count of items (skip for auto move for same player from bank)
9082 uint32 no_similar_count = 0; // can't store this amount similar items
9083 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
9084 if (res!=EQUIP_ERR_OK)
9086 if (count==no_similar_count)
9088 if (no_space_count)
9089 *no_space_count = no_similar_count;
9090 return res;
9092 count -= no_similar_count;
9095 // in specific slot
9096 if (bag != NULL_BAG && slot != NULL_SLOT)
9098 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9099 if (res!=EQUIP_ERR_OK)
9101 if (no_space_count)
9102 *no_space_count = count + no_similar_count;
9103 return res;
9106 if (count==0)
9108 if (no_similar_count==0)
9109 return EQUIP_ERR_OK;
9111 if (no_space_count)
9112 *no_space_count = count + no_similar_count;
9113 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9117 // not specific slot or have space for partly store only in specific slot
9119 // in specific bag
9120 if (bag != NULL_BAG)
9122 // search stack in bag for merge to
9123 if (pProto->Stackable != 1)
9125 if (bag == INVENTORY_SLOT_BAG_0) // inventory
9127 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9128 if (res!=EQUIP_ERR_OK)
9130 if (no_space_count)
9131 *no_space_count = count + no_similar_count;
9132 return res;
9135 if (count==0)
9137 if (no_similar_count==0)
9138 return EQUIP_ERR_OK;
9140 if (no_space_count)
9141 *no_space_count = count + no_similar_count;
9142 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9145 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9146 if (res!=EQUIP_ERR_OK)
9148 if (no_space_count)
9149 *no_space_count = count + no_similar_count;
9150 return res;
9153 if (count==0)
9155 if (no_similar_count==0)
9156 return EQUIP_ERR_OK;
9158 if (no_space_count)
9159 *no_space_count = count + no_similar_count;
9160 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9163 else // equipped bag
9165 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9166 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9167 if (res!=EQUIP_ERR_OK)
9168 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9170 if (res!=EQUIP_ERR_OK)
9172 if (no_space_count)
9173 *no_space_count = count + no_similar_count;
9174 return res;
9177 if (count==0)
9179 if (no_similar_count==0)
9180 return EQUIP_ERR_OK;
9182 if (no_space_count)
9183 *no_space_count = count + no_similar_count;
9184 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9189 // search free slot in bag for place to
9190 if(bag == INVENTORY_SLOT_BAG_0) // inventory
9192 // search free slot - keyring case
9193 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9195 uint32 keyringSize = GetMaxKeyringSize();
9196 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9197 if (res!=EQUIP_ERR_OK)
9199 if (no_space_count)
9200 *no_space_count = count + no_similar_count;
9201 return res;
9204 if (count==0)
9206 if (no_similar_count==0)
9207 return EQUIP_ERR_OK;
9209 if (no_space_count)
9210 *no_space_count = count + no_similar_count;
9211 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9214 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9215 if (res!=EQUIP_ERR_OK)
9217 if (no_space_count)
9218 *no_space_count = count + no_similar_count;
9219 return res;
9222 if (count==0)
9224 if (no_similar_count==0)
9225 return EQUIP_ERR_OK;
9227 if (no_space_count)
9228 *no_space_count = count + no_similar_count;
9229 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9232 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9234 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9235 if (res!=EQUIP_ERR_OK)
9237 if (no_space_count)
9238 *no_space_count = count + no_similar_count;
9239 return res;
9242 if (count==0)
9244 if (no_similar_count==0)
9245 return EQUIP_ERR_OK;
9247 if (no_space_count)
9248 *no_space_count = count + no_similar_count;
9249 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9253 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9254 if (res!=EQUIP_ERR_OK)
9256 if (no_space_count)
9257 *no_space_count = count + no_similar_count;
9258 return res;
9261 if (count==0)
9263 if (no_similar_count==0)
9264 return EQUIP_ERR_OK;
9266 if (no_space_count)
9267 *no_space_count = count + no_similar_count;
9268 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9271 else // equipped bag
9273 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9274 if (res!=EQUIP_ERR_OK)
9275 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9277 if (res!=EQUIP_ERR_OK)
9279 if (no_space_count)
9280 *no_space_count = count + no_similar_count;
9281 return res;
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;
9296 // not specific bag or have space for partly store only in specific bag
9298 // search stack for merge to
9299 if (pProto->Stackable != 1)
9301 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9302 if (res!=EQUIP_ERR_OK)
9304 if (no_space_count)
9305 *no_space_count = count + no_similar_count;
9306 return res;
9309 if (count==0)
9311 if (no_similar_count==0)
9312 return EQUIP_ERR_OK;
9314 if (no_space_count)
9315 *no_space_count = count + no_similar_count;
9316 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9319 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9320 if (res!=EQUIP_ERR_OK)
9322 if (no_space_count)
9323 *no_space_count = count + no_similar_count;
9324 return res;
9327 if (count==0)
9329 if (no_similar_count==0)
9330 return EQUIP_ERR_OK;
9332 if (no_space_count)
9333 *no_space_count = count + no_similar_count;
9334 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9337 if (pProto->BagFamily)
9339 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9341 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9342 if (res!=EQUIP_ERR_OK)
9343 continue;
9345 if (count==0)
9347 if (no_similar_count==0)
9348 return EQUIP_ERR_OK;
9350 if (no_space_count)
9351 *no_space_count = count + no_similar_count;
9352 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9357 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9359 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9360 if (res!=EQUIP_ERR_OK)
9361 continue;
9363 if (count==0)
9365 if (no_similar_count==0)
9366 return EQUIP_ERR_OK;
9368 if (no_space_count)
9369 *no_space_count = count + no_similar_count;
9370 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9375 // search free slot - special bag case
9376 if (pProto->BagFamily)
9378 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9380 uint32 keyringSize = GetMaxKeyringSize();
9381 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9382 if (res!=EQUIP_ERR_OK)
9384 if (no_space_count)
9385 *no_space_count = count + no_similar_count;
9386 return res;
9389 if (count==0)
9391 if (no_similar_count==0)
9392 return EQUIP_ERR_OK;
9394 if (no_space_count)
9395 *no_space_count = count + no_similar_count;
9396 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9399 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9401 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9402 if (res!=EQUIP_ERR_OK)
9404 if (no_space_count)
9405 *no_space_count = count + no_similar_count;
9406 return res;
9409 if (count==0)
9411 if (no_similar_count==0)
9412 return EQUIP_ERR_OK;
9414 if (no_space_count)
9415 *no_space_count = count + no_similar_count;
9416 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9420 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9422 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9423 if (res!=EQUIP_ERR_OK)
9424 continue;
9426 if (count==0)
9428 if (no_similar_count==0)
9429 return EQUIP_ERR_OK;
9431 if (no_space_count)
9432 *no_space_count = count + no_similar_count;
9433 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9438 // search free slot
9439 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9440 if (res!=EQUIP_ERR_OK)
9442 if (no_space_count)
9443 *no_space_count = count + no_similar_count;
9444 return res;
9447 if (count==0)
9449 if (no_similar_count==0)
9450 return EQUIP_ERR_OK;
9452 if (no_space_count)
9453 *no_space_count = count + no_similar_count;
9454 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9457 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9459 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9460 if (res!=EQUIP_ERR_OK)
9461 continue;
9463 if (count==0)
9465 if (no_similar_count==0)
9466 return EQUIP_ERR_OK;
9468 if (no_space_count)
9469 *no_space_count = count + no_similar_count;
9470 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9474 if (no_space_count)
9475 *no_space_count = count + no_similar_count;
9477 return EQUIP_ERR_INVENTORY_FULL;
9480 //////////////////////////////////////////////////////////////////////////
9481 uint8 Player::CanStoreItems( Item **pItems,int count) const
9483 Item *pItem2;
9485 // fill space table
9486 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9487 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9488 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9489 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9491 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9492 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9493 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9494 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9496 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9498 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9500 if (pItem2 && !pItem2->IsInTrade())
9502 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9506 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
9508 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9510 if (pItem2 && !pItem2->IsInTrade())
9512 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9516 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9518 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9520 if (pItem2 && !pItem2->IsInTrade())
9522 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9526 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9528 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9530 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9532 pItem2 = GetItemByPos( i, j );
9533 if (pItem2 && !pItem2->IsInTrade())
9535 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9541 // check free space for all items
9542 for (int k = 0; k < count; ++k)
9544 Item *pItem = pItems[k];
9546 // no item
9547 if (!pItem) continue;
9549 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9550 ItemPrototype const *pProto = pItem->GetProto();
9552 // strange item
9553 if( !pProto )
9554 return EQUIP_ERR_ITEM_NOT_FOUND;
9556 // item it 'bind'
9557 if(pItem->IsBindedNotWith(this))
9558 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9560 Bag *pBag;
9561 ItemPrototype const *pBagProto;
9563 // item is 'one item only'
9564 uint8 res = CanTakeMoreSimilarItems(pItem);
9565 if(res != EQUIP_ERR_OK)
9566 return res;
9568 // search stack for merge to
9569 if( pProto->Stackable != 1 )
9571 bool b_found = false;
9573 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
9575 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9576 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9578 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9579 b_found = true;
9580 break;
9583 if (b_found) continue;
9585 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9587 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9588 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9590 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9591 b_found = true;
9592 break;
9595 if (b_found) continue;
9597 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9599 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9600 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9602 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9603 b_found = true;
9604 break;
9607 if (b_found) continue;
9609 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9611 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9612 if( pBag )
9614 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9616 pItem2 = GetItemByPos( t, j );
9617 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9619 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9620 b_found = true;
9621 break;
9626 if (b_found) continue;
9629 // special bag case
9630 if( pProto->BagFamily )
9632 bool b_found = false;
9633 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9635 uint32 keyringSize = GetMaxKeyringSize();
9636 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9638 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9640 inv_keys[t-KEYRING_SLOT_START] = 1;
9641 b_found = true;
9642 break;
9647 if (b_found) continue;
9649 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9651 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9653 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9655 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9656 b_found = true;
9657 break;
9662 if (b_found) continue;
9664 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9666 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9667 if( pBag )
9669 pBagProto = pBag->GetProto();
9671 // not plain container check
9672 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9673 ItemCanGoIntoBag(pProto,pBagProto) )
9675 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9677 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9679 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9680 b_found = true;
9681 break;
9687 if (b_found) continue;
9690 // search free slot
9691 bool b_found = false;
9692 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9694 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9696 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9697 b_found = true;
9698 break;
9701 if (b_found) continue;
9703 // search free slot in bags
9704 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9706 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9707 if( pBag )
9709 pBagProto = pBag->GetProto();
9711 // special bag already checked
9712 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9713 continue;
9715 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9717 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9719 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9720 b_found = true;
9721 break;
9727 // no free slot found?
9728 if (!b_found)
9729 return EQUIP_ERR_INVENTORY_FULL;
9732 return EQUIP_ERR_OK;
9735 //////////////////////////////////////////////////////////////////////////
9736 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9738 dest = 0;
9739 Item *pItem = Item::CreateItem( item, 1, this );
9740 if( pItem )
9742 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9743 delete pItem;
9744 return result;
9747 return EQUIP_ERR_ITEM_NOT_FOUND;
9750 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9752 dest = 0;
9753 if( pItem )
9755 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9756 ItemPrototype const *pProto = pItem->GetProto();
9757 if( pProto )
9759 if(pItem->IsBindedNotWith(this))
9760 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9762 // check count of items (skip for auto move for same player from bank)
9763 uint8 res = CanTakeMoreSimilarItems(pItem);
9764 if(res != EQUIP_ERR_OK)
9765 return res;
9767 // check this only in game
9768 if(not_loading)
9770 // May be here should be more stronger checks; STUNNED checked
9771 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9772 if (hasUnitState(UNIT_STAT_STUNNED))
9773 return EQUIP_ERR_YOU_ARE_STUNNED;
9775 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9776 // - combat
9777 // - in-progress arenas
9778 if( !pProto->CanChangeEquipStateInCombat() )
9780 if( isInCombat() )
9781 return EQUIP_ERR_NOT_IN_COMBAT;
9783 if(BattleGround* bg = GetBattleGround())
9784 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9785 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9788 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9789 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9791 if(IsNonMeleeSpellCasted(false))
9792 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9795 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0;
9796 // check allowed level (extend range to upper values if MaxLevel more or equal max player level, this let GM set high level with 1...max range items)
9797 if (ssd && ssd->MaxLevel < DEFAULT_MAX_LEVEL && ssd->MaxLevel < getLevel())
9798 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9800 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9801 if (eslot == NULL_SLOT)
9802 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9804 uint8 msg = CanUseItem(pItem , not_loading);
9805 if (msg != EQUIP_ERR_OK)
9806 return msg;
9807 if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
9808 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9810 // if swap ignore item (equipped also)
9811 if (uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9812 return res2;
9814 // check unique-equipped special item classes
9815 if (pProto->Class == ITEM_CLASS_QUIVER)
9817 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9819 if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
9821 if (pBag != pItem)
9823 if (ItemPrototype const* pBagProto = pBag->GetProto())
9825 if (pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot))
9826 return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9827 ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
9828 : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9835 uint32 type = pProto->InventoryType;
9837 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9839 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9841 if (!CanDualWield())
9842 return EQUIP_ERR_CANT_DUAL_WIELD;
9844 else if (type == INVTYPE_2HWEAPON)
9846 if (!CanDualWield() || !CanTitanGrip())
9847 return EQUIP_ERR_CANT_DUAL_WIELD;
9850 if (IsTwoHandUsed())
9851 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9854 // equip two-hand weapon case (with possible unequip 2 items)
9855 if (type == INVTYPE_2HWEAPON)
9857 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9859 if (!CanTitanGrip())
9860 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9862 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9863 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9865 if (!CanTitanGrip())
9867 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9868 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9869 ItemPosCountVec off_dest;
9870 if (offItem && (!not_loading ||
9871 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9872 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ))
9873 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9876 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9877 return EQUIP_ERR_OK;
9881 return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9884 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9886 // Applied only to equipped items and bank bags
9887 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9888 return EQUIP_ERR_OK;
9890 Item* pItem = GetItemByPos(pos);
9892 // Applied only to existed equipped item
9893 if( !pItem )
9894 return EQUIP_ERR_OK;
9896 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9898 ItemPrototype const *pProto = pItem->GetProto();
9899 if( !pProto )
9900 return EQUIP_ERR_ITEM_NOT_FOUND;
9902 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9903 // - combat
9904 // - in-progress arenas
9905 if( !pProto->CanChangeEquipStateInCombat() )
9907 if( isInCombat() )
9908 return EQUIP_ERR_NOT_IN_COMBAT;
9910 if(BattleGround* bg = GetBattleGround())
9911 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9912 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9915 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9916 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9918 return EQUIP_ERR_OK;
9921 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9923 if (!pItem)
9924 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9926 uint32 count = pItem->GetCount();
9928 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9929 ItemPrototype const *pProto = pItem->GetProto();
9930 if (!pProto)
9931 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9933 if (pItem->IsBindedNotWith(this))
9934 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9936 // check count of items (skip for auto move for same player from bank)
9937 uint8 res = CanTakeMoreSimilarItems(pItem);
9938 if (res != EQUIP_ERR_OK)
9939 return res;
9941 // in specific slot
9942 if (bag != NULL_BAG && slot != NULL_SLOT)
9944 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
9946 if (!pItem->IsBag())
9947 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9949 if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
9950 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9952 if (uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK)
9953 return cantuse;
9956 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9957 if (res!=EQUIP_ERR_OK)
9958 return res;
9960 if (count==0)
9961 return EQUIP_ERR_OK;
9964 // not specific slot or have space for partly store only in specific slot
9966 // in specific bag
9967 if( bag != NULL_BAG )
9969 if( pProto->InventoryType == INVTYPE_BAG )
9971 Bag *pBag = (Bag*)pItem;
9972 if( pBag && !pBag->IsEmpty() )
9973 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9976 // search stack in bag for merge to
9977 if( pProto->Stackable != 1 )
9979 if( bag == INVENTORY_SLOT_BAG_0 )
9981 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9982 if(res!=EQUIP_ERR_OK)
9983 return res;
9985 if(count==0)
9986 return EQUIP_ERR_OK;
9988 else
9990 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9991 if(res!=EQUIP_ERR_OK)
9992 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9994 if(res!=EQUIP_ERR_OK)
9995 return res;
9997 if(count==0)
9998 return EQUIP_ERR_OK;
10002 // search free slot in bag
10003 if( bag == INVENTORY_SLOT_BAG_0 )
10005 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10006 if(res!=EQUIP_ERR_OK)
10007 return res;
10009 if(count==0)
10010 return EQUIP_ERR_OK;
10012 else
10014 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
10015 if(res != EQUIP_ERR_OK)
10016 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
10018 if(res != EQUIP_ERR_OK)
10019 return res;
10021 if(count == 0)
10022 return EQUIP_ERR_OK;
10026 // not specific bag or have space for partly store only in specific bag
10028 // search stack for merge to
10029 if( pProto->Stackable != 1 )
10031 // in slots
10032 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10033 if(res != EQUIP_ERR_OK)
10034 return res;
10036 if(count == 0)
10037 return EQUIP_ERR_OK;
10039 // in special bags
10040 if( pProto->BagFamily )
10042 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10044 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
10045 if(res!=EQUIP_ERR_OK)
10046 continue;
10048 if(count==0)
10049 return EQUIP_ERR_OK;
10053 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10055 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
10056 if(res!=EQUIP_ERR_OK)
10057 continue;
10059 if(count==0)
10060 return EQUIP_ERR_OK;
10064 // search free place in special bag
10065 if( pProto->BagFamily )
10067 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10069 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
10070 if(res!=EQUIP_ERR_OK)
10071 continue;
10073 if(count==0)
10074 return EQUIP_ERR_OK;
10078 // search free space
10079 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10080 if(res!=EQUIP_ERR_OK)
10081 return res;
10083 if(count==0)
10084 return EQUIP_ERR_OK;
10086 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10088 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
10089 if(res!=EQUIP_ERR_OK)
10090 continue;
10092 if(count==0)
10093 return EQUIP_ERR_OK;
10095 return EQUIP_ERR_BANK_FULL;
10098 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
10100 if (pItem)
10102 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
10104 if (!isAlive() && not_loading)
10105 return EQUIP_ERR_YOU_ARE_DEAD;
10107 //if (isStunned())
10108 // return EQUIP_ERR_YOU_ARE_STUNNED;
10110 ItemPrototype const *pProto = pItem->GetProto();
10111 if (pProto)
10113 if (pItem->IsBindedNotWith(this))
10114 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10116 if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0)
10117 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10119 if (pItem->GetSkill() != 0)
10121 if (GetSkillValue( pItem->GetSkill() ) == 0)
10122 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10125 if (pProto->RequiredSkill != 0)
10127 if (GetSkillValue( pProto->RequiredSkill ) == 0)
10128 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10130 if (GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank)
10131 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10134 if (pProto->RequiredSpell != 0 && !HasSpell(pProto->RequiredSpell))
10135 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10137 if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
10138 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10140 if (getLevel() < pProto->RequiredLevel)
10141 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10143 return EQUIP_ERR_OK;
10146 return EQUIP_ERR_ITEM_NOT_FOUND;
10149 bool Player::CanUseItem( ItemPrototype const *pProto )
10151 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10153 if( pProto )
10155 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10156 return false;
10157 if( pProto->RequiredSkill != 0 )
10159 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10160 return false;
10161 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10162 return false;
10164 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10165 return false;
10166 if( getLevel() < pProto->RequiredLevel )
10167 return false;
10168 return true;
10170 return false;
10173 uint8 Player::CanUseAmmo( uint32 item ) const
10175 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10176 if( !isAlive() )
10177 return EQUIP_ERR_YOU_ARE_DEAD;
10178 //if( isStunned() )
10179 // return EQUIP_ERR_YOU_ARE_STUNNED;
10180 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
10181 if( pProto )
10183 if( pProto->InventoryType!= INVTYPE_AMMO )
10184 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10185 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10186 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10187 if( pProto->RequiredSkill != 0 )
10189 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10190 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10191 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10192 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10194 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10195 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10196 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
10197 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10199 if( getLevel() < pProto->RequiredLevel )
10200 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10202 // Requires No Ammo
10203 if(GetDummyAura(46699))
10204 return EQUIP_ERR_BAG_FULL6;
10206 return EQUIP_ERR_OK;
10208 return EQUIP_ERR_ITEM_NOT_FOUND;
10211 void Player::SetAmmo( uint32 item )
10213 if(!item)
10214 return;
10216 // already set
10217 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10218 return;
10220 // check ammo
10221 if(item)
10223 uint8 msg = CanUseAmmo( item );
10224 if( msg != EQUIP_ERR_OK )
10226 SendEquipError( msg, NULL, NULL );
10227 return;
10231 SetUInt32Value(PLAYER_AMMO_ID, item);
10233 _ApplyAmmoBonuses();
10236 void Player::RemoveAmmo()
10238 SetUInt32Value(PLAYER_AMMO_ID, 0);
10240 m_ammoDPS = 0.0f;
10242 if(CanModifyStats())
10243 UpdateDamagePhysical(RANGED_ATTACK);
10246 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10247 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10249 uint32 count = 0;
10250 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10251 count += itr->count;
10253 Item *pItem = Item::CreateItem( item, count, this );
10254 if( pItem )
10256 ItemAddedQuestCheck( item, count );
10257 if(randomPropertyId)
10258 pItem->SetItemRandomProperties(randomPropertyId);
10259 pItem = StoreItem( dest, pItem, update );
10261 return pItem;
10264 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10266 if( !pItem )
10267 return NULL;
10269 Item* lastItem = pItem;
10270 uint32 entry = pItem->GetEntry();
10271 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10273 uint16 pos = itr->pos;
10274 uint32 count = itr->count;
10276 ++itr;
10278 if(itr == dest.end())
10280 lastItem = _StoreItem(pos,pItem,count,false,update);
10281 break;
10284 lastItem = _StoreItem(pos,pItem,count,true,update);
10286 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
10287 return lastItem;
10290 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10291 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10293 if( !pItem )
10294 return NULL;
10296 uint8 bag = pos >> 8;
10297 uint8 slot = pos & 255;
10299 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10301 Item *pItem2 = GetItemByPos( bag, slot );
10303 if (!pItem2)
10305 if (clone)
10306 pItem = pItem->CloneItem(count, this);
10307 else
10308 pItem->SetCount(count);
10310 if (!pItem)
10311 return NULL;
10313 if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10314 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10315 (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10316 pItem->SetBinding( true );
10318 if (bag == INVENTORY_SLOT_BAG_0)
10320 m_items[slot] = pItem;
10321 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10322 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10323 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10325 pItem->SetSlot( slot );
10326 pItem->SetContainer( NULL );
10328 // need update known currency
10329 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10330 UpdateKnownCurrencies(pItem->GetEntry(), true);
10332 if (IsInWorld() && update)
10334 pItem->AddToWorld();
10335 pItem->SendUpdateToPlayer( this );
10338 pItem->SetState(ITEM_CHANGED, this);
10340 else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10342 pBag->StoreItem( slot, pItem, update );
10343 if( IsInWorld() && update )
10345 pItem->AddToWorld();
10346 pItem->SendUpdateToPlayer( this );
10348 pItem->SetState(ITEM_CHANGED, this);
10349 pBag->SetState(ITEM_CHANGED, this);
10352 AddEnchantmentDurations(pItem);
10353 AddItemDurations(pItem);
10355 return pItem;
10357 else
10359 if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10360 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10361 (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10362 pItem2->SetBinding( true );
10364 pItem2->SetCount( pItem2->GetCount() + count );
10365 if (IsInWorld() && update)
10366 pItem2->SendUpdateToPlayer( this );
10368 if (!clone)
10370 // delete item (it not in any slot currently)
10371 if (IsInWorld() && update)
10373 pItem->RemoveFromWorld();
10374 pItem->DestroyForPlayer( this );
10377 RemoveEnchantmentDurations(pItem);
10378 RemoveItemDurations(pItem);
10380 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10381 pItem->SetState(ITEM_REMOVED, this);
10384 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10385 AddEnchantmentDurations(pItem2);
10387 pItem2->SetState(ITEM_CHANGED, this);
10389 return pItem2;
10393 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10395 if (Item *pItem = Item::CreateItem( item, 1, this ))
10397 ItemAddedQuestCheck( item, 1 );
10398 return EquipItem( pos, pItem, update );
10401 return NULL;
10404 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10406 AddEnchantmentDurations(pItem);
10407 AddItemDurations(pItem);
10409 uint8 bag = pos >> 8;
10410 uint8 slot = pos & 255;
10412 Item *pItem2 = GetItemByPos( bag, slot );
10414 if( !pItem2 )
10416 VisualizeItem( slot, pItem);
10418 if(isAlive())
10420 ItemPrototype const *pProto = pItem->GetProto();
10422 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10423 if(pProto && pProto->ItemSet)
10424 AddItemsSetItem(this, pItem);
10426 _ApplyItemMods(pItem, slot, true);
10428 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10430 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10432 if (getClass() == CLASS_ROGUE)
10433 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10435 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10437 if (!spellProto)
10438 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10439 else
10441 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10443 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10444 data << uint64(GetGUID());
10445 data << uint8(1);
10446 data << uint32(cooldownSpell);
10447 data << uint32(0);
10448 GetSession()->SendPacket(&data);
10453 if( IsInWorld() && update )
10455 pItem->AddToWorld();
10456 pItem->SendUpdateToPlayer( this );
10459 ApplyEquipCooldown(pItem);
10461 if( slot == EQUIPMENT_SLOT_MAINHAND )
10463 UpdateExpertise(BASE_ATTACK);
10464 UpdateArmorPenetration();
10466 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10468 UpdateExpertise(OFF_ATTACK);
10469 UpdateArmorPenetration();
10472 else
10474 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10475 if( IsInWorld() && update )
10476 pItem2->SendUpdateToPlayer( this );
10478 // delete item (it not in any slot currently)
10479 //pItem->DeleteFromDB();
10480 if( IsInWorld() && update )
10482 pItem->RemoveFromWorld();
10483 pItem->DestroyForPlayer( this );
10486 RemoveEnchantmentDurations(pItem);
10487 RemoveItemDurations(pItem);
10489 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10490 pItem->SetState(ITEM_REMOVED, this);
10491 pItem2->SetState(ITEM_CHANGED, this);
10493 ApplyEquipCooldown(pItem2);
10495 return pItem2;
10498 // only for full equip instead adding to stack
10499 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10501 return pItem;
10504 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10506 if( pItem )
10508 AddEnchantmentDurations(pItem);
10509 AddItemDurations(pItem);
10511 uint8 slot = pos & 255;
10512 VisualizeItem( slot, pItem);
10514 if( IsInWorld() )
10516 pItem->AddToWorld();
10517 pItem->SendUpdateToPlayer( this );
10520 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10524 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10526 if(pItem)
10528 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
10529 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
10530 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT));
10532 else
10534 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
10535 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
10539 void Player::VisualizeItem( uint8 slot, Item *pItem)
10541 if(!pItem)
10542 return;
10544 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10545 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10546 pItem->SetBinding( true );
10548 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10550 m_items[slot] = pItem;
10551 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10552 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10553 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10554 pItem->SetSlot( slot );
10555 pItem->SetContainer( NULL );
10557 if( slot < EQUIPMENT_SLOT_END )
10558 SetVisibleItemSlot(slot, pItem);
10560 pItem->SetState(ITEM_CHANGED, this);
10563 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10565 // note: removeitem does not actually change the item
10566 // it only takes the item out of storage temporarily
10567 // note2: if removeitem is to be used for delinking
10568 // the item must be removed from the player's updatequeue
10570 Item *pItem = GetItemByPos( bag, slot );
10571 if( pItem )
10573 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10575 RemoveEnchantmentDurations(pItem);
10576 RemoveItemDurations(pItem);
10578 if( bag == INVENTORY_SLOT_BAG_0 )
10580 if ( slot < INVENTORY_SLOT_BAG_END )
10582 ItemPrototype const *pProto = pItem->GetProto();
10583 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10585 if(pProto && pProto->ItemSet)
10586 RemoveItemsSetItem(this, pProto);
10588 _ApplyItemMods(pItem, slot, false);
10590 // remove item dependent auras and casts (only weapon and armor slots)
10591 if(slot < EQUIPMENT_SLOT_END)
10593 RemoveItemDependentAurasAndCasts(pItem);
10595 // remove held enchantments, update expertise
10596 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10598 if (pItem->GetItemSuffixFactor())
10600 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10601 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10603 else
10605 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10606 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10609 UpdateExpertise(BASE_ATTACK);
10610 UpdateArmorPenetration();
10612 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10614 UpdateExpertise(OFF_ATTACK);
10615 UpdateArmorPenetration();
10619 // need update known currency
10620 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10621 UpdateKnownCurrencies(pItem->GetEntry(), false);
10623 m_items[slot] = NULL;
10624 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10626 if ( slot < EQUIPMENT_SLOT_END )
10627 SetVisibleItemSlot(slot, NULL);
10629 else
10631 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10632 if( pBag )
10633 pBag->RemoveItem(slot, update);
10635 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10636 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10637 pItem->SetSlot( NULL_SLOT );
10638 if( IsInWorld() && update )
10639 pItem->SendUpdateToPlayer( this );
10643 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10644 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10646 if(Item* it = GetItemByPos(bag,slot))
10648 ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
10649 RemoveItem(bag, slot, update);
10650 it->RemoveFromUpdateQueueOf(this);
10651 if(it->IsInWorld())
10653 it->RemoveFromWorld();
10654 it->DestroyForPlayer( this );
10659 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10660 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10662 // update quest counters
10663 ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
10665 // store item
10666 Item* pLastItem = StoreItem(dest, pItem, update);
10668 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10669 if(pLastItem == pItem)
10671 // update owner for last item (this can be original item with wrong owner
10672 if(pLastItem->GetOwnerGUID() != GetGUID())
10673 pLastItem->SetOwnerGUID(GetGUID());
10675 // if this original item then it need create record in inventory
10676 // in case trade we already have item in other player inventory
10677 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10681 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10683 Item *pItem = GetItemByPos( bag, slot );
10684 if( pItem )
10686 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10688 // start from destroy contained items (only equipped bag can have its)
10689 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10691 for (int i = 0; i < MAX_BAG_SIZE; ++i)
10692 DestroyItem(slot, i, update);
10695 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10696 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10698 RemoveEnchantmentDurations(pItem);
10699 RemoveItemDurations(pItem);
10701 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10703 if( bag == INVENTORY_SLOT_BAG_0 )
10705 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10707 // equipment and equipped bags can have applied bonuses
10708 if ( slot < INVENTORY_SLOT_BAG_END )
10710 ItemPrototype const *pProto = pItem->GetProto();
10712 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10713 if(pProto && pProto->ItemSet)
10714 RemoveItemsSetItem(this, pProto);
10716 _ApplyItemMods(pItem, slot, false);
10719 if ( slot < EQUIPMENT_SLOT_END )
10721 // remove item dependent auras and casts (only weapon and armor slots)
10722 RemoveItemDependentAurasAndCasts(pItem);
10724 // update expertise
10725 if( slot == EQUIPMENT_SLOT_MAINHAND )
10727 UpdateExpertise(BASE_ATTACK);
10728 UpdateArmorPenetration();
10730 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10732 UpdateExpertise(OFF_ATTACK);
10733 UpdateArmorPenetration();
10736 // equipment visual show
10737 SetVisibleItemSlot(slot, NULL);
10739 // need update known currency
10740 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10741 UpdateKnownCurrencies(pItem->GetEntry(), false);
10743 m_items[slot] = NULL;
10745 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10746 pBag->RemoveItem(slot, update);
10748 if( IsInWorld() && update )
10750 pItem->RemoveFromWorld();
10751 pItem->DestroyForPlayer(this);
10754 //pItem->SetOwnerGUID(0);
10755 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10756 pItem->SetSlot( NULL_SLOT );
10757 pItem->SetState(ITEM_REMOVED, this);
10761 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10763 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10764 uint32 remcount = 0;
10766 // in inventory
10767 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10769 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10771 if (pItem->GetEntry() == item)
10773 if (pItem->GetCount() + remcount <= count)
10775 // all items in inventory can unequipped
10776 remcount += pItem->GetCount();
10777 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10779 if (remcount >= count)
10780 return;
10782 else
10784 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10785 pItem->SetCount( pItem->GetCount() - count + remcount );
10786 if (IsInWorld() & update)
10787 pItem->SendUpdateToPlayer( this );
10788 pItem->SetState(ITEM_CHANGED, this);
10789 return;
10795 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10797 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10799 if (pItem->GetEntry() == item)
10801 if (pItem->GetCount() + remcount <= count)
10803 // all keys can be unequipped
10804 remcount += pItem->GetCount();
10805 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10807 if (remcount >= count)
10808 return;
10810 else
10812 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10813 pItem->SetCount( pItem->GetCount() - count + remcount );
10814 if (IsInWorld() & update)
10815 pItem->SendUpdateToPlayer( this );
10816 pItem->SetState(ITEM_CHANGED, this);
10817 return;
10823 // in inventory bags
10824 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10826 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10828 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10830 if(Item* pItem = pBag->GetItemByPos(j))
10832 if (pItem->GetEntry() == item)
10834 // all items in bags can be unequipped
10835 if (pItem->GetCount() + remcount <= count)
10837 remcount += pItem->GetCount();
10838 DestroyItem( i, j, update );
10840 if (remcount >= count)
10841 return;
10843 else
10845 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10846 pItem->SetCount( pItem->GetCount() - count + remcount );
10847 if (IsInWorld() && update)
10848 pItem->SendUpdateToPlayer( this );
10849 pItem->SetState(ITEM_CHANGED, this);
10850 return;
10858 // in equipment and bag list
10859 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10861 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10863 if (pItem && pItem->GetEntry() == item)
10865 if (pItem->GetCount() + remcount <= count)
10867 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
10869 remcount += pItem->GetCount();
10870 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10872 if (remcount >= count)
10873 return;
10876 else
10878 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10879 pItem->SetCount( pItem->GetCount() - count + remcount );
10880 if (IsInWorld() & update)
10881 pItem->SendUpdateToPlayer( this );
10882 pItem->SetState(ITEM_CHANGED, this);
10883 return;
10890 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10892 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10894 // in inventory
10895 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10896 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10897 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10898 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10900 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10901 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10902 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10903 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10905 // in inventory bags
10906 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10907 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10908 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10909 if (Item* pItem = pBag->GetItemByPos(j))
10910 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10911 DestroyItem(i, j, update);
10913 // in equipment and bag list
10914 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10915 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10916 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10917 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10920 void Player::DestroyConjuredItems( bool update )
10922 // used when entering arena
10923 // destroys all conjured items
10924 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10926 // in inventory
10927 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10928 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10929 if (pItem->IsConjuredConsumable())
10930 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10932 // in inventory bags
10933 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10934 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10935 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10936 if (Item* pItem = pBag->GetItemByPos(j))
10937 if (pItem->IsConjuredConsumable())
10938 DestroyItem( i, j, update);
10940 // in equipment and bag list
10941 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10942 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10943 if (pItem->IsConjuredConsumable())
10944 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10947 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10949 if(!pItem)
10950 return;
10952 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10954 if( pItem->GetCount() <= count )
10956 count -= pItem->GetCount();
10958 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10960 else
10962 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10963 pItem->SetCount( pItem->GetCount() - count );
10964 count = 0;
10965 if( IsInWorld() & update )
10966 pItem->SendUpdateToPlayer( this );
10967 pItem->SetState(ITEM_CHANGED, this);
10971 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10973 uint8 srcbag = src >> 8;
10974 uint8 srcslot = src & 255;
10976 uint8 dstbag = dst >> 8;
10977 uint8 dstslot = dst & 255;
10979 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10980 if( !pSrcItem )
10982 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10983 return;
10986 // not let split all items (can be only at cheating)
10987 if(pSrcItem->GetCount() == count)
10989 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10990 return;
10993 // not let split more existed items (can be only at cheating)
10994 if(pSrcItem->GetCount() < count)
10996 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10997 return;
11000 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
11002 //best error message found for attempting to split while looting
11003 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11004 return;
11007 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
11008 Item *pNewItem = pSrcItem->CloneItem( count, this );
11009 if( !pNewItem )
11011 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11012 return;
11015 if( IsInventoryPos( dst ) )
11017 // change item amount before check (for unique max count check)
11018 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11020 ItemPosCountVec dest;
11021 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
11022 if( msg != EQUIP_ERR_OK )
11024 delete pNewItem;
11025 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11026 SendEquipError( msg, pSrcItem, NULL );
11027 return;
11030 if( IsInWorld() )
11031 pSrcItem->SendUpdateToPlayer( this );
11032 pSrcItem->SetState(ITEM_CHANGED, this);
11033 StoreItem( dest, pNewItem, true);
11035 else if( IsBankPos ( dst ) )
11037 // change item amount before check (for unique max count check)
11038 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11040 ItemPosCountVec dest;
11041 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
11042 if( msg != EQUIP_ERR_OK )
11044 delete pNewItem;
11045 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11046 SendEquipError( msg, pSrcItem, NULL );
11047 return;
11050 if( IsInWorld() )
11051 pSrcItem->SendUpdateToPlayer( this );
11052 pSrcItem->SetState(ITEM_CHANGED, this);
11053 BankItem( dest, pNewItem, true);
11055 else if( IsEquipmentPos ( dst ) )
11057 // change item amount before check (for unique max count check), provide space for splitted items
11058 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11060 uint16 dest;
11061 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
11062 if( msg != EQUIP_ERR_OK )
11064 delete pNewItem;
11065 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11066 SendEquipError( msg, pSrcItem, NULL );
11067 return;
11070 if( IsInWorld() )
11071 pSrcItem->SendUpdateToPlayer( this );
11072 pSrcItem->SetState(ITEM_CHANGED, this);
11073 EquipItem( dest, pNewItem, true);
11074 AutoUnequipOffhandIfNeed();
11078 void Player::SwapItem( uint16 src, uint16 dst )
11080 uint8 srcbag = src >> 8;
11081 uint8 srcslot = src & 255;
11083 uint8 dstbag = dst >> 8;
11084 uint8 dstslot = dst & 255;
11086 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11087 Item *pDstItem = GetItemByPos( dstbag, dstslot );
11089 if( !pSrcItem )
11090 return;
11092 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
11094 if(!isAlive() )
11096 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
11097 return;
11100 // SRC checks
11102 if(pSrcItem->m_lootGenerated) // prevent swap looting item
11104 //best error message found for attempting to swap while looting
11105 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
11106 return;
11109 // check unequip potability for equipped items and bank bags
11110 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
11112 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11113 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || (pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty()));
11114 if(msg != EQUIP_ERR_OK)
11116 SendEquipError( msg, pSrcItem, pDstItem );
11117 return;
11121 // prevent put equipped/bank bag in self
11122 if( IsBagPos ( src ) && srcslot == dstbag)
11124 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11125 return;
11128 // DST checks
11130 if (pDstItem)
11132 if(pDstItem->m_lootGenerated) // prevent swap looting item
11134 //best error message found for attempting to swap while looting
11135 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
11136 return;
11139 // check unequip potability for equipped items and bank bags
11140 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11142 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11143 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || (pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty()));
11144 if(msg != EQUIP_ERR_OK)
11146 SendEquipError( msg, pSrcItem, pDstItem );
11147 return;
11152 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11153 // or swap empty bag with another empty or not empty bag (with items exchange)
11155 // Move case
11156 if( !pDstItem )
11158 if( IsInventoryPos( dst ) )
11160 ItemPosCountVec dest;
11161 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
11162 if( msg != EQUIP_ERR_OK )
11164 SendEquipError( msg, pSrcItem, NULL );
11165 return;
11168 RemoveItem(srcbag, srcslot, true);
11169 StoreItem( dest, pSrcItem, true);
11171 else if( IsBankPos ( dst ) )
11173 ItemPosCountVec dest;
11174 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11175 if( msg != EQUIP_ERR_OK )
11177 SendEquipError( msg, pSrcItem, NULL );
11178 return;
11181 RemoveItem(srcbag, srcslot, true);
11182 BankItem( dest, pSrcItem, true);
11184 else if( IsEquipmentPos ( dst ) )
11186 uint16 dest;
11187 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11188 if( msg != EQUIP_ERR_OK )
11190 SendEquipError( msg, pSrcItem, NULL );
11191 return;
11194 RemoveItem(srcbag, srcslot, true);
11195 EquipItem(dest, pSrcItem, true);
11196 AutoUnequipOffhandIfNeed();
11199 return;
11202 // attempt merge to / fill target item
11203 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
11205 uint8 msg;
11206 ItemPosCountVec sDest;
11207 uint16 eDest;
11208 if( IsInventoryPos( dst ) )
11209 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11210 else if( IsBankPos ( dst ) )
11211 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11212 else if( IsEquipmentPos ( dst ) )
11213 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11214 else
11215 return;
11217 // can be merge/fill
11218 if(msg == EQUIP_ERR_OK)
11220 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11222 RemoveItem(srcbag, srcslot, true);
11224 if( IsInventoryPos( dst ) )
11225 StoreItem( sDest, pSrcItem, true);
11226 else if( IsBankPos ( dst ) )
11227 BankItem( sDest, pSrcItem, true);
11228 else if( IsEquipmentPos ( dst ) )
11230 EquipItem( eDest, pSrcItem, true);
11231 AutoUnequipOffhandIfNeed();
11234 else
11236 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11237 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11238 pSrcItem->SetState(ITEM_CHANGED, this);
11239 pDstItem->SetState(ITEM_CHANGED, this);
11240 if( IsInWorld() )
11242 pSrcItem->SendUpdateToPlayer( this );
11243 pDstItem->SendUpdateToPlayer( this );
11246 return;
11250 // impossible merge/fill, do real swap
11251 uint8 msg;
11253 // check src->dest move possibility
11254 ItemPosCountVec sDest;
11255 uint16 eDest = 0;
11256 if( IsInventoryPos( dst ) )
11257 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11258 else if( IsBankPos( dst ) )
11259 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11260 else if( IsEquipmentPos( dst ) )
11262 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11263 if( msg == EQUIP_ERR_OK )
11264 msg = CanUnequipItem( eDest, true );
11267 if( msg != EQUIP_ERR_OK )
11269 SendEquipError( msg, pSrcItem, pDstItem );
11270 return;
11273 // check dest->src move possibility
11274 ItemPosCountVec sDest2;
11275 uint16 eDest2 = 0;
11276 if( IsInventoryPos( src ) )
11277 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11278 else if( IsBankPos( src ) )
11279 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11280 else if( IsEquipmentPos( src ) )
11282 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11283 if( msg == EQUIP_ERR_OK )
11284 msg = CanUnequipItem( eDest2, true);
11287 if( msg != EQUIP_ERR_OK )
11289 SendEquipError( msg, pDstItem, pSrcItem );
11290 return;
11293 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11294 if(pSrcItem->IsBag() && pDstItem->IsBag())
11296 Bag* emptyBag = NULL;
11297 Bag* fullBag = NULL;
11298 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11300 emptyBag = (Bag*)pSrcItem;
11301 fullBag = (Bag*)pDstItem;
11303 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11305 emptyBag = (Bag*)pDstItem;
11306 fullBag = (Bag*)pSrcItem;
11309 // bag swap (with items exchange) case
11310 if(emptyBag && fullBag)
11312 ItemPrototype const* emotyProto = emptyBag->GetProto();
11314 uint32 count = 0;
11316 for(int i=0; i < fullBag->GetBagSize(); ++i)
11318 Item *bagItem = fullBag->GetItemByPos(i);
11319 if (!bagItem)
11320 continue;
11322 ItemPrototype const* bagItemProto = bagItem->GetProto();
11323 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11325 // one from items not go to empty target bag
11326 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11327 return;
11330 ++count;
11334 if (count > emptyBag->GetBagSize())
11336 // too small targeted bag
11337 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11338 return;
11341 // Items swap
11342 count = 0; // will pos in new bag
11343 for(int i = 0; i< fullBag->GetBagSize(); ++i)
11345 Item *bagItem = fullBag->GetItemByPos(i);
11346 if (!bagItem)
11347 continue;
11349 fullBag->RemoveItem(i, true);
11350 emptyBag->StoreItem(count, bagItem, true);
11351 bagItem->SetState(ITEM_CHANGED, this);
11353 ++count;
11358 // now do moves, remove...
11359 RemoveItem(dstbag, dstslot, false);
11360 RemoveItem(srcbag, srcslot, false);
11362 // add to dest
11363 if (IsInventoryPos(dst))
11364 StoreItem(sDest, pSrcItem, true);
11365 else if (IsBankPos(dst))
11366 BankItem(sDest, pSrcItem, true);
11367 else if (IsEquipmentPos(dst))
11368 EquipItem(eDest, pSrcItem, true);
11370 // add to src
11371 if (IsInventoryPos(src))
11372 StoreItem(sDest2, pDstItem, true);
11373 else if (IsBankPos(src))
11374 BankItem(sDest2, pDstItem, true);
11375 else if (IsEquipmentPos(src))
11376 EquipItem(eDest2, pDstItem, true);
11378 AutoUnequipOffhandIfNeed();
11381 void Player::AddItemToBuyBackSlot( Item *pItem )
11383 if (pItem)
11385 uint32 slot = m_currentBuybackSlot;
11386 // if current back slot non-empty search oldest or free
11387 if (m_items[slot])
11389 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11390 uint32 oldest_slot = BUYBACK_SLOT_START;
11392 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11394 // found empty
11395 if (!m_items[i])
11397 slot = i;
11398 break;
11401 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11403 if (oldest_time > i_time)
11405 oldest_time = i_time;
11406 oldest_slot = i;
11410 // find oldest
11411 slot = oldest_slot;
11414 RemoveItemFromBuyBackSlot( slot, true );
11415 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11417 m_items[slot] = pItem;
11418 time_t base = time(NULL);
11419 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11420 uint32 eslot = slot - BUYBACK_SLOT_START;
11422 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID() );
11423 if (ItemPrototype const *pProto = pItem->GetProto())
11424 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11425 else
11426 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11427 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11429 // move to next (for non filled list is move most optimized choice)
11430 if (m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
11431 ++m_currentBuybackSlot;
11435 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11437 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11438 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
11439 return m_items[slot];
11440 return NULL;
11443 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11445 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11446 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
11448 Item *pItem = m_items[slot];
11449 if (pItem)
11451 pItem->RemoveFromWorld();
11452 if(del) pItem->SetState(ITEM_REMOVED, this);
11455 m_items[slot] = NULL;
11457 uint32 eslot = slot - BUYBACK_SLOT_START;
11458 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0 );
11459 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11460 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11462 // if current backslot is filled set to now free slot
11463 if (m_items[m_currentBuybackSlot])
11464 m_currentBuybackSlot = slot;
11468 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11470 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
11471 WorldPacket data(SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : (msg == EQUIP_ERR_OK ? 1 : 18)));
11472 data << uint8(msg);
11474 if (msg != EQUIP_ERR_OK)
11476 data << uint64(pItem ? pItem->GetGUID() : 0);
11477 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11478 data << uint8(0); // not 0 there...
11480 if (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11482 uint32 level = 0;
11484 if (pItem)
11485 if (ItemPrototype const* proto = pItem->GetProto())
11486 level = proto->RequiredLevel;
11488 data << uint32(level); // new 2.4.0
11491 GetSession()->SendPacket(&data);
11494 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11496 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11497 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11498 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11499 data << uint32(item);
11500 if (param > 0)
11501 data << uint32(param);
11502 data << uint8(msg);
11503 GetSession()->SendPacket(&data);
11506 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11508 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11509 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11510 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11511 data << uint64(guid);
11512 if (param > 0)
11513 data << uint32(param);
11514 data << uint8(msg);
11515 GetSession()->SendPacket(&data);
11518 void Player::ClearTrade()
11520 tradeGold = 0;
11521 acceptTrade = false;
11522 for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
11523 tradeItems[i] = NULL_SLOT;
11526 void Player::TradeCancel(bool sendback)
11528 if (pTrader)
11530 // send yellow "Trade canceled" message to both traders
11531 WorldSession* ws;
11532 ws = GetSession();
11533 if (sendback)
11534 ws->SendCancelTrade();
11535 ws = pTrader->GetSession();
11536 if (!ws->PlayerLogout())
11537 ws->SendCancelTrade();
11539 // cleanup
11540 ClearTrade();
11541 pTrader->ClearTrade();
11542 // prevent loss of reference
11543 pTrader->pTrader = NULL;
11544 pTrader = NULL;
11548 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11550 if (m_itemDuration.empty())
11551 return;
11553 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
11555 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); )
11557 Item* item = *itr;
11558 ++itr; // current element can be erased in UpdateDuration
11560 if ((realtimeonly && item->GetProto()->Duration < 0) || !realtimeonly)
11561 item->UpdateDuration(this,time);
11565 void Player::UpdateEnchantTime(uint32 time)
11567 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11569 assert(itr->item);
11570 next = itr;
11571 if (!itr->item->GetEnchantmentId(itr->slot))
11573 next = m_enchantDuration.erase(itr);
11575 else if (itr->leftduration <= time)
11577 ApplyEnchantment(itr->item, itr->slot, false, false);
11578 itr->item->ClearEnchantment(itr->slot);
11579 next = m_enchantDuration.erase(itr);
11581 else if (itr->leftduration > time)
11583 itr->leftduration -= time;
11584 ++next;
11589 void Player::AddEnchantmentDurations(Item *item)
11591 for(int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
11593 if (!item->GetEnchantmentId(EnchantmentSlot(x)))
11594 continue;
11596 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11597 if (duration > 0)
11598 AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
11602 void Player::RemoveEnchantmentDurations(Item *item)
11604 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
11606 if (itr->item == item)
11608 // save duration in item
11609 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
11610 itr = m_enchantDuration.erase(itr);
11612 else
11613 ++itr;
11617 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11619 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11620 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
11622 next = itr;
11623 if (itr->slot == slot)
11625 if (itr->item && itr->item->GetEnchantmentId(slot))
11627 // remove from stats
11628 ApplyEnchantment(itr->item, slot, false, false);
11629 // remove visual
11630 itr->item->ClearEnchantment(slot);
11632 // remove from update list
11633 next = m_enchantDuration.erase(itr);
11635 else
11636 ++next;
11639 // remove enchants from inventory items
11640 // NOTE: no need to remove these from stats, since these aren't equipped
11641 // in inventory
11642 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11643 if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
11644 if (pItem->GetEnchantmentId(slot))
11645 pItem->ClearEnchantment(slot);
11647 // in inventory bags
11648 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11649 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11650 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11651 if (Item* pItem = pBag->GetItemByPos(j))
11652 if (pItem->GetEnchantmentId(slot))
11653 pItem->ClearEnchantment(slot);
11656 // duration == 0 will remove item enchant
11657 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11659 if (!item)
11660 return;
11662 if (slot >= MAX_ENCHANTMENT_SLOT)
11663 return;
11665 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11667 if (itr->item == item && itr->slot == slot)
11669 itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
11670 m_enchantDuration.erase(itr);
11671 break;
11674 if (item && duration > 0 )
11676 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
11677 m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
11681 void Player::ApplyEnchantment(Item *item,bool apply)
11683 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11684 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11687 void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
11689 if (!item)
11690 return;
11692 if (!item->IsEquipped())
11693 return;
11695 if (slot >= MAX_ENCHANTMENT_SLOT)
11696 return;
11698 uint32 enchant_id = item->GetEnchantmentId(slot);
11699 if (!enchant_id)
11700 return;
11702 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11703 if (!pEnchant)
11704 return;
11706 if (!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11707 return;
11709 if (!item->IsBroken())
11711 for (int s = 0; s < 3; ++s)
11713 uint32 enchant_display_type = pEnchant->type[s];
11714 uint32 enchant_amount = pEnchant->amount[s];
11715 uint32 enchant_spell_id = pEnchant->spellid[s];
11717 switch(enchant_display_type)
11719 case ITEM_ENCHANTMENT_TYPE_NONE:
11720 break;
11721 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11722 // processed in Player::CastItemCombatSpell
11723 break;
11724 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11725 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11726 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11727 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11728 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11729 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11730 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11731 break;
11732 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11733 if (enchant_spell_id)
11735 if (apply)
11737 int32 basepoints = 0;
11738 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11739 if (item->GetItemRandomPropertyId())
11741 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11742 if (item_rand)
11744 // Search enchant_amount
11745 for (int k = 0; k < 3; ++k)
11747 if(item_rand->enchant_id[k] == enchant_id)
11749 basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11750 break;
11755 // Cast custom spell vs all equal basepoints getted from enchant_amount
11756 if (basepoints)
11757 CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
11758 else
11759 CastSpell(this, enchant_spell_id, true, item);
11761 else
11762 RemoveAurasDueToItemSpell(item, enchant_spell_id);
11764 break;
11765 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11766 if (!enchant_amount)
11768 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11769 if(item_rand)
11771 for (int k = 0; k < 3; ++k)
11773 if(item_rand->enchant_id[k] == enchant_id)
11775 enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11776 break;
11782 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11783 break;
11784 case ITEM_ENCHANTMENT_TYPE_STAT:
11786 if (!enchant_amount)
11788 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11789 if(item_rand_suffix)
11791 for (int k = 0; k < 3; ++k)
11793 if(item_rand_suffix->enchant_id[k] == enchant_id)
11795 enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11796 break;
11802 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11803 switch (enchant_spell_id)
11805 case ITEM_MOD_MANA:
11806 sLog.outDebug("+ %u MANA",enchant_amount);
11807 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
11808 break;
11809 case ITEM_MOD_HEALTH:
11810 sLog.outDebug("+ %u HEALTH",enchant_amount);
11811 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
11812 break;
11813 case ITEM_MOD_AGILITY:
11814 sLog.outDebug("+ %u AGILITY",enchant_amount);
11815 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11816 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11817 break;
11818 case ITEM_MOD_STRENGTH:
11819 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11820 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11821 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11822 break;
11823 case ITEM_MOD_INTELLECT:
11824 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11825 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11826 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11827 break;
11828 case ITEM_MOD_SPIRIT:
11829 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11830 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11831 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11832 break;
11833 case ITEM_MOD_STAMINA:
11834 sLog.outDebug("+ %u STAMINA",enchant_amount);
11835 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11836 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11837 break;
11838 case ITEM_MOD_DEFENSE_SKILL_RATING:
11839 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11840 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11841 break;
11842 case ITEM_MOD_DODGE_RATING:
11843 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11844 sLog.outDebug("+ %u DODGE", enchant_amount);
11845 break;
11846 case ITEM_MOD_PARRY_RATING:
11847 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11848 sLog.outDebug("+ %u PARRY", enchant_amount);
11849 break;
11850 case ITEM_MOD_BLOCK_RATING:
11851 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11852 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11853 break;
11854 case ITEM_MOD_HIT_MELEE_RATING:
11855 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11856 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11857 break;
11858 case ITEM_MOD_HIT_RANGED_RATING:
11859 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11860 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11861 break;
11862 case ITEM_MOD_HIT_SPELL_RATING:
11863 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11864 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11865 break;
11866 case ITEM_MOD_CRIT_MELEE_RATING:
11867 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11868 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11869 break;
11870 case ITEM_MOD_CRIT_RANGED_RATING:
11871 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11872 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11873 break;
11874 case ITEM_MOD_CRIT_SPELL_RATING:
11875 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11876 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11877 break;
11878 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11879 // in Enchantments
11880 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11881 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11882 // break;
11883 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11884 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11885 // break;
11886 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11887 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11888 // break;
11889 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11890 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11891 // break;
11892 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11893 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11894 // break;
11895 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11896 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11897 // break;
11898 // case ITEM_MOD_HASTE_MELEE_RATING:
11899 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11900 // break;
11901 // case ITEM_MOD_HASTE_RANGED_RATING:
11902 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11903 // break;
11904 case ITEM_MOD_HASTE_SPELL_RATING:
11905 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11906 break;
11907 case ITEM_MOD_HIT_RATING:
11908 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11909 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11910 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11911 sLog.outDebug("+ %u HIT", enchant_amount);
11912 break;
11913 case ITEM_MOD_CRIT_RATING:
11914 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11915 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11916 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11917 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11918 break;
11919 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11920 // case ITEM_MOD_HIT_TAKEN_RATING:
11921 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11922 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11923 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11924 // break;
11925 // case ITEM_MOD_CRIT_TAKEN_RATING:
11926 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11927 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11928 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11929 // break;
11930 case ITEM_MOD_RESILIENCE_RATING:
11931 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11932 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11933 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11934 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11935 break;
11936 case ITEM_MOD_HASTE_RATING:
11937 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11938 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11939 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11940 sLog.outDebug("+ %u HASTE", enchant_amount);
11941 break;
11942 case ITEM_MOD_EXPERTISE_RATING:
11943 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11944 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11945 break;
11946 case ITEM_MOD_ATTACK_POWER:
11947 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
11948 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11949 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
11950 break;
11951 case ITEM_MOD_RANGED_ATTACK_POWER:
11952 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11953 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
11954 break;
11955 case ITEM_MOD_FERAL_ATTACK_POWER:
11956 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
11957 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
11958 break;
11959 case ITEM_MOD_MANA_REGENERATION:
11960 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
11961 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
11962 break;
11963 case ITEM_MOD_ARMOR_PENETRATION_RATING:
11964 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
11965 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
11966 break;
11967 case ITEM_MOD_SPELL_POWER:
11968 ((Player*)this)->ApplySpellPowerBonus(enchant_amount, apply);
11969 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
11970 break;
11971 case ITEM_MOD_SPELL_HEALING_DONE: // deprecated
11972 case ITEM_MOD_SPELL_DAMAGE_DONE: // deprecated
11973 default:
11974 break;
11976 break;
11978 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11980 if(getClass() == CLASS_SHAMAN)
11982 float addValue = 0.0f;
11983 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11985 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
11986 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11988 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11990 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
11991 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11994 break;
11996 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
11997 // processed in Player::CastItemUseSpell
11998 break;
11999 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
12000 // nothing do..
12001 break;
12002 default:
12003 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
12004 break;
12005 } /*switch(enchant_display_type)*/
12006 } /*for*/
12009 // visualize enchantment at player and equipped items
12010 if(slot == PERM_ENCHANTMENT_SLOT)
12011 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
12013 if(slot == TEMP_ENCHANTMENT_SLOT)
12014 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
12017 if(apply_dur)
12019 if(apply)
12021 // set duration
12022 uint32 duration = item->GetEnchantmentDuration(slot);
12023 if(duration > 0)
12024 AddEnchantmentDuration(item, slot, duration);
12026 else
12028 // duration == 0 will remove EnchantDuration
12029 AddEnchantmentDuration(item, slot, 0);
12034 void Player::SendEnchantmentDurations()
12036 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
12038 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
12042 void Player::SendItemDurations()
12044 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
12046 (*itr)->SendTimeUpdate(this);
12050 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
12052 if(!item) // prevent crash
12053 return;
12055 // last check 2.0.10
12056 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
12057 data << uint64(GetGUID()); // player GUID
12058 data << uint32(received); // 0=looted, 1=from npc
12059 data << uint32(created); // 0=received, 1=created
12060 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
12061 data << uint8(item->GetBagSlot()); // bagslot
12062 // item slot, but when added to stack: 0xFFFFFFFF
12063 data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
12064 data << uint32(item->GetEntry()); // item id
12065 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
12066 data << uint32(item->GetItemRandomPropertyId()); // random item property id
12067 data << uint32(count); // count of items
12068 data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
12070 if (broadcast && GetGroup())
12071 GetGroup()->BroadcastPacket(&data, true);
12072 else
12073 GetSession()->SendPacket(&data);
12076 /*********************************************************/
12077 /*** QUEST SYSTEM ***/
12078 /*********************************************************/
12080 void Player::PrepareQuestMenu( uint64 guid )
12082 Object *pObject;
12083 QuestRelations* pObjectQR;
12084 QuestRelations* pObjectQIR;
12086 // pets also can have quests
12087 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
12088 if( pCreature )
12090 pObject = (Object*)pCreature;
12091 pObjectQR = &objmgr.mCreatureQuestRelations;
12092 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12094 else
12096 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12097 //only for quests which cast teleport spells on player
12098 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
12099 ASSERT(_map);
12100 GameObject *pGameObject = _map->GetGameObject(guid);
12101 if( pGameObject )
12103 pObject = (Object*)pGameObject;
12104 pObjectQR = &objmgr.mGOQuestRelations;
12105 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12107 else
12108 return;
12111 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
12112 qm.ClearMenu();
12114 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
12116 uint32 quest_id = i->second;
12117 QuestStatus status = GetQuestStatus( quest_id );
12118 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
12119 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12120 else if ( status == QUEST_STATUS_INCOMPLETE )
12121 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12122 else if (status == QUEST_STATUS_AVAILABLE )
12123 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12126 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
12128 uint32 quest_id = i->second;
12129 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12130 if(!pQuest) continue;
12132 QuestStatus status = GetQuestStatus( quest_id );
12134 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
12135 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12136 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
12137 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12141 void Player::SendPreparedQuest(uint64 guid)
12143 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
12145 if (questMenu.Empty())
12146 return;
12148 QuestMenuItem const& qmi0 = questMenu.GetItem(0);
12150 uint32 status = qmi0.m_qIcon;
12152 // single element case
12153 if (questMenu.MenuItemCount() == 1)
12155 // Auto open -- maybe also should verify there is no greeting
12156 uint32 quest_id = qmi0.m_qId;
12157 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12159 if (pQuest)
12161 if (status == DIALOG_STATUS_UNK2 && !GetQuestRewardStatus(quest_id))
12162 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
12163 else if (status == DIALOG_STATUS_UNK2)
12164 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
12165 // Send completable on repeatable and autoCompletable quest if player don't have quest
12166 // TODO: verify if check for !pQuest->IsDaily() is really correct (possibly not)
12167 else if (pQuest->IsAutoComplete() && pQuest->IsRepeatable() && !pQuest->IsDaily())
12168 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanCompleteRepeatableQuest(pQuest), true);
12169 else
12170 PlayerTalkClass->SendQuestGiverQuestDetails(pQuest, guid, true);
12173 // multiply entries
12174 else
12176 QEmote qe;
12177 qe._Delay = 0;
12178 qe._Emote = 0;
12179 std::string title = "";
12181 // need pet case for some quests
12182 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
12183 if (pCreature)
12185 uint32 textid = pCreature->GetNpcTextId();
12186 GossipText const* gossiptext = objmgr.GetGossipText(textid);
12187 if (!gossiptext)
12189 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12190 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12191 title = "";
12193 else
12195 qe = gossiptext->Options[0].Emotes[0];
12197 if(!gossiptext->Options[0].Text_0.empty())
12199 title = gossiptext->Options[0].Text_0;
12201 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12202 if (loc_idx >= 0)
12204 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12205 if (nl)
12207 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12208 title = nl->Text_0[0][loc_idx];
12212 else
12214 title = gossiptext->Options[0].Text_1;
12216 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12217 if (loc_idx >= 0)
12219 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12220 if (nl)
12222 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12223 title = nl->Text_1[0][loc_idx];
12229 PlayerTalkClass->SendQuestGiverQuestList(qe, title, guid);
12233 bool Player::IsActiveQuest( uint32 quest_id ) const
12235 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12237 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12240 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12242 Object *pObject;
12243 QuestRelations* pObjectQR;
12244 QuestRelations* pObjectQIR;
12246 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
12247 if( pCreature )
12249 pObject = (Object*)pCreature;
12250 pObjectQR = &objmgr.mCreatureQuestRelations;
12251 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12253 else
12255 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12256 //only for quests which cast teleport spells on player
12257 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
12258 ASSERT(_map);
12259 GameObject *pGameObject = _map->GetGameObject(guid);
12260 if( pGameObject )
12262 pObject = (Object*)pGameObject;
12263 pObjectQR = &objmgr.mGOQuestRelations;
12264 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12266 else
12267 return NULL;
12270 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12271 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12273 if (itr->second == nextQuestID)
12274 return objmgr.GetQuestTemplate(nextQuestID);
12277 return NULL;
12280 bool Player::CanSeeStartQuest( Quest const *pQuest )
12282 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12283 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12284 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12285 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12287 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12290 return false;
12293 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12295 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12296 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12297 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12298 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12299 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12300 && SatisfyQuestDay( pQuest, msg );
12303 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12305 if( !SatisfyQuestLog( msg ) )
12306 return false;
12308 uint32 srcitem = pQuest->GetSrcItemId();
12309 if( srcitem > 0 )
12311 uint32 count = pQuest->GetSrcItemCount();
12312 ItemPosCountVec dest;
12313 uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12315 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12316 if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12317 return true;
12318 else if( msg2 != EQUIP_ERR_OK )
12320 SendEquipError( msg2, NULL, NULL );
12321 return false;
12324 return true;
12327 bool Player::CanCompleteQuest( uint32 quest_id )
12329 if( quest_id )
12331 QuestStatusData& q_status = mQuestStatus[quest_id];
12332 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12333 return false; // not allow re-complete quest
12335 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12337 if(!qInfo)
12338 return false;
12340 // auto complete quest
12341 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12342 return true;
12344 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12347 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12349 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12351 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12352 return false;
12356 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12358 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12360 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12361 continue;
12363 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12364 return false;
12368 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12369 return false;
12371 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12372 return false;
12374 if ( qInfo->GetRewOrReqMoney() < 0 )
12376 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12377 return false;
12380 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12381 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12382 return false;
12384 return true;
12387 return false;
12390 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12392 // Solve problem that player don't have the quest and try complete it.
12393 // if repeatable she must be able to complete event if player don't have it.
12394 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12395 if( !CanTakeQuest(pQuest, false) )
12396 return false;
12398 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12399 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12400 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12401 return false;
12403 if( !CanRewardQuest(pQuest, false) )
12404 return false;
12406 return true;
12409 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12411 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12412 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12413 return false;
12415 // daily quest can't be rewarded (25 daily quest already completed)
12416 if(!SatisfyQuestDay(pQuest,true))
12417 return false;
12419 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12420 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12421 return false;
12423 // prevent receive reward with quest items in bank
12424 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12426 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12428 if( pQuest->ReqItemCount[i]!= 0 &&
12429 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12431 if(msg)
12432 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12433 return false;
12438 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12439 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12440 return false;
12442 return true;
12445 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12447 // prevent receive reward with quest items in bank or for not completed quest
12448 if(!CanRewardQuest(pQuest,msg))
12449 return false;
12451 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12453 if( pQuest->RewChoiceItemId[reward] )
12455 ItemPosCountVec dest;
12456 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12457 if( res != EQUIP_ERR_OK )
12459 SendEquipError( res, NULL, NULL );
12460 return false;
12465 if ( pQuest->GetRewItemsCount() > 0 )
12467 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12469 if( pQuest->RewItemId[i] )
12471 ItemPosCountVec dest;
12472 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12473 if( res != EQUIP_ERR_OK )
12475 SendEquipError( res, NULL, NULL );
12476 return false;
12482 return true;
12485 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12487 uint16 log_slot = FindQuestSlot( 0 );
12488 assert(log_slot < MAX_QUEST_LOG_SIZE);
12490 uint32 quest_id = pQuest->GetQuestId();
12492 // if not exist then created with set uState==NEW and rewarded=false
12493 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12495 // check for repeatable quests status reset
12496 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12497 questStatusData.m_explored = false;
12499 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12501 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12502 questStatusData.m_itemcount[i] = 0;
12505 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12507 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12508 questStatusData.m_creatureOrGOcount[i] = 0;
12511 GiveQuestSourceItem( pQuest );
12512 AdjustQuestReqItemCount( pQuest, questStatusData );
12514 if( pQuest->GetRepObjectiveFaction() )
12515 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
12516 GetReputationMgr().SetVisible(factionEntry);
12518 uint32 qtime = 0;
12519 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12521 uint32 limittime = pQuest->GetLimitTime();
12523 // shared timed quest
12524 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12525 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
12527 AddTimedQuest( quest_id );
12528 questStatusData.m_timer = limittime * IN_MILISECONDS;
12529 qtime = static_cast<uint32>(time(NULL)) + limittime;
12531 else
12532 questStatusData.m_timer = 0;
12534 SetQuestSlot(log_slot, quest_id, qtime);
12536 if (questStatusData.uState != QUEST_NEW)
12537 questStatusData.uState = QUEST_CHANGED;
12539 //starting initial quest script
12540 if(questGiver && pQuest->GetQuestStartScript()!=0)
12541 GetMap()->ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12543 // Some spells applied at quest activation
12544 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,true);
12545 if(saBounds.first != saBounds.second)
12547 uint32 zone, area;
12548 GetZoneAndAreaId(zone,area);
12550 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12551 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12552 if( !HasAura(itr->second->spellId,0) )
12553 CastSpell(this,itr->second->spellId,true);
12556 UpdateForQuestWorldObjects();
12559 void Player::CompleteQuest( uint32 quest_id )
12561 if( quest_id )
12563 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12565 uint16 log_slot = FindQuestSlot( quest_id );
12566 if( log_slot < MAX_QUEST_LOG_SIZE)
12567 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12569 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12571 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12572 RewardQuest(qInfo,0,this,false);
12573 else
12574 SendQuestComplete( quest_id );
12579 void Player::IncompleteQuest( uint32 quest_id )
12581 if( quest_id )
12583 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12585 uint16 log_slot = FindQuestSlot( quest_id );
12586 if( log_slot < MAX_QUEST_LOG_SIZE)
12587 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12591 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12593 //this THING should be here to protect code from quest, which cast on player far teleport as a reward
12594 //should work fine, cause far teleport will be executed in Player::Update()
12595 SetCanDelayTeleport(true);
12597 uint32 quest_id = pQuest->GetQuestId();
12599 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i )
12601 if (pQuest->ReqItemId[i])
12602 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12605 RemoveTimedQuest(quest_id);
12607 if (pQuest->GetRewChoiceItemsCount() > 0)
12609 if (uint32 itemId = pQuest->RewChoiceItemId[reward])
12611 ItemPosCountVec dest;
12612 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK)
12614 Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
12615 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12620 if (pQuest->GetRewItemsCount() > 0)
12622 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12624 if (uint32 itemId = pQuest->RewItemId[i])
12626 ItemPosCountVec dest;
12627 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewItemCount[i] ) == EQUIP_ERR_OK)
12629 Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
12630 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12636 RewardReputation( pQuest );
12638 uint16 log_slot = FindQuestSlot( quest_id );
12639 if (log_slot < MAX_QUEST_LOG_SIZE)
12640 SetQuestSlot(log_slot,0);
12642 QuestStatusData& q_status = mQuestStatus[quest_id];
12644 // Not give XP in case already completed once repeatable quest
12645 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12647 if (getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
12648 GiveXP( XP , NULL );
12649 else
12651 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
12652 ModifyMoney( money );
12653 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
12656 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12657 if (pQuest->GetRewOrReqMoney())
12659 ModifyMoney( pQuest->GetRewOrReqMoney() );
12661 if (pQuest->GetRewOrReqMoney() > 0)
12662 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
12665 // honor reward
12666 if (pQuest->GetRewHonorableKills())
12667 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12669 // title reward
12670 if (pQuest->GetCharTitleId())
12672 if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12673 SetTitle(titleEntry);
12676 if (pQuest->GetBonusTalents())
12678 m_questRewardTalentCount+=pQuest->GetBonusTalents();
12679 InitTalentForLevel();
12682 // Send reward mail
12683 if (pQuest->GetRewMailTemplateId())
12685 MailMessageType mailType;
12686 uint32 senderGuidOrEntry;
12687 switch(questGiver->GetTypeId())
12689 case TYPEID_UNIT:
12690 mailType = MAIL_CREATURE;
12691 senderGuidOrEntry = questGiver->GetEntry();
12692 break;
12693 case TYPEID_GAMEOBJECT:
12694 mailType = MAIL_GAMEOBJECT;
12695 senderGuidOrEntry = questGiver->GetEntry();
12696 break;
12697 case TYPEID_ITEM:
12698 mailType = MAIL_ITEM;
12699 senderGuidOrEntry = questGiver->GetEntry();
12700 break;
12701 case TYPEID_PLAYER:
12702 mailType = MAIL_NORMAL;
12703 senderGuidOrEntry = questGiver->GetGUIDLow();
12704 break;
12705 default:
12706 mailType = MAIL_NORMAL;
12707 senderGuidOrEntry = GetGUIDLow();
12708 break;
12711 Loot questMailLoot;
12713 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this,true);
12715 // fill mail
12716 MailItemsInfo mi; // item list preparing
12718 uint32 max_slot = questMailLoot.GetMaxSlotInLootFor(this);
12719 for(uint32 i = 0; mi.size() < MAX_MAIL_ITEMS && i < max_slot; ++i)
12721 if (LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12723 if (Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12725 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12726 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12731 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12734 if (pQuest->IsDaily())
12736 SetDailyQuestStatus(quest_id);
12737 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12740 if (!pQuest->IsRepeatable())
12741 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12742 else
12743 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12745 q_status.m_rewarded = true;
12746 if (q_status.uState != QUEST_NEW)
12747 q_status.uState = QUEST_CHANGED;
12749 if (announce)
12750 SendQuestReward( pQuest, XP, questGiver );
12752 // cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data)
12753 if (pQuest->GetRewSpellCast() > 0)
12754 CastSpell( this, pQuest->GetRewSpellCast(), true);
12755 else if ( pQuest->GetRewSpell() > 0)
12756 CastSpell( this, pQuest->GetRewSpell(), true);
12758 if (pQuest->GetZoneOrSort() > 0)
12759 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
12760 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12761 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
12763 uint32 zone = 0;
12764 uint32 area = 0;
12766 // remove auras from spells with quest reward state limitations
12767 SpellAreaForQuestMapBounds saEndBounds = spellmgr.GetSpellAreaForQuestEndMapBounds(quest_id);
12768 if(saEndBounds.first != saEndBounds.second)
12770 GetZoneAndAreaId(zone,area);
12772 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
12773 if(!itr->second->IsFitToRequirements(this,zone,area))
12774 RemoveAurasDueToSpell(itr->second->spellId);
12777 // Some spells applied at quest reward
12778 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,false);
12779 if(saBounds.first != saBounds.second)
12781 if(!zone || !area)
12782 GetZoneAndAreaId(zone,area);
12784 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12785 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12786 if( !HasAura(itr->second->spellId,0) )
12787 CastSpell(this,itr->second->spellId,true);
12790 //lets remove flag for delayed teleports
12791 SetCanDelayTeleport(false);
12794 void Player::FailQuest(uint32 questId)
12796 if (Quest const* pQuest = objmgr.GetQuestTemplate(questId))
12798 SetQuestStatus(questId, QUEST_STATUS_FAILED);
12800 uint16 log_slot = FindQuestSlot(questId);
12802 if (log_slot < MAX_QUEST_LOG_SIZE)
12804 SetQuestSlotTimer(log_slot, 1);
12805 SetQuestSlotState(log_slot, QUEST_STATE_FAIL);
12808 if (pQuest->HasFlag(QUEST_MANGOS_FLAGS_TIMED))
12810 QuestStatusData& q_status = mQuestStatus[questId];
12812 RemoveTimedQuest(questId);
12813 q_status.m_timer = 0;
12815 SendQuestTimerFailed(questId);
12817 else
12818 SendQuestFailed(questId);
12822 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12824 int32 zoneOrSort = qInfo->GetZoneOrSort();
12825 int32 skillOrClass = qInfo->GetSkillOrClass();
12827 // skip zone zoneOrSort and 0 case skillOrClass
12828 if( zoneOrSort >= 0 && skillOrClass == 0 )
12829 return true;
12831 int32 questSort = -zoneOrSort;
12832 uint8 reqSortClass = ClassByQuestSort(questSort);
12834 // check class sort cases in zoneOrSort
12835 if( reqSortClass != 0 && getClass() != reqSortClass)
12837 if( msg )
12838 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12839 return false;
12842 // check class
12843 if( skillOrClass < 0 )
12845 uint8 reqClass = -int32(skillOrClass);
12846 if(getClass() != reqClass)
12848 if( msg )
12849 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12850 return false;
12853 // check skill
12854 else if( skillOrClass > 0 )
12856 uint32 reqSkill = skillOrClass;
12857 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12859 if( msg )
12860 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12861 return false;
12865 return true;
12868 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12870 if( getLevel() < qInfo->GetMinLevel() )
12872 if( msg )
12873 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12874 return false;
12876 return true;
12879 bool Player::SatisfyQuestLog( bool msg )
12881 // exist free slot
12882 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12883 return true;
12885 if( msg )
12887 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12888 GetSession()->SendPacket( &data );
12889 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12891 return false;
12894 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12896 // No previous quest (might be first quest in a series)
12897 if( qInfo->prevQuests.empty())
12898 return true;
12900 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12902 uint32 prevId = abs(*iter);
12904 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12905 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12907 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12909 // If any of the positive previous quests completed, return true
12910 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12912 // skip one-from-all exclusive group
12913 if(qPrevInfo->GetExclusiveGroup() >= 0)
12914 return true;
12916 // each-from-all exclusive group ( < 0)
12917 // can be start if only all quests in prev quest exclusive group completed and rewarded
12918 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12919 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12921 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12923 for(; iter2 != end; ++iter2)
12925 uint32 exclude_Id = iter2->second;
12927 // skip checked quest id, only state of other quests in group is interesting
12928 if(exclude_Id == prevId)
12929 continue;
12931 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12933 // alternative quest from group also must be completed and rewarded(reported)
12934 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12936 if( msg )
12937 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12938 return false;
12941 return true;
12943 // If any of the negative previous quests active, return true
12944 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12945 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12947 // skip one-from-all exclusive group
12948 if(qPrevInfo->GetExclusiveGroup() >= 0)
12949 return true;
12951 // each-from-all exclusive group ( < 0)
12952 // can be start if only all quests in prev quest exclusive group active
12953 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12954 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12956 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12958 for(; iter2 != end; ++iter2)
12960 uint32 exclude_Id = iter2->second;
12962 // skip checked quest id, only state of other quests in group is interesting
12963 if(exclude_Id == prevId)
12964 continue;
12966 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12968 // alternative quest from group also must be active
12969 if( i_exstatus == mQuestStatus.end() ||
12970 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12971 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12973 if( msg )
12974 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12975 return false;
12978 return true;
12983 // Has only positive prev. quests in non-rewarded state
12984 // and negative prev. quests in non-active state
12985 if( msg )
12986 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12988 return false;
12991 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12993 uint32 reqraces = qInfo->GetRequiredRaces();
12994 if ( reqraces == 0 )
12995 return true;
12996 if( (reqraces & getRaceMask()) == 0 )
12998 if( msg )
12999 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
13000 return false;
13002 return true;
13005 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
13007 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
13008 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
13010 if( msg )
13011 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13012 return false;
13015 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
13016 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
13018 if( msg )
13019 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13020 return false;
13023 return true;
13026 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
13028 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
13029 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
13031 if( msg )
13032 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
13033 return false;
13035 return true;
13038 bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg)
13040 if (!m_timedquests.empty() && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED))
13042 if (msg)
13043 SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED);
13045 return false;
13047 return true;
13050 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
13052 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13053 if(qInfo->GetExclusiveGroup() <= 0)
13054 return true;
13056 ObjectMgr::ExclusiveQuestGroups::const_iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
13057 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
13059 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
13061 for(; iter != end; ++iter)
13063 uint32 exclude_Id = iter->second;
13065 // skip checked quest id, only state of other quests in group is interesting
13066 if(exclude_Id == qInfo->GetQuestId())
13067 continue;
13069 // not allow have daily quest if daily quest from exclusive group already recently completed
13070 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
13071 if( !SatisfyQuestDay(Nquest, false) )
13073 if( msg )
13074 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13075 return false;
13078 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13080 // alternative quest already started or completed
13081 if( i_exstatus != mQuestStatus.end()
13082 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
13084 if( msg )
13085 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13086 return false;
13089 return true;
13092 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
13094 if(!qInfo->GetNextQuestInChain())
13095 return true;
13097 // next quest in chain already started or completed
13098 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
13099 if( itr != mQuestStatus.end()
13100 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
13102 if( msg )
13103 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13104 return false;
13107 // check for all quests further up the chain
13108 // only necessary if there are quest chains with more than one quest that can be skipped
13109 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13110 return true;
13113 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
13115 // No previous quest in chain
13116 if( qInfo->prevChainQuests.empty())
13117 return true;
13119 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
13121 uint32 prevId = *iter;
13123 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
13125 if( i_prevstatus != mQuestStatus.end() )
13127 // If any of the previous quests in chain active, return false
13128 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13129 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
13131 if( msg )
13132 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13133 return false;
13137 // check for all quests further down the chain
13138 // only necessary if there are quest chains with more than one quest that can be skipped
13139 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13140 // return false;
13143 // No previous quest in chain active
13144 return true;
13147 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
13149 if(!qInfo->IsDaily())
13150 return true;
13152 bool have_slot = false;
13153 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
13155 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
13156 if(qInfo->GetQuestId()==id)
13157 return false;
13159 if(!id)
13160 have_slot = true;
13163 if(!have_slot)
13165 if( msg )
13166 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
13167 return false;
13170 return true;
13173 bool Player::GiveQuestSourceItem( Quest const *pQuest )
13175 uint32 srcitem = pQuest->GetSrcItemId();
13176 if( srcitem > 0 )
13178 uint32 count = pQuest->GetSrcItemCount();
13179 if( count <= 0 )
13180 count = 1;
13182 ItemPosCountVec dest;
13183 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13184 if( msg == EQUIP_ERR_OK )
13186 Item * item = StoreNewItem(dest, srcitem, true);
13187 SendNewItem(item, count, true, false);
13188 return true;
13190 // player already have max amount required item, just report success
13191 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13192 return true;
13193 else
13194 SendEquipError( msg, NULL, NULL );
13195 return false;
13198 return true;
13201 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13203 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13204 if( qInfo )
13206 uint32 srcitem = qInfo->GetSrcItemId();
13207 if( srcitem > 0 )
13209 uint32 count = qInfo->GetSrcItemCount();
13210 if( count <= 0 )
13211 count = 1;
13213 // exist one case when destroy source quest item not possible:
13214 // non un-equippable item (equipped non-empty bag, for example)
13215 uint8 res = CanUnequipItems(srcitem,count);
13216 if(res != EQUIP_ERR_OK)
13218 if(msg)
13219 SendEquipError( res, NULL, NULL );
13220 return false;
13223 DestroyItemCount(srcitem, count, true, true);
13226 return true;
13229 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13231 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13232 if( qInfo )
13234 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13235 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13236 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13237 && !qInfo->IsRepeatable() )
13238 return itr->second.m_rewarded;
13240 return false;
13242 return false;
13245 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13247 if( quest_id )
13249 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13250 if( itr != mQuestStatus.end() )
13251 return itr->second.m_status;
13253 return QUEST_STATUS_NONE;
13256 bool Player::CanShareQuest(uint32 quest_id) const
13258 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13259 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13261 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13262 if( itr != mQuestStatus.end() )
13263 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13265 return false;
13268 void Player::SetQuestStatus(uint32 quest_id, QuestStatus status)
13270 if (Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
13272 QuestStatusData& q_status = mQuestStatus[quest_id];
13274 q_status.m_status = status;
13276 if (q_status.uState != QUEST_NEW)
13277 q_status.uState = QUEST_CHANGED;
13280 UpdateForQuestWorldObjects();
13283 // not used in MaNGOS, but used in scripting code
13284 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13286 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13287 if( !qInfo )
13288 return 0;
13290 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13291 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13292 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13294 return 0;
13297 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13299 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13301 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13303 uint32 reqitemcount = pQuest->ReqItemCount[i];
13304 if( reqitemcount != 0 )
13306 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13308 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13309 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13315 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13317 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13318 if ( GetQuestSlotQuestId(i) == quest_id )
13319 return i;
13321 return MAX_QUEST_LOG_SIZE;
13324 void Player::AreaExploredOrEventHappens( uint32 questId )
13326 if( questId )
13328 uint16 log_slot = FindQuestSlot( questId );
13329 if( log_slot < MAX_QUEST_LOG_SIZE)
13331 QuestStatusData& q_status = mQuestStatus[questId];
13333 if(!q_status.m_explored)
13335 q_status.m_explored = true;
13336 if (q_status.uState != QUEST_NEW)
13337 q_status.uState = QUEST_CHANGED;
13340 if( CanCompleteQuest( questId ) )
13341 CompleteQuest( questId );
13345 //not used in mangosd, function for external script library
13346 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13348 if( Group *pGroup = GetGroup() )
13350 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13352 Player *pGroupGuy = itr->getSource();
13354 // for any leave or dead (with not released body) group member at appropriate distance
13355 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13356 pGroupGuy->AreaExploredOrEventHappens(questId);
13359 else
13360 AreaExploredOrEventHappens(questId);
13363 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13365 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13367 uint32 questid = GetQuestSlotQuestId(i);
13368 if ( questid == 0 )
13369 continue;
13371 QuestStatusData& q_status = mQuestStatus[questid];
13373 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13374 continue;
13376 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13377 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13378 continue;
13380 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13382 uint32 reqitem = qInfo->ReqItemId[j];
13383 if ( reqitem == entry )
13385 uint32 reqitemcount = qInfo->ReqItemCount[j];
13386 uint32 curitemcount = q_status.m_itemcount[j];
13387 if ( curitemcount < reqitemcount )
13389 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13390 q_status.m_itemcount[j] += additemcount;
13391 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13393 SendQuestUpdateAddItem( qInfo, j, additemcount );
13395 if ( CanCompleteQuest( questid ) )
13396 CompleteQuest( questid );
13397 return;
13401 UpdateForQuestWorldObjects();
13404 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13406 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13408 uint32 questid = GetQuestSlotQuestId(i);
13409 if(!questid)
13410 continue;
13411 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13412 if ( !qInfo )
13413 continue;
13414 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13415 continue;
13417 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13419 uint32 reqitem = qInfo->ReqItemId[j];
13420 if ( reqitem == entry )
13422 QuestStatusData& q_status = mQuestStatus[questid];
13424 uint32 reqitemcount = qInfo->ReqItemCount[j];
13425 uint32 curitemcount;
13426 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13427 curitemcount = q_status.m_itemcount[j];
13428 else
13429 curitemcount = GetItemCount(entry,true);
13430 if ( curitemcount < reqitemcount + count )
13432 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13433 q_status.m_itemcount[j] = curitemcount - remitemcount;
13434 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13436 IncompleteQuest( questid );
13438 return;
13442 UpdateForQuestWorldObjects();
13445 void Player::KilledMonster( CreatureInfo const* cInfo, uint64 guid )
13447 if(cInfo->Entry)
13448 KilledMonsterCredit(cInfo->Entry,guid);
13450 for(int i = 0; i < MAX_KILL_CREDIT; ++i)
13451 if(cInfo->KillCredit[i])
13452 KilledMonsterCredit(cInfo->KillCredit[i],guid);
13455 void Player::KilledMonsterCredit( uint32 entry, uint64 guid )
13457 uint32 addkillcount = 1;
13458 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13459 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13461 uint32 questid = GetQuestSlotQuestId(i);
13462 if(!questid)
13463 continue;
13465 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13466 if( !qInfo )
13467 continue;
13468 // just if !ingroup || !noraidgroup || raidgroup
13469 QuestStatusData& q_status = mQuestStatus[questid];
13470 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13472 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13474 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13476 // skip GO activate objective or none
13477 if(qInfo->ReqCreatureOrGOId[j] <=0)
13478 continue;
13480 // skip Cast at creature objective
13481 if(qInfo->ReqSpell[j] !=0 )
13482 continue;
13484 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13486 if ( reqkill == entry )
13488 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13489 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13490 if ( curkillcount < reqkillcount )
13492 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13493 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13495 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13497 if ( CanCompleteQuest( questid ) )
13498 CompleteQuest( questid );
13500 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13501 continue;
13509 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13511 bool isCreature = IS_CREATURE_GUID(guid);
13513 uint32 addCastCount = 1;
13514 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
13516 uint32 questid = GetQuestSlotQuestId(i);
13517 if(!questid)
13518 continue;
13520 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13521 if ( !qInfo )
13522 continue;
13524 QuestStatusData& q_status = mQuestStatus[questid];
13526 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13528 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13530 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13532 // skip kill creature objective (0) or wrong spell casts
13533 if(qInfo->ReqSpell[j] != spell_id )
13534 continue;
13536 uint32 reqTarget = 0;
13538 if(isCreature)
13540 // creature activate objectives
13541 if(qInfo->ReqCreatureOrGOId[j] > 0)
13542 // checked at quest_template loading
13543 reqTarget = qInfo->ReqCreatureOrGOId[j];
13545 else
13547 // GO activate objective
13548 if(qInfo->ReqCreatureOrGOId[j] < 0)
13549 // checked at quest_template loading
13550 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13553 // other not this creature/GO related objectives
13554 if( reqTarget != entry )
13555 continue;
13557 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13558 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13559 if ( curCastCount < reqCastCount )
13561 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13562 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13564 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13567 if ( CanCompleteQuest( questid ) )
13568 CompleteQuest( questid );
13570 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13571 break;
13578 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13580 uint32 addTalkCount = 1;
13581 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13583 uint32 questid = GetQuestSlotQuestId(i);
13584 if(!questid)
13585 continue;
13587 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13588 if ( !qInfo )
13589 continue;
13591 QuestStatusData& q_status = mQuestStatus[questid];
13593 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13595 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13597 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13599 // skip spell casts and Gameobject objectives
13600 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13601 continue;
13603 uint32 reqTarget = 0;
13605 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13606 // checked at quest_template loading
13607 reqTarget = qInfo->ReqCreatureOrGOId[j];
13608 else
13609 continue;
13611 if ( reqTarget == entry )
13613 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13614 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13615 if ( curTalkCount < reqTalkCount )
13617 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13618 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13620 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13622 if ( CanCompleteQuest( questid ) )
13623 CompleteQuest( questid );
13625 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13626 continue;
13634 void Player::MoneyChanged( uint32 count )
13636 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13638 uint32 questid = GetQuestSlotQuestId(i);
13639 if (!questid)
13640 continue;
13642 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13643 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13645 QuestStatusData& q_status = mQuestStatus[questid];
13647 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13649 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13651 if ( CanCompleteQuest( questid ) )
13652 CompleteQuest( questid );
13655 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13657 if(int32(count) < -qInfo->GetRewOrReqMoney())
13658 IncompleteQuest( questid );
13664 void Player::ReputationChanged(FactionEntry const* factionEntry )
13666 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13668 if(uint32 questid = GetQuestSlotQuestId(i))
13670 if(Quest const* qInfo = objmgr.GetQuestTemplate(questid))
13672 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
13674 QuestStatusData& q_status = mQuestStatus[questid];
13675 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13677 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
13678 if ( CanCompleteQuest( questid ) )
13679 CompleteQuest( questid );
13681 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13683 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
13684 IncompleteQuest( questid );
13692 bool Player::HasQuestForItem( uint32 itemid ) const
13694 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13696 uint32 questid = GetQuestSlotQuestId(i);
13697 if ( questid == 0 )
13698 continue;
13700 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
13701 if(qs_itr == mQuestStatus.end())
13702 continue;
13704 QuestStatusData const& q_status = qs_itr->second;
13706 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13708 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
13709 if(!qinfo)
13710 continue;
13712 // hide quest if player is in raid-group and quest is no raid quest
13713 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13714 continue;
13716 // There should be no mixed ReqItem/ReqSource drop
13717 // This part for ReqItem drop
13718 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13720 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13721 return true;
13723 // This part - for ReqSource
13724 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
13726 // examined item is a source item
13727 if (qinfo->ReqSourceId[j] == itemid)
13729 ItemPrototype const *pProto = objmgr.GetItemPrototype(itemid);
13731 // 'unique' item
13732 if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
13733 return true;
13735 // allows custom amount drop when not 0
13736 if (qinfo->ReqSourceCount[j])
13738 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13739 return true;
13740 } else if (GetItemCount(itemid,true) < pProto->Stackable)
13741 return true;
13746 return false;
13749 void Player::SendQuestComplete( uint32 quest_id )
13751 if( quest_id )
13753 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13754 data << uint32(quest_id);
13755 GetSession()->SendPacket( &data );
13756 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13760 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13762 uint32 questid = pQuest->GetQuestId();
13763 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13764 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13765 data << uint32(questid);
13767 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13769 data << uint32(XP);
13770 data << uint32(pQuest->GetRewOrReqMoney());
13772 else
13774 data << uint32(0);
13775 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13778 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13779 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13780 GetSession()->SendPacket( &data );
13782 if (pQuest->GetQuestCompleteScript() != 0)
13783 GetMap()->ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13786 void Player::SendQuestFailed( uint32 quest_id )
13788 if( quest_id )
13790 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13791 data << quest_id;
13792 data << uint32(0); // failed reason (4 for inventory is full)
13793 GetSession()->SendPacket( &data );
13794 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13798 void Player::SendQuestTimerFailed( uint32 quest_id )
13800 if( quest_id )
13802 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13803 data << quest_id;
13804 GetSession()->SendPacket( &data );
13805 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13809 void Player::SendCanTakeQuestResponse( uint32 msg )
13811 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13812 data << uint32(msg);
13813 GetSession()->SendPacket( &data );
13814 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13817 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13819 if( pPlayer )
13821 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13822 data << uint64(pPlayer->GetGUID());
13823 data << uint8(msg); // valid values: 0-8
13824 GetSession()->SendPacket( &data );
13825 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13829 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13831 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13832 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13833 //data << pQuest->ReqItemId[item_idx];
13834 //data << count;
13835 GetSession()->SendPacket( &data );
13838 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13840 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13842 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13843 if (entry < 0)
13844 // client expected gameobject template id in form (id|0x80000000)
13845 entry = (-entry) | 0x80000000;
13847 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13848 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13849 data << uint32(pQuest->GetQuestId());
13850 data << uint32(entry);
13851 data << uint32(old_count + add_count);
13852 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13853 data << uint64(guid);
13854 GetSession()->SendPacket(&data);
13856 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13857 if( log_slot < MAX_QUEST_LOG_SIZE)
13858 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13861 /*********************************************************/
13862 /*** LOAD SYSTEM ***/
13863 /*********************************************************/
13865 void Player::_LoadDeclinedNames(QueryResult* result)
13867 if(!result)
13868 return;
13870 if(m_declinedname)
13871 delete m_declinedname;
13873 m_declinedname = new DeclinedName;
13874 Field *fields = result->Fetch();
13875 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13876 m_declinedname->name[i] = fields[i].GetCppString();
13878 delete result;
13881 void Player::_LoadArenaTeamInfo(QueryResult *result)
13883 // arenateamid, played_week, played_season, personal_rating
13884 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
13885 if (!result)
13886 return;
13890 Field *fields = result->Fetch();
13892 uint32 arenateamid = fields[0].GetUInt32();
13893 uint32 played_week = fields[1].GetUInt32();
13894 uint32 played_season = fields[2].GetUInt32();
13895 uint32 personal_rating = fields[3].GetUInt32();
13897 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
13898 if(!aTeam)
13900 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
13901 continue;
13903 uint8 arenaSlot = aTeam->GetSlot();
13905 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
13906 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
13907 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
13908 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
13909 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
13910 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
13912 }while (result->NextRow());
13913 delete result;
13916 void Player::_LoadEquipmentSets(QueryResult *result)
13918 // SetPQuery(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS, "SELECT setguid, setindex, name, iconname, item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18 FROM character_equipmentsets WHERE guid = '%u' ORDER BY setindex", GUID_LOPART(m_guid));
13919 if (!result)
13920 return;
13922 uint32 count = 0;
13925 Field *fields = result->Fetch();
13927 EquipmentSet eqSet;
13929 eqSet.Guid = fields[0].GetUInt64();
13930 uint32 index = fields[1].GetUInt32();
13931 eqSet.Name = fields[2].GetCppString();
13932 eqSet.IconName = fields[3].GetCppString();
13933 eqSet.state = EQUIPMENT_SET_UNCHANGED;
13935 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
13936 eqSet.Items[i] = fields[4+i].GetUInt32();
13938 m_EquipmentSets[index] = eqSet;
13940 ++count;
13942 if(count >= MAX_EQUIPMENT_SET_INDEX) // client limit
13943 break;
13944 } while (result->NextRow());
13945 delete result;
13948 void Player::_LoadBGData(QueryResult* result)
13950 if (!result)
13951 return;
13953 // Expecting only one row
13954 Field *fields = result->Fetch();
13955 /* bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
13956 m_bgData.bgInstanceID = fields[0].GetUInt32();
13957 m_bgData.bgTeam = fields[1].GetUInt32();
13958 m_bgData.joinPos = WorldLocation(fields[6].GetUInt32(), // Map
13959 fields[2].GetFloat(), // X
13960 fields[3].GetFloat(), // Y
13961 fields[4].GetFloat(), // Z
13962 fields[5].GetFloat()); // Orientation
13963 m_bgData.taxiPath[0] = fields[7].GetUInt32();
13964 m_bgData.taxiPath[1] = fields[8].GetUInt32();
13965 m_bgData.mountSpell = fields[9].GetUInt32();
13967 delete result;
13970 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13972 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13973 if(!result)
13974 return false;
13976 Field *fields = result->Fetch();
13978 x = fields[0].GetFloat();
13979 y = fields[1].GetFloat();
13980 z = fields[2].GetFloat();
13981 o = fields[3].GetFloat();
13982 mapid = fields[4].GetUInt32();
13983 in_flight = !fields[5].GetCppString().empty();
13985 delete result;
13986 return true;
13989 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13991 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13992 if( !result )
13993 return false;
13995 Field *fields = result->Fetch();
13997 data = StrSplit(fields[0].GetCppString(), " ");
13999 delete result;
14001 return true;
14004 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
14006 if(index >= data.size())
14007 return 0;
14009 return (uint32)atoi(data[index].c_str());
14012 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
14014 float result;
14015 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
14016 memcpy(&result, &temp, sizeof(result));
14018 return result;
14021 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
14023 Tokens data;
14024 if(!LoadValuesArrayFromDB(data,guid))
14025 return 0;
14027 return GetUInt32ValueFromArray(data,index);
14030 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
14032 float result;
14033 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
14034 memcpy(&result, &temp, sizeof(result));
14036 return result;
14039 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
14041 //// 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
14042 //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags, 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 FROM characters WHERE guid = '%u'", guid);
14043 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
14045 if(!result)
14047 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
14048 return false;
14051 Field *fields = result->Fetch();
14053 uint32 dbAccountId = fields[1].GetUInt32();
14055 // check if the character's account in the db and the logged in account match.
14056 // player should be able to load/delete character only with correct account!
14057 if( dbAccountId != GetSession()->GetAccountId() )
14059 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
14060 delete result;
14061 return false;
14064 Object::_Create( guid, 0, HIGHGUID_PLAYER );
14066 m_name = fields[3].GetCppString();
14068 // check name limitations
14069 if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS ||
14070 (GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name)))
14072 delete result;
14073 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
14074 return false;
14077 if(!LoadValues( fields[2].GetString()))
14079 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid));
14080 delete result;
14081 return false;
14084 // overwrite possible wrong/corrupted guid
14085 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
14087 // overwrite some data fields
14088 uint32 bytes0 = GetUInt32Value(UNIT_FIELD_BYTES_0) & 0xFF000000;
14089 bytes0 |= fields[4].GetUInt8(); // race
14090 bytes0 |= fields[5].GetUInt8() << 8; // class
14091 bytes0 |= fields[6].GetUInt8() << 16; // gender
14092 SetUInt32Value(UNIT_FIELD_BYTES_0, bytes0);
14094 SetUInt32Value(UNIT_FIELD_LEVEL, fields[7].GetUInt8());
14095 SetUInt32Value(PLAYER_XP, fields[8].GetUInt32());
14096 SetUInt32Value(PLAYER_FIELD_COINAGE, fields[9].GetUInt32());
14097 SetUInt32Value(PLAYER_BYTES, fields[10].GetUInt32());
14098 SetUInt32Value(PLAYER_BYTES_2, fields[11].GetUInt32());
14099 SetUInt32Value(PLAYER_BYTES_3, (GetUInt32Value(PLAYER_BYTES_3) & ~1) | fields[6].GetUInt8());
14100 SetUInt32Value(PLAYER_FLAGS, fields[12].GetUInt32());
14102 InitDisplayIds();
14104 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14105 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
14107 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0 );
14108 SetVisibleItemSlot(slot, NULL);
14110 if (m_items[slot])
14112 delete m_items[slot];
14113 m_items[slot] = NULL;
14117 // update money limits
14118 if(GetMoney() > MAX_MONEY_AMOUNT)
14119 SetMoney(MAX_MONEY_AMOUNT);
14121 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
14122 outDebugValues();
14124 //Need to call it to initialize m_team (m_team can be calculated from race)
14125 //Other way is to saves m_team into characters table.
14126 setFactionForRace(getRace());
14127 SetCharm(NULL);
14129 // load home bind and check in same time class/race pair, it used later for restore broken positions
14130 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
14132 delete result;
14133 return false;
14136 InitPrimaryProfessions(); // to max set before any spell loaded
14138 // init saved position, and fix it later if problematic
14139 uint32 transGUID = fields[31].GetUInt32();
14140 Relocate(fields[13].GetFloat(),fields[14].GetFloat(),fields[15].GetFloat(),fields[17].GetFloat());
14141 SetLocationMapId(fields[16].GetUInt32());
14142 SetDifficulty(fields[39].GetUInt32()); // may be changed in _LoadGroup
14144 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
14146 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
14148 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[40].GetUInt32();
14149 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
14150 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
14152 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
14154 // check arena teams integrity
14155 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
14157 uint32 arena_team_id = GetArenaTeamId(arena_slot);
14158 if(!arena_team_id)
14159 continue;
14161 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
14162 if(at->HaveMember(GetGUID()))
14163 continue;
14165 // arena team not exist or not member, cleanup fields
14166 for(int j =0; j < 6; ++j)
14167 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
14170 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
14172 if(!IsPositionValid())
14174 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());
14175 RelocateToHomebind();
14177 transGUID = 0;
14179 m_movementInfo.t_x = 0.0f;
14180 m_movementInfo.t_y = 0.0f;
14181 m_movementInfo.t_z = 0.0f;
14182 m_movementInfo.t_o = 0.0f;
14185 _LoadBGData(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBGDATA));
14187 if(m_bgData.bgInstanceID) //saved in BattleGround
14189 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(m_bgData.bgInstanceID, BATTLEGROUND_TYPE_NONE);
14191 if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID()))
14193 BattleGroundQueueTypeId bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
14194 AddBattleGroundQueueId(bgQueueTypeId);
14196 m_bgData.bgTypeID = currentBg->GetTypeID();
14198 //join player to battleground group
14199 currentBg->EventPlayerLoggedIn(this, GetGUID());
14200 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), m_bgData.bgTeam);
14202 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
14204 else
14206 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14207 SetLocationMapId(_loc.mapid);
14208 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14210 // We are not in BG anymore
14211 m_bgData.bgInstanceID = 0;
14214 else
14216 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14217 // if server restart after player save in BG or area
14218 // player can have current coordinates in to BG/Arean map, fix this
14219 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
14221 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14222 SetLocationMapId(_loc.mapid);
14223 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14227 if (transGUID != 0)
14229 m_movementInfo.t_x = fields[27].GetFloat();
14230 m_movementInfo.t_y = fields[28].GetFloat();
14231 m_movementInfo.t_z = fields[29].GetFloat();
14232 m_movementInfo.t_o = fields[30].GetFloat();
14234 if( !MaNGOS::IsValidMapCoord(
14235 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14236 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
14237 // transport size limited
14238 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
14240 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14241 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14242 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
14244 RelocateToHomebind();
14246 m_movementInfo.t_x = 0.0f;
14247 m_movementInfo.t_y = 0.0f;
14248 m_movementInfo.t_z = 0.0f;
14249 m_movementInfo.t_o = 0.0f;
14251 transGUID = 0;
14255 if (transGUID != 0)
14257 for (MapManager::TransportSet::const_iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
14259 if( (*iter)->GetGUIDLow() == transGUID)
14261 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
14262 // client without expansion support
14263 if(GetSession()->Expansion() < transMapEntry->Expansion())
14265 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
14266 break;
14269 m_transport = *iter;
14270 m_transport->AddPassenger(this);
14271 SetLocationMapId(m_transport->GetMapId());
14272 break;
14276 if(!m_transport)
14278 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14279 guid,transGUID);
14281 RelocateToHomebind();
14283 m_movementInfo.t_x = 0.0f;
14284 m_movementInfo.t_y = 0.0f;
14285 m_movementInfo.t_z = 0.0f;
14286 m_movementInfo.t_o = 0.0f;
14288 transGUID = 0;
14291 else // not transport case
14293 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14294 // client without expansion support
14295 if(GetSession()->Expansion() < mapEntry->Expansion())
14297 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14298 RelocateToHomebind();
14302 // NOW player must have valid map
14303 // load the player's map here if it's not already loaded
14304 SetMap(MapManager::Instance().CreateMap(GetMapId(), this));
14306 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14307 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
14309 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
14310 if(at)
14311 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14312 else
14313 sLog.outError("Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no area-trigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), GetMapId());
14316 SaveRecallPosition();
14318 time_t now = time(NULL);
14319 time_t logoutTime = time_t(fields[23].GetUInt64());
14321 // since last logout (in seconds)
14322 uint64 time_diff = uint64(now - logoutTime);
14324 // set value, including drunk invisibility detection
14325 // calculate sobering. after 15 minutes logged out, the player will be sober again
14326 float soberFactor;
14327 if(time_diff > 15*MINUTE)
14328 soberFactor = 0;
14329 else
14330 soberFactor = 1-time_diff/(15.0f*MINUTE);
14331 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14332 SetDrunkValue(newDrunkenValue);
14334 m_rest_bonus = fields[22].GetFloat();
14335 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14336 float bubble0 = 0.031;
14337 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14338 float bubble1 = 0.125;
14340 if(time_diff > 0)
14342 float bubble = fields[24].GetUInt32() > 0
14343 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14344 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14346 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14349 m_cinematic = fields[19].GetUInt32();
14350 m_Played_time[PLAYED_TIME_TOTAL]= fields[20].GetUInt32();
14351 m_Played_time[PLAYED_TIME_LEVEL]= fields[21].GetUInt32();
14353 m_resetTalentsCost = fields[25].GetUInt32();
14354 m_resetTalentsTime = time_t(fields[26].GetUInt64());
14356 // reserve some flags
14357 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14359 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14360 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14362 m_taxi.LoadTaxiMask( fields[18].GetString() ); // must be before InitTaxiNodesForLevel
14364 uint32 extraflags = fields[32].GetUInt32();
14366 m_stableSlots = fields[33].GetUInt32();
14367 if(m_stableSlots > MAX_PET_STABLES)
14369 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
14370 m_stableSlots = MAX_PET_STABLES;
14373 m_atLoginFlags = fields[34].GetUInt32();
14375 // Honor system
14376 // Update Honor kills data
14377 m_lastHonorUpdateTime = logoutTime;
14378 UpdateHonorFields();
14380 m_deathExpireTime = (time_t)fields[37].GetUInt64();
14381 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14382 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14384 std::string taxi_nodes = fields[38].GetCppString();
14386 delete result;
14388 // clear channel spell data (if saved at channel spell casting)
14389 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14390 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14392 // clear charm/summon related fields
14393 SetCharm(NULL);
14394 SetPet(NULL);
14395 SetCharmerGUID(0);
14396 SetOwnerGUID(0);
14397 SetCreatorGUID(0);
14399 // reset some aura modifiers before aura apply
14400 SetFarSightGUID(0);
14401 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14402 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14404 _LoadSkills();
14406 // make sure the unit is considered out of combat for proper loading
14407 ClearInCombat();
14409 // make sure the unit is considered not in duel for proper loading
14410 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14411 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14413 // remember loaded power/health values to restore after stats initialization and modifier applying
14414 uint32 savedHealth = GetHealth();
14415 uint32 savedPower[MAX_POWERS];
14416 for(uint32 i = 0; i < MAX_POWERS; ++i)
14417 savedPower[i] = GetPower(Powers(i));
14419 // reset stats before loading any modifiers
14420 InitStatsForLevel();
14421 InitTaxiNodesForLevel();
14422 InitGlyphsForLevel();
14423 InitRunes();
14425 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14427 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14428 //_LoadMail();
14430 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14431 _LoadGlyphAuras();
14433 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14434 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14435 m_deathState = DEAD;
14437 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14439 // after spell load, learn rewarded spell if need also
14440 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14441 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14443 // after spell and quest load
14444 InitTalentForLevel();
14445 learnDefaultSpells();
14447 // must be before inventory (some items required reputation check)
14448 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14450 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14452 // update items with duration and realtime
14453 UpdateItemDuration(time_diff, true);
14455 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14457 // unread mails and next delivery time, actual mails not loaded
14458 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14460 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14462 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14463 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14464 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14466 if(!HasTitle(curTitle))
14467 SetUInt32Value(PLAYER_CHOSEN_TITLE, 0);
14470 // Not finish taxi flight path
14471 if(m_bgData.HasTaxiPath())
14473 m_taxi.ClearTaxiDestinations();
14474 for (int i = 0; i < 2; ++i)
14475 m_taxi.AddTaxiDestination(m_bgData.taxiPath[i]);
14477 else if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14479 // problems with taxi path loading
14480 TaxiNodesEntry const* nodeEntry = NULL;
14481 if(uint32 node_id = m_taxi.GetTaxiSource())
14482 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14484 if(!nodeEntry) // don't know taxi start node, to homebind
14486 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14487 RelocateToHomebind();
14489 else // have start node, to it
14491 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14492 SetLocationMapId(nodeEntry->map_id);
14493 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14496 //we can be relocated from taxi and still have an outdated Map pointer!
14497 //so we need to get a new Map pointer!
14498 SetMap(MapManager::Instance().CreateMap(GetMapId(), this));
14499 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14501 m_taxi.ClearTaxiDestinations();
14504 if(uint32 node_id = m_taxi.GetTaxiSource())
14506 // save source node as recall coord to prevent recall and fall from sky
14507 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14508 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14509 m_recallMap = nodeEntry->map_id;
14510 m_recallX = nodeEntry->x;
14511 m_recallY = nodeEntry->y;
14512 m_recallZ = nodeEntry->z;
14514 // flight will started later
14517 // has to be called after last Relocate() in Player::LoadFromDB
14518 SetFallInformation(0, GetPositionZ());
14520 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14522 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14523 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14524 if(!isAlive())
14525 RemoveAllAurasOnDeath();
14527 //apply all stat bonuses from items and auras
14528 SetCanModifyStats(true);
14529 UpdateAllStats();
14531 // restore remembered power/health values (but not more max values)
14532 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14533 for(uint32 i = 0; i < MAX_POWERS; ++i)
14534 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14536 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14537 outDebugValues();
14539 // GM state
14540 if(GetSession()->GetSecurity() > SEC_PLAYER)
14542 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14544 default:
14545 case 0: break; // disable
14546 case 1: SetGameMaster(true); break; // enable
14547 case 2: // save state
14548 if(extraflags & PLAYER_EXTRA_GM_ON)
14549 SetGameMaster(true);
14550 break;
14553 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
14555 default:
14556 case 0: SetGMVisible(false); break; // invisible
14557 case 1: break; // visible
14558 case 2: // save state
14559 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
14560 SetGMVisible(false);
14561 break;
14564 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14566 default:
14567 case 0: break; // disable
14568 case 1: SetAcceptTicket(true); break; // enable
14569 case 2: // save state
14570 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14571 SetAcceptTicket(true);
14572 break;
14575 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14577 default:
14578 case 0: break; // disable
14579 case 1: SetGMChat(true); break; // enable
14580 case 2: // save state
14581 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14582 SetGMChat(true);
14583 break;
14586 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14588 default:
14589 case 0: break; // disable
14590 case 1: SetAcceptWhispers(true); break; // enable
14591 case 2: // save state
14592 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14593 SetAcceptWhispers(true);
14594 break;
14598 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14600 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14601 m_achievementMgr.CheckAllAchievementCriteria();
14603 _LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
14605 return true;
14608 bool Player::isAllowedToLoot(Creature* creature)
14610 if(Player* recipient = creature->GetLootRecipient())
14612 if (recipient == this)
14613 return true;
14614 if( Group* otherGroup = recipient->GetGroup())
14616 Group* thisGroup = GetGroup();
14617 if(!thisGroup)
14618 return false;
14619 return thisGroup == otherGroup;
14621 return false;
14623 else
14624 // prevent other players from looting if the recipient got disconnected
14625 return !creature->hasLootRecipient();
14628 void Player::_LoadActions(QueryResult *result)
14630 m_actionButtons.clear();
14632 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14634 if(result)
14638 Field *fields = result->Fetch();
14640 uint8 button = fields[0].GetUInt8();
14641 uint32 action = fields[1].GetUInt32();
14642 uint8 type = fields[2].GetUInt8();
14644 if(ActionButton* ab = addActionButton(button, action, type))
14645 ab->uState = ACTIONBUTTON_UNCHANGED;
14646 else
14648 sLog.outError( " ...at loading, and will deleted in DB also");
14650 // Will deleted in DB at next save (it can create data until save but marked as deleted)
14651 m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
14654 while( result->NextRow() );
14656 delete result;
14660 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14662 m_Auras.clear();
14663 for (int i = 0; i < TOTAL_AURAS; ++i)
14664 m_modAuras[i].clear();
14666 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14668 if(result)
14672 Field *fields = result->Fetch();
14673 uint64 caster_guid = fields[0].GetUInt64();
14674 uint32 spellid = fields[1].GetUInt32();
14675 uint32 effindex = fields[2].GetUInt32();
14676 uint32 stackcount = fields[3].GetUInt32();
14677 int32 damage = (int32)fields[4].GetUInt32();
14678 int32 maxduration = (int32)fields[5].GetUInt32();
14679 int32 remaintime = (int32)fields[6].GetUInt32();
14680 int32 remaincharges = (int32)fields[7].GetUInt32();
14682 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14683 if(!spellproto)
14685 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14686 continue;
14689 if(effindex >= 3)
14691 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14692 continue;
14695 // negative effects should continue counting down after logout
14696 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14698 if(remaintime <= int32(timediff))
14699 continue;
14701 remaintime -= timediff;
14704 // prevent wrong values of remaincharges
14705 if(spellproto->procCharges)
14707 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14708 remaincharges = spellproto->procCharges;
14710 else
14711 remaincharges = 0;
14714 for(uint32 i=0; i<stackcount; ++i)
14716 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14717 if(!damage)
14718 damage = aura->GetModifier()->m_amount;
14720 // reset stolen single target auras
14721 if (caster_guid != GetGUID() && aura->IsSingleTarget())
14722 aura->SetIsSingleTarget(false);
14724 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14725 AddAura(aura);
14726 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14729 while( result->NextRow() );
14731 delete result;
14734 if(getClass() == CLASS_WARRIOR && !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT))
14735 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14738 void Player::_LoadGlyphAuras()
14740 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
14742 if (uint32 glyph = GetGlyph(i))
14744 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
14746 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
14748 if(gp->TypeFlags == gs->TypeFlags)
14750 CastSpell(this, gp->SpellId, true);
14751 continue;
14753 else
14754 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
14756 else
14757 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
14759 else
14760 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
14762 // On any error remove glyph
14763 SetGlyph(i, 0);
14768 void Player::LoadCorpse()
14770 if( isAlive() )
14772 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14774 else
14776 if(Corpse *corpse = GetCorpse())
14778 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14780 else
14782 //Prevent Dead Player login without corpse
14783 ResurrectPlayer(0.5f);
14788 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14790 //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());
14791 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14792 //NOTE: the "order by `bag`" is important because it makes sure
14793 //the bagMap is filled before items in the bags are loaded
14794 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14795 //expected to be equipped before offhand items (TODO: fixme)
14797 uint32 zone = GetZoneId();
14799 if (result)
14801 std::list<Item*> problematicItems;
14803 // prevent items from being added to the queue when stored
14804 m_itemUpdateQueueBlocked = true;
14807 Field *fields = result->Fetch();
14808 uint32 bag_guid = fields[1].GetUInt32();
14809 uint8 slot = fields[2].GetUInt8();
14810 uint32 item_guid = fields[3].GetUInt32();
14811 uint32 item_id = fields[4].GetUInt32();
14813 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14815 if(!proto)
14817 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14818 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14819 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14820 continue;
14823 Item *item = NewItemOrBag(proto);
14825 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14827 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14828 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14829 item->FSetState(ITEM_REMOVED);
14830 item->SaveToDB(); // it also deletes item object !
14831 continue;
14834 // not allow have in alive state item limited to another map/zone
14835 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14837 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14838 item->FSetState(ITEM_REMOVED);
14839 item->SaveToDB(); // it also deletes item object !
14840 continue;
14843 // "Conjured items disappear if you are logged out for more than 15 minutes"
14844 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14846 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14847 item->FSetState(ITEM_REMOVED);
14848 item->SaveToDB(); // it also deletes item object !
14849 continue;
14852 bool success = true;
14854 if (!bag_guid)
14856 // the item is not in a bag
14857 item->SetContainer( NULL );
14858 item->SetSlot(slot);
14860 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14862 ItemPosCountVec dest;
14863 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14864 item = StoreItem(dest, item, true);
14865 else
14866 success = false;
14868 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14870 uint16 dest;
14871 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14872 QuickEquipItem(dest, item);
14873 else
14874 success = false;
14876 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14878 ItemPosCountVec dest;
14879 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14880 item = BankItem(dest, item, true);
14881 else
14882 success = false;
14885 if(success)
14887 // store bags that may contain items in them
14888 if(item->IsBag() && IsBagPos(item->GetPos()))
14889 bagMap[item_guid] = (Bag*)item;
14892 else
14894 item->SetSlot(NULL_SLOT);
14895 // the item is in a bag, find the bag
14896 std::map<uint64, Bag*>::const_iterator itr = bagMap.find(bag_guid);
14897 if(itr != bagMap.end() && slot < itr->second->GetBagSize())
14898 itr->second->StoreItem(slot, item, true );
14899 else
14900 success = false;
14903 // item's state may have changed after stored
14904 if (success)
14905 item->SetState(ITEM_UNCHANGED, this);
14906 else
14908 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);
14909 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14910 problematicItems.push_back(item);
14912 } while (result->NextRow());
14914 delete result;
14915 m_itemUpdateQueueBlocked = false;
14917 // send by mail problematic items
14918 while(!problematicItems.empty())
14920 // fill mail
14921 MailItemsInfo mi; // item list preparing
14923 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14925 Item* item = problematicItems.front();
14926 problematicItems.pop_front();
14928 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14931 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14933 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14936 //if(isAlive())
14937 _ApplyAllItemMods();
14940 // load mailed item which should receive current player
14941 void Player::_LoadMailedItems(Mail *mail)
14943 // data needs to be at first place for Item::LoadFromDB
14944 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);
14945 if(!result)
14946 return;
14950 Field *fields = result->Fetch();
14951 uint32 item_guid_low = fields[1].GetUInt32();
14952 uint32 item_template = fields[2].GetUInt32();
14954 mail->AddItem(item_guid_low, item_template);
14956 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14958 if(!proto)
14960 sLog.outError( "Player %u has unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), item_guid_low, item_template,mail->messageID);
14961 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14962 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14963 continue;
14966 Item *item = NewItemOrBag(proto);
14968 if(!item->LoadFromDB(item_guid_low, 0, result))
14970 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14971 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14972 item->FSetState(ITEM_REMOVED);
14973 item->SaveToDB(); // it also deletes item object !
14974 continue;
14977 AddMItem(item);
14978 } while (result->NextRow());
14980 delete result;
14983 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14985 //set a count of unread mails
14986 //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);
14987 if (resultUnread)
14989 Field *fieldMail = resultUnread->Fetch();
14990 unReadMails = fieldMail[0].GetUInt8();
14991 delete resultUnread;
14994 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14995 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14996 if (resultDelivery)
14998 Field *fieldMail = resultDelivery->Fetch();
14999 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
15000 delete resultDelivery;
15004 void Player::_LoadMail()
15006 m_mail.clear();
15007 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
15008 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());
15009 if(result)
15013 Field *fields = result->Fetch();
15014 Mail *m = new Mail;
15015 m->messageID = fields[0].GetUInt32();
15016 m->messageType = fields[1].GetUInt8();
15017 m->sender = fields[2].GetUInt32();
15018 m->receiver = fields[3].GetUInt32();
15019 m->subject = fields[4].GetCppString();
15020 m->itemTextId = fields[5].GetUInt32();
15021 bool has_items = fields[6].GetBool();
15022 m->expire_time = (time_t)fields[7].GetUInt64();
15023 m->deliver_time = (time_t)fields[8].GetUInt64();
15024 m->money = fields[9].GetUInt32();
15025 m->COD = fields[10].GetUInt32();
15026 m->checked = fields[11].GetUInt32();
15027 m->stationery = fields[12].GetUInt8();
15028 m->mailTemplateId = fields[13].GetInt16();
15030 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
15032 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
15033 m->mailTemplateId = 0;
15036 m->state = MAIL_STATE_UNCHANGED;
15038 if (has_items)
15039 _LoadMailedItems(m);
15041 m_mail.push_back(m);
15042 } while( result->NextRow() );
15043 delete result;
15045 m_mailsLoaded = true;
15048 void Player::LoadPet()
15050 //fixme: the pet should still be loaded if the player is not in world
15051 // just not added to the map
15052 if(IsInWorld())
15054 Pet *pet = new Pet;
15055 if(!pet->LoadPetFromDB(this,0,0,true))
15056 delete pet;
15060 void Player::_LoadQuestStatus(QueryResult *result)
15062 mQuestStatus.clear();
15064 uint32 slot = 0;
15066 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15067 //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());
15069 if(result)
15073 Field *fields = result->Fetch();
15075 uint32 quest_id = fields[0].GetUInt32();
15076 // used to be new, no delete?
15077 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15078 if( pQuest )
15080 // find or create
15081 QuestStatusData& questStatusData = mQuestStatus[quest_id];
15083 uint32 qstatus = fields[1].GetUInt32();
15084 if(qstatus < MAX_QUEST_STATUS)
15085 questStatusData.m_status = QuestStatus(qstatus);
15086 else
15088 questStatusData.m_status = QUEST_STATUS_NONE;
15089 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
15092 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
15093 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
15095 time_t quest_time = time_t(fields[4].GetUInt64());
15097 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
15099 AddTimedQuest( quest_id );
15101 if (quest_time <= sWorld.GetGameTime())
15102 questStatusData.m_timer = 1;
15103 else
15104 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
15106 else
15107 quest_time = 0;
15109 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
15110 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
15111 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
15112 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
15113 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
15114 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
15115 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
15116 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
15118 questStatusData.uState = QUEST_UNCHANGED;
15120 // add to quest log
15121 if (slot < MAX_QUEST_LOG_SIZE &&
15122 ((questStatusData.m_status == QUEST_STATUS_INCOMPLETE ||
15123 questStatusData.m_status == QUEST_STATUS_COMPLETE ||
15124 questStatusData.m_status == QUEST_STATUS_FAILED) &&
15125 (!questStatusData.m_rewarded || pQuest->IsRepeatable())))
15127 SetQuestSlot(slot, quest_id, quest_time);
15129 if (questStatusData.m_status == QUEST_STATUS_COMPLETE)
15130 SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
15132 if (questStatusData.m_status == QUEST_STATUS_FAILED)
15133 SetQuestSlotState(slot, QUEST_STATE_FAIL);
15135 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
15136 if(questStatusData.m_creatureOrGOcount[idx])
15137 SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]);
15139 ++slot;
15142 if(questStatusData.m_rewarded)
15144 // learn rewarded spell if unknown
15145 learnQuestRewardedSpells(pQuest);
15147 // set rewarded title if any
15148 if(pQuest->GetCharTitleId())
15150 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
15151 SetTitle(titleEntry);
15154 if(pQuest->GetBonusTalents())
15155 m_questRewardTalentCount += pQuest->GetBonusTalents();
15158 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
15161 while( result->NextRow() );
15163 delete result;
15166 // clear quest log tail
15167 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
15168 SetQuestSlot(i, 0);
15171 void Player::_LoadDailyQuestStatus(QueryResult *result)
15173 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15174 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
15176 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15178 if(result)
15180 uint32 quest_daily_idx = 0;
15184 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
15186 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15187 break;
15190 Field *fields = result->Fetch();
15192 uint32 quest_id = fields[0].GetUInt32();
15194 // save _any_ from daily quest times (it must be after last reset anyway)
15195 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
15197 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15198 if( !pQuest )
15199 continue;
15201 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
15202 ++quest_daily_idx;
15204 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
15206 while( result->NextRow() );
15208 delete result;
15211 m_DailyQuestChanged = false;
15214 void Player::_LoadSpells(QueryResult *result)
15216 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15218 if(result)
15222 Field *fields = result->Fetch();
15224 addSpell(fields[0].GetUInt32(), fields[1].GetBool(), false, false, fields[2].GetBool());
15226 while( result->NextRow() );
15228 delete result;
15232 void Player::_LoadGroup(QueryResult *result)
15234 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15235 if(result)
15237 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
15238 delete result;
15239 Group* group = objmgr.GetGroupByLeader(leaderGuid);
15240 if(group)
15242 uint8 subgroup = group->GetMemberGroup(GetGUID());
15243 SetGroup(group, subgroup);
15244 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
15246 // the group leader may change the instance difficulty while the player is offline
15247 SetDifficulty(group->GetDifficulty());
15253 void Player::_LoadBoundInstances(QueryResult *result)
15255 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15256 m_boundInstances[i].clear();
15258 Group *group = GetGroup();
15260 //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));
15261 if(result)
15265 Field *fields = result->Fetch();
15266 bool perm = fields[1].GetBool();
15267 uint32 mapId = fields[2].GetUInt32();
15268 uint32 instanceId = fields[0].GetUInt32();
15269 uint8 difficulty = fields[3].GetUInt8();
15270 time_t resetTime = (time_t)fields[4].GetUInt64();
15271 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15272 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15273 // and in that case it is not used
15275 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
15276 if(!mapEntry || !mapEntry->IsDungeon())
15278 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
15279 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15280 continue;
15283 if(!perm && group)
15285 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);
15286 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15287 continue;
15290 // since non permanent binds are always solo bind, they can always be reset
15291 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
15292 if(save) BindToInstance(save, perm, true);
15293 } while(result->NextRow());
15294 delete result;
15298 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
15300 // some instances only have one difficulty
15301 const MapEntry* entry = sMapStore.LookupEntry(mapid);
15302 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
15304 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15305 if(itr != m_boundInstances[difficulty].end())
15306 return &itr->second;
15307 else
15308 return NULL;
15311 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
15313 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15314 UnbindInstance(itr, difficulty, unload);
15317 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
15319 if(itr != m_boundInstances[difficulty].end())
15321 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15322 itr->second.save->RemovePlayer(this); // save can become invalid
15323 m_boundInstances[difficulty].erase(itr++);
15327 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15329 if(save)
15331 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15332 if(bind.save)
15334 // update the save when the group kills a boss
15335 if(permanent != bind.perm || save != bind.save)
15336 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());
15338 else
15339 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15341 if(bind.save != save)
15343 if(bind.save) bind.save->RemovePlayer(this);
15344 save->AddPlayer(this);
15347 if(permanent) save->SetCanReset(false);
15349 bind.save = save;
15350 bind.perm = permanent;
15351 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());
15352 return &bind;
15354 else
15355 return NULL;
15358 void Player::SendRaidInfo()
15360 uint32 counter = 0;
15362 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15364 size_t p_counter = data.wpos();
15365 data << uint32(counter); // placeholder
15367 time_t now = time(NULL);
15369 for(int i = 0; i < TOTAL_DIFFICULTIES; ++i)
15371 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15373 if(itr->second.perm)
15375 InstanceSave *save = itr->second.save;
15376 data << uint32(save->GetMapId()); // map id
15377 data << uint32(save->GetDifficulty()); // difficulty
15378 data << uint64(save->GetInstanceId()); // instance id
15379 data << uint32(save->GetResetTime() - now); // reset time
15380 data << uint32(0); // is extended
15381 ++counter;
15385 data.put<uint32>(p_counter, counter);
15386 GetSession()->SendPacket(&data);
15390 - called on every successful teleportation to a map
15392 void Player::SendSavedInstances()
15394 bool hasBeenSaved = false;
15395 WorldPacket data;
15397 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15399 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15401 if(itr->second.perm) // only permanent binds are sent
15403 hasBeenSaved = true;
15404 break;
15409 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15410 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15411 data << uint32(hasBeenSaved);
15412 GetSession()->SendPacket(&data);
15414 if(!hasBeenSaved)
15415 return;
15417 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15419 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15421 if(itr->second.perm)
15423 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15424 data << uint32(itr->second.save->GetMapId());
15425 GetSession()->SendPacket(&data);
15431 /// convert the player's binds to the group
15432 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15434 bool has_binds = false;
15435 bool has_solo = false;
15437 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15438 assert(player_guid);
15440 // copy all binds to the group, when changing leader it's assumed the character
15441 // will not have any solo binds
15443 if(player)
15445 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15447 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15449 has_binds = true;
15450 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15451 // permanent binds are not removed
15452 if(!itr->second.perm)
15454 player->UnbindInstance(itr, i, true); // increments itr
15455 has_solo = true;
15457 else
15458 ++itr;
15463 // if the player's not online we don't know what binds it has
15464 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));
15465 // the following should not get executed when changing leaders
15466 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15469 bool Player::_LoadHomeBind(QueryResult *result)
15471 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15472 if(!info)
15474 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
15475 return false;
15478 bool ok = false;
15479 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15480 if (result)
15482 Field *fields = result->Fetch();
15483 m_homebindMapId = fields[0].GetUInt32();
15484 m_homebindZoneId = fields[1].GetUInt16();
15485 m_homebindX = fields[2].GetFloat();
15486 m_homebindY = fields[3].GetFloat();
15487 m_homebindZ = fields[4].GetFloat();
15488 delete result;
15490 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
15492 // accept saved data only for valid position (and non instanceable), and accessable
15493 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15494 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
15496 ok = true;
15498 else
15499 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15502 if(!ok)
15504 m_homebindMapId = info->mapId;
15505 m_homebindZoneId = info->zoneId;
15506 m_homebindX = info->positionX;
15507 m_homebindY = info->positionY;
15508 m_homebindZ = info->positionZ;
15510 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);
15513 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
15514 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15516 return true;
15519 /*********************************************************/
15520 /*** SAVE SYSTEM ***/
15521 /*********************************************************/
15523 void Player::SaveToDB()
15525 // delay auto save at any saves (manual, in code, or autosave)
15526 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15528 //lets allow only players in world to be saved
15529 if(IsBeingTeleportedFar())
15531 ScheduleDelayedOperation(DELAYED_SAVE_PLAYER);
15532 return;
15535 // first save/honor gain after midnight will also update the player's honor fields
15536 UpdateHonorFields();
15538 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15539 outDebugValues();
15541 CharacterDatabase.BeginTransaction();
15543 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15545 std::string sql_name = m_name;
15546 CharacterDatabase.escape_string(sql_name);
15548 std::ostringstream ss;
15549 ss << "INSERT INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags,"
15550 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15551 "taximask, online, cinematic, "
15552 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15553 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15554 "death_expire_time, taxi_path, arena_pending_points) VALUES ("
15555 << GetGUIDLow() << ", "
15556 << GetSession()->GetAccountId() << ", '"
15557 << sql_name << "', "
15558 << (uint32)getRace() << ", "
15559 << (uint32)getClass() << ", "
15560 << (uint32)getGender() << ", "
15561 << getLevel() << ", "
15562 << GetUInt32Value(PLAYER_XP) << ", "
15563 << GetMoney() << ", "
15564 << GetUInt32Value(PLAYER_BYTES) << ", "
15565 << GetUInt32Value(PLAYER_BYTES_2) << ", "
15566 << GetUInt32Value(PLAYER_FLAGS) << ", ";
15568 if(!IsBeingTeleported())
15570 ss << GetMapId() << ", "
15571 << (uint32)GetDifficulty() << ", "
15572 << finiteAlways(GetPositionX()) << ", "
15573 << finiteAlways(GetPositionY()) << ", "
15574 << finiteAlways(GetPositionZ()) << ", "
15575 << finiteAlways(GetOrientation()) << ", '";
15577 else
15579 ss << GetTeleportDest().mapid << ", "
15580 << (uint32)GetDifficulty() << ", "
15581 << finiteAlways(GetTeleportDest().coord_x) << ", "
15582 << finiteAlways(GetTeleportDest().coord_y) << ", "
15583 << finiteAlways(GetTeleportDest().coord_z) << ", "
15584 << finiteAlways(GetTeleportDest().orientation) << ", '";
15587 uint16 i;
15588 for( i = 0; i < m_valuesCount; ++i )
15590 ss << GetUInt32Value(i) << " ";
15593 ss << "', ";
15595 ss << m_taxi << ", "; // string with TaxiMaskSize numbers
15597 ss << (IsInWorld() ? 1 : 0) << ", ";
15599 ss << m_cinematic << ", ";
15601 ss << m_Played_time[PLAYED_TIME_TOTAL] << ", ";
15602 ss << m_Played_time[PLAYED_TIME_LEVEL] << ", ";
15604 ss << finiteAlways(m_rest_bonus) << ", ";
15605 ss << (uint64)time(NULL) << ", ";
15606 ss << (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0) << ", ";
15607 //save, far from tavern/city
15608 //save, but in tavern/city
15609 ss << m_resetTalentsCost << ", ";
15610 ss << (uint64)m_resetTalentsTime << ", ";
15612 ss << finiteAlways(m_movementInfo.t_x) << ", ";
15613 ss << finiteAlways(m_movementInfo.t_y) << ", ";
15614 ss << finiteAlways(m_movementInfo.t_z) << ", ";
15615 ss << finiteAlways(m_movementInfo.t_o) << ", ";
15616 if (m_transport)
15617 ss << m_transport->GetGUIDLow();
15618 else
15619 ss << "0";
15620 ss << ", ";
15622 ss << m_ExtraFlags << ", ";
15624 ss << uint32(m_stableSlots) << ", "; // to prevent save uint8 as char
15626 ss << uint32(m_atLoginFlags) << ", ";
15628 ss << GetZoneId() << ", ";
15630 ss << (uint64)m_deathExpireTime << ", '";
15632 ss << m_taxi.SaveTaxiDestinationsToString() << "', ";
15633 ss << "'0' "; // arena_pending_points
15634 ss << ")";
15636 CharacterDatabase.Execute( ss.str().c_str() );
15638 if(m_mailsUpdated) //save mails only when needed
15639 _SaveMail();
15641 _SaveBGData();
15642 _SaveInventory();
15643 _SaveQuestStatus();
15644 _SaveDailyQuestStatus();
15645 _SaveSpells();
15646 _SaveSpellCooldowns();
15647 _SaveActions();
15648 _SaveAuras();
15649 m_achievementMgr.SaveToDB();
15650 m_reputationMgr.SaveToDB();
15651 _SaveEquipmentSets();
15652 GetSession()->SaveTutorialsData(); // changed only while character in game
15654 CharacterDatabase.CommitTransaction();
15656 // save pet (hunter pet level and experience and all type pets health/mana).
15657 if(Pet* pet = GetPet())
15658 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15661 // fast save function for item/money cheating preventing - save only inventory and money state
15662 void Player::SaveInventoryAndGoldToDB()
15664 _SaveInventory();
15665 SaveGoldToDB();
15668 void Player::SaveGoldToDB()
15670 CharacterDatabase.PExecute("UPDATE characters SET money = '%u' WHERE guid = '%u'", GetMoney(), GetGUIDLow());
15673 void Player::_SaveActions()
15675 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15677 switch (itr->second.uState)
15679 case ACTIONBUTTON_NEW:
15680 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type) VALUES ('%u', '%u', '%u', '%u')",
15681 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.GetAction(), (uint32)itr->second.GetType() );
15682 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15683 ++itr;
15684 break;
15685 case ACTIONBUTTON_CHANGED:
15686 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u' WHERE guid= '%u' AND button= '%u' ",
15687 (uint32)itr->second.GetAction(), (uint32)itr->second.GetType(), GetGUIDLow(), (uint32)itr->first );
15688 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15689 ++itr;
15690 break;
15691 case ACTIONBUTTON_DELETED:
15692 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15693 m_actionButtons.erase(itr++);
15694 break;
15695 default:
15696 ++itr;
15697 break;
15702 void Player::_SaveAuras()
15704 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15706 AuraMap const& auras = GetAuras();
15708 if (auras.empty())
15709 return;
15711 spellEffectPair lastEffectPair = auras.begin()->first;
15712 uint32 stackCounter = 1;
15714 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15716 if(itr == auras.end() || lastEffectPair != itr->first)
15718 AuraMap::const_iterator itr2 = itr;
15719 // save previous spellEffectPair to db
15720 itr2--;
15722 //skip all auras from spells that are passive
15723 //do not save single target auras (unless they were cast by the player)
15724 if (!itr2->second->IsPassive() && (itr2->second->GetCasterGUID() == GetGUID() || !itr2->second->IsSingleTarget()))
15726 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15727 "VALUES ('%u', '" UI64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15728 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()));
15731 if(itr == auras.end())
15732 break;
15735 if (lastEffectPair == itr->first)
15736 stackCounter++;
15737 else
15739 lastEffectPair = itr->first;
15740 stackCounter = 1;
15745 void Player::_SaveInventory()
15747 // force items in buyback slots to new state
15748 // and remove those that aren't already
15749 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
15751 Item *item = m_items[i];
15752 if (!item || item->GetState() == ITEM_NEW) continue;
15753 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15754 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15755 m_items[i]->FSetState(ITEM_NEW);
15758 // update enchantment durations
15759 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15761 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15764 // if no changes
15765 if (m_itemUpdateQueue.empty()) return;
15767 // do not save if the update queue is corrupt
15768 bool error = false;
15769 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15771 Item *item = m_itemUpdateQueue[i];
15772 if(!item || item->GetState() == ITEM_REMOVED) continue;
15773 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15775 if (test == NULL)
15777 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());
15778 error = true;
15780 else if (test != item)
15782 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());
15783 error = true;
15787 if (error)
15789 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15790 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15791 return;
15794 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15796 Item *item = m_itemUpdateQueue[i];
15797 if(!item) continue;
15799 Bag *container = item->GetContainer();
15800 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15802 switch(item->GetState())
15804 case ITEM_NEW:
15805 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());
15806 break;
15807 case ITEM_CHANGED:
15808 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());
15809 break;
15810 case ITEM_REMOVED:
15811 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15812 break;
15813 case ITEM_UNCHANGED:
15814 break;
15817 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15819 m_itemUpdateQueue.clear();
15822 void Player::_SaveMail()
15824 if (!m_mailsLoaded)
15825 return;
15827 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15829 Mail *m = (*itr);
15830 if (m->state == MAIL_STATE_CHANGED)
15832 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'",
15833 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15834 if(m->removedItems.size())
15836 for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15837 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15838 m->removedItems.clear();
15840 m->state = MAIL_STATE_UNCHANGED;
15842 else if (m->state == MAIL_STATE_DELETED)
15844 if (m->HasItems())
15845 for(std::vector<MailItemInfo>::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15846 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15847 if (m->itemTextId)
15848 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15849 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15850 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15854 //deallocate deleted mails...
15855 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15857 if ((*itr)->state == MAIL_STATE_DELETED)
15859 Mail* m = *itr;
15860 m_mail.erase(itr);
15861 delete m;
15862 itr = m_mail.begin();
15864 else
15865 ++itr;
15868 m_mailsUpdated = false;
15871 void Player::_SaveQuestStatus()
15873 // we don't need transactions here.
15874 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15876 switch (i->second.uState)
15878 case QUEST_NEW :
15879 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15880 "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15881 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]);
15882 break;
15883 case QUEST_CHANGED :
15884 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' ",
15885 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 );
15886 break;
15887 case QUEST_UNCHANGED:
15888 break;
15890 i->second.uState = QUEST_UNCHANGED;
15894 void Player::_SaveDailyQuestStatus()
15896 if(!m_DailyQuestChanged)
15897 return;
15899 m_DailyQuestChanged = false;
15901 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15903 // we don't need transactions here.
15904 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15905 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15906 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15907 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" UI64FMTD "')",
15908 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15911 void Player::_SaveSpells()
15913 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
15915 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15916 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15918 // add only changed/new not dependent spells
15919 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
15920 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);
15922 if (itr->second->state == PLAYERSPELL_REMOVED)
15924 delete itr->second;
15925 m_spells.erase(itr++);
15927 else
15929 itr->second->state = PLAYERSPELL_UNCHANGED;
15930 ++itr;
15936 void Player::outDebugValues() const
15938 if(!sLog.IsOutDebug()) // optimize disabled debug output
15939 return;
15941 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15942 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15943 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15944 sLog.outDebug("STAMINA is: \t\t%f",GetStat(STAT_STAMINA));
15945 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15946 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15947 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15948 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15949 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15950 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15951 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15952 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15955 /*********************************************************/
15956 /*** FLOOD FILTER SYSTEM ***/
15957 /*********************************************************/
15959 void Player::UpdateSpeakTime()
15961 // ignore chat spam protection for GMs in any mode
15962 if(GetSession()->GetSecurity() > SEC_PLAYER)
15963 return;
15965 time_t current = time (NULL);
15966 if(m_speakTime > current)
15968 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15969 if(!max_count)
15970 return;
15972 ++m_speakCount;
15973 if(m_speakCount >= max_count)
15975 // prevent overwrite mute time, if message send just before mutes set, for example.
15976 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15977 if(GetSession()->m_muteTime < new_mute)
15978 GetSession()->m_muteTime = new_mute;
15980 m_speakCount = 0;
15983 else
15984 m_speakCount = 0;
15986 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15989 bool Player::CanSpeak() const
15991 return GetSession()->m_muteTime <= time (NULL);
15994 /*********************************************************/
15995 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15996 /*********************************************************/
15998 void Player::SendAttackSwingNotInRange()
16000 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
16001 GetSession()->SendPacket( &data );
16004 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
16006 std::ostringstream ss;
16007 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
16008 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
16009 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
16010 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16011 sLog.outDebug(ss.str().c_str());
16012 CharacterDatabase.Execute(ss.str().c_str());
16015 void Player::SaveDataFieldToDB()
16017 std::ostringstream ss;
16018 ss<<"UPDATE characters SET data='";
16020 for(uint16 i = 0; i < m_valuesCount; ++i )
16022 ss << GetUInt32Value(i) << " ";
16024 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16026 CharacterDatabase.Execute(ss.str().c_str());
16029 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
16031 std::ostringstream ss2;
16032 ss2<<"UPDATE characters SET data='";
16033 int i=0;
16034 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
16036 ss2<<tokens[i]<<" ";
16038 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16040 return CharacterDatabase.Execute(ss2.str().c_str());
16043 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
16045 char buf[11];
16046 snprintf(buf,11,"%u",value);
16048 if(index >= tokens.size())
16049 return;
16051 tokens[index] = buf;
16054 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
16056 Tokens tokens;
16057 if(!LoadValuesArrayFromDB(tokens,guid))
16058 return;
16060 if(index >= tokens.size())
16061 return;
16063 char buf[11];
16064 snprintf(buf,11,"%u",value);
16065 tokens[index] = buf;
16067 SaveValuesArrayInDB(tokens,guid);
16070 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
16072 uint32 temp;
16073 memcpy(&temp, &value, sizeof(value));
16074 Player::SetUInt32ValueInDB(index, temp, guid);
16077 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
16079 // 0
16080 QueryResult* result = CharacterDatabase.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
16081 if(!result)
16082 return;
16084 Field* fields = result->Fetch();
16086 uint32 player_bytes2 = fields[0].GetUInt32();
16087 player_bytes2 &= ~0xFF;
16088 player_bytes2 |= facialHair;
16090 CharacterDatabase.PExecute("UPDATE characters SET gender = '%u', playerBytes = '%u', playerBytes2 = '%u' WHERE guid = '%u'", gender, skin | (face << 8) | (hairStyle << 16) | (hairColor << 24), player_bytes2, GUID_LOPART(guid));
16092 delete result;
16095 void Player::SendAttackSwingDeadTarget()
16097 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
16098 GetSession()->SendPacket( &data );
16101 void Player::SendAttackSwingCantAttack()
16103 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
16104 GetSession()->SendPacket( &data );
16107 void Player::SendAttackSwingCancelAttack()
16109 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
16110 GetSession()->SendPacket( &data );
16113 void Player::SendAttackSwingBadFacingAttack()
16115 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
16116 GetSession()->SendPacket( &data );
16119 void Player::SendAutoRepeatCancel(Unit *target)
16121 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, target->GetPackGUID().size());
16122 data.append(target->GetPackGUID()); // may be it's target guid
16123 GetSession()->SendPacket( &data );
16126 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
16128 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
16129 data << Area;
16130 data << Experience;
16131 GetSession()->SendPacket(&data);
16134 void Player::SendDungeonDifficulty(bool IsInGroup)
16136 uint8 val = 0x00000001;
16137 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
16138 data << (uint32)GetDifficulty();
16139 data << uint32(val);
16140 data << uint32(IsInGroup);
16141 GetSession()->SendPacket(&data);
16144 void Player::SendResetFailedNotify(uint32 mapid)
16146 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
16147 data << uint32(mapid);
16148 GetSession()->SendPacket(&data);
16151 /// Reset all solo instances and optionally send a message on success for each
16152 void Player::ResetInstances(uint8 method)
16154 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16156 // we assume that when the difficulty changes, all instances that can be reset will be
16157 uint8 dif = GetDifficulty();
16159 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
16161 InstanceSave *p = itr->second.save;
16162 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
16163 if(!entry || !p->CanReset())
16165 ++itr;
16166 continue;
16169 if(method == INSTANCE_RESET_ALL)
16171 // the "reset all instances" method can only reset normal maps
16172 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
16174 ++itr;
16175 continue;
16179 // if the map is loaded, reset it
16180 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
16181 if(map && map->IsDungeon())
16182 ((InstanceMap*)map)->Reset(method);
16184 // since this is a solo instance there should not be any players inside
16185 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16186 SendResetInstanceSuccess(p->GetMapId());
16188 p->DeleteFromDB();
16189 m_boundInstances[dif].erase(itr++);
16191 // the following should remove the instance save from the manager and delete it as well
16192 p->RemovePlayer(this);
16196 void Player::SendResetInstanceSuccess(uint32 MapId)
16198 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16199 data << MapId;
16200 GetSession()->SendPacket(&data);
16203 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16205 // TODO: find what other fail reasons there are besides players in the instance
16206 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16207 data << reason;
16208 data << MapId;
16209 GetSession()->SendPacket(&data);
16212 /*********************************************************/
16213 /*** Update timers ***/
16214 /*********************************************************/
16216 ///checks the 15 afk reports per 5 minutes limit
16217 void Player::UpdateAfkReport(time_t currTime)
16219 if(m_bgData.bgAfkReportedTimer <= currTime)
16221 m_bgData.bgAfkReportedCount = 0;
16222 m_bgData.bgAfkReportedTimer = currTime+5*MINUTE;
16226 void Player::UpdateContestedPvP(uint32 diff)
16228 if(!m_contestedPvPTimer||isInCombat())
16229 return;
16230 if(m_contestedPvPTimer <= diff)
16232 ResetContestedPvP();
16234 else
16235 m_contestedPvPTimer -= diff;
16238 void Player::UpdatePvPFlag(time_t currTime)
16240 if(!IsPvP())
16241 return;
16242 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16243 return;
16245 UpdatePvP(false);
16248 void Player::UpdateDuelFlag(time_t currTime)
16250 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16251 return;
16253 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16254 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16256 duel->startTimer = 0;
16257 duel->startTime = currTime;
16258 duel->opponent->duel->startTimer = 0;
16259 duel->opponent->duel->startTime = currTime;
16262 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16264 if(!pet)
16265 pet = GetPet();
16267 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16269 //returning of reagents only for players, so best done here
16270 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16271 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16273 if(spellInfo)
16275 for(uint32 i = 0; i < 7; ++i)
16277 if(spellInfo->Reagent[i] > 0)
16279 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16280 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16281 if( msg == EQUIP_ERR_OK )
16283 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16284 if(IsInWorld())
16285 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16290 m_temporaryUnsummonedPetNumber = 0;
16293 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16294 return;
16296 // only if current pet in slot
16297 switch(pet->getPetType())
16299 case MINI_PET:
16300 m_miniPet = 0;
16301 break;
16302 case GUARDIAN_PET:
16303 RemoveGuardian(pet);
16304 break;
16305 default:
16306 if(GetPetGUID() == pet->GetGUID())
16307 SetPet(NULL);
16308 break;
16311 pet->CombatStop();
16313 if(returnreagent)
16315 switch(pet->GetEntry())
16317 //warlock pets except imp are removed(?) when logging out
16318 case 1860:
16319 case 1863:
16320 case 417:
16321 case 17252:
16322 mode = PET_SAVE_NOT_IN_SLOT;
16323 break;
16327 pet->SavePetToDB(mode);
16329 pet->AddObjectToRemoveList();
16330 pet->m_removed = true;
16332 if(pet->isControlled())
16334 RemovePetActionBar();
16336 if(GetGroup())
16337 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16341 void Player::RemoveMiniPet()
16343 if(Pet* pet = GetMiniPet())
16345 pet->Remove(PET_SAVE_AS_DELETED);
16346 m_miniPet = 0;
16350 Pet* Player::GetMiniPet()
16352 if(!m_miniPet)
16353 return NULL;
16354 return ObjectAccessor::GetPet(m_miniPet);
16357 void Player::Uncharm()
16359 Unit* charm = GetCharm();
16360 if(!charm)
16361 return;
16363 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16364 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16367 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16369 *data << (uint8)msgtype;
16370 *data << (uint32)language;
16371 *data << (uint64)GetGUID();
16372 *data << (uint32)language; //language 2.1.0 ?
16373 *data << (uint64)GetGUID();
16374 *data << (uint32)(text.length()+1);
16375 *data << text;
16376 *data << (uint8)chatTag();
16379 void Player::Say(const std::string& text, const uint32 language)
16381 WorldPacket data(SMSG_MESSAGECHAT, 200);
16382 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16383 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16386 void Player::Yell(const std::string& text, const uint32 language)
16388 WorldPacket data(SMSG_MESSAGECHAT, 200);
16389 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16390 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16393 void Player::TextEmote(const std::string& text)
16395 WorldPacket data(SMSG_MESSAGECHAT, 200);
16396 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16397 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16400 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16402 if (language != LANG_ADDON) // if not addon data
16403 language = LANG_UNIVERSAL; // whispers should always be readable
16405 Player *rPlayer = objmgr.GetPlayer(receiver);
16407 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16408 if(!rPlayer->isDND() || isGameMaster())
16410 WorldPacket data(SMSG_MESSAGECHAT, 200);
16411 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16412 rPlayer->GetSession()->SendPacket(&data);
16414 data.Initialize(SMSG_MESSAGECHAT, 200);
16415 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16416 GetSession()->SendPacket(&data);
16418 else
16420 // announce to player that player he is whispering to is dnd and cannot receive his message
16421 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16424 if(!isAcceptWhispers())
16426 SetAcceptWhispers(true);
16427 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16430 // announce to player that player he is whispering to is afk
16431 if(rPlayer->isAFK())
16432 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16434 // if player whisper someone, auto turn of dnd to be able to receive an answer
16435 if(isDND() && !rPlayer->isGameMaster())
16436 ToggleDND();
16439 void Player::PetSpellInitialize()
16441 Pet* pet = GetPet();
16443 if(!pet)
16444 return;
16446 sLog.outDebug("Pet Spells Groups");
16448 CharmInfo *charmInfo = pet->GetCharmInfo();
16450 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
16451 data << uint64(pet->GetGUID());
16452 data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16453 data << uint32(0);
16454 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16456 // action bar loop
16457 charmInfo->BuildActionBar(&data);
16459 size_t spellsCountPos = data.wpos();
16461 // spells count
16462 uint8 addlist = 0;
16463 data << uint8(addlist); // placeholder
16465 if (pet->IsPermanentPetFor(this))
16467 // spells loop
16468 for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16470 if(itr->second.state == PETSPELL_REMOVED)
16471 continue;
16473 data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first,itr->second.active));
16474 ++addlist;
16478 data.put<uint8>(spellsCountPos, addlist);
16480 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16481 data << uint8(cooldownsCount);
16483 time_t curTime = time(NULL);
16485 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16487 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16489 data << uint32(itr->first); // spellid
16490 data << uint16(0); // spell category?
16491 data << uint32(cooldown); // cooldown
16492 data << uint32(0); // category cooldown
16495 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16497 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16499 data << uint32(itr->first); // spellid
16500 data << uint16(0); // spell category?
16501 data << uint32(0); // cooldown
16502 data << uint32(cooldown); // category cooldown
16505 GetSession()->SendPacket(&data);
16508 void Player::PossessSpellInitialize()
16510 Unit* charm = GetCharm();
16512 if(!charm)
16513 return;
16515 CharmInfo *charmInfo = charm->GetCharmInfo();
16517 if(!charmInfo)
16519 sLog.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
16520 return;
16523 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
16524 data << uint64(charm->GetGUID());
16525 data << uint16(0);
16526 data << uint32(0);
16527 data << uint32(0);
16529 charmInfo->BuildActionBar(&data);
16531 data << uint8(0); // spells count
16532 data << uint8(0); // cooldowns count
16534 GetSession()->SendPacket(&data);
16537 void Player::CharmSpellInitialize()
16539 Unit* charm = GetCharm();
16541 if(!charm)
16542 return;
16544 CharmInfo *charmInfo = charm->GetCharmInfo();
16545 if(!charmInfo)
16547 sLog.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
16548 return;
16551 uint8 addlist = 0;
16553 if(charm->GetTypeId() != TYPEID_PLAYER)
16555 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16557 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16559 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16561 if(charmInfo->GetCharmSpell(i)->GetAction())
16562 ++addlist;
16567 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1);
16568 data << uint64(charm->GetGUID());
16569 data << uint16(0);
16570 data << uint32(0);
16572 if(charm->GetTypeId() != TYPEID_PLAYER)
16573 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16574 else
16575 data << uint8(0) << uint8(0) << uint16(0);
16577 charmInfo->BuildActionBar(&data);
16579 data << uint8(addlist);
16581 if(addlist)
16583 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16585 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16586 if(cspell->GetAction())
16587 data << uint32(cspell->packedData);
16591 data << uint8(0); // cooldowns count
16593 GetSession()->SendPacket(&data);
16596 void Player::RemovePetActionBar()
16598 WorldPacket data(SMSG_PET_SPELLS, 8);
16599 data << uint64(0);
16600 SendDirectMessage(&data);
16603 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16605 if (!mod || !spellInfo)
16606 return false;
16608 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16610 // prevent apply to any spell except spell that trigger expire
16611 if(spell)
16613 if(mod->lastAffected != spell)
16614 return false;
16616 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16617 return false;
16620 return spellmgr.IsAffectedByMod(spellInfo, mod);
16623 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16625 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16627 for(int eff=0;eff<96;++eff)
16629 uint64 _mask = 0;
16630 uint64 _mask2= 0;
16631 if (eff<64) _mask = uint64(1) << (eff- 0);
16632 else _mask2= uint64(1) << (eff-64);
16633 if ( mod->mask & _mask || mod->mask2 & _mask2)
16635 int32 val = 0;
16636 for (SpellModList::const_iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16638 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16639 val += (*itr)->value;
16641 val += apply ? mod->value : -(mod->value);
16642 WorldPacket data(Opcode, (1+1+4));
16643 data << uint8(eff);
16644 data << uint8(mod->op);
16645 data << int32(val);
16646 SendDirectMessage(&data);
16650 if (apply)
16651 m_spellMods[mod->op].push_back(mod);
16652 else
16654 if (mod->charges == -1)
16655 --m_SpellModRemoveCount;
16656 m_spellMods[mod->op].remove(mod);
16657 delete mod;
16661 void Player::RemoveSpellMods(Spell const* spell)
16663 if(!spell || (m_SpellModRemoveCount == 0))
16664 return;
16666 for(int i=0;i<MAX_SPELLMOD;++i)
16668 for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16670 SpellModifier *mod = *itr;
16671 ++itr;
16673 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16675 RemoveAurasDueToSpell(mod->spellId);
16676 if (m_spellMods[i].empty())
16677 break;
16678 else
16679 itr = m_spellMods[i].begin();
16685 // send Proficiency
16686 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16688 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16689 data << pr1 << pr2;
16690 GetSession()->SendPacket (&data);
16693 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16695 QueryResult *result = NULL;
16696 if(type==10)
16697 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16698 else
16699 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16700 if(result)
16702 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.
16703 { // and SendPetitionQueryOpcode reads data from the DB
16704 Field *fields = result->Fetch();
16705 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16706 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16708 // send update if charter owner in game
16709 Player* owner = objmgr.GetPlayer(ownerguid);
16710 if(owner)
16711 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16713 } while ( result->NextRow() );
16715 delete result;
16717 if(type==10)
16718 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16719 else
16720 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16723 CharacterDatabase.BeginTransaction();
16724 if(type == 10)
16726 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16727 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16729 else
16731 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16732 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16734 CharacterDatabase.CommitTransaction();
16737 void Player::LeaveAllArenaTeams(uint64 guid)
16739 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));
16740 if(!result)
16741 return;
16745 Field *fields = result->Fetch();
16746 uint32 at_id = fields[0].GetUInt32();
16747 if(at_id != 0)
16749 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
16750 if(at)
16751 at->DelMember(guid);
16753 } while (result->NextRow());
16755 delete result;
16758 void Player::SetRestBonus (float rest_bonus_new)
16760 // Prevent resting on max level
16761 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16762 rest_bonus_new = 0;
16764 if(rest_bonus_new < 0)
16765 rest_bonus_new = 0;
16767 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16769 if(rest_bonus_new > rest_bonus_max)
16770 m_rest_bonus = rest_bonus_max;
16771 else
16772 m_rest_bonus = rest_bonus_new;
16774 // update data for client
16775 if(m_rest_bonus>10)
16776 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16777 else if(m_rest_bonus<=1)
16778 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16780 //RestTickUpdate
16781 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16784 void Player::HandleStealthedUnitsDetection()
16786 std::list<Unit*> stealthedUnits;
16788 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16789 Cell cell(p);
16790 cell.data.Part.reserved = ALL_DISTRICT;
16791 cell.SetNoCreate();
16793 MaNGOS::AnyStealthedCheck u_check;
16794 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
16796 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16797 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16799 CellLock<GridReadGuard> cell_lock(cell, p);
16800 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE);
16801 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE);
16803 WorldObject const* viewPoint = GetViewPoint();
16805 for (std::list<Unit*>::const_iterator i = stealthedUnits.begin(); i != stealthedUnits.end(); ++i)
16807 if((*i)==this)
16808 continue;
16810 bool hasAtClient = HaveAtClient((*i));
16811 bool hasDetected = (*i)->isVisibleForOrDetect(this, viewPoint, true);
16813 if (hasDetected)
16815 if(!hasAtClient)
16817 (*i)->SendUpdateToPlayer(this);
16818 m_clientGUIDs.insert((*i)->GetGUID());
16820 #ifdef MANGOS_DEBUG
16821 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16822 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16823 #endif
16825 // target aura duration for caster show only if target exist at caster client
16826 // send data at target visibility change (adding to client)
16827 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16828 SendAurasForTarget(*i);
16831 else
16833 if(hasAtClient)
16835 (*i)->DestroyForPlayer(this);
16836 m_clientGUIDs.erase((*i)->GetGUID());
16842 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
16844 if(nodes.size() < 2)
16845 return false;
16847 // 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
16848 if(GetSession()->isLogingOut() || isInCombat())
16850 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16851 data << uint32(ERR_TAXIPLAYERBUSY);
16852 GetSession()->SendPacket(&data);
16853 return false;
16856 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16857 return false;
16859 // taximaster case
16860 if(npc)
16862 // not let cheating with start flight mounted
16863 if(IsMounted())
16865 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16866 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16867 GetSession()->SendPacket(&data);
16868 return false;
16871 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16873 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16874 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16875 GetSession()->SendPacket(&data);
16876 return false;
16879 // 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
16880 if(IsNonMeleeSpellCasted(false))
16882 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16883 data << uint32(ERR_TAXIPLAYERBUSY);
16884 GetSession()->SendPacket(&data);
16885 return false;
16888 // cast case or scripted call case
16889 else
16891 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
16893 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16894 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
16896 if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
16897 if (spell->m_spellInfo->Id != spellid)
16898 InterruptSpell(CURRENT_GENERIC_SPELL,false);
16900 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false);
16902 if (Spell* spell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
16903 if (spell->m_spellInfo->Id != spellid)
16904 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
16907 uint32 sourcenode = nodes[0];
16909 // starting node too far away (cheat?)
16910 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16911 if (!node)
16913 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16914 data << uint32(ERR_TAXINOSUCHPATH);
16915 GetSession()->SendPacket(&data);
16916 return false;
16919 // check node starting pos data set case if provided
16920 if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
16922 if (node->map_id != GetMapId() ||
16923 (node->x - GetPositionX())*(node->x - GetPositionX())+
16924 (node->y - GetPositionY())*(node->y - GetPositionY())+
16925 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16926 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
16928 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16929 data << uint32(ERR_TAXITOOFARAWAY);
16930 GetSession()->SendPacket(&data);
16931 return false;
16934 // node must have pos if taxi master case (npc != NULL)
16935 else if (npc)
16937 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16938 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16939 GetSession()->SendPacket(&data);
16940 return false;
16943 // Prepare to flight start now
16945 // stop combat at start taxi flight if any
16946 CombatStop();
16948 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16949 TradeCancel(true);
16951 // clean not finished taxi path if any
16952 m_taxi.ClearTaxiDestinations();
16954 // 0 element current node
16955 m_taxi.AddTaxiDestination(sourcenode);
16957 // fill destinations path tail
16958 uint32 sourcepath = 0;
16959 uint32 totalcost = 0;
16961 uint32 prevnode = sourcenode;
16962 uint32 lastnode = 0;
16964 for(uint32 i = 1; i < nodes.size(); ++i)
16966 uint32 path, cost;
16968 lastnode = nodes[i];
16969 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16971 if(!path)
16973 m_taxi.ClearTaxiDestinations();
16974 return false;
16977 totalcost += cost;
16979 if(prevnode == sourcenode)
16980 sourcepath = path;
16982 m_taxi.AddTaxiDestination(lastnode);
16984 prevnode = lastnode;
16987 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
16988 uint32 mount_display_id = objmgr.GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL);
16990 // in spell case allow 0 model
16991 if ((mount_display_id == 0 && spellid == 0) || sourcepath == 0)
16993 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16994 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16995 GetSession()->SendPacket(&data);
16996 m_taxi.ClearTaxiDestinations();
16997 return false;
17000 uint32 money = GetMoney();
17002 if (npc)
17003 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
17005 if(money < totalcost)
17007 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17008 data << uint32(ERR_TAXINOTENOUGHMONEY);
17009 GetSession()->SendPacket(&data);
17010 m_taxi.ClearTaxiDestinations();
17011 return false;
17014 //Checks and preparations done, DO FLIGHT
17015 ModifyMoney(-(int32)totalcost);
17016 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
17017 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
17019 // prevent stealth flight
17020 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
17022 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17023 data << uint32(ERR_TAXIOK);
17024 GetSession()->SendPacket(&data);
17026 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17028 GetSession()->SendDoFlight(mount_display_id, sourcepath);
17030 return true;
17033 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ )
17035 TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
17036 if(!entry)
17037 return false;
17039 std::vector<uint32> nodes;
17041 nodes.resize(2);
17042 nodes[0] = entry->from;
17043 nodes[1] = entry->to;
17045 return ActivateTaxiPathTo(nodes,NULL,spellid);
17048 void Player::ContinueTaxiFlight()
17050 uint32 sourceNode = m_taxi.GetTaxiSource();
17051 if (!sourceNode)
17052 return;
17054 sLog.outDebug( "WORLD: Restart character %u taxi flight", GetGUIDLow() );
17056 uint32 mountDisplayId = objmgr.GetTaxiMountDisplayId(sourceNode, GetTeam(),true);
17057 uint32 path = m_taxi.GetCurrentTaxiPath();
17059 // search appropriate start path node
17060 uint32 startNode = 0;
17062 TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];
17064 float distPrev = MAP_SIZE*MAP_SIZE;
17065 float distNext =
17066 (nodeList[0].x-GetPositionX())*(nodeList[0].x-GetPositionX())+
17067 (nodeList[0].y-GetPositionY())*(nodeList[0].y-GetPositionY())+
17068 (nodeList[0].z-GetPositionZ())*(nodeList[0].z-GetPositionZ());
17070 for(uint32 i = 1; i < nodeList.size(); ++i)
17072 TaxiPathNode const& node = nodeList[i];
17073 TaxiPathNode const& prevNode = nodeList[i-1];
17075 // skip nodes at another map
17076 if(node.mapid != GetMapId())
17077 continue;
17079 distPrev = distNext;
17081 distNext =
17082 (node.x-GetPositionX())*(node.x-GetPositionX())+
17083 (node.y-GetPositionY())*(node.y-GetPositionY())+
17084 (node.z-GetPositionZ())*(node.z-GetPositionZ());
17086 float distNodes =
17087 (node.x-prevNode.x)*(node.x-prevNode.x)+
17088 (node.y-prevNode.y)*(node.y-prevNode.y)+
17089 (node.z-prevNode.z)*(node.z-prevNode.z);
17091 if(distNext + distPrev < distNodes)
17093 startNode = i;
17094 break;
17098 GetSession()->SendDoFlight(mountDisplayId, path, startNode);
17101 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
17103 // last check 2.0.10
17104 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
17105 data << GetGUID();
17106 data << uint8(0x0); // flags (0x1, 0x2)
17107 time_t curTime = time(NULL);
17108 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17110 if (itr->second->state == PLAYERSPELL_REMOVED)
17111 continue;
17112 uint32 unSpellId = itr->first;
17113 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
17114 if (!spellInfo)
17116 ASSERT(spellInfo);
17117 continue;
17120 // Not send cooldown for this spells
17121 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
17122 continue;
17124 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
17126 data << uint32(unSpellId);
17127 data << uint32(unTimeMs); // in m.secs
17128 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
17131 GetSession()->SendPacket(&data);
17134 void Player::InitDataForForm(bool reapplyMods)
17136 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
17137 if(ssEntry && ssEntry->attackSpeed)
17139 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
17140 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
17141 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
17143 else
17144 SetRegularAttackTime();
17146 switch(m_form)
17148 case FORM_CAT:
17150 if(getPowerType()!=POWER_ENERGY)
17151 setPowerType(POWER_ENERGY);
17152 break;
17154 case FORM_BEAR:
17155 case FORM_DIREBEAR:
17157 if(getPowerType()!=POWER_RAGE)
17158 setPowerType(POWER_RAGE);
17159 break;
17161 default: // 0, for example
17163 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
17164 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
17165 setPowerType(Powers(cEntry->powerType));
17166 break;
17170 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17171 if (!reapplyMods)
17172 UpdateEquipSpellsAtFormChange();
17174 UpdateAttackPowerAndDamage();
17175 UpdateAttackPowerAndDamage(true);
17178 void Player::InitDisplayIds()
17180 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
17181 if(!info)
17183 sLog.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
17184 return;
17187 uint8 gender = getGender();
17188 switch(gender)
17190 case GENDER_FEMALE:
17191 SetDisplayId(info->displayId_f );
17192 SetNativeDisplayId(info->displayId_f );
17193 break;
17194 case GENDER_MALE:
17195 SetDisplayId(info->displayId_m );
17196 SetNativeDisplayId(info->displayId_m );
17197 break;
17198 default:
17199 sLog.outError("Invalid gender %u for player",gender);
17200 return;
17204 // Return true is the bought item has a max count to force refresh of window by caller
17205 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint8 bag, uint8 slot)
17207 // cheating attempt
17208 if (count < 1) count = 1;
17210 if (!isAlive())
17211 return false;
17213 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
17214 if (!pProto)
17216 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
17217 return false;
17220 Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
17221 if (!pCreature)
17223 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
17224 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
17225 return false;
17228 VendorItemData const* vItems = pCreature->GetVendorItems();
17229 if(!vItems || vItems->Empty())
17231 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17232 return false;
17235 size_t vendor_slot = vItems->FindItemSlot(item);
17236 if (vendor_slot >= vItems->GetItemCount())
17238 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17239 return false;
17242 VendorItem const* crItem = vItems->m_items[vendor_slot];
17244 // check current item amount if it limited
17245 if (crItem->maxcount != 0)
17247 if (pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
17249 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
17250 return false;
17254 if (uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
17256 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
17257 return false;
17260 if (crItem->ExtendedCost)
17262 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17263 if (!iece)
17265 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
17266 return false;
17269 // honor points price
17270 if (GetHonorPoints() < (iece->reqhonorpoints * count))
17272 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
17273 return false;
17276 // arena points price
17277 if (GetArenaPoints() < (iece->reqarenapoints * count))
17279 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
17280 return false;
17283 // item base price
17284 for (uint8 i = 0; i < 5; ++i)
17286 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17288 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17289 return false;
17293 // check for personal arena rating requirement
17294 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
17296 // probably not the proper equip err
17297 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17298 return false;
17302 uint32 price = pProto->BuyPrice * count;
17304 // reputation discount
17305 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17307 if (GetMoney() < price)
17309 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17310 return false;
17313 if ((bag == NULL_BAG && slot == NULL_SLOT) || IsInventoryPos(bag, slot))
17315 ItemPosCountVec dest;
17316 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17317 if (msg != EQUIP_ERR_OK)
17319 SendEquipError( msg, NULL, NULL );
17320 return false;
17323 ModifyMoney( -(int32)price );
17324 if (crItem->ExtendedCost) // case for new honor system
17326 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17327 if (iece->reqhonorpoints)
17328 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17329 if (iece->reqarenapoints)
17330 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17331 for (uint8 i = 0; i < 5; ++i)
17333 if (iece->reqitem[i])
17334 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17338 if (Item *it = StoreNewItem( dest, item, true ))
17340 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17342 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17343 data << pCreature->GetGUID();
17344 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17345 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17346 data << (uint32)count;
17347 GetSession()->SendPacket(&data);
17349 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17352 else if (IsEquipmentPos(bag, slot))
17354 if (pProto->BuyCount * count != 1)
17356 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17357 return false;
17360 uint16 dest;
17361 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17362 if (msg != EQUIP_ERR_OK)
17364 SendEquipError( msg, NULL, NULL );
17365 return false;
17368 ModifyMoney( -(int32)price );
17369 if (crItem->ExtendedCost) // case for new honor system
17371 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17372 if (iece->reqhonorpoints)
17373 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17374 if (iece->reqarenapoints)
17375 ModifyArenaPoints( - int32(iece->reqarenapoints));
17376 for (uint8 i = 0; i < 5; ++i)
17378 if(iece->reqitem[i])
17379 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17383 if (Item *it = EquipNewItem( dest, item, true ))
17385 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17387 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17388 data << pCreature->GetGUID();
17389 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17390 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17391 data << (uint32)count;
17392 GetSession()->SendPacket(&data);
17394 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17396 AutoUnequipOffhandIfNeed();
17399 else
17401 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17402 return false;
17405 return crItem->maxcount != 0;
17408 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17410 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17411 // the personal rating of the arena team must match the required limit as well
17412 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17413 uint32 max_personal_rating = 0;
17414 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17416 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17418 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17419 uint32 t_rating = at->GetRating();
17420 p_rating = p_rating<t_rating? p_rating : t_rating;
17421 if(max_personal_rating < p_rating)
17422 max_personal_rating = p_rating;
17425 return max_personal_rating;
17428 void Player::UpdateHomebindTime(uint32 time)
17430 // GMs never get homebind timer online
17431 if (m_InstanceValid || isGameMaster())
17433 if(m_HomebindTimer) // instance valid, but timer not reset
17435 // hide reminder
17436 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17437 data << uint32(0);
17438 data << uint32(0);
17439 GetSession()->SendPacket(&data);
17441 // instance is valid, reset homebind timer
17442 m_HomebindTimer = 0;
17444 else if (m_HomebindTimer > 0)
17446 if (time >= m_HomebindTimer)
17448 // teleport to nearest graveyard
17449 RepopAtGraveyard();
17451 else
17452 m_HomebindTimer -= time;
17454 else
17456 // instance is invalid, start homebind timer
17457 m_HomebindTimer = 60000;
17458 // send message to player
17459 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17460 data << m_HomebindTimer;
17461 data << uint32(1);
17462 GetSession()->SendPacket(&data);
17463 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17467 void Player::UpdatePvP(bool state, bool ovrride)
17469 if(!state || ovrride)
17471 SetPvP(state);
17472 pvpInfo.endTimer = 0;
17474 else
17476 if(pvpInfo.endTimer != 0)
17477 pvpInfo.endTimer = time(NULL);
17478 else
17479 SetPvP(state);
17483 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
17485 // init cooldown values
17486 uint32 cat = 0;
17487 int32 rec = -1;
17488 int32 catrec = -1;
17490 // some special item spells without correct cooldown in SpellInfo
17491 // cooldown information stored in item prototype
17492 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17494 if(itemId)
17496 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
17498 for(int idx = 0; idx < 5; ++idx)
17500 if(proto->Spells[idx].SpellId == spellInfo->Id)
17502 cat = proto->Spells[idx].SpellCategory;
17503 rec = proto->Spells[idx].SpellCooldown;
17504 catrec = proto->Spells[idx].SpellCategoryCooldown;
17505 break;
17511 // if no cooldown found above then base at DBC data
17512 if(rec < 0 && catrec < 0)
17514 cat = spellInfo->Category;
17515 rec = spellInfo->RecoveryTime;
17516 catrec = spellInfo->CategoryRecoveryTime;
17519 time_t curTime = time(NULL);
17521 time_t catrecTime;
17522 time_t recTime;
17524 // overwrite time for selected category
17525 if(infinityCooldown)
17527 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17528 // but not allow ignore until reset or re-login
17529 catrecTime = catrec > 0 ? curTime+infinityCooldownDelay : 0;
17530 recTime = rec > 0 ? curTime+infinityCooldownDelay : catrecTime;
17532 else
17534 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17535 // prevent 0 cooldowns set by another way
17536 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
17537 rec = GetAttackTime(RANGED_ATTACK);
17539 // Now we have cooldown data (if found any), time to apply mods
17540 if(rec > 0)
17541 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
17543 if(catrec > 0)
17544 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
17546 // replace negative cooldowns by 0
17547 if (rec < 0) rec = 0;
17548 if (catrec < 0) catrec = 0;
17550 // no cooldown after applying spell mods
17551 if( rec == 0 && catrec == 0)
17552 return;
17554 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
17555 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
17558 // self spell cooldown
17559 if(recTime > 0)
17560 AddSpellCooldown(spellInfo->Id, itemId, recTime);
17562 // category spells
17563 if (cat && catrec > 0)
17565 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
17566 if(i_scstore != sSpellCategoryStore.end())
17568 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
17570 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
17571 continue;
17573 AddSpellCooldown(*i_scset, itemId, catrecTime);
17579 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17581 SpellCooldown sc;
17582 sc.end = end_time;
17583 sc.itemid = itemid;
17584 m_spellCooldowns[spellid] = sc;
17587 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
17589 // start cooldowns at server side, if any
17590 AddSpellAndCategoryCooldowns(spellInfo,itemId,spell);
17592 // Send activate cooldown timer (possible 0) at client side
17593 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17594 data << spellInfo->Id;
17595 data << GetGUID();
17596 SendDirectMessage(&data);
17599 void Player::UpdatePotionCooldown(Spell* spell)
17601 // no potion used i combat or still in combat
17602 if(!m_lastPotionId || isInCombat())
17603 return;
17605 // Call not from spell cast, send cooldown event for item spells if no in combat
17606 if(!spell)
17608 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17609 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
17610 for(int idx = 0; idx < 5; ++idx)
17611 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
17612 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
17613 SendCooldownEvent(spellInfo,m_lastPotionId);
17615 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17616 else
17617 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
17619 m_lastPotionId = 0;
17622 //slot to be excluded while counting
17623 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17625 if(!enchantmentcondition)
17626 return true;
17628 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17630 if(!Condition)
17631 return true;
17633 uint8 curcount[4] = {0, 0, 0, 0};
17635 //counting current equipped gem colors
17636 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17638 if(i == slot)
17639 continue;
17640 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17641 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17643 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17645 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17646 if(!enchant_id)
17647 continue;
17649 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17650 if(!enchantEntry)
17651 continue;
17653 uint32 gemid = enchantEntry->GemID;
17654 if(!gemid)
17655 continue;
17657 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17658 if(!gemProto)
17659 continue;
17661 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17662 if(!gemProperty)
17663 continue;
17665 uint8 GemColor = gemProperty->color;
17667 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17669 if(tmpcolormask & GemColor)
17670 ++curcount[b];
17676 bool activate = true;
17678 for(int i = 0; i < 5; ++i)
17680 if(!Condition->Color[i])
17681 continue;
17683 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17685 // if have <CompareColor> use them as count, else use <value> from Condition
17686 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17688 switch(Condition->Comparator[i])
17690 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17691 activate &= (_cur_gem < _cmp_gem) ? true : false;
17692 break;
17693 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17694 activate &= (_cur_gem > _cmp_gem) ? true : false;
17695 break;
17696 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17697 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17698 break;
17702 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");
17704 return activate;
17707 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17709 //cycle all equipped items
17710 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17712 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17713 if(slot == exceptslot)
17714 continue;
17716 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17718 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17719 continue;
17721 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17723 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17724 if(!enchant_id)
17725 continue;
17727 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17728 if(!enchantEntry)
17729 continue;
17731 uint32 condition = enchantEntry->EnchantmentCondition;
17732 if(condition)
17734 //was enchant active with/without item?
17735 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17736 //should it now be?
17737 if(wasactive != EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17739 // ignore item gem conditions
17740 //if state changed, (dis)apply enchant
17741 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17748 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17749 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17751 //cycle all equipped items
17752 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17754 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17755 if(slot == exceptslot)
17756 continue;
17758 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17760 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17761 continue;
17763 //cycle all (gem)enchants
17764 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17766 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17767 if(!enchant_id) //if no enchant go to next enchant(slot)
17768 continue;
17770 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17771 if(!enchantEntry)
17772 continue;
17774 //only metagems to be (de)activated, so only enchants with condition
17775 uint32 condition = enchantEntry->EnchantmentCondition;
17776 if(condition)
17777 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17782 void Player::SetBattleGroundEntryPoint()
17784 // Taxi path store
17785 if (!m_taxi.empty())
17787 m_bgData.mountSpell = 0;
17788 m_bgData.taxiPath[0] = m_taxi.GetTaxiSource();
17789 m_bgData.taxiPath[1] = m_taxi.GetTaxiDestination();
17791 // On taxi we don't need check for dungeon
17792 m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
17793 return;
17795 else
17797 m_bgData.ClearTaxiPath();
17799 // Mount spell id storing
17800 if (IsMounted())
17802 AuraList const& auras = GetAurasByType(SPELL_AURA_MOUNTED);
17803 if (!auras.empty())
17804 m_bgData.mountSpell = (*auras.begin())->GetId();
17806 else
17807 m_bgData.mountSpell = 0;
17809 // If map is dungeon find linked graveyard
17810 if(GetMap()->IsDungeon())
17812 if (const WorldSafeLocsEntry* entry = objmgr.GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
17814 m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f);
17815 return;
17817 else
17818 sLog.outError("SetBattleGroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId());
17820 // If new entry point is not BG or arena set it
17821 else if (!GetMap()->IsBattleGroundOrArena())
17823 m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
17824 return;
17828 // In error cases use homebind position
17829 m_bgData.joinPos = WorldLocation(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, 0.0f);
17832 void Player::LeaveBattleground(bool teleportToEntryPoint)
17834 if(BattleGround *bg = GetBattleGround())
17836 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17838 // call after remove to be sure that player resurrected for correct cast
17839 if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) )
17841 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
17843 //lets check if player was teleported from BG and schedule delayed Deserter spell cast
17844 if(IsBeingTeleportedFar())
17846 ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER);
17847 return;
17850 CastSpell(this, 26013, true); // Deserter
17856 bool Player::CanJoinToBattleground() const
17858 // check Deserter debuff
17859 if(GetDummyAura(26013))
17860 return false;
17862 return true;
17865 bool Player::CanReportAfkDueToLimit()
17867 // a player can complain about 15 people per 5 minutes
17868 if(m_bgData.bgAfkReportedCount++ >= 15)
17869 return false;
17871 return true;
17874 ///This player has been blamed to be inactive in a battleground
17875 void Player::ReportedAfkBy(Player* reporter)
17877 BattleGround *bg = GetBattleGround();
17878 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17879 return;
17881 // check if player has 'Idle' or 'Inactive' debuff
17882 if(m_bgData.bgAfkReporter.find(reporter->GetGUIDLow())==m_bgData.bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17884 m_bgData.bgAfkReporter.insert(reporter->GetGUIDLow());
17885 // 3 players have to complain to apply debuff
17886 if(m_bgData.bgAfkReporter.size() >= 3)
17888 // cast 'Idle' spell
17889 CastSpell(this, 43680, true);
17890 m_bgData.bgAfkReporter.clear();
17895 WorldObject const* Player::GetViewPoint() const
17897 if(uint64 far_sight = GetFarSight())
17899 WorldObject const* viewPoint = ObjectAccessor::GetWorldObject(*this,far_sight);
17900 return viewPoint ? viewPoint : this; // always expected not NULL
17902 else
17903 return this;
17906 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17908 // gamemaster in GM mode see all, including ghosts
17909 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17910 return true;
17912 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17913 if (InBattleGround())
17915 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17916 return false;
17917 return true;
17920 // Live player see live player or dead player with not realized corpse
17921 if(pl->isAlive() || pl->m_deathTimer > 0)
17923 return isAlive() || m_deathTimer > 0;
17926 // Ghost see other friendly ghosts, that's for sure
17927 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17928 return true;
17930 // Dead player see live players near own corpse
17931 if(isAlive())
17933 Corpse *corpse = pl->GetCorpse();
17934 if(corpse)
17936 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17937 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17938 return true;
17942 // and not see any other
17943 return false;
17946 bool Player::IsVisibleGloballyFor( Player* u ) const
17948 if(!u)
17949 return false;
17951 // Always can see self
17952 if (u==this)
17953 return true;
17955 // Visible units, always are visible for all players
17956 if (GetVisibility() == VISIBILITY_ON)
17957 return true;
17959 // GMs are visible for higher gms (or players are visible for gms)
17960 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17961 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17963 // non faction visibility non-breakable for non-GMs
17964 if (GetVisibility() == VISIBILITY_OFF)
17965 return false;
17967 // non-gm stealth/invisibility not hide from global player lists
17968 return true;
17971 void Player::UpdateVisibilityOf(WorldObject const* viewPoint, WorldObject* target)
17973 if(HaveAtClient(target))
17975 if(!target->isVisibleForInState(this, viewPoint, true))
17977 target->DestroyForPlayer(this);
17978 m_clientGUIDs.erase(target->GetGUID());
17980 #ifdef MANGOS_DEBUG
17981 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17982 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17983 #endif
17986 else
17988 if(target->isVisibleForInState(this, viewPoint, false))
17990 target->SendUpdateToPlayer(this);
17991 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17992 m_clientGUIDs.insert(target->GetGUID());
17994 #ifdef MANGOS_DEBUG
17995 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17996 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17997 #endif
17999 // target aura duration for caster show only if target exist at caster client
18000 // send data at target visibility change (adding to client)
18001 if(target!=this && target->isType(TYPEMASK_UNIT))
18002 SendAurasForTarget((Unit*)target);
18004 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
18005 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
18010 template<class T>
18011 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
18013 s64.insert(target->GetGUID());
18016 template<>
18017 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
18019 if(!target->IsTransport())
18020 s64.insert(target->GetGUID());
18023 template<class T>
18024 void Player::UpdateVisibilityOf(WorldObject const* viewPoint, T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
18026 if(HaveAtClient(target))
18028 if(!target->isVisibleForInState(this,viewPoint,true))
18030 target->BuildOutOfRangeUpdateBlock(&data);
18031 m_clientGUIDs.erase(target->GetGUID());
18033 #ifdef MANGOS_DEBUG
18034 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18035 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));
18036 #endif
18039 else
18041 if(target->isVisibleForInState(this,viewPoint,false))
18043 visibleNow.insert(target);
18044 target->BuildUpdate(data_updates);
18045 target->BuildCreateUpdateBlockForPlayer(&data, this);
18046 UpdateVisibilityOf_helper(m_clientGUIDs,target);
18048 #ifdef MANGOS_DEBUG
18049 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18050 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));
18051 #endif
18056 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18057 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18058 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18059 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18060 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18062 void Player::InitPrimaryProfessions()
18064 SetFreePrimaryProfessions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
18067 void Player::SendComboPoints()
18069 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
18070 if (combotarget)
18072 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
18073 data.append(combotarget->GetPackGUID());
18074 data << uint8(m_comboPoints);
18075 GetSession()->SendPacket(&data);
18079 void Player::AddComboPoints(Unit* target, int8 count)
18081 if(!count)
18082 return;
18084 // without combo points lost (duration checked in aura)
18085 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18087 if(target->GetGUID() == m_comboTarget)
18089 m_comboPoints += count;
18091 else
18093 if(m_comboTarget)
18094 if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget))
18095 target2->RemoveComboPointHolder(GetGUIDLow());
18097 m_comboTarget = target->GetGUID();
18098 m_comboPoints = count;
18100 target->AddComboPointHolder(GetGUIDLow());
18103 if (m_comboPoints > 5) m_comboPoints = 5;
18104 if (m_comboPoints < 0) m_comboPoints = 0;
18106 SendComboPoints();
18109 void Player::ClearComboPoints()
18111 if(!m_comboTarget)
18112 return;
18114 // without combopoints lost (duration checked in aura)
18115 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18117 m_comboPoints = 0;
18119 SendComboPoints();
18121 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
18122 target->RemoveComboPointHolder(GetGUIDLow());
18124 m_comboTarget = 0;
18127 void Player::SetGroup(Group *group, int8 subgroup)
18129 if(group == NULL)
18130 m_group.unlink();
18131 else
18133 // never use SetGroup without a subgroup unless you specify NULL for group
18134 assert(subgroup >= 0);
18135 m_group.link(group, this);
18136 m_group.setSubGroup((uint8)subgroup);
18140 void Player::SendInitialPacketsBeforeAddToMap()
18142 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
18143 data << uint32(0); // unknown, may be rest state time or experience
18144 GetSession()->SendPacket(&data);
18146 GetSocial()->SendSocialList();
18148 // Homebind
18149 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
18150 data << m_homebindX << m_homebindY << m_homebindZ;
18151 data << (uint32) m_homebindMapId;
18152 data << (uint32) m_homebindZoneId;
18153 GetSession()->SendPacket(&data);
18155 // SMSG_SET_PROFICIENCY
18156 // SMSG_UPDATE_AURA_DURATION
18158 SendTalentsInfoData(false);
18159 SendInitialSpells();
18161 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
18162 data << uint32(0); // count, for(count) uint32;
18163 GetSession()->SendPacket(&data);
18165 SendInitialActionButtons();
18166 m_reputationMgr.SendInitialReputations();
18167 m_achievementMgr.SendAllAchievementData();
18169 SendEquipmentSetList();
18171 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4);
18172 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
18173 data << (float)0.01666667f; // game speed
18174 data << uint32(0); // added in 3.1.2
18175 GetSession()->SendPacket( &data );
18177 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
18178 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || HasAuraType(SPELL_AURA_FLY) || isInFlight())
18179 m_movementInfo.AddMovementFlag(MOVEMENTFLAG_FLYING2);
18181 m_mover = this;
18184 void Player::SendInitialPacketsAfterAddToMap()
18186 // update zone
18187 uint32 newzone, newarea;
18188 GetZoneAndAreaId(newzone,newarea);
18189 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
18191 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
18192 data << uint32(0x00000000); // on blizz it increments periodically
18193 GetSession()->SendPacket(&data);
18195 CastSpell(this, 836, true); // LOGINEFFECT
18197 // set some aura effects that send packet to player client after add player to map
18198 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
18199 // same auras state lost at far teleport, send it one more time in this case also
18200 static const AuraType auratypes[] =
18202 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
18203 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
18204 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
18206 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
18208 Unit::AuraList const& auraList = GetAurasByType(*itr);
18209 if(!auraList.empty())
18210 auraList.front()->ApplyModifier(true,true);
18213 if(HasAuraType(SPELL_AURA_MOD_STUN))
18214 SetMovement(MOVE_ROOT);
18216 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
18217 if(HasAuraType(SPELL_AURA_MOD_ROOT))
18219 WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
18220 data2.append(GetPackGUID());
18221 data2 << (uint32)2;
18222 SendMessageToSet(&data2,true);
18225 SendAurasForTarget(this);
18226 SendEnchantmentDurations(); // must be after add to map
18227 SendItemDurations(); // must be after add to map
18230 void Player::SendUpdateToOutOfRangeGroupMembers()
18232 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
18233 return;
18234 if(Group* group = GetGroup())
18235 group->UpdatePlayerOutOfRange(this);
18237 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
18238 m_auraUpdateMask = 0;
18239 if(Pet *pet = GetPet())
18240 pet->ResetAuraUpdateMask();
18243 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
18245 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
18246 data << uint32(mapid);
18247 data << uint8(reason); // transfer abort reason
18248 switch(reason)
18250 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
18251 case TRANSFER_ABORT_DIFFICULTY:
18252 case TRANSFER_ABORT_UNIQUE_MESSAGE:
18253 data << uint8(arg);
18254 break;
18256 GetSession()->SendPacket(&data);
18259 void Player::SendInstanceResetWarning( uint32 mapid, uint32 difficulty, uint32 time )
18261 // type of warning, based on the time remaining until reset
18262 uint32 type;
18263 if(time > 3600)
18264 type = RAID_INSTANCE_WELCOME;
18265 else if(time > 900 && time <= 3600)
18266 type = RAID_INSTANCE_WARNING_HOURS;
18267 else if(time > 300 && time <= 900)
18268 type = RAID_INSTANCE_WARNING_MIN;
18269 else
18270 type = RAID_INSTANCE_WARNING_MIN_SOON;
18272 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4);
18273 data << uint32(type);
18274 data << uint32(mapid);
18275 data << uint32(difficulty); // difficulty
18276 data << uint32(time);
18277 if(type == RAID_INSTANCE_WELCOME)
18279 data << uint8(0); // is your (1)
18280 data << uint8(0); // is extended (1), ignored if prev field is 0
18282 GetSession()->SendPacket(&data);
18285 void Player::ApplyEquipCooldown( Item * pItem )
18287 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
18289 _Spell const& spellData = pItem->GetProto()->Spells[i];
18291 // no spell
18292 if( !spellData.SpellId )
18293 continue;
18295 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18296 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
18297 continue;
18299 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
18301 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
18302 data << pItem->GetGUID();
18303 data << uint32(spellData.SpellId);
18304 GetSession()->SendPacket(&data);
18308 void Player::resetSpells()
18310 // not need after this call
18311 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
18312 RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS,true);
18314 // make full copy of map (spells removed and marked as deleted at another spell remove
18315 // and we can't use original map for safe iterative with visit each spell at loop end
18316 PlayerSpellMap smap = GetSpellMap();
18318 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
18319 removeSpell(iter->first,false,false); // only iter->first can be accessed, object by iter->second can be deleted already
18321 learnDefaultSpells();
18322 learnQuestRewardedSpells();
18325 void Player::learnDefaultSpells()
18327 // learn default race/class spells
18328 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
18329 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
18331 uint32 tspell = *itr;
18332 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
18333 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18334 addSpell(tspell,true,true,true,false);
18335 else // but send in normal spell in game learn case
18336 learnSpell(tspell,true);
18340 void Player::learnQuestRewardedSpells(Quest const* quest)
18342 uint32 spell_id = quest->GetRewSpellCast();
18344 // skip quests without rewarded spell
18345 if( !spell_id )
18346 return;
18348 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
18349 if(!spellInfo)
18350 return;
18352 // check learned spells state
18353 bool found = false;
18354 for(int i=0; i < 3; ++i)
18356 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
18358 found = true;
18359 break;
18363 // skip quests with not teaching spell or already known spell
18364 if(!found)
18365 return;
18367 // prevent learn non first rank unknown profession and second specialization for same profession)
18368 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
18369 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
18371 // not have first rank learned (unlearned prof?)
18372 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
18373 if( !HasSpell(first_spell) )
18374 return;
18376 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
18377 if(!learnedInfo)
18378 return;
18380 // specialization
18381 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
18383 // search other specialization for same prof
18384 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
18386 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
18387 continue;
18389 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
18390 if(!itrInfo)
18391 return;
18393 // compare only specializations
18394 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18395 continue;
18397 // compare same chain spells
18398 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18399 continue;
18401 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18402 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18403 return;
18408 CastSpell( this, spell_id, true);
18411 void Player::learnQuestRewardedSpells()
18413 // learn spells received from quest completing
18414 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18416 // skip no rewarded quests
18417 if(!itr->second.m_rewarded)
18418 continue;
18420 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18421 if( !quest )
18422 continue;
18424 learnQuestRewardedSpells(quest);
18428 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
18430 uint32 raceMask = getRaceMask();
18431 uint32 classMask = getClassMask();
18432 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18434 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18435 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18436 continue;
18437 // Check race if set
18438 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18439 continue;
18440 // Check class if set
18441 if (pAbility->classmask && !(pAbility->classmask & classMask))
18442 continue;
18444 if (sSpellStore.LookupEntry(pAbility->spellId))
18446 // need unlearn spell
18447 if (skill_value < pAbility->req_skill_value)
18448 removeSpell(pAbility->spellId);
18449 // need learn
18450 else if (!IsInWorld())
18451 addSpell(pAbility->spellId,true,true,true,false);
18452 else
18453 learnSpell(pAbility->spellId,true);
18458 void Player::SendAurasForTarget(Unit *target)
18460 if(target->GetVisibleAuras()->empty()) // speedup things
18461 return;
18463 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18464 data.append(target->GetPackGUID());
18466 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18467 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18469 for(uint32 j = 0; j < 3; ++j)
18471 if(Aura *aura = target->GetAura(itr->second, j))
18473 data << uint8(aura->GetAuraSlot());
18474 data << uint32(aura->GetId());
18476 if(aura->GetId())
18478 uint8 auraFlags = aura->GetAuraFlags();
18479 // flags
18480 data << uint8(auraFlags);
18481 // level
18482 data << uint8(aura->GetAuraLevel());
18483 // charges
18484 if (aura->GetAuraCharges())
18485 data << uint8(aura->GetAuraCharges() * aura->GetStackAmount());
18486 else
18487 data << uint8(aura->GetStackAmount());
18489 if(!(auraFlags & AFLAG_NOT_CASTER))
18491 data << uint8(0); // packed GUID of someone (caster?)
18494 if(auraFlags & AFLAG_DURATION) // include aura duration
18496 data << uint32(aura->GetAuraMaxDuration());
18497 data << uint32(aura->GetAuraDuration());
18500 break;
18505 GetSession()->SendPacket(&data);
18508 void Player::SetDailyQuestStatus( uint32 quest_id )
18510 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18512 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18514 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18515 m_lastDailyQuestTime = time(NULL); // last daily quest time
18516 m_DailyQuestChanged = true;
18517 break;
18522 void Player::ResetDailyQuestStatus()
18524 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18525 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18527 // DB data deleted in caller
18528 m_DailyQuestChanged = false;
18529 m_lastDailyQuestTime = 0;
18532 BattleGround* Player::GetBattleGround() const
18534 if(GetBattleGroundId()==0)
18535 return NULL;
18537 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgData.bgTypeID);
18540 bool Player::InArena() const
18542 BattleGround *bg = GetBattleGround();
18543 if(!bg || !bg->isArena())
18544 return false;
18546 return true;
18549 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
18551 // get a template bg instead of running one
18552 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18553 if(!bg)
18554 return false;
18556 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18557 return false;
18559 return true;
18562 BGQueueIdBasedOnLevel Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId) const
18564 //returned to hardcoded version of this function, because there is no way to code it dynamic
18565 uint32 level = getLevel();
18566 if( bgTypeId == BATTLEGROUND_AV )
18567 level--;
18569 uint32 queue_id = (level / 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18570 if( queue_id >= MAX_BATTLEGROUND_QUEUES )
18572 sLog.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id);
18573 return QUEUE_ID_MAX_LEVEL_80;
18575 return BGQueueIdBasedOnLevel(queue_id);
18578 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18580 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18581 if(!vendor_faction || !vendor_faction->faction)
18582 return 1.0f;
18584 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18585 if(rank <= REP_NEUTRAL)
18586 return 1.0f;
18588 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18591 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18593 uint32 racemask = getRaceMask();
18594 uint32 classmask = getClassMask();
18596 SkillLineAbilityMapBounds bounds = spellmgr.GetSkillLineAbilityMapBounds(spell_id);
18597 if (bounds.first==bounds.second)
18598 return true;
18600 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
18602 // skip wrong race skills
18603 if (_spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18604 continue;
18606 // skip wrong class skills
18607 if (_spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18608 continue;
18610 return true;
18613 return false;
18616 bool Player::HasQuestForGO(int32 GOId) const
18618 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
18620 uint32 questid = GetQuestSlotQuestId(i);
18621 if ( questid == 0 )
18622 continue;
18624 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
18625 if(qs_itr == mQuestStatus.end())
18626 continue;
18628 QuestStatusData const& qs = qs_itr->second;
18630 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18632 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
18633 if(!qinfo)
18634 continue;
18636 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18637 continue;
18639 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
18641 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18642 continue;
18644 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18645 return true;
18649 return false;
18652 void Player::UpdateForQuestWorldObjects()
18654 if(m_clientGUIDs.empty())
18655 return;
18657 UpdateData udata;
18658 WorldPacket packet;
18659 for(ClientGUIDs::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18661 if(IS_GAMEOBJECT_GUID(*itr))
18663 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18664 if(obj)
18665 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18667 else if(IS_CREATURE_GUID(*itr) || IS_VEHICLE_GUID(*itr))
18669 Creature *obj = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr);
18670 if(!obj)
18671 continue;
18673 // check if this unit requires quest specific flags
18674 if(!obj->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
18675 continue;
18677 SpellClickInfoMapBounds clickPair = objmgr.GetSpellClickInfoMapBounds(obj->GetEntry());
18678 for(SpellClickInfoMap::const_iterator _itr = clickPair.first; _itr != clickPair.second; ++_itr)
18680 if(_itr->second.questStart || _itr->second.questEnd)
18682 obj->BuildCreateUpdateBlockForPlayer(&udata,this);
18683 break;
18688 udata.BuildPacket(&packet);
18689 GetSession()->SendPacket(&packet);
18692 void Player::SummonIfPossible(bool agree)
18694 if(!agree)
18696 m_summon_expire = 0;
18697 return;
18700 // expire and auto declined
18701 if(m_summon_expire < time(NULL))
18702 return;
18704 // stop taxi flight at summon
18705 if(isInFlight())
18707 GetMotionMaster()->MovementExpired();
18708 m_taxi.ClearTaxiDestinations();
18711 // drop flag at summon
18712 // 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
18713 if(BattleGround *bg = GetBattleGround())
18714 bg->EventPlayerDroppedFlag(this);
18716 m_summon_expire = 0;
18718 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
18720 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18723 void Player::RemoveItemDurations( Item *item )
18725 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18727 if(*itr==item)
18729 m_itemDuration.erase(itr);
18730 break;
18735 void Player::AddItemDurations( Item *item )
18737 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18739 m_itemDuration.push_back(item);
18740 item->SendTimeUpdate(this);
18744 void Player::AutoUnequipOffhandIfNeed()
18746 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18747 if(!offItem)
18748 return;
18750 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18751 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
18752 return;
18754 ItemPosCountVec off_dest;
18755 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18756 if( off_msg == EQUIP_ERR_OK )
18758 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18759 StoreItem( off_dest, offItem, true );
18761 else
18763 MailItemsInfo mi;
18764 mi.AddItem(offItem->GetGUIDLow(), offItem->GetEntry(), offItem);
18765 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18766 CharacterDatabase.BeginTransaction();
18767 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
18768 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18769 CharacterDatabase.CommitTransaction();
18771 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
18772 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
18776 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18778 if(spellInfo->EquippedItemClass < 0)
18779 return true;
18781 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18782 // for optimize check 2 used cases only
18783 switch(spellInfo->EquippedItemClass)
18785 case ITEM_CLASS_WEAPON:
18787 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18788 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18789 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18790 return true;
18791 break;
18793 case ITEM_CLASS_ARMOR:
18795 // tabard not have dependent spells
18796 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18797 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18798 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18799 return true;
18801 // shields can be equipped to offhand slot
18802 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18803 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18804 return true;
18806 // ranged slot can have some armor subclasses
18807 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18808 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18809 return true;
18811 break;
18813 default:
18814 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18815 break;
18818 return false;
18821 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18823 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18824 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18825 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18826 return true;
18828 // Check no reagent use mask
18829 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18830 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18831 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18832 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18833 return true;
18835 return false;
18838 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18840 AuraMap& auras = GetAuras();
18841 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); )
18843 Aura* aura = itr->second;
18845 // skip passive (passive item dependent spells work in another way) and not self applied auras
18846 SpellEntry const* spellInfo = aura->GetSpellProto();
18847 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18849 ++itr;
18850 continue;
18853 // skip if not item dependent or have alternative item
18854 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18856 ++itr;
18857 continue;
18860 // no alt item, remove aura, restart check
18861 RemoveAurasDueToSpell(aura->GetId());
18862 itr = auras.begin();
18865 // currently casted spells can be dependent from item
18866 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
18867 if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i)))
18868 if (spell->getState()!=SPELL_STATE_DELAYED && !HasItemFitToSpellReqirements(spell->m_spellInfo,pItem) )
18869 InterruptSpell(CurrentSpellTypes(i));
18872 uint32 Player::GetResurrectionSpellId()
18874 // search priceless resurrection possibilities
18875 uint32 prio = 0;
18876 uint32 spell_id = 0;
18877 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18878 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18880 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18881 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18883 switch((*itr)->GetId())
18885 case 20707: spell_id = 3026; break; // rank 1
18886 case 20762: spell_id = 20758; break; // rank 2
18887 case 20763: spell_id = 20759; break; // rank 3
18888 case 20764: spell_id = 20760; break; // rank 4
18889 case 20765: spell_id = 20761; break; // rank 5
18890 case 27239: spell_id = 27240; break; // rank 6
18891 case 47883: spell_id = 47882; break; // rank 7
18892 default:
18893 sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
18894 continue;
18897 prio = 3;
18899 // Twisting Nether // prio: 2 (max)
18900 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18902 prio = 2;
18903 spell_id = 23700;
18907 // Reincarnation (passive spell) // prio: 1
18908 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18909 spell_id = 21169;
18911 return spell_id;
18914 // Used in triggers for check "Only to targets that grant experience or honor" req
18915 bool Player::isHonorOrXPTarget(Unit* pVictim)
18917 uint32 v_level = pVictim->getLevel();
18918 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
18920 // Victim level less gray level
18921 if(v_level<=k_grey)
18922 return false;
18924 if(pVictim->GetTypeId() == TYPEID_UNIT)
18926 if (((Creature*)pVictim)->isTotem() ||
18927 ((Creature*)pVictim)->isPet() ||
18928 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
18929 return false;
18931 return true;
18934 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18936 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18938 // prepare data for near group iteration (PvP and !PvP cases)
18939 uint32 xp = 0;
18940 bool honored_kill = false;
18942 if(Group *pGroup = GetGroup())
18944 uint32 count = 0;
18945 uint32 sum_level = 0;
18946 Player* member_with_max_level = NULL;
18947 Player* not_gray_member_with_max_level = NULL;
18949 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18951 if(member_with_max_level)
18953 /// not get Xp in PvP or no not gray players in group
18954 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18956 /// skip in check PvP case (for speed, not used)
18957 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18958 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18959 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18961 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18963 Player* pGroupGuy = itr->getSource();
18964 if(!pGroupGuy)
18965 continue;
18967 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18968 continue; // member (alive or dead) or his corpse at req. distance
18970 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18971 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18972 honored_kill = true;
18974 // xp and reputation only in !PvP case
18975 if(!PvP)
18977 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18979 // if is in dungeon then all receive full reputation at kill
18980 // rewarded any alive/dead/near_corpse group member
18981 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18983 // XP updated only for alive group member
18984 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18985 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18987 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18989 pGroupGuy->GiveXP(itr_xp, pVictim);
18990 if(Pet* pet = pGroupGuy->GetPet())
18991 pet->GivePetXP(itr_xp/2);
18994 // quest objectives updated only for alive group member or dead but with not released body
18995 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18997 // normal creature (not pet/etc) can be only in !PvP case
18998 if(pVictim->GetTypeId()==TYPEID_UNIT)
18999 pGroupGuy->KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
19005 else // if (!pGroup)
19007 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
19009 // honor can be in PvP and !PvP (racial leader) cases
19010 if(RewardHonor(pVictim,1))
19011 honored_kill = true;
19013 // xp and reputation only in !PvP case
19014 if(!PvP)
19016 RewardReputation(pVictim,1);
19017 GiveXP(xp, pVictim);
19019 if(Pet* pet = GetPet())
19020 pet->GivePetXP(xp);
19022 // normal creature (not pet/etc) can be only in !PvP case
19023 if(pVictim->GetTypeId()==TYPEID_UNIT)
19024 KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
19027 return xp || honored_kill;
19030 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
19032 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
19034 // prepare data for near group iteration
19035 if(Group *pGroup = GetGroup())
19037 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19039 Player* pGroupGuy = itr->getSource();
19040 if(!pGroupGuy)
19041 continue;
19043 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
19044 continue; // member (alive or dead) or his corpse at req. distance
19046 // quest objectives updated only for alive group member or dead but with not released body
19047 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
19048 pGroupGuy->KilledMonsterCredit(creature_id, creature_guid);
19051 else // if (!pGroup)
19052 KilledMonsterCredit(creature_id, creature_guid);
19055 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
19057 if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE)))
19058 return true;
19060 if (isAlive())
19061 return false;
19063 Corpse* corpse = GetCorpse();
19064 if (!corpse)
19065 return false;
19067 return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE));
19070 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
19072 Item* item = GetWeaponForAttack(attType,true);
19074 // unarmed only with base attack
19075 if(attType != BASE_ATTACK && !item)
19076 return 0;
19078 // weapon skill or (unarmed for base attack)
19079 uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
19080 return GetBaseSkillValue(skill);
19083 void Player::ResurectUsingRequestData()
19085 /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
19086 if(IS_PLAYER_GUID(m_resurrectGUID))
19087 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
19089 //we cannot resurrect player when we triggered far teleport
19090 //player will be resurrected upon teleportation
19091 if(IsBeingTeleportedFar())
19093 ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER);
19094 return;
19097 ResurrectPlayer(0.0f,false);
19099 if(GetMaxHealth() > m_resurrectHealth)
19100 SetHealth( m_resurrectHealth );
19101 else
19102 SetHealth( GetMaxHealth() );
19104 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
19105 SetPower(POWER_MANA, m_resurrectMana );
19106 else
19107 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
19109 SetPower(POWER_RAGE, 0 );
19111 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
19113 SpawnCorpseBones();
19116 void Player::SetClientControl(Unit* target, uint8 allowMove)
19118 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
19119 data.append(target->GetPackGUID());
19120 data << uint8(allowMove);
19121 GetSession()->SendPacket(&data);
19124 void Player::UpdateZoneDependentAuras( uint32 newZone )
19126 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
19127 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newZone);
19128 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19129 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
19130 if( !HasAura(itr->second->spellId,0) )
19131 CastSpell(this,itr->second->spellId,true);
19134 void Player::UpdateAreaDependentAuras( uint32 newArea )
19136 // remove auras from spells with area limitations
19137 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
19139 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
19140 if(spellmgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
19141 RemoveAura(iter);
19142 else
19143 ++iter;
19146 // some auras applied at subzone enter
19147 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newArea);
19148 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19149 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
19150 if( !HasAura(itr->second->spellId,0) )
19151 CastSpell(this,itr->second->spellId,true);
19154 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
19156 if ((pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
19157 (!pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
19159 return copseReclaimDelay[0];
19162 time_t now = time(NULL);
19163 // 0..2 full period
19164 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
19165 return copseReclaimDelay[count];
19168 void Player::UpdateCorpseReclaimDelay()
19170 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
19172 if ((pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
19173 (!pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
19174 return;
19176 time_t now = time(NULL);
19177 if(now < m_deathExpireTime)
19179 // full and partly periods 1..3
19180 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
19181 if(count < MAX_DEATH_COUNT)
19182 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
19183 else
19184 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
19186 else
19187 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
19190 void Player::SendCorpseReclaimDelay(bool load)
19192 Corpse* corpse = GetCorpse();
19193 if(!corpse)
19194 return;
19196 uint32 delay;
19197 if(load)
19199 if(corpse->GetGhostTime() > m_deathExpireTime)
19200 return;
19202 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
19204 uint32 count;
19205 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19206 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19208 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
19209 if(count>=MAX_DEATH_COUNT)
19210 count = MAX_DEATH_COUNT-1;
19212 else
19213 count=0;
19215 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
19217 time_t now = time(NULL);
19218 if(now >= expected_time)
19219 return;
19221 delay = expected_time-now;
19223 else
19224 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
19226 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19227 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
19228 data << uint32(delay*IN_MILISECONDS);
19229 GetSession()->SendPacket( &data );
19232 Player* Player::GetNextRandomRaidMember(float radius)
19234 Group *pGroup = GetGroup();
19235 if(!pGroup)
19236 return NULL;
19238 std::vector<Player*> nearMembers;
19239 nearMembers.reserve(pGroup->GetMembersCount());
19241 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19243 Player* Target = itr->getSource();
19245 // IsHostileTo check duel and controlled by enemy
19246 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
19247 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
19248 nearMembers.push_back(Target);
19251 if (nearMembers.empty())
19252 return NULL;
19254 uint32 randTarget = urand(0,nearMembers.size()-1);
19255 return nearMembers[randTarget];
19258 PartyResult Player::CanUninviteFromGroup() const
19260 const Group* grp = GetGroup();
19261 if(!grp)
19262 return PARTY_RESULT_YOU_NOT_IN_GROUP;
19264 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
19265 return PARTY_RESULT_YOU_NOT_LEADER;
19267 if(InBattleGround())
19268 return PARTY_RESULT_INVITE_RESTRICTED;
19270 return PARTY_RESULT_OK;
19273 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
19275 //we must move references from m_group to m_originalGroup
19276 SetOriginalGroup(GetGroup(), GetSubGroup());
19278 m_group.unlink();
19279 m_group.link(group, this);
19280 m_group.setSubGroup((uint8)subgroup);
19283 void Player::RemoveFromBattleGroundRaid()
19285 //remove existing reference
19286 m_group.unlink();
19287 if( Group* group = GetOriginalGroup() )
19289 m_group.link(group, this);
19290 m_group.setSubGroup(GetOriginalSubGroup());
19292 SetOriginalGroup(NULL);
19295 void Player::SetOriginalGroup(Group *group, int8 subgroup)
19297 if( group == NULL )
19298 m_originalGroup.unlink();
19299 else
19301 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
19302 assert(subgroup >= 0);
19303 m_originalGroup.link(group, this);
19304 m_originalGroup.setSubGroup((uint8)subgroup);
19308 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
19310 LiquidData liquid_status;
19311 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
19312 if (!res)
19314 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
19315 // Small hack for enable breath in WMO
19316 if (IsInWater())
19317 m_MirrorTimerFlags|=UNDERWATER_INWATER;
19318 return;
19321 // All liquids type - check under water position
19322 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
19324 if ( res & LIQUID_MAP_UNDER_WATER)
19325 m_MirrorTimerFlags |= UNDERWATER_INWATER;
19326 else
19327 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
19330 // Allow travel in dark water on taxi or transport
19331 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
19332 m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
19333 else
19334 m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
19336 // in lava check, anywhere in lava level
19337 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
19339 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19340 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
19341 else
19342 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
19344 // in slime check, anywhere in slime level
19345 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
19347 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19348 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
19349 else
19350 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
19354 void Player::SetCanParry( bool value )
19356 if(m_canParry==value)
19357 return;
19359 m_canParry = value;
19360 UpdateParryPercentage();
19363 void Player::SetCanBlock( bool value )
19365 if(m_canBlock==value)
19366 return;
19368 m_canBlock = value;
19369 UpdateBlockPercentage();
19372 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
19374 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
19375 if(itr->pos == pos)
19376 return true;
19378 return false;
19381 bool Player::CanUseBattleGroundObject()
19383 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
19384 // maybe gameobject code should handle that ForceReaction usage
19385 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
19386 return ( //InBattleGround() && // in battleground - not need, check in other cases
19387 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
19388 //player cannot use object when he is invulnerable (immune)
19389 !isTotalImmune() && // not totally immune
19390 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
19391 !HasStealthAura() && // not stealthed
19392 !HasInvisibilityAura() && // not invisible
19393 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
19394 isAlive() // live player
19398 bool Player::CanCaptureTowerPoint()
19400 return ( !HasStealthAura() && // not stealthed
19401 !HasInvisibilityAura() && // not invisible
19402 isAlive() // live player
19406 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
19408 uint32 level = getLevel();
19410 if(level > GT_MAX_LEVEL)
19411 level = GT_MAX_LEVEL; // max level in this dbc
19413 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
19414 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
19415 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
19417 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
19418 return 0;
19420 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
19422 if(!bsc) // shouldn't happen
19423 return 0xFFFFFFFF;
19425 float cost = 0;
19427 if(hairstyle != newhairstyle)
19428 cost += bsc->cost; // full price
19430 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
19431 cost += bsc->cost * 0.5f; // +1/2 of price
19433 if(facialhair != newfacialhair)
19434 cost += bsc->cost * 0.75f; // +3/4 of price
19436 return uint32(cost);
19439 void Player::InitGlyphsForLevel()
19441 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
19442 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
19443 if(gs->Order)
19444 SetGlyphSlot(gs->Order - 1, gs->Id);
19446 uint32 level = getLevel();
19447 uint32 value = 0;
19449 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19450 if(level >= 15)
19451 value |= (0x01 | 0x02);
19452 if(level >= 30)
19453 value |= 0x08;
19454 if(level >= 50)
19455 value |= 0x04;
19456 if(level >= 70)
19457 value |= 0x10;
19458 if(level >= 80)
19459 value |= 0x20;
19461 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
19464 void Player::EnterVehicle(Vehicle *vehicle)
19466 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
19467 if(!ve)
19468 return;
19470 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
19471 if(!veSeat)
19472 return;
19474 vehicle->SetCharmerGUID(GetGUID());
19475 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19476 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
19477 vehicle->setFaction(getFaction());
19479 SetCharm(vehicle); // charm
19480 SetFarSightGUID(vehicle->GetGUID()); // set view
19482 SetClientControl(vehicle, 1); // redirect controls to vehicle
19483 SetMover(vehicle);
19485 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
19486 GetSession()->SendPacket(&data);
19488 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
19489 data.append(GetPackGUID());
19490 data << uint32(0); // counter?
19491 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
19492 data << uint16(0); // special flags
19493 data << uint32(getMSTime()); // time
19494 data << vehicle->GetPositionX(); // x
19495 data << vehicle->GetPositionY(); // y
19496 data << vehicle->GetPositionZ(); // z
19497 data << vehicle->GetOrientation(); // o
19498 // transport part, TODO: load/calculate seat offsets
19499 data << uint64(vehicle->GetGUID()); // transport guid
19500 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19501 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19502 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19503 data << float(0); // transport orientation
19504 data << uint32(getMSTime()); // transport time
19505 data << uint8(0); // seat
19506 // end of transport part
19507 data << uint32(0); // fall time
19508 GetSession()->SendPacket(&data);
19510 data.Initialize(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
19511 data << uint64(vehicle->GetGUID());
19512 data << uint16(0);
19513 data << uint32(0);
19514 data << uint32(0x00000101);
19516 for(uint32 i = 0; i < 10; ++i)
19517 data << uint16(0) << uint8(0) << uint8(i+8);
19519 data << uint8(0);
19520 data << uint8(0);
19521 GetSession()->SendPacket(&data);
19524 void Player::ExitVehicle(Vehicle *vehicle)
19526 vehicle->SetCharmerGUID(0);
19527 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19528 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
19529 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19531 SetCharm(NULL);
19532 SetFarSightGUID(0);
19534 SetClientControl(vehicle, 0);
19535 SetMover(NULL);
19537 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19538 data.append(GetPackGUID());
19539 data << uint32(0); // counter?
19540 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19541 data << uint16(0x40); // special flags
19542 data << uint32(getMSTime()); // time
19543 data << vehicle->GetPositionX(); // x
19544 data << vehicle->GetPositionY(); // y
19545 data << vehicle->GetPositionZ(); // z
19546 data << vehicle->GetOrientation(); // o
19547 data << uint32(0); // fall time
19548 GetSession()->SendPacket(&data);
19550 RemovePetActionBar();
19552 // maybe called at dummy aura remove?
19553 // CastSpell(this, 45472, true); // Parachute
19556 bool Player::isTotalImmune()
19558 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
19560 uint32 immuneMask = 0;
19561 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
19563 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
19564 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
19565 return true;
19567 return false;
19570 bool Player::HasTitle(uint32 bitIndex)
19572 if (bitIndex > MAX_TITLE_INDEX)
19573 return false;
19575 uint32 fieldIndexOffset = bitIndex / 32;
19576 uint32 flag = 1 << (bitIndex % 32);
19577 return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19580 void Player::SetTitle(CharTitlesEntry const* title, bool lost)
19582 uint32 fieldIndexOffset = title->bit_index / 32;
19583 uint32 flag = 1 << (title->bit_index % 32);
19585 if(lost)
19587 if(!HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
19588 return;
19590 RemoveFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19592 else
19594 if(HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
19595 return;
19597 SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19600 WorldPacket data(SMSG_TITLE_EARNED, 4 + 4);
19601 data << uint32(title->bit_index);
19602 data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost
19603 GetSession()->SendPacket(&data);
19606 void Player::ConvertRune(uint8 index, RuneType newType)
19608 SetCurrentRune(index, newType);
19610 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19611 data << uint8(index);
19612 data << uint8(newType);
19613 GetSession()->SendPacket(&data);
19616 void Player::ResyncRunes(uint8 count)
19618 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19619 for(uint32 i = 0; i < count; ++i)
19621 data << uint8(GetCurrentRune(i)); // rune type
19622 data << uint8(255 - ((GetRuneCooldown(i) / REGEN_TIME_FULL) * 51)); // passed cooldown time (0-255)
19624 GetSession()->SendPacket(&data);
19627 void Player::AddRunePower(uint8 index)
19629 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19630 data << uint32(1 << index); // mask (0x00-0x3F probably)
19631 GetSession()->SendPacket(&data);
19634 static RuneType runeSlotTypes[MAX_RUNES] = {
19635 /*0*/ RUNE_BLOOD,
19636 /*1*/ RUNE_BLOOD,
19637 /*2*/ RUNE_UNHOLY,
19638 /*3*/ RUNE_UNHOLY,
19639 /*4*/ RUNE_FROST,
19640 /*5*/ RUNE_FROST
19643 void Player::InitRunes()
19645 if(getClass() != CLASS_DEATH_KNIGHT)
19646 return;
19648 m_runes = new Runes;
19650 m_runes->runeState = 0;
19652 for(uint32 i = 0; i < MAX_RUNES; ++i)
19654 SetBaseRune(i, runeSlotTypes[i]); // init base types
19655 SetCurrentRune(i, runeSlotTypes[i]); // init current types
19656 SetRuneCooldown(i, 0); // reset cooldowns
19657 m_runes->SetRuneState(i);
19660 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19661 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
19665 bool Player::IsBaseRuneSlotsOnCooldown( RuneType runeType ) const
19667 for(uint32 i = 0; i < MAX_RUNES; ++i)
19668 if (GetBaseRune(i) == runeType && GetRuneCooldown(i) == 0)
19669 return false;
19671 return true;
19674 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
19676 Loot loot;
19677 loot.FillLoot (loot_id,store,this,true);
19679 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
19680 for(uint32 i = 0; i < max_slot; ++i)
19682 LootItem* lootItem = loot.LootItemInSlot(i,this);
19684 ItemPosCountVec dest;
19685 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
19686 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
19687 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19688 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
19689 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19690 if(msg != EQUIP_ERR_OK)
19692 SendEquipError( msg, NULL, NULL );
19693 continue;
19696 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
19697 SendNewItem(pItem, lootItem->count, false, false, broadcast);
19701 uint32 Player::CalculateTalentsPoints() const
19703 uint32 base_talent = getLevel() < 10 ? 0 : getLevel()-9;
19705 if(getClass() != CLASS_DEATH_KNIGHT)
19706 return uint32(base_talent * sWorld.getRate(RATE_TALENT));
19708 uint32 talentPointsForLevel = getLevel() < 56 ? 0 : getLevel() - 55;
19709 talentPointsForLevel += m_questRewardTalentCount;
19711 if(talentPointsForLevel > base_talent)
19712 talentPointsForLevel = base_talent;
19714 return uint32(talentPointsForLevel * sWorld.getRate(RATE_TALENT));
19717 bool Player::IsKnowHowFlyIn(uint32 mapid, uint32 zone) const
19719 // continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update
19720 uint32 v_map = GetVirtualMapForMapAndZone(mapid, zone);
19721 return v_map != 571 || HasSpell(54197); // Cold Weather Flying
19724 struct DoPlayerLearnSpell
19726 DoPlayerLearnSpell(Player& _player) : player(_player) {}
19727 void operator() (uint32 spell_id) { player.learnSpell(spell_id,false); }
19728 Player& player;
19731 void Player::learnSpellHighRank(uint32 spellid)
19733 learnSpell(spellid,false);
19735 DoPlayerLearnSpell worker(*this);
19736 spellmgr.doForHighRanks(spellid,worker);
19739 void Player::_LoadSkills()
19741 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19743 // reset skill modifiers and set correct unlearn flags
19744 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; ++i)
19746 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
19748 // set correct unlearn bit
19749 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
19750 if(!id) continue;
19752 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
19753 if(!pSkill) continue;
19755 // enable unlearn button for primary professions only
19756 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
19757 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
19758 else
19759 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
19761 // set fixed skill ranges
19762 switch(GetSkillRangeType(pSkill,false))
19764 case SKILL_RANGE_LANGUAGE: // 300..300
19765 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(300,300));
19766 break;
19767 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
19768 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(1,1));
19769 break;
19770 default:
19771 break;
19774 uint32 vskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
19775 learnSkillRewardedSpells(id, vskill);
19778 // special settings
19779 if(getClass()==CLASS_DEATH_KNIGHT)
19781 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
19782 if(base_level < 1)
19783 base_level = 1;
19784 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
19785 if(base_skill < 1)
19786 base_skill = 1; // skill mast be known and then > 0 in any case
19788 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
19789 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
19790 if(GetPureSkillValue (SKILL_AXES) < base_skill)
19791 SetSkill(SKILL_AXES, base_skill,base_skill);
19792 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
19793 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
19794 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
19795 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
19796 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
19797 SetSkill(SKILL_SWORDS, base_skill,base_skill);
19798 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
19799 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
19800 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
19801 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
19802 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
19803 SetSkill(SKILL_UNARMED, base_skill,base_skill);
19807 uint32 Player::GetPhaseMaskForSpawn() const
19809 uint32 phase = PHASEMASK_NORMAL;
19810 if(!isGameMaster())
19811 phase = GetPhaseMask();
19812 else
19814 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
19815 if(!phases.empty())
19816 phase = phases.front()->GetMiscValue();
19819 // some aura phases include 1 normal map in addition to phase itself
19820 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
19821 return n_phase;
19823 return PHASEMASK_NORMAL;
19826 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
19828 ItemPrototype const* pProto = pItem->GetProto();
19830 // proto based limitations
19831 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
19832 return res;
19834 // check unique-equipped on gems
19835 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
19837 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
19838 if(!enchant_id)
19839 continue;
19840 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
19841 if(!enchantEntry)
19842 continue;
19844 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
19845 if(!pGem)
19846 continue;
19848 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19849 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
19850 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
19852 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
19853 return res;
19856 return EQUIP_ERR_OK;
19859 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
19861 // check unique-equipped on item
19862 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
19864 // there is an equip limit on this item
19865 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
19866 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19869 // check unique-equipped limit
19870 if (itemProto->ItemLimitCategory)
19872 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
19873 if(!limitEntry)
19874 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19876 if(limit_count > limitEntry->maxCount)
19877 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
19879 // there is an equip limit on this item
19880 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
19881 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19884 return EQUIP_ERR_OK;
19887 void Player::HandleFall(MovementInfo const& movementInfo)
19889 // calculate total z distance of the fall
19890 float z_diff = m_lastFallZ - movementInfo.z;
19891 sLog.outDebug("zDiff = %f", z_diff);
19893 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19894 // 14.57 can be calculated by resolving damageperc formula below to 0
19895 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
19896 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
19897 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
19899 //Safe fall, fall height reduction
19900 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
19902 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
19904 if(damageperc >0 )
19906 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
19908 float height = movementInfo.z;
19909 UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
19911 if (damage > 0)
19913 //Prevent fall damage from being more than the player maximum health
19914 if (damage > GetMaxHealth())
19915 damage = GetMaxHealth();
19917 // Gust of Wind
19918 if (GetDummyAura(43621))
19919 damage = GetMaxHealth()/2;
19921 uint32 original_health = GetHealth();
19922 uint32 final_damage = EnvironmentalDamage(DAMAGE_FALL, damage);
19924 // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
19925 if (isAlive() && final_damage < original_health)
19926 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
19929 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
19930 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);
19935 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
19937 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
19940 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
19942 uint32 CurTalentPoints = GetFreeTalentPoints();
19944 if(CurTalentPoints == 0)
19945 return;
19947 if (talentRank >= MAX_TALENT_RANK)
19948 return;
19950 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
19952 if(!talentInfo)
19953 return;
19955 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
19957 if(!talentTabInfo)
19958 return;
19960 // prevent learn talent for different class (cheating)
19961 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
19962 return;
19964 // find current max talent rank
19965 int32 curtalent_maxrank = 0;
19966 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19968 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
19970 curtalent_maxrank = k + 1;
19971 break;
19975 // we already have same or higher talent rank learned
19976 if(curtalent_maxrank >= (talentRank + 1))
19977 return;
19979 // check if we have enough talent points
19980 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19981 return;
19983 // Check if it requires another talent
19984 if (talentInfo->DependsOn > 0)
19986 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19988 bool hasEnoughRank = false;
19989 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19991 if (depTalentInfo->RankID[i] != 0)
19992 if (HasSpell(depTalentInfo->RankID[i]))
19993 hasEnoughRank = true;
19995 if (!hasEnoughRank)
19996 return;
20000 // Find out how many points we have in this field
20001 uint32 spentPoints = 0;
20003 uint32 tTab = talentInfo->TalentTab;
20004 if (talentInfo->Row > 0)
20006 unsigned int numRows = sTalentStore.GetNumRows();
20007 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
20009 // Someday, someone needs to revamp
20010 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
20011 if (tmpTalent) // the way talents are tracked
20013 if (tmpTalent->TalentTab == tTab)
20015 for (int j = 0; j < MAX_TALENT_RANK; ++j)
20017 if (tmpTalent->RankID[j] != 0)
20019 if (HasSpell(tmpTalent->RankID[j]))
20021 spentPoints += j + 1;
20030 // not have required min points spent in talent tree
20031 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
20032 return;
20034 // spell not set in talent.dbc
20035 uint32 spellid = talentInfo->RankID[talentRank];
20036 if( spellid == 0 )
20038 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
20039 return;
20042 // already known
20043 if(HasSpell(spellid))
20044 return;
20046 // learn! (other talent ranks will unlearned at learning)
20047 learnSpell(spellid, false);
20048 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
20050 // update free talent points
20051 SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
20054 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
20056 Pet *pet = GetPet();
20058 if(!pet)
20059 return;
20061 if(petGuid != pet->GetGUID())
20062 return;
20064 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
20066 if(CurTalentPoints == 0)
20067 return;
20069 if (talentRank >= MAX_PET_TALENT_RANK)
20070 return;
20072 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
20074 if(!talentInfo)
20075 return;
20077 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
20079 if(!talentTabInfo)
20080 return;
20082 CreatureInfo const *ci = pet->GetCreatureInfo();
20084 if(!ci)
20085 return;
20087 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
20089 if(!pet_family)
20090 return;
20092 if(pet_family->petTalentType < 0) // not hunter pet
20093 return;
20095 // prevent learn talent for different family (cheating)
20096 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
20097 return;
20099 // find current max talent rank
20100 int32 curtalent_maxrank = 0;
20101 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
20103 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
20105 curtalent_maxrank = k + 1;
20106 break;
20110 // we already have same or higher talent rank learned
20111 if(curtalent_maxrank >= (talentRank + 1))
20112 return;
20114 // check if we have enough talent points
20115 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
20116 return;
20118 // Check if it requires another talent
20119 if (talentInfo->DependsOn > 0)
20121 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
20123 bool hasEnoughRank = false;
20124 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
20126 if (depTalentInfo->RankID[i] != 0)
20127 if (pet->HasSpell(depTalentInfo->RankID[i]))
20128 hasEnoughRank = true;
20130 if (!hasEnoughRank)
20131 return;
20135 // Find out how many points we have in this field
20136 uint32 spentPoints = 0;
20138 uint32 tTab = talentInfo->TalentTab;
20139 if (talentInfo->Row > 0)
20141 unsigned int numRows = sTalentStore.GetNumRows();
20142 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
20144 // Someday, someone needs to revamp
20145 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
20146 if (tmpTalent) // the way talents are tracked
20148 if (tmpTalent->TalentTab == tTab)
20150 for (int j = 0; j < MAX_TALENT_RANK; ++j)
20152 if (tmpTalent->RankID[j] != 0)
20154 if (pet->HasSpell(tmpTalent->RankID[j]))
20156 spentPoints += j + 1;
20165 // not have required min points spent in talent tree
20166 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
20167 return;
20169 // spell not set in talent.dbc
20170 uint32 spellid = talentInfo->RankID[talentRank];
20171 if( spellid == 0 )
20173 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
20174 return;
20177 // already known
20178 if(pet->HasSpell(spellid))
20179 return;
20181 // learn! (other talent ranks will unlearned at learning)
20182 pet->learnSpell(spellid);
20183 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
20185 // update free talent points
20186 pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
20189 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
20191 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
20193 if(apply)
20194 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(UI64LIT(1) << (ctEntry->BitIndex-1)));
20195 else
20196 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(UI64LIT(1) << (ctEntry->BitIndex-1)));
20200 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
20202 if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <=minfo.z || opcode == MSG_MOVE_FALL_LAND)
20203 SetFallInformation(minfo.fallTime, minfo.z);
20206 void Player::UnsummonPetTemporaryIfAny()
20208 Pet* pet = GetPet();
20209 if(!pet)
20210 return;
20212 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
20214 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
20215 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
20218 RemovePet(pet, PET_SAVE_AS_CURRENT);
20221 void Player::ResummonPetTemporaryUnSummonedIfAny()
20223 if(!m_temporaryUnsummonedPetNumber)
20224 return;
20226 // not resummon in not appropriate state
20227 if(IsPetNeedBeTemporaryUnsummoned())
20228 return;
20230 if(GetPetGUID())
20231 return;
20233 Pet* NewPet = new Pet;
20234 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
20235 delete NewPet;
20237 m_temporaryUnsummonedPetNumber = 0;
20240 bool Player::canSeeSpellClickOn(Creature const *c) const
20242 if(!c->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
20243 return false;
20245 SpellClickInfoMapBounds clickPair = objmgr.GetSpellClickInfoMapBounds(c->GetEntry());
20246 for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
20247 if(itr->second.IsFitToRequirements(this))
20248 return true;
20250 return false;
20253 void Player::BuildPlayerTalentsInfoData(WorldPacket *data)
20255 *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
20256 *data << uint8(m_specsCount); // talent group count (0, 1 or 2)
20257 *data << uint8(m_activeSpec); // talent group index (0 or 1)
20259 if(m_specsCount)
20261 // loop through all specs (only 1 for now)
20262 for(uint32 specIdx = 0; specIdx < m_specsCount; ++specIdx)
20264 uint8 talentIdCount = 0;
20265 size_t pos = data->wpos();
20266 *data << uint8(talentIdCount); // [PH], talentIdCount
20268 // find class talent tabs (all players have 3 talent tabs)
20269 uint32 const* talentTabIds = GetTalentTabPages(getClass());
20271 for(uint32 i = 0; i < 3; ++i)
20273 uint32 talentTabId = talentTabIds[i];
20275 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
20277 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
20278 if(!talentInfo)
20279 continue;
20281 // skip another tab talents
20282 if(talentInfo->TalentTab != talentTabId)
20283 continue;
20285 // find max talent rank
20286 int32 curtalent_maxrank = -1;
20287 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
20289 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
20291 curtalent_maxrank = k;
20292 break;
20296 // not learned talent
20297 if(curtalent_maxrank < 0)
20298 continue;
20300 *data << uint32(talentInfo->TalentID); // Talent.dbc
20301 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
20303 ++talentIdCount;
20307 data->put<uint8>(pos, talentIdCount); // put real count
20309 *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
20311 for(uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
20312 *data << uint16(GetGlyph(i)); // GlyphProperties.dbc
20317 void Player::BuildPetTalentsInfoData(WorldPacket *data)
20319 uint32 unspentTalentPoints = 0;
20320 size_t pointsPos = data->wpos();
20321 *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
20323 uint8 talentIdCount = 0;
20324 size_t countPos = data->wpos();
20325 *data << uint8(talentIdCount); // [PH], talentIdCount
20327 Pet *pet = GetPet();
20328 if(!pet)
20329 return;
20331 unspentTalentPoints = pet->GetFreeTalentPoints();
20333 data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
20335 CreatureInfo const *ci = pet->GetCreatureInfo();
20336 if(!ci)
20337 return;
20339 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
20340 if(!pet_family || pet_family->petTalentType < 0)
20341 return;
20343 for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
20345 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
20346 if(!talentTabInfo)
20347 continue;
20349 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
20350 continue;
20352 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
20354 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
20355 if(!talentInfo)
20356 continue;
20358 // skip another tab talents
20359 if(talentInfo->TalentTab != talentTabId)
20360 continue;
20362 // find max talent rank
20363 int32 curtalent_maxrank = -1;
20364 for(int32 k = 4; k > -1; --k)
20366 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
20368 curtalent_maxrank = k;
20369 break;
20373 // not learned talent
20374 if(curtalent_maxrank < 0)
20375 continue;
20377 *data << uint32(talentInfo->TalentID); // Talent.dbc
20378 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
20380 ++talentIdCount;
20383 data->put<uint8>(countPos, talentIdCount); // put real count
20385 break;
20389 void Player::SendTalentsInfoData(bool pet)
20391 WorldPacket data(SMSG_TALENTS_INFO, 50);
20392 data << uint8(pet ? 1 : 0);
20393 if(pet)
20394 BuildPetTalentsInfoData(&data);
20395 else
20396 BuildPlayerTalentsInfoData(&data);
20397 GetSession()->SendPacket(&data);
20400 void Player::BuildEnchantmentsInfoData(WorldPacket *data)
20402 uint32 slotUsedMask = 0;
20403 size_t slotUsedMaskPos = data->wpos();
20404 *data << uint32(slotUsedMask); // slotUsedMask < 0x80000
20406 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
20408 Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
20410 if(!item)
20411 continue;
20413 slotUsedMask |= (1 << i);
20415 *data << uint32(item->GetEntry()); // item entry
20417 uint16 enchantmentMask = 0;
20418 size_t enchantmentMaskPos = data->wpos();
20419 *data << uint16(enchantmentMask); // enchantmentMask < 0x1000
20421 for(uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
20423 uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
20425 if(!enchId)
20426 continue;
20428 enchantmentMask |= (1 << j);
20430 *data << uint16(enchId); // enchantmentId?
20433 data->put<uint16>(enchantmentMaskPos, enchantmentMask);
20435 *data << uint16(0); // ?
20436 *data << uint8(0); // PGUID!
20437 *data << uint32(0); // seed?
20440 data->put<uint32>(slotUsedMaskPos, slotUsedMask);
20443 void Player::SendEquipmentSetList()
20445 uint32 count = 0;
20446 WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4);
20447 size_t count_pos = data.wpos();
20448 data << uint32(count); // count placeholder
20449 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20451 if(itr->second.state==EQUIPMENT_SET_DELETED)
20452 continue;
20453 data.appendPackGUID(itr->second.Guid);
20454 data << uint32(itr->first);
20455 data << itr->second.Name;
20456 data << itr->second.IconName;
20457 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
20458 data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM));
20460 ++count; // client have limit but it checked at loading and set
20462 data.put<uint32>(count_pos, count);
20463 GetSession()->SendPacket(&data);
20466 void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
20468 if(eqset.Guid != 0)
20470 bool found = false;
20472 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20474 if((itr->second.Guid == eqset.Guid) && (itr->first == index))
20476 found = true;
20477 break;
20481 if(!found) // something wrong...
20483 sLog.outError("Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
20484 return;
20488 EquipmentSet& eqslot = m_EquipmentSets[index];
20490 EquipmentSetUpdateState old_state = eqslot.state;
20492 eqslot = eqset;
20494 if(eqset.Guid == 0)
20496 eqslot.Guid = objmgr.GenerateEquipmentSetGuid();
20498 WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1);
20499 data << uint32(index);
20500 data.appendPackGUID(eqslot.Guid);
20501 GetSession()->SendPacket(&data);
20504 eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
20507 void Player::_SaveEquipmentSets()
20509 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
20511 uint32 index = itr->first;
20512 EquipmentSet& eqset = itr->second;
20513 switch(eqset.state)
20515 case EQUIPMENT_SET_UNCHANGED:
20516 ++itr;
20517 break; // nothing do
20518 case EQUIPMENT_SET_CHANGED:
20519 CharacterDatabase.PExecute("UPDATE character_equipmentsets SET name='%s', iconname='%s', item0='%u', item1='%u', item2='%u', item3='%u', item4='%u', item5='%u', item6='%u', item7='%u', item8='%u', item9='%u', item10='%u', item11='%u', item12='%u', item13='%u', item14='%u', item15='%u', item16='%u', item17='%u', item18='%u' WHERE guid='%u' AND setguid='"UI64FMTD"' AND setindex='%u'",
20520 eqset.Name.c_str(), eqset.IconName.c_str(), eqset.Items[0], eqset.Items[1], eqset.Items[2], eqset.Items[3], eqset.Items[4], eqset.Items[5], eqset.Items[6], eqset.Items[7],
20521 eqset.Items[8], eqset.Items[9], eqset.Items[10], eqset.Items[11], eqset.Items[12], eqset.Items[13], eqset.Items[14], eqset.Items[15], eqset.Items[16], eqset.Items[17], eqset.Items[18], GetGUIDLow(), eqset.Guid, index);
20522 eqset.state = EQUIPMENT_SET_UNCHANGED;
20523 ++itr;
20524 break;
20525 case EQUIPMENT_SET_NEW:
20526 CharacterDatabase.PExecute("INSERT INTO character_equipmentsets VALUES ('%u', '"UI64FMTD"', '%u', '%s', '%s', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
20527 GetGUIDLow(), eqset.Guid, index, eqset.Name.c_str(), eqset.IconName.c_str(), eqset.Items[0], eqset.Items[1], eqset.Items[2], eqset.Items[3], eqset.Items[4], eqset.Items[5], eqset.Items[6], eqset.Items[7],
20528 eqset.Items[8], eqset.Items[9], eqset.Items[10], eqset.Items[11], eqset.Items[12], eqset.Items[13], eqset.Items[14], eqset.Items[15], eqset.Items[16], eqset.Items[17], eqset.Items[18]);
20529 eqset.state = EQUIPMENT_SET_UNCHANGED;
20530 ++itr;
20531 break;
20532 case EQUIPMENT_SET_DELETED:
20533 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE setguid="UI64FMTD, eqset.Guid);
20534 m_EquipmentSets.erase(itr++);
20535 break;
20540 void Player::_SaveBGData()
20542 CharacterDatabase.PExecute("DELETE FROM character_battleground_data WHERE guid='%u'", GetGUIDLow());
20543 if (m_bgData.bgInstanceID)
20545 /* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
20546 CharacterDatabase.PExecute("INSERT INTO character_battleground_data VALUES ('%u', '%u', '%u', '%f', '%f', '%f', '%f', '%u', '%u', '%u', '%u')",
20547 GetGUIDLow(), m_bgData.bgInstanceID, m_bgData.bgTeam, m_bgData.joinPos.coord_x, m_bgData.joinPos.coord_y, m_bgData.joinPos.coord_z,
20548 m_bgData.joinPos.orientation, m_bgData.joinPos.mapid, m_bgData.taxiPath[0], m_bgData.taxiPath[1], m_bgData.mountSpell);
20552 void Player::DeleteEquipmentSet(uint64 setGuid)
20554 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20556 if(itr->second.Guid == setGuid)
20558 if(itr->second.state == EQUIPMENT_SET_NEW)
20559 m_EquipmentSets.erase(itr);
20560 else
20561 itr->second.state = EQUIPMENT_SET_DELETED;
20562 break;
20567 void Player::ActivateSpec(uint32 specNum)
20569 if(GetActiveSpec() == specNum)
20570 return;
20572 resetTalents(true);
20575 void Player::RemoveAtLoginFlag( AtLoginFlags f, bool in_db_also /*= false*/ )
20577 m_atLoginFlags &= ~f;
20579 if(in_db_also)
20580 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f), GetGUIDLow());
20583 void Player::SendClearCooldown( uint32 spell_id, Unit* target )
20585 WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
20586 data << uint32(spell_id);
20587 data << uint64(target->GetGUID());
20588 SendDirectMessage(&data);
20591 void Player::BuildTeleportAckMsg( WorldPacket *data, float x, float y, float z, float ang ) const
20593 data->Initialize(MSG_MOVE_TELEPORT_ACK, 41);
20594 data->append(GetPackGUID());
20595 *data << uint32(0); // this value increments every time
20596 *data << uint32(m_movementInfo.GetMovementFlags()); // movement flags
20597 *data << uint16(0); // 2.3.0
20598 *data << uint32(getMSTime()); // time
20599 *data << x;
20600 *data << y;
20601 *data << z;
20602 *data << ang;
20603 *data << uint32(0);
20606 bool Player::HasMovementFlag( MovementFlags f ) const
20608 return m_movementInfo.HasMovementFlag(f);
20611 void Player::SetFarSightGUID( uint64 guid )
20613 if(GetFarSight()==guid)
20614 return;
20616 SetUInt64Value(PLAYER_FARSIGHT, guid);
20618 // need triggering load grids around new view point
20619 ObjectAccessor::UpdateVisibilityForPlayer(this);