[7017] Updated copyright notice for new year
[getmangos.git] / src / game / Player.cpp
blobadc55bb7ee9492bfb06d7c3ea485ac2bcd942962
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 "ObjectMgr.h"
25 #include "SpellMgr.h"
26 #include "World.h"
27 #include "WorldPacket.h"
28 #include "WorldSession.h"
29 #include "UpdateMask.h"
30 #include "Player.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 "SpellAuras.h"
51 #include "Util.h"
52 #include "Transports.h"
53 #include "Weather.h"
54 #include "BattleGround.h"
55 #include "BattleGroundMgr.h"
56 #include "ArenaTeam.h"
57 #include "Chat.h"
58 #include "Database/DatabaseImpl.h"
59 #include "Spell.h"
60 #include "SocialMgr.h"
61 #include "AchievementMgr.h"
63 #include <cmath>
65 #define ZONE_UPDATE_INTERVAL 1000
67 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
68 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
69 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
71 #define SKILL_VALUE(x) PAIR32_LOPART(x)
72 #define SKILL_MAX(x) PAIR32_HIPART(x)
73 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
75 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
76 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
77 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
79 enum CharacterFlags
81 CHARACTER_FLAG_NONE = 0x00000000,
82 CHARACTER_FLAG_UNK1 = 0x00000001,
83 CHARACTER_FLAG_UNK2 = 0x00000002,
84 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
85 CHARACTER_FLAG_UNK4 = 0x00000008,
86 CHARACTER_FLAG_UNK5 = 0x00000010,
87 CHARACTER_FLAG_UNK6 = 0x00000020,
88 CHARACTER_FLAG_UNK7 = 0x00000040,
89 CHARACTER_FLAG_UNK8 = 0x00000080,
90 CHARACTER_FLAG_UNK9 = 0x00000100,
91 CHARACTER_FLAG_UNK10 = 0x00000200,
92 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
93 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
94 CHARACTER_FLAG_UNK13 = 0x00001000,
95 CHARACTER_FLAG_GHOST = 0x00002000,
96 CHARACTER_FLAG_RENAME = 0x00004000,
97 CHARACTER_FLAG_UNK16 = 0x00008000,
98 CHARACTER_FLAG_UNK17 = 0x00010000,
99 CHARACTER_FLAG_UNK18 = 0x00020000,
100 CHARACTER_FLAG_UNK19 = 0x00040000,
101 CHARACTER_FLAG_UNK20 = 0x00080000,
102 CHARACTER_FLAG_UNK21 = 0x00100000,
103 CHARACTER_FLAG_UNK22 = 0x00200000,
104 CHARACTER_FLAG_UNK23 = 0x00400000,
105 CHARACTER_FLAG_UNK24 = 0x00800000,
106 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
107 CHARACTER_FLAG_DECLINED = 0x02000000,
108 CHARACTER_FLAG_UNK27 = 0x04000000,
109 CHARACTER_FLAG_UNK28 = 0x08000000,
110 CHARACTER_FLAG_UNK29 = 0x10000000,
111 CHARACTER_FLAG_UNK30 = 0x20000000,
112 CHARACTER_FLAG_UNK31 = 0x40000000,
113 CHARACTER_FLAG_UNK32 = 0x80000000
116 // corpse reclaim times
117 #define DEATH_EXPIRE_STEP (5*MINUTE)
118 #define MAX_DEATH_COUNT 3
120 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
122 //== PlayerTaxi ================================================
124 PlayerTaxi::PlayerTaxi()
126 // Taxi nodes
127 memset(m_taximask, 0, sizeof(m_taximask));
130 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
132 // capital and taxi hub masks
133 switch(race)
135 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
136 case RACE_ORC: SetTaximaskNode(23); break; // Orc
137 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
138 case RACE_NIGHTELF: SetTaximaskNode(26);
139 SetTaximaskNode(27); break; // Night Elf
140 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
141 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
142 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
143 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
144 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
145 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
148 switch(chrClass)
150 case CLASS_DEATH_KNIGHT: // TODO: figure out initial known nodes
151 break;
154 // new continent starting masks (It will be accessible only at new map)
155 switch(Player::TeamForRace(race))
157 case ALLIANCE: SetTaximaskNode(100); break;
158 case HORDE: SetTaximaskNode(99); break;
160 // level dependent taxi hubs
161 if(level>=68)
162 SetTaximaskNode(213); //Shattered Sun Staging Area
165 void PlayerTaxi::LoadTaxiMask(const char* data)
167 Tokens tokens = StrSplit(data, " ");
169 int index;
170 Tokens::iterator iter;
171 for (iter = tokens.begin(), index = 0;
172 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
174 // load and set bits only for existed taxi nodes
175 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
179 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
181 if(all)
183 for (uint8 i=0; i<TaxiMaskSize; i++)
184 data << uint32(sTaxiNodesMask[i]); // all existed nodes
186 else
188 for (uint8 i=0; i<TaxiMaskSize; i++)
189 data << uint32(m_taximask[i]); // known nodes
193 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values )
195 ClearTaxiDestinations();
197 Tokens tokens = StrSplit(values," ");
199 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
201 uint32 node = uint32(atol(iter->c_str()));
202 AddTaxiDestination(node);
205 if(m_TaxiDestinations.empty())
206 return true;
208 // Check integrity
209 if(m_TaxiDestinations.size() < 2)
210 return false;
212 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
214 uint32 cost;
215 uint32 path;
216 objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
217 if(!path)
218 return false;
221 return true;
224 std::string PlayerTaxi::SaveTaxiDestinationsToString()
226 if(m_TaxiDestinations.empty())
227 return "";
229 std::ostringstream ss;
231 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
232 ss << m_TaxiDestinations[i] << " ";
234 return ss.str();
237 uint32 PlayerTaxi::GetCurrentTaxiPath() const
239 if(m_TaxiDestinations.size() < 2)
240 return 0;
242 uint32 path;
243 uint32 cost;
245 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
247 return path;
250 //== Player ====================================================
252 const int32 Player::ReputationRank_Length[MAX_REPUTATION_RANK] = {36000, 3000, 3000, 3000, 6000, 12000, 21000, 1000};
254 UpdateMask Player::updateVisualBits;
256 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this)
258 m_transport = 0;
260 m_speakTime = 0;
261 m_speakCount = 0;
263 m_objectType |= TYPEMASK_PLAYER;
264 m_objectTypeId = TYPEID_PLAYER;
266 m_valuesCount = PLAYER_END;
268 m_session = session;
270 m_divider = 0;
272 m_ExtraFlags = 0;
273 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
274 SetAcceptTicket(true);
276 // players always accept
277 if(GetSession()->GetSecurity() == SEC_PLAYER)
278 SetAcceptWhispers(true);
280 m_curSelection = 0;
281 m_lootGuid = 0;
283 m_comboTarget = 0;
284 m_comboPoints = 0;
286 m_usedTalentCount = 0;
288 m_regenTimer = 0;
289 m_weaponChangeTimer = 0;
291 m_zoneUpdateId = 0;
292 m_zoneUpdateTimer = 0;
294 m_areaUpdateId = 0;
296 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
298 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
299 // this must help in case next save after mass player load after server startup
300 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
302 clearResurrectRequestData();
304 m_SpellModRemoveCount = 0;
306 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
308 m_social = NULL;
310 // group is initialized in the reference constructor
311 SetGroupInvite(NULL);
312 m_groupUpdateMask = 0;
313 m_auraUpdateMask = 0;
315 duel = NULL;
317 m_GuildIdInvited = 0;
318 m_ArenaTeamIdInvited = 0;
320 m_atLoginFlags = AT_LOGIN_NONE;
322 m_dontMove = false;
324 pTrader = 0;
325 ClearTrade();
327 m_cinematic = 0;
329 PlayerTalkClass = new PlayerMenu( GetSession() );
330 m_currentBuybackSlot = BUYBACK_SLOT_START;
332 for ( int aX = 0 ; aX < 8 ; aX++ )
333 m_Tutorials[ aX ] = 0x00;
334 m_TutorialsChanged = false;
336 m_DailyQuestChanged = false;
337 m_lastDailyQuestTime = 0;
339 m_regenTimer = 0;
340 m_weaponChangeTimer = 0;
341 m_breathTimer = 0;
342 m_isunderwater = 0;
343 m_isInWater = false;
344 m_drunkTimer = 0;
345 m_drunk = 0;
346 m_restTime = 0;
347 m_deathTimer = 0;
348 m_deathExpireTime = 0;
350 m_swingErrorMsg = 0;
352 m_DetectInvTimer = 1000;
354 m_bgBattleGroundID = 0;
355 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; j++)
357 m_bgBattleGroundQueueID[j].bgQueueType = 0;
358 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
360 m_bgTeam = 0;
362 m_logintime = time(NULL);
363 m_Last_tick = m_logintime;
364 m_WeaponProficiency = 0;
365 m_ArmorProficiency = 0;
366 m_canParry = false;
367 m_canBlock = false;
368 m_canDualWield = false;
369 m_canTitanGrip = false;
370 m_ammoDPS = 0.0f;
372 m_temporaryUnsummonedPetNumber = 0;
373 //cache for UNIT_CREATED_BY_SPELL to allow
374 //returning reagents for temporarily removed pets
375 //when dying/logging out
376 m_oldpetspell = 0;
378 ////////////////////Rest System/////////////////////
379 time_inn_enter=0;
380 inn_pos_mapid=0;
381 inn_pos_x=0;
382 inn_pos_y=0;
383 inn_pos_z=0;
384 m_rest_bonus=0;
385 rest_type=REST_TYPE_NO;
386 ////////////////////Rest System/////////////////////
388 m_mailsLoaded = false;
389 m_mailsUpdated = false;
390 unReadMails = 0;
391 m_nextMailDelivereTime = 0;
393 m_resetTalentsCost = 0;
394 m_resetTalentsTime = 0;
395 m_itemUpdateQueueBlocked = false;
397 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
398 m_forced_speed_changes[i] = 0;
400 m_stableSlots = 0;
402 /////////////////// Instance System /////////////////////
404 m_HomebindTimer = 0;
405 m_InstanceValid = true;
406 m_dungeonDifficulty = DIFFICULTY_NORMAL;
408 for (int i = 0; i < BASEMOD_END; i++)
410 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
411 m_auraBaseMod[i][PCT_MOD] = 1.0f;
414 for (int i = 0; i < MAX_COMBAT_RATING; i++)
415 m_baseRatingValue[i] = 0;
417 // Honor System
418 m_lastHonorUpdateTime = time(NULL);
420 // Player summoning
421 m_summon_expire = 0;
422 m_summon_mapid = 0;
423 m_summon_x = 0.0f;
424 m_summon_y = 0.0f;
425 m_summon_z = 0.0f;
427 //Default movement to run mode
428 m_unit_movement_flags = 0;
430 m_mover = NULL;
432 m_miniPet = 0;
433 m_bgAfkReportedTimer = 0;
434 m_contestedPvPTimer = 0;
436 m_declinedname = NULL;
437 m_runes = NULL;
440 Player::~Player ()
442 CleanupsBeforeDelete();
444 // it must be unloaded already in PlayerLogout and accessed only for loggined player
445 //m_social = NULL;
447 // Note: buy back item already deleted from DB when player was saved
448 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
450 if(m_items[i])
451 delete m_items[i];
453 CleanupChannels();
455 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
456 delete itr->second;
458 //all mailed items should be deleted, also all mail should be deallocated
459 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
460 delete *itr;
462 for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
463 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
465 delete PlayerTalkClass;
467 if (m_transport)
469 m_transport->RemovePassenger(this);
472 for(size_t x = 0; x < ItemSetEff.size(); x++)
473 if(ItemSetEff[x])
474 delete ItemSetEff[x];
476 // clean up player-instance binds, may unload some instance saves
477 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
478 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
479 itr->second.save->RemovePlayer(this);
481 delete m_declinedname;
482 delete m_runes;
485 void Player::CleanupsBeforeDelete()
487 if(m_uint32Values) // only for fully created Object
489 TradeCancel(false);
490 DuelComplete(DUEL_INTERUPTED);
492 Unit::CleanupsBeforeDelete();
495 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 )
497 //FIXME: outfitId not used in player creating
499 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
501 m_name = name;
503 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
504 if(!info)
506 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
507 return false;
510 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
511 m_items[i] = NULL;
513 m_race = race;
514 m_class = class_;
516 SetMapId(info->mapId);
517 Relocate(info->positionX,info->positionY,info->positionZ);
519 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
520 if(!cEntry)
522 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
523 return false;
526 uint8 powertype = cEntry->powerType;
528 //uint32 unitfield;
530 /*switch(powertype)
532 case POWER_ENERGY:
533 case POWER_MANA:
534 unitfield = 0x00000000;
535 break;
536 case POWER_RAGE:
537 unitfield = 0x00110000;
538 break;
539 case POWER_RUNIC_POWER:
540 unitfield = 0x0000EE00; //TODO: find correct unitfield here
541 break;
542 default:
543 sLog.outError("Invalid default powertype %u for player (class %u)",powertype,class_);
544 return false;
547 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
548 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
550 switch(gender)
552 case GENDER_FEMALE:
553 SetDisplayId(info->displayId_f );
554 SetNativeDisplayId(info->displayId_f );
555 break;
556 case GENDER_MALE:
557 SetDisplayId(info->displayId_m );
558 SetNativeDisplayId(info->displayId_m );
559 break;
560 default:
561 sLog.outError("Invalid gender %u for player",gender);
562 return false;
563 break;
566 setFactionForRace(m_race);
568 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
570 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
571 //SetUInt32Value(UNIT_FIELD_BYTES_1, unitfield);
572 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
573 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
574 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
575 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
576 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
578 // -1 is default value
579 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
581 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
582 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
583 SetByteValue(PLAYER_BYTES_3, 0, gender);
585 SetUInt32Value( PLAYER_GUILDID, 0 );
586 SetUInt32Value( PLAYER_GUILDRANK, 0 );
587 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
589 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
590 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
591 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
592 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
593 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
594 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
595 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
597 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
599 GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i);
600 if(gs && gs->Order)
601 SetGlyphSlot(gs->Order - 1, gs->Id);
604 // set starting level
605 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
606 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
607 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
609 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
611 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
612 if(gm_level > start_level)
613 start_level = gm_level;
616 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
618 InitRunes();
620 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
621 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
622 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
624 // Played time
625 m_Last_tick = time(NULL);
626 m_Played_time[0] = 0;
627 m_Played_time[1] = 0;
629 // base stats and related field values
630 InitStatsForLevel();
631 InitTaxiNodesForLevel();
632 InitGlyphsForLevel();
633 InitTalentForLevel();
634 InitPrimaryProffesions(); // to max set before any spell added
636 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
637 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
638 SetHealth(GetMaxHealth());
639 if (getPowerType()==POWER_MANA)
641 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
642 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
645 if(getPowerType() == POWER_RUNIC_POWER)
647 SetPower(POWER_RUNE, 8);
648 SetMaxPower(POWER_RUNE, 8);
649 SetPower(POWER_RUNIC_POWER, 0);
650 SetMaxPower(POWER_RUNIC_POWER, 1000);
653 // original spells
654 learnDefaultSpells(true);
656 // original action bar
657 std::list<uint16>::const_iterator action_itr[4];
658 for(int i=0; i<4; i++)
659 action_itr[i] = info->action[i].begin();
661 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
663 uint16 taction[4];
664 for(int i=0; i<4 ;i++)
665 taction[i] = (*action_itr[i]);
667 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
669 for(int i=0; i<4 ;i++)
670 ++action_itr[i];
673 // original items
674 CharStartOutfitEntry const* oEntry = NULL;
675 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
677 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
679 if(entry->RaceClassGender == RaceClassGender)
681 oEntry = entry;
682 break;
687 if(oEntry)
689 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
691 if(oEntry->ItemId[j] <= 0)
692 continue;
694 uint32 item_id = oEntry->ItemId[j];
697 // Hack for not existed item id in dbc 3.0.3
698 if(item_id==40582)
699 continue;
701 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
702 if(!iProto)
704 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
705 continue;
708 // max stack by default (mostly 1), 1 for infinity stackable
709 uint32 count = iProto->Stackable > 0 ? uint32(iProto->Stackable) : 1;
711 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
713 switch(iProto->Spells[0].SpellCategory)
715 case 11: // food
716 if(iProto->Stackable > 4)
717 count = 4;
718 break;
719 case 59: // drink
720 if(iProto->Stackable > 2)
721 count = 2;
722 break;
726 StoreNewItemInBestSlots(item_id, count);
730 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
731 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
733 // bags and main-hand weapon must equipped at this moment
734 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
735 // or ammo not equipped in special bag
736 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
738 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
740 uint16 eDest;
741 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
742 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
743 if( msg == EQUIP_ERR_OK )
745 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
746 EquipItem( eDest, pItem, true);
748 // move other items to more appropriate slots (ammo not equipped in special bag)
749 else
751 ItemPosCountVec sDest;
752 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
753 if( msg == EQUIP_ERR_OK )
755 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
756 pItem = StoreItem( sDest, pItem, true);
759 // if this is ammo then use it
760 uint8 msg = CanUseAmmo( pItem->GetProto()->ItemId );
761 if( msg == EQUIP_ERR_OK )
762 SetAmmo( pItem->GetProto()->ItemId );
766 // all item positions resolved
768 return true;
771 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
773 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
775 // attempt equip by one
776 while(titem_amount > 0)
778 uint16 eDest;
779 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
780 if( msg != EQUIP_ERR_OK )
781 break;
783 EquipNewItem( eDest, titem_id, true);
784 AutoUnequipOffhandIfNeed();
785 --titem_amount;
788 if(titem_amount == 0)
789 return true; // equipped
791 // attempt store
792 ItemPosCountVec sDest;
793 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
794 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
795 if( msg == EQUIP_ERR_OK )
797 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
798 return true; // stored
801 // item can't be added
802 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
803 return false;
806 void Player::StartMirrorTimer(MirrorTimerType Type, uint32 MaxValue)
808 uint32 BreathRegen = (uint32)-1;
810 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
811 data << (uint32)Type;
812 data << MaxValue;
813 data << MaxValue;
814 data << BreathRegen;
815 data << (uint8)0;
816 data << (uint32)0; // spell id
817 GetSession()->SendPacket(&data);
820 void Player::ModifyMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, uint32 Regen)
822 if(Type==BREATH_TIMER)
823 m_breathTimer = ((MaxValue + 1000) - CurrentValue) / Regen;
825 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
826 data << (uint32)Type;
827 data << CurrentValue;
828 data << MaxValue;
829 data << Regen;
830 data << (uint8)0;
831 data << (uint32)0; // spell id
832 GetSession()->SendPacket( &data );
835 void Player::StopMirrorTimer(MirrorTimerType Type)
837 if(Type==BREATH_TIMER)
838 m_breathTimer = 0;
840 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
841 data << (uint32)Type;
842 GetSession()->SendPacket( &data );
845 void Player::EnvironmentalDamage(uint64 guid, EnviromentalDamage type, uint32 damage)
847 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
848 data << (uint64)guid;
849 data << (uint8)(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
850 data << (uint32)damage;
851 data << (uint32)0;
852 data << (uint32)0;
853 SendMessageToSet(&data, true);
855 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
857 if(type==DAMAGE_FALL && !isAlive()) // DealDamage not apply item durability loss at self damage
859 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
860 DurabilityLossAll(0.10f,false);
861 // durability lost message
862 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
863 GetSession()->SendPacket(&data);
867 void Player::HandleDrowning()
869 if(!m_isunderwater)
870 return;
872 //if player is GM, have waterbreath, is dead or if breathing is disabled then return
873 if(waterbreath || isGameMaster() || !isAlive() || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
875 StopMirrorTimer(BREATH_TIMER);
876 m_isunderwater = 0;
877 return;
880 uint32 UnderWaterTime = 1*MINUTE*1000; // default length 1 min
882 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
883 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
884 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
886 if ((m_isunderwater & 0x01) && !(m_isunderwater & 0x80) && isAlive())
888 //single trigger timer
889 if (!(m_isunderwater & 0x02))
891 m_isunderwater|= 0x02;
892 m_breathTimer = UnderWaterTime + 1000;
894 //single trigger "Breathbar"
895 if ( m_breathTimer <= UnderWaterTime && !(m_isunderwater & 0x04))
897 m_isunderwater|= 0x04;
898 StartMirrorTimer(BREATH_TIMER, UnderWaterTime);
900 //continuous trigger drowning "Damage"
901 if ((m_breathTimer == 0) && (m_isunderwater & 0x01))
903 //TODO: Check this formula
904 uint64 guid = GetGUID();
905 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
907 EnvironmentalDamage(guid, DAMAGE_DROWNING,damage);
908 m_breathTimer = 2000;
911 //single trigger retract bar
912 else if (!(m_isunderwater & 0x01) && !(m_isunderwater & 0x08) && (m_isunderwater & 0x02) && (m_breathTimer > 0) && isAlive())
914 m_isunderwater = 0x08;
916 uint32 BreathRegen = 10;
917 ModifyMirrorTimer(BREATH_TIMER, UnderWaterTime, m_breathTimer,BreathRegen);
918 m_isunderwater = 0x10;
920 //remove bar
921 else if ((m_breathTimer < 50) && !(m_isunderwater & 0x01) && (m_isunderwater == 0x10))
923 StopMirrorTimer(BREATH_TIMER);
924 m_isunderwater = 0;
928 void Player::HandleLava()
930 if ((m_isunderwater & 0x80) && isAlive())
932 // Single trigger Set BreathTimer
933 if (!(m_isunderwater & 0x80))
935 m_isunderwater|= 0x04;
936 m_breathTimer = 1000;
939 // Reset BreathTimer and still in the lava
940 if (!m_breathTimer)
942 uint64 guid = GetGUID();
943 uint32 damage = urand(600, 700); // TODO: Get more detailed information about lava damage
945 // if not gamemaster then deal damage
946 if ( !isGameMaster() )
947 EnvironmentalDamage(guid, DAMAGE_LAVA, damage);
949 m_breathTimer = 1000;
952 else if (m_deathState == DEAD) // Disable breath timer and reset underwater flags
954 m_breathTimer = 0;
955 m_isunderwater = 0;
959 ///The player sobers by 256 every 10 seconds
960 void Player::HandleSobering()
962 m_drunkTimer = 0;
964 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
965 SetDrunkValue(drunk);
968 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
970 if(value >= 23000)
971 return DRUNKEN_SMASHED;
972 if(value >= 12800)
973 return DRUNKEN_DRUNK;
974 if(value & 0xFFFE)
975 return DRUNKEN_TIPSY;
976 return DRUNKEN_SOBER;
979 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
981 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
983 m_drunk = newDrunkenValue;
984 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
986 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
988 // special drunk invisibility detection
989 if(newDrunkenState >= DRUNKEN_DRUNK)
990 m_detectInvisibilityMask |= (1<<6);
991 else
992 m_detectInvisibilityMask &= ~(1<<6);
994 if(newDrunkenState == oldDrunkenState)
995 return;
997 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
998 data << uint64(GetGUID());
999 data << uint32(newDrunkenState);
1000 data << uint32(itemId);
1002 SendMessageToSet(&data, true);
1005 void Player::Update( uint32 p_time )
1007 if(!IsInWorld())
1008 return;
1010 // undelivered mail
1011 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1013 SendNewMail();
1014 ++unReadMails;
1016 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1017 m_nextMailDelivereTime = 0;
1020 Unit::Update( p_time );
1022 // update player only attacks
1023 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1025 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1028 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1030 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1033 time_t now = time (NULL);
1035 UpdatePvPFlag(now);
1037 UpdateContestedPvP(p_time);
1039 UpdateDuelFlag(now);
1041 CheckDuelDistance(now);
1043 UpdateAfkReport(now);
1045 CheckExploreSystem();
1047 // Update items that have just a limited lifetime
1048 if (now>m_Last_tick)
1049 UpdateItemDuration(uint32(now- m_Last_tick));
1051 if (!m_timedquests.empty())
1053 std::set<uint32>::iterator iter = m_timedquests.begin();
1054 while (iter != m_timedquests.end())
1056 QuestStatusData& q_status = mQuestStatus[*iter];
1057 if( q_status.m_timer <= p_time )
1059 uint32 quest_id = *iter;
1060 ++iter; // current iter will be removed in FailTimedQuest
1061 FailTimedQuest( quest_id );
1063 else
1065 q_status.m_timer -= p_time;
1066 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1067 ++iter;
1072 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1074 Unit *pVictim = getVictim();
1075 if( !IsNonMeleeSpellCasted(false) && pVictim)
1077 // default combat reach 10
1078 // TODO add weapon,skill check
1080 float pldistance = ATTACK_DISTANCE;
1082 if (isAttackReady(BASE_ATTACK))
1084 if(!IsWithinDistInMap(pVictim, pldistance))
1086 setAttackTimer(BASE_ATTACK,100);
1087 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1089 SendAttackSwingNotInRange();
1090 m_swingErrorMsg = 1;
1093 //120 degrees of radiant range
1094 else if( !HasInArc( 2*M_PI/3, pVictim ))
1096 setAttackTimer(BASE_ATTACK,100);
1097 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1099 SendAttackSwingBadFacingAttack();
1100 m_swingErrorMsg = 2;
1103 else
1105 m_swingErrorMsg = 0; // reset swing error state
1107 // prevent base and off attack in same time, delay attack at 0.2 sec
1108 if(haveOffhandWeapon())
1110 uint32 off_att = getAttackTimer(OFF_ATTACK);
1111 if(off_att < ATTACK_DISPLAY_DELAY)
1112 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1114 AttackerStateUpdate(pVictim, BASE_ATTACK);
1115 resetAttackTimer(BASE_ATTACK);
1119 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1121 if(!IsWithinDistInMap(pVictim, pldistance))
1123 setAttackTimer(OFF_ATTACK,100);
1125 else if( !HasInArc( 2*M_PI/3, pVictim ))
1127 setAttackTimer(OFF_ATTACK,100);
1129 else
1131 // prevent base and off attack in same time, delay attack at 0.2 sec
1132 uint32 base_att = getAttackTimer(BASE_ATTACK);
1133 if(base_att < ATTACK_DISPLAY_DELAY)
1134 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1135 // do attack
1136 AttackerStateUpdate(pVictim, OFF_ATTACK);
1137 resetAttackTimer(OFF_ATTACK);
1141 Unit *owner = pVictim->GetOwner();
1142 Unit *u = owner ? owner : pVictim;
1143 if(u->IsPvP() && (!duel || duel->opponent != u))
1145 UpdatePvP(true);
1146 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1151 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1153 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1155 int time_inn = time(NULL)-GetTimeInnEnter();
1156 if (time_inn >= 10) //freeze update
1158 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1159 //speed collect rest bonus (section/in hour)
1160 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1161 UpdateInnerTime(time(NULL));
1166 if(m_regenTimer > 0)
1168 if(p_time >= m_regenTimer)
1169 m_regenTimer = 0;
1170 else
1171 m_regenTimer -= p_time;
1174 if (m_weaponChangeTimer > 0)
1176 if(p_time >= m_weaponChangeTimer)
1177 m_weaponChangeTimer = 0;
1178 else
1179 m_weaponChangeTimer -= p_time;
1182 if (m_zoneUpdateTimer > 0)
1184 if(p_time >= m_zoneUpdateTimer)
1186 uint32 newzone = GetZoneId();
1187 if( m_zoneUpdateId != newzone )
1188 UpdateZone(newzone); // also update area
1189 else
1191 // use area updates as well
1192 // needed for free far all arenas for example
1193 uint32 newarea = GetAreaId();
1194 if( m_areaUpdateId != newarea )
1195 UpdateArea(newarea);
1197 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1200 else
1201 m_zoneUpdateTimer -= p_time;
1204 if (isAlive())
1206 RegenerateAll();
1209 if (m_deathState == JUST_DIED)
1211 KillPlayer();
1214 if(m_nextSave > 0)
1216 if(p_time >= m_nextSave)
1218 // m_nextSave reseted in SaveToDB call
1219 SaveToDB();
1220 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1222 else
1224 m_nextSave -= p_time;
1228 //Breathtimer
1229 if(m_breathTimer > 0)
1231 if(p_time >= m_breathTimer)
1232 m_breathTimer = 0;
1233 else
1234 m_breathTimer -= p_time;
1238 //Handle Water/drowning
1239 HandleDrowning();
1241 //Handle lava
1242 HandleLava();
1244 //Handle detect stealth players
1245 if (m_DetectInvTimer > 0)
1247 if (p_time >= m_DetectInvTimer)
1249 m_DetectInvTimer = 3000;
1250 HandleStealthedUnitsDetection();
1252 else
1253 m_DetectInvTimer -= p_time;
1256 // Played time
1257 if (now > m_Last_tick)
1259 uint32 elapsed = uint32(now - m_Last_tick);
1260 m_Played_time[0] += elapsed; // Total played time
1261 m_Played_time[1] += elapsed; // Level played time
1262 m_Last_tick = now;
1265 if (m_drunk)
1267 m_drunkTimer += p_time;
1269 if (m_drunkTimer > 10000)
1270 HandleSobering();
1273 // not auto-free ghost from body in instances
1274 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1276 if(p_time >= m_deathTimer)
1278 m_deathTimer = 0;
1279 BuildPlayerRepop();
1280 RepopAtGraveyard();
1282 else
1283 m_deathTimer -= p_time;
1286 UpdateEnchantTime(p_time);
1287 UpdateHomebindTime(p_time);
1289 // group update
1290 SendUpdateToOutOfRangeGroupMembers();
1292 Pet* pet = GetPet();
1293 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1295 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1296 return;
1300 void Player::setDeathState(DeathState s)
1302 uint32 ressSpellId = 0;
1304 bool cur = isAlive();
1306 if(s == JUST_DIED && cur)
1308 // drunken state is cleared on death
1309 SetDrunkValue(0);
1310 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1311 ClearComboPoints();
1313 clearResurrectRequestData();
1315 // remove form before other mods to prevent incorrect stats calculation
1316 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1318 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1319 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1321 // remove uncontrolled pets
1322 RemoveMiniPet();
1323 RemoveGuardians();
1325 // save value before aura remove in Unit::setDeathState
1326 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1328 // passive spell
1329 if(!ressSpellId)
1330 ressSpellId = GetResurrectionSpellId();
1331 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1333 Unit::setDeathState(s);
1335 // restore resurrection spell id for player after aura remove
1336 if(s == JUST_DIED && cur && ressSpellId)
1337 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1339 if(isAlive() && !cur)
1341 //clear aura case after resurrection by another way (spells will be applied before next death)
1342 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1344 // restore default warrior stance
1345 if(getClass()== CLASS_WARRIOR)
1346 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1350 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1352 Field *fields = result->Fetch();
1354 *p_data << uint64(GetGUID());
1355 *p_data << m_name;
1357 *p_data << uint8(getRace());
1358 uint8 pClass = getClass();
1359 *p_data << uint8(pClass);
1360 *p_data << uint8(getGender());
1362 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1363 *p_data << uint8(bytes);
1364 *p_data << uint8(bytes >> 8);
1365 *p_data << uint8(bytes >> 16);
1366 *p_data << uint8(bytes >> 24);
1368 bytes = GetUInt32Value(PLAYER_BYTES_2);
1369 *p_data << uint8(bytes);
1371 *p_data << uint8(getLevel()); // player level
1372 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1373 uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY(),GetPositionZ());
1374 sLog.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId);
1375 *p_data << uint32(zoneId);
1376 *p_data << uint32(GetMapId());
1378 *p_data << GetPositionX();
1379 *p_data << GetPositionY();
1380 *p_data << GetPositionZ();
1382 // guild id
1383 *p_data << (result ? fields[13].GetUInt32() : 0);
1385 uint32 char_flags = 0;
1386 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1387 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1388 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1389 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1390 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1391 char_flags |= CHARACTER_FLAG_GHOST;
1392 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1393 char_flags |= CHARACTER_FLAG_RENAME;
1394 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) && (fields[14].GetCppString() != ""))
1395 char_flags |= CHARACTER_FLAG_DECLINED;
1397 *p_data << uint32(char_flags); // character flags
1398 // character customize (flags?)
1399 *p_data << uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE) ? 1 : 0);
1400 *p_data << uint8(1); // unknown
1402 // Pets info
1404 uint32 petDisplayId = 0;
1405 uint32 petLevel = 0;
1406 uint32 petFamily = 0;
1408 // show pet at selection character in character list only for non-ghost character
1409 if(result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER))
1411 uint32 entry = fields[10].GetUInt32();
1412 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1413 if(cInfo)
1415 petDisplayId = fields[11].GetUInt32();
1416 petLevel = fields[12].GetUInt32();
1417 petFamily = cInfo->family;
1421 *p_data << uint32(petDisplayId);
1422 *p_data << uint32(petLevel);
1423 *p_data << uint32(petFamily);
1426 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1428 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
1429 uint32 item_id = GetUInt32Value(visualbase);
1430 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1431 SpellItemEnchantmentEntry const *enchant = NULL;
1433 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot<=TEMP_ENCHANTMENT_SLOT; enchantSlot++)
1435 uint32 enchantId = GetUInt32Value(visualbase+1+enchantSlot);
1436 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1437 break;
1440 if (proto != NULL)
1442 *p_data << uint32(proto->DisplayInfoID);
1443 *p_data << uint8(proto->InventoryType);
1444 *p_data << uint32(enchant ? enchant->aura_id : 0);
1446 else
1448 *p_data << uint32(0);
1449 *p_data << uint8(0);
1450 *p_data << uint32(0); // enchant?
1453 *p_data << uint32(0); // first bag display id
1454 *p_data << uint8(0); // first bag inventory type
1455 *p_data << uint32(0); // enchant?
1458 bool Player::ToggleAFK()
1460 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1462 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1464 // afk player not allowed in battleground
1465 if(state && InBattleGround())
1466 LeaveBattleground();
1468 return state;
1471 bool Player::ToggleDND()
1473 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1475 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1478 uint8 Player::chatTag() const
1480 // it's bitmask
1481 // 0x8 - ??
1482 // 0x4 - gm
1483 // 0x2 - dnd
1484 // 0x1 - afk
1485 if(isGMChat())
1486 return 4;
1487 else if(isDND())
1488 return 3;
1489 if(isAFK())
1490 return 1;
1491 else
1492 return 0;
1495 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1497 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1499 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1500 return false;
1503 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1504 Pet* pet = GetPet();
1506 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1508 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1509 // don't let gm level > 1 either
1510 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1511 return false;
1513 // client without expansion support
1514 if(GetSession()->Expansion() < mEntry->Expansion())
1516 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1518 if(GetTransport())
1519 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1521 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1523 return false; // normal client can't teleport to this map...
1525 else
1527 sLog.outDebug("Player %s will teleported to map %u", GetName(), mapid);
1530 // if we were on a transport, leave
1531 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1533 m_transport->RemovePassenger(this);
1534 m_transport = NULL;
1535 m_movementInfo.t_x = 0.0f;
1536 m_movementInfo.t_y = 0.0f;
1537 m_movementInfo.t_z = 0.0f;
1538 m_movementInfo.t_o = 0.0f;
1539 m_movementInfo.t_time = 0;
1542 SetSemaphoreTeleport(true);
1544 // The player was ported to another map and looses the duel immediately.
1545 // We have to perform this check before the teleport, otherwise the
1546 // ObjectAccessor won't find the flag.
1547 if (duel && GetMapId()!=mapid)
1549 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
1550 if (obj)
1551 DuelComplete(DUEL_FLED);
1554 // reset movement flags at teleport, because player will continue move with these flags after teleport
1555 SetUnitMovementFlags(0);
1557 if ((GetMapId() == mapid) && (!m_transport))
1559 // prepare zone change detect
1560 uint32 old_zone = GetZoneId();
1562 // near teleport
1563 if(!GetSession()->PlayerLogout())
1565 WorldPacket data;
1566 BuildTeleportAckMsg(&data, x, y, z, orientation);
1567 GetSession()->SendPacket(&data);
1568 SetPosition( x, y, z, orientation, true);
1570 else
1571 // this will be used instead of the current location in SaveToDB
1572 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1573 SetFallInformation(0, z);
1575 //BuildHeartBeatMsg(&data);
1576 //SendMessageToSet(&data, true);
1577 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1579 //same map, only remove pet if out of range
1580 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1582 if(pet->isControlled() && !pet->isTemporarySummoned() )
1583 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1584 else
1585 m_temporaryUnsummonedPetNumber = 0;
1587 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1591 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1592 CombatStop();
1594 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1596 // resummon pet
1597 if(pet && m_temporaryUnsummonedPetNumber)
1599 Pet* NewPet = new Pet;
1600 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
1601 delete NewPet;
1603 m_temporaryUnsummonedPetNumber = 0;
1607 if(!GetSession()->PlayerLogout())
1609 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1610 SetSemaphoreTeleport(false);
1612 UpdateZone(GetZoneId());
1615 // new zone
1616 if(old_zone != GetZoneId())
1618 // honorless target
1619 if(pvpInfo.inHostileArea)
1620 CastSpell(this, 2479, true);
1623 else
1625 // far teleport to another map
1626 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1627 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1629 // Check enter rights before map getting to avoid creating instance copy for player
1630 // this check not dependent from map instance copy and same for all instance copies of selected map
1631 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1633 SetSemaphoreTeleport(false);
1634 return false;
1637 // If the map is not created, assume it is possible to enter it.
1638 // It will be created in the WorldPortAck.
1639 Map *map = MapManager::Instance().FindMap(mapid);
1640 if (!map || map->CanEnter(this))
1642 SetSelection(0);
1644 CombatStop();
1646 ResetContestedPvP();
1648 // remove player from battleground on far teleport (when changing maps)
1649 if(BattleGround const* bg = GetBattleGround())
1651 // Note: at battleground join battleground id set before teleport
1652 // and we already will found "current" battleground
1653 // just need check that this is targeted map or leave
1654 if(bg->GetMapId() != mapid)
1655 LeaveBattleground(false); // don't teleport to entry point
1658 // remove pet on map change
1659 if (pet)
1661 //leaving map -> delete pet right away (doing this later will cause problems)
1662 if(pet->isControlled() && !pet->isTemporarySummoned())
1663 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1664 else
1665 m_temporaryUnsummonedPetNumber = 0;
1667 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1670 // remove all dyn objects
1671 RemoveAllDynObjects();
1673 // stop spellcasting
1674 // not attempt interrupt teleportation spell at caster teleport
1675 if(!(options & TELE_TO_SPELL))
1676 if(IsNonMeleeSpellCasted(true))
1677 InterruptNonMeleeSpells(true);
1679 if(!GetSession()->PlayerLogout())
1681 // send transfer packets
1682 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1683 data << uint32(mapid);
1684 if (m_transport)
1686 data << m_transport->GetEntry() << GetMapId();
1688 GetSession()->SendPacket(&data);
1690 data.Initialize(SMSG_NEW_WORLD, (20));
1691 if (m_transport)
1693 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1695 else
1697 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1699 GetSession()->SendPacket( &data );
1700 SendSavedInstances();
1702 // remove from old map now
1703 if(oldmap) oldmap->Remove(this, false);
1706 // new final coordinates
1707 float final_x = x;
1708 float final_y = y;
1709 float final_z = z;
1710 float final_o = orientation;
1712 if(m_transport)
1714 final_x += m_movementInfo.t_x;
1715 final_y += m_movementInfo.t_y;
1716 final_z += m_movementInfo.t_z;
1717 final_o += m_movementInfo.t_o;
1720 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1721 SetFallInformation(0, final_z);
1722 // if the player is saved before worldportack (at logout for example)
1723 // this will be used instead of the current location in SaveToDB
1725 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
1727 // move packet sent by client always after far teleport
1728 // SetPosition(final_x, final_y, final_z, final_o, true);
1729 SetDontMove(true);
1731 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1733 else
1734 return false;
1736 return true;
1739 void Player::AddToWorld()
1741 ///- Do not add/remove the player from the object storage
1742 ///- It will crash when updating the ObjectAccessor
1743 ///- The player should only be added when logging in
1744 Unit::AddToWorld();
1746 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1748 if(m_items[i])
1749 m_items[i]->AddToWorld();
1753 void Player::RemoveFromWorld()
1755 // cleanup
1756 if(IsInWorld())
1758 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1759 Uncharm();
1760 UnsummonAllTotems();
1761 RemoveMiniPet();
1762 RemoveGuardians();
1765 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1767 if(m_items[i])
1768 m_items[i]->RemoveFromWorld();
1771 ///- Do not add/remove the player from the object storage
1772 ///- It will crash when updating the ObjectAccessor
1773 ///- The player should only be removed when logging out
1774 Unit::RemoveFromWorld();
1777 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1779 float addRage;
1781 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1783 if(attacker)
1785 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1787 // talent who gave more rage on attack
1788 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1790 else
1792 addRage = damage/rageconversion*2.5;
1794 // Berserker Rage effect
1795 if(HasAura(18499,0))
1796 addRage *= 1.3;
1799 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1801 ModifyPower(POWER_RAGE, uint32(addRage*10));
1804 void Player::RegenerateAll()
1806 if (m_regenTimer != 0)
1807 return;
1808 uint32 regenDelay = 2000;
1810 // Not in combat or they have regeneration
1811 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1812 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1814 RegenerateHealth();
1815 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1817 Regenerate(POWER_RAGE);
1818 if(getClass() == CLASS_DEATH_KNIGHT)
1819 Regenerate(POWER_RUNIC_POWER);
1823 Regenerate( POWER_ENERGY );
1825 Regenerate( POWER_MANA );
1827 if(getClass() == CLASS_DEATH_KNIGHT)
1828 Regenerate( POWER_RUNE );
1830 m_regenTimer = regenDelay;
1833 void Player::Regenerate(Powers power)
1835 uint32 curValue = GetPower(power);
1836 uint32 maxValue = GetMaxPower(power);
1838 float addvalue = 0.0f;
1840 switch (power)
1842 case POWER_MANA:
1844 bool recentCast = IsUnderLastManaUseEffect();
1845 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1846 if (recentCast)
1848 // Mangos Updates Mana in intervals of 2s, which is correct
1849 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1851 else
1853 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1855 } break;
1856 case POWER_RAGE: // Regenerate rage
1858 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1859 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1860 } break;
1861 case POWER_ENERGY: // Regenerate energy (rogue)
1862 addvalue = 20;
1863 break;
1864 case POWER_RUNIC_POWER:
1866 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1867 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1868 } break;
1869 case POWER_RUNE:
1871 for(uint32 i = 0; i < MAX_RUNES; ++i)
1872 if(uint8 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1873 SetRuneCooldown(i, cd - 1); // ... by 2 sec (because update is every 2 sec)
1874 } break;
1875 case POWER_FOCUS:
1876 case POWER_HAPPINESS:
1877 break;
1880 // Mana regen calculated in Player::UpdateManaRegen()
1881 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1882 if(power != POWER_MANA)
1884 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1885 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1886 if ((*i)->GetModifier()->m_miscvalue == power)
1887 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1890 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
1892 curValue += uint32(addvalue);
1893 if (curValue > maxValue)
1894 curValue = maxValue;
1896 else
1898 if(curValue <= uint32(addvalue))
1899 curValue = 0;
1900 else
1901 curValue -= uint32(addvalue);
1903 SetPower(power, curValue);
1906 void Player::RegenerateHealth()
1908 uint32 curValue = GetHealth();
1909 uint32 maxValue = GetMaxHealth();
1911 if (curValue >= maxValue) return;
1913 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1915 float addvalue = 0.0f;
1917 // polymorphed case
1918 if ( IsPolymorphed() )
1919 addvalue = GetMaxHealth()/3;
1920 // normal regen case (maybe partly in combat case)
1921 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1923 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1924 if (!isInCombat())
1926 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1927 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1928 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1930 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1931 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1933 if(!IsStandState())
1934 addvalue *= 1.5;
1937 // always regeneration bonus (including combat)
1938 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1940 if(addvalue < 0)
1941 addvalue = 0;
1943 ModifyHealth(int32(addvalue));
1946 bool Player::CanInteractWithNPCs(bool alive) const
1948 if(alive && !isAlive())
1949 return false;
1950 if(isInFlight())
1951 return false;
1953 return true;
1956 bool Player::IsUnderWater() const
1958 return IsInWater() &&
1959 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1962 void Player::SetInWater(bool apply)
1964 if(m_isInWater==apply)
1965 return;
1967 //define player in water by opcodes
1968 //move player's guid into HateOfflineList of those mobs
1969 //which can't swim and move guid back into ThreatList when
1970 //on surface.
1971 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1972 m_isInWater = apply;
1974 // remove auras that need water/land
1975 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
1977 getHostilRefManager().updateThreatTables();
1980 void Player::SetGameMaster(bool on)
1982 if(on)
1984 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
1985 setFaction(35);
1986 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1988 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
1989 ResetContestedPvP();
1991 getHostilRefManager().setOnlineOfflineState(false);
1992 CombatStop();
1994 else
1996 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
1997 setFactionForRace(getRace());
1998 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2000 // restore FFA PvP Server state
2001 if(sWorld.IsFFAPvPRealm())
2002 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2004 // restore FFA PvP area state, remove not allowed for GM mounts
2005 UpdateArea(m_areaUpdateId);
2007 getHostilRefManager().setOnlineOfflineState(true);
2010 ObjectAccessor::UpdateVisibilityForPlayer(this);
2013 void Player::SetGMVisible(bool on)
2015 if(on)
2017 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2019 // Reapply stealth/invisibility if active or show if not any
2020 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2021 SetVisibility(VISIBILITY_GROUP_STEALTH);
2022 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2023 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2024 else
2025 SetVisibility(VISIBILITY_ON);
2027 else
2029 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2031 SetAcceptWhispers(false);
2032 SetGameMaster(true);
2034 SetVisibility(VISIBILITY_OFF);
2038 bool Player::IsGroupVisibleFor(Player* p) const
2040 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2042 default: return IsInSameGroupWith(p);
2043 case 1: return IsInSameRaidWith(p);
2044 case 2: return GetTeam()==p->GetTeam();
2048 bool Player::IsInSameGroupWith(Player const* p) const
2050 return p==this || GetGroup() != NULL &&
2051 GetGroup() == p->GetGroup() &&
2052 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2055 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2056 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2057 void Player::UninviteFromGroup()
2059 Group* group = GetGroupInvite();
2060 if(!group)
2061 return;
2063 group->RemoveInvite(this);
2065 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2067 if(group->IsCreated())
2069 group->Disband(true);
2070 objmgr.RemoveGroup(group);
2072 else
2073 group->RemoveAllInvites();
2075 delete group;
2079 void Player::RemoveFromGroup(Group* group, uint64 guid)
2081 if(group)
2083 if (group->RemoveMember(guid, 0) <= 1)
2085 // group->Disband(); already disbanded in RemoveMember
2086 objmgr.RemoveGroup(group);
2087 delete group;
2088 // removemember sets the player's group pointer to NULL
2093 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2095 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2096 data << uint64(victim ? victim->GetGUID() : 0); // guid
2097 data << uint32(GivenXP+RestXP); // given experience
2098 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2099 if(victim)
2101 data << uint32(GivenXP); // experience without rested bonus
2102 data << float(1); // 1 - none 0 - 100% group bonus output
2104 data << uint8(0); // new 2.4.0
2105 GetSession()->SendPacket(&data);
2108 void Player::GiveXP(uint32 xp, Unit* victim)
2110 if ( xp < 1 )
2111 return;
2113 if(!isAlive())
2114 return;
2116 uint32 level = getLevel();
2118 // XP to money conversion processed in Player::RewardQuest
2119 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2120 return;
2122 // handle SPELL_AURA_MOD_XP_PCT auras
2123 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2124 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2125 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2127 // XP resting bonus for kill
2128 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2130 SendLogXPGain(xp,victim,rested_bonus_xp);
2132 uint32 curXP = GetUInt32Value(PLAYER_XP);
2133 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2134 uint32 newXP = curXP + xp + rested_bonus_xp;
2136 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2138 newXP -= nextLvlXP;
2140 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2141 GiveLevel(level + 1);
2143 level = getLevel();
2144 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2147 SetUInt32Value(PLAYER_XP, newXP);
2150 // Update player to next level
2151 // Current player experience not update (must be update by caller)
2152 void Player::GiveLevel(uint32 level)
2154 if ( level == getLevel() )
2155 return;
2157 PlayerLevelInfo info;
2158 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2160 PlayerClassLevelInfo classInfo;
2161 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2163 // send levelup info to client
2164 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2165 data << uint32(level);
2166 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2167 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2168 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2169 data << uint32(0);
2170 data << uint32(0);
2171 data << uint32(0);
2172 data << uint32(0);
2173 data << uint32(0);
2174 data << uint32(0);
2175 // end for
2176 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2177 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2179 GetSession()->SendPacket(&data);
2181 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(level));
2183 //update level, max level of skills
2184 if(getLevel()!= level)
2185 m_Played_time[1] = 0; // Level Played Time reset
2186 SetLevel(level);
2187 UpdateSkillsForLevel ();
2189 // save base values (bonuses already included in stored stats
2190 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2191 SetCreateStat(Stats(i), info.stats[i]);
2193 SetCreateHealth(classInfo.basehealth);
2194 SetCreateMana(classInfo.basemana);
2196 InitTalentForLevel();
2197 InitTaxiNodesForLevel();
2198 InitGlyphsForLevel();
2200 UpdateAllStats();
2202 // set current level health and mana/energy to maximum after applying all mods.
2203 SetHealth(GetMaxHealth());
2204 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2205 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2206 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2207 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2208 SetPower(POWER_FOCUS, 0);
2209 SetPower(POWER_HAPPINESS, 0);
2211 // give level to summoned pet
2212 Pet* pet = GetPet();
2213 if(pet && pet->getPetType()==SUMMON_PET)
2214 pet->GivePetLevel(level);
2215 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2218 void Player::InitTalentForLevel()
2220 uint32 level = getLevel();
2221 // talents base at level diff ( talents = level - 9 but some can be used already)
2222 if(level < 10)
2224 // Remove all talent points
2225 if(m_usedTalentCount > 0) // Free any used talents
2227 resetTalents(true);
2228 SetFreeTalentPoints(0);
2231 else
2233 uint32 talentPointsForLevel = uint32((level-9)*sWorld.getRate(RATE_TALENT));
2234 // if used more that have then reset
2235 if(m_usedTalentCount > talentPointsForLevel)
2237 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2238 resetTalents(true);
2239 else
2240 SetFreeTalentPoints(0);
2242 // else update amount of free points
2243 else
2244 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2248 void Player::InitStatsForLevel(bool reapplyMods)
2250 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2251 _RemoveAllStatBonuses();
2253 PlayerClassLevelInfo classInfo;
2254 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2256 PlayerLevelInfo info;
2257 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2259 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2260 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(getLevel()));
2262 UpdateSkillsForLevel ();
2264 // set default cast time multiplier
2265 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2267 // reset size before reapply auras
2268 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2270 // save base values (bonuses already included in stored stats
2271 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2272 SetCreateStat(Stats(i), info.stats[i]);
2274 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2275 SetStat(Stats(i), info.stats[i]);
2277 SetCreateHealth(classInfo.basehealth);
2279 //set create powers
2280 SetCreateMana(classInfo.basemana);
2282 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2284 InitStatBuffMods();
2286 //reset rating fields values
2287 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2288 SetUInt32Value(index, 0);
2290 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2291 for (int i = 0; i < 7; i++)
2293 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2294 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2295 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2298 //reset attack power, damage and attack speed fields
2299 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2300 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2301 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2303 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2304 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2305 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2306 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2307 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2308 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2310 SetUInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2311 SetUInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2312 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2313 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2314 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2315 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2317 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2318 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2319 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2320 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2322 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2323 for (uint8 i = 0; i < 7; ++i)
2324 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2326 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2327 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2328 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2330 // Dodge percentage
2331 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2333 // set armor (resistance 0) to original value (create_agility*2)
2334 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2335 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2336 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2337 // set other resistance to original value (0)
2338 for (int i = 1; i < MAX_SPELL_SCHOOL; i++)
2340 SetResistance(SpellSchools(i), 0);
2341 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2342 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2345 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2346 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2347 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2349 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER+i,0.0f);
2350 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2352 // Reset no reagent cost field
2353 for(int i = 0; i < 3; i++)
2354 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2355 // Init data for form but skip reapply item mods for form
2356 InitDataForForm(reapplyMods);
2358 // save new stats
2359 for (int i = POWER_MANA; i < MAX_POWERS; i++)
2360 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2362 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2364 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2365 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2367 // cleanup unit flags (will be re-applied if need at aura load).
2368 RemoveFlag( UNIT_FIELD_FLAGS,
2369 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2370 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2371 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2372 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2373 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2374 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2376 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2377 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2379 SetByteValue(UNIT_FIELD_BYTES_1, 2, 0x00); // one form stealth modified bytes
2380 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2382 // restore if need some important flags
2383 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2385 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2386 _ApplyAllStatBonuses();
2388 // set current level health and mana/energy to maximum after applying all mods.
2389 SetHealth(GetMaxHealth());
2390 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2391 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2392 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2393 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2394 SetPower(POWER_FOCUS, 0);
2395 SetPower(POWER_HAPPINESS, 0);
2396 SetPower(POWER_RUNIC_POWER, 0);
2399 void Player::SendInitialSpells()
2401 uint16 spellCount = 0;
2403 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2404 data << uint8(0);
2406 size_t countPos = data.wpos();
2407 data << uint16(spellCount); // spell count placeholder
2409 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2411 if(itr->second->state == PLAYERSPELL_REMOVED)
2412 continue;
2414 if(!itr->second->active || itr->second->disabled)
2415 continue;
2417 data << uint16(itr->first);
2418 data << uint16(0); // it's not slot id
2420 spellCount +=1;
2423 data.put<uint16>(countPos,spellCount); // write real count value
2425 uint16 spellCooldowns = m_spellCooldowns.size();
2426 data << uint16(spellCooldowns);
2427 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2429 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2430 if(!sEntry)
2431 continue;
2433 data << uint16(itr->first);
2435 time_t cooldown = 0;
2436 time_t curTime = time(NULL);
2437 if(itr->second.end > curTime)
2438 cooldown = (itr->second.end-curTime)*1000;
2440 data << uint16(itr->second.itemid); // cast item id
2441 data << uint16(sEntry->Category); // spell category
2442 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2444 data << uint32(0); // cooldown
2445 data << uint32(cooldown); // category cooldown
2447 else
2449 data << uint32(cooldown); // cooldown
2450 data << uint32(0); // category cooldown
2454 GetSession()->SendPacket(&data);
2456 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2459 void Player::RemoveMail(uint32 id)
2461 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2463 if ((*itr)->messageID == id)
2465 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2466 m_mail.erase(itr);
2467 return;
2472 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2474 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2475 data << (uint32) mailId;
2476 data << (uint32) mailAction;
2477 data << (uint32) mailError;
2478 if ( mailError == MAIL_ERR_BAG_FULL )
2479 data << (uint32) equipError;
2480 else if( mailAction == MAIL_ITEM_TAKEN )
2482 data << (uint32) item_guid; // item guid low?
2483 data << (uint32) item_count; // item count?
2485 GetSession()->SendPacket(&data);
2488 void Player::SendNewMail()
2490 // deliver undelivered mail
2491 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2492 data << (uint32) 0;
2493 GetSession()->SendPacket(&data);
2496 void Player::UpdateNextMailTimeAndUnreads()
2498 // calculate next delivery time (min. from non-delivered mails
2499 // and recalculate unReadMail
2500 time_t cTime = time(NULL);
2501 m_nextMailDelivereTime = 0;
2502 unReadMails = 0;
2503 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2505 if((*itr)->deliver_time > cTime)
2507 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2508 m_nextMailDelivereTime = (*itr)->deliver_time;
2510 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2511 ++unReadMails;
2515 void Player::AddNewMailDeliverTime(time_t deliver_time)
2517 if(deliver_time <= time(NULL)) // ready now
2519 ++unReadMails;
2520 SendNewMail();
2522 else // not ready and no have ready mails
2524 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2525 m_nextMailDelivereTime = deliver_time;
2529 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool loading, uint16 slot_id, bool disabled)
2531 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2532 if (!spellInfo)
2534 // do character spell book cleanup (all characters)
2535 if(loading && !learning) // spell load case
2537 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2538 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2540 else
2541 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2543 return false;
2546 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2548 // do character spell book cleanup (all characters)
2549 if(loading && !learning) // spell load case
2551 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2552 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2554 else
2555 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2557 return false;
2560 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2562 bool disabled_case = false;
2563 bool superceded_old = false;
2565 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2566 if (itr != m_spells.end())
2568 // update active state for known spell
2569 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2571 itr->second->active = active;
2573 // loading && !learning == explicitly load from DB and then exist in it already and set correctly
2574 if(loading && !learning)
2575 itr->second->state = PLAYERSPELL_UNCHANGED;
2576 else if(itr->second->state != PLAYERSPELL_NEW)
2577 itr->second->state = PLAYERSPELL_CHANGED;
2579 if(!active)
2581 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2582 data << uint16(spell_id);
2583 GetSession()->SendPacket(&data);
2585 return active; // learn (show in spell book if active now)
2588 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2590 if(itr->second->state != PLAYERSPELL_NEW)
2591 itr->second->state = PLAYERSPELL_CHANGED;
2592 itr->second->disabled = disabled;
2594 if(disabled)
2595 return false;
2597 disabled_case = true;
2599 else switch(itr->second->state)
2601 case PLAYERSPELL_UNCHANGED: // known saved spell
2602 return false;
2603 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2605 delete itr->second;
2606 m_spells.erase(itr);
2607 state = PLAYERSPELL_CHANGED;
2608 break; // need re-add
2610 default: // known not saved yet spell (new or modified)
2612 // can be in case spell loading but learned at some previous spell loading
2613 if(loading && !learning)
2614 itr->second->state = PLAYERSPELL_UNCHANGED;
2616 return false;
2621 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2623 // talent: unlearn all other talent ranks (high and low)
2624 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2626 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2628 for(int i=0; i <5; ++i)
2630 // skip learning spell and no rank spell case
2631 uint32 rankSpellId = talentInfo->RankID[i];
2632 if(!rankSpellId || rankSpellId==spell_id)
2633 continue;
2635 // skip unknown ranks
2636 if(!HasSpell(rankSpellId))
2637 continue;
2639 removeSpell(rankSpellId);
2643 // non talent spell: learn low ranks (recursive call)
2644 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2646 if(loading) // at spells loading, no output, but allow save
2647 addSpell(prev_spell,active,true,loading,SPELL_WITHOUT_SLOT_ID,disabled);
2648 else // at normal learning
2649 learnSpell(prev_spell);
2652 PlayerSpell *newspell = new PlayerSpell;
2653 newspell->active = active;
2654 newspell->state = state;
2655 newspell->disabled = disabled;
2657 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2658 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2660 for( PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr )
2662 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
2663 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr->first);
2664 if(!i_spellInfo) continue;
2666 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr->first) )
2668 if(itr->second->active)
2670 if(spellmgr.IsHighRankOfSpell(spell_id,itr->first))
2672 if(!loading) // not send spell (re-/over-)learn packets at loading
2674 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2675 data << uint16(itr->first);
2676 data << uint16(spell_id);
2677 GetSession()->SendPacket( &data );
2680 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2681 itr->second->active = false;
2682 itr->second->state = PLAYERSPELL_CHANGED;
2683 superceded_old = true; // new spell replace old in action bars and spell book.
2685 else if(spellmgr.IsHighRankOfSpell(itr->first,spell_id))
2687 if(!loading) // not send spell (re-/over-)learn packets at loading
2689 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2690 data << uint16(spell_id);
2691 data << uint16(itr->first);
2692 GetSession()->SendPacket( &data );
2695 // mark new spell as disable (not learned yet for client and will not learned)
2696 newspell->active = false;
2697 if(newspell->state != PLAYERSPELL_NEW)
2698 newspell->state = PLAYERSPELL_CHANGED;
2705 uint16 tmpslot=slot_id;
2707 if (tmpslot == SPELL_WITHOUT_SLOT_ID)
2709 uint16 maxid = 0;
2710 PlayerSpellMap::iterator itr;
2711 for (itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2713 if(itr->second->state == PLAYERSPELL_REMOVED)
2714 continue;
2715 if (itr->second->slotId > maxid)
2716 maxid = itr->second->slotId;
2718 tmpslot = maxid + 1;
2721 newspell->slotId = tmpslot;
2722 m_spells[spell_id] = newspell;
2724 // return false if spell disabled
2725 if (newspell->disabled)
2726 return false;
2729 uint32 talentCost = GetTalentSpellCost(spell_id);
2731 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2732 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2733 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2735 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2736 CastSpell(this, spell_id, true);
2738 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2739 else if (IsPassiveSpell(spell_id))
2741 // if spell doesn't require a stance or the player is in the required stance
2742 if( ( !spellInfo->Stances &&
2743 spell_id != 5420 && spell_id != 5419 && spell_id != 7376 &&
2744 spell_id != 7381 && spell_id != 21156 && spell_id != 21009 &&
2745 spell_id != 21178 && spell_id != 33948 && spell_id != 40121 ) ||
2746 m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))) ||
2747 (spell_id == 5420 && m_form == FORM_TREE) ||
2748 (spell_id == 5419 && m_form == FORM_TRAVEL) ||
2749 (spell_id == 7376 && m_form == FORM_DEFENSIVESTANCE) ||
2750 (spell_id == 7381 && m_form == FORM_BERSERKERSTANCE) ||
2751 (spell_id == 21156 && m_form == FORM_BATTLESTANCE)||
2752 (spell_id == 21178 && (m_form == FORM_BEAR || m_form == FORM_DIREBEAR) ) ||
2753 (spell_id == 33948 && m_form == FORM_FLIGHT) ||
2754 (spell_id == 40121 && m_form == FORM_FLIGHT_EPIC) )
2755 //Check CasterAuraStates
2756 if (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)))
2757 CastSpell(this, spell_id, true);
2759 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2761 CastSpell(this, spell_id, true);
2762 return false;
2765 // update used talent points count
2766 m_usedTalentCount += talentCost;
2768 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2769 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2771 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2772 SetFreePrimaryProffesions(freeProfs-1);
2775 // add dependent skills
2776 uint16 maxskill = GetMaxSkillValueForLevel();
2778 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2780 if(spellLearnSkill)
2782 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2783 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2785 if(skill_value < spellLearnSkill->value)
2786 skill_value = spellLearnSkill->value;
2788 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2790 if(skill_max_value < new_skill_max_value)
2791 skill_max_value = new_skill_max_value;
2793 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2795 else
2797 // not ranked skills
2798 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2799 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2801 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2803 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2804 if(!pSkill)
2805 continue;
2807 if(HasSkill(pSkill->id))
2808 continue;
2810 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2811 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2812 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2814 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2816 case SKILL_RANGE_LANGUAGE:
2817 SetSkill(pSkill->id, 300, 300 );
2818 break;
2819 case SKILL_RANGE_LEVEL:
2820 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2821 break;
2822 case SKILL_RANGE_MONO:
2823 SetSkill(pSkill->id, 1, 1 );
2824 break;
2825 default:
2826 break;
2832 // learn dependent spells
2833 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2834 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2836 for(SpellLearnSpellMap::const_iterator itr = spell_begin; itr != spell_end; ++itr)
2838 if(!itr->second.autoLearned)
2840 if(loading) // at spells loading, no output, but allow save
2841 addSpell(itr->second.spell,true,true,loading);
2842 else // at normal learning
2843 learnSpell(itr->second.spell);
2847 if(!loading)
2849 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL);
2850 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS);
2853 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2854 return active && !disabled && !superceded_old;
2857 void Player::learnSpell(uint32 spell_id)
2859 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2861 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
2862 bool active = disabled ? itr->second->active : true;
2864 bool learning = addSpell(spell_id,active);
2866 // learn all disabled higher ranks (recursive)
2867 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2868 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
2870 PlayerSpellMap::iterator iter = m_spells.find(i->second);
2871 if (disabled && iter != m_spells.end() && iter->second->disabled)
2872 learnSpell(i->second);
2875 // prevent duplicated entires in spell book
2876 if(!learning)
2877 return;
2879 WorldPacket data(SMSG_LEARNED_SPELL, 4);
2880 data << uint32(spell_id);
2881 GetSession()->SendPacket(&data);
2884 void Player::removeSpell(uint32 spell_id, bool disabled)
2886 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2887 if (itr == m_spells.end())
2888 return;
2890 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
2891 return;
2893 // unlearn non talent higher ranks (recursive)
2894 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2895 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
2896 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
2897 removeSpell(itr2->second,disabled);
2899 // removing
2900 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2901 data << uint16(spell_id);
2902 GetSession()->SendPacket(&data);
2904 if (disabled)
2906 itr->second->disabled = disabled;
2907 if(itr->second->state != PLAYERSPELL_NEW)
2908 itr->second->state = PLAYERSPELL_CHANGED;
2910 else
2912 if(itr->second->state == PLAYERSPELL_NEW)
2914 delete itr->second;
2915 m_spells.erase(itr);
2917 else
2918 itr->second->state = PLAYERSPELL_REMOVED;
2921 RemoveAurasDueToSpell(spell_id);
2923 // remove pet auras
2924 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
2925 RemovePetAura(petSpell);
2927 // free talent points
2928 uint32 talentCosts = GetTalentSpellCost(spell_id);
2929 if(talentCosts > 0)
2931 if(talentCosts < m_usedTalentCount)
2932 m_usedTalentCount -= talentCosts;
2933 else
2934 m_usedTalentCount = 0;
2937 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2938 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2940 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
2941 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
2942 SetFreePrimaryProffesions(freeProfs);
2945 // remove dependent skill
2946 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2947 if(spellLearnSkill)
2949 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
2950 if(!prev_spell) // first rank, remove skill
2951 SetSkill(spellLearnSkill->skill,0,0);
2952 else
2954 // search prev. skill setting by spell ranks chain
2955 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
2956 while(!prevSkill && prev_spell)
2958 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
2959 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
2962 if(!prevSkill) // not found prev skill setting, remove skill
2963 SetSkill(spellLearnSkill->skill,0,0);
2964 else // set to prev. skill setting values
2966 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
2967 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
2969 if(skill_value > prevSkill->value)
2970 skill_value = prevSkill->value;
2972 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
2974 if(skill_max_value > new_skill_max_value)
2975 skill_max_value = new_skill_max_value;
2977 SetSkill(prevSkill->skill,skill_value,skill_max_value);
2982 else
2984 // not ranked skills
2985 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2986 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2988 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2990 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2991 if(!pSkill)
2992 continue;
2994 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2995 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2996 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2998 // not reset skills for professions and racial abilities
2999 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3000 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
3001 continue;
3003 SetSkill(pSkill->id, 0, 0 );
3008 // remove dependent spells
3009 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
3010 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
3012 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
3013 removeSpell(itr2->second.spell, disabled);
3015 // TODO: recast if need lesser ranks spell for passive with IsPassiveSpellStackableWithRanks
3018 void Player::RemoveArenaSpellCooldowns()
3020 // remove cooldowns on spells that has < 15 min CD
3021 SpellCooldowns::iterator itr, next;
3022 // iterate spell cooldowns
3023 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3025 next = itr;
3026 ++next;
3027 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3028 // check if spellentry is present and if the cooldown is less than 15 mins
3029 if( entry &&
3030 entry->RecoveryTime <= 15 * MINUTE * 1000 &&
3031 entry->CategoryRecoveryTime <= 15 * MINUTE * 1000 )
3033 // notify player
3034 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3035 data << uint32(itr->first);
3036 data << GetGUID();
3037 GetSession()->SendPacket(&data);
3038 // remove cooldown
3039 m_spellCooldowns.erase(itr);
3044 void Player::RemoveAllSpellCooldown()
3046 if(!m_spellCooldowns.empty())
3048 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3050 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3051 data << uint32(itr->first);
3052 data << uint64(GetGUID());
3053 GetSession()->SendPacket(&data);
3055 m_spellCooldowns.clear();
3059 void Player::_LoadSpellCooldowns(QueryResult *result)
3061 m_spellCooldowns.clear();
3063 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3065 if(result)
3067 time_t curTime = time(NULL);
3071 Field *fields = result->Fetch();
3073 uint32 spell_id = fields[0].GetUInt32();
3074 uint32 item_id = fields[1].GetUInt32();
3075 time_t db_time = (time_t)fields[2].GetUInt64();
3077 if(!sSpellStore.LookupEntry(spell_id))
3079 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3080 continue;
3083 // skip outdated cooldown
3084 if(db_time <= curTime)
3085 continue;
3087 AddSpellCooldown(spell_id, item_id, db_time);
3089 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3091 while( result->NextRow() );
3093 delete result;
3097 void Player::_SaveSpellCooldowns()
3099 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3101 time_t curTime = time(NULL);
3103 // remove outdated and save active
3104 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3106 if(itr->second.end <= curTime)
3107 m_spellCooldowns.erase(itr++);
3108 else
3110 CharacterDatabase.PExecute("INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ('%u', '%u', '%u', '" I64FMTD "')", GetGUIDLow(), itr->first, itr->second.itemid, uint64(itr->second.end));
3111 ++itr;
3116 uint32 Player::resetTalentsCost() const
3118 // The first time reset costs 1 gold
3119 if(m_resetTalentsCost < 1*GOLD)
3120 return 1*GOLD;
3121 // then 5 gold
3122 else if(m_resetTalentsCost < 5*GOLD)
3123 return 5*GOLD;
3124 // After that it increases in increments of 5 gold
3125 else if(m_resetTalentsCost < 10*GOLD)
3126 return 10*GOLD;
3127 else
3129 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3130 if(months > 0)
3132 // This cost will be reduced by a rate of 5 gold per month
3133 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3134 // to a minimum of 10 gold.
3135 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3137 else
3139 // After that it increases in increments of 5 gold
3140 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3141 // until it hits a cap of 50 gold.
3142 if(new_cost > 50*GOLD)
3143 new_cost = 50*GOLD;
3144 return new_cost;
3149 bool Player::resetTalents(bool no_cost)
3151 // not need after this call
3152 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3154 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3155 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3158 uint32 level = getLevel();
3159 uint32 talentPointsForLevel = level < 10 ? 0 : uint32((level-9)*sWorld.getRate(RATE_TALENT));
3161 if (m_usedTalentCount == 0)
3163 SetFreeTalentPoints(talentPointsForLevel);
3164 return false;
3167 uint32 cost = 0;
3169 if(!no_cost)
3171 cost = resetTalentsCost();
3173 if (GetMoney() < cost)
3175 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3176 return false;
3180 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); i++)
3182 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3184 if (!talentInfo) continue;
3186 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3188 if(!talentTabInfo)
3189 continue;
3191 // unlearn only talents for character class
3192 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3193 // to prevent unexpected lost normal learned spell skip another class talents
3194 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3195 continue;
3197 for (int j = 0; j < 5; j++)
3199 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3201 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3203 ++itr;
3204 continue;
3207 // remove learned spells (all ranks)
3208 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3210 // unlearn if first rank is talent or learned by talent
3211 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3213 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3214 itr = GetSpellMap().begin();
3215 continue;
3217 else
3218 ++itr;
3223 SetFreeTalentPoints(talentPointsForLevel);
3225 if(!no_cost)
3227 ModifyMoney(-(int32)cost);
3229 m_resetTalentsCost = cost;
3230 m_resetTalentsTime = time(NULL);
3233 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3234 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3236 return true;
3239 bool Player::_removeSpell(uint16 spell_id)
3241 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3242 if (itr != m_spells.end())
3244 delete itr->second;
3245 m_spells.erase(itr);
3246 return true;
3248 return false;
3251 Mail* Player::GetMail(uint32 id)
3253 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3255 if ((*itr)->messageID == id)
3257 return (*itr);
3260 return NULL;
3263 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3265 if(target == this)
3267 Object::_SetCreateBits(updateMask, target);
3269 else
3271 for(uint16 index = 0; index < m_valuesCount; index++)
3273 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3274 updateMask->SetBit(index);
3279 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3281 if(target == this)
3283 Object::_SetUpdateBits(updateMask, target);
3285 else
3287 Object::_SetUpdateBits(updateMask, target);
3288 *updateMask &= updateVisualBits;
3292 void Player::InitVisibleBits()
3294 updateVisualBits.SetCount(PLAYER_END);
3296 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3297 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3298 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3299 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3300 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3301 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3302 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3303 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3304 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3305 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3306 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3307 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3308 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3309 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3310 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3311 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3312 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3313 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3314 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3315 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3316 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3317 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3318 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3319 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3320 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3321 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3322 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3323 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3324 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3325 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3326 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3327 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3328 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3329 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3330 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3331 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3332 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3333 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3334 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3335 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3336 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3337 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3338 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3339 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3340 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3341 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3342 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3343 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3344 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3345 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3346 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3347 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3348 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3349 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3350 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3352 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3353 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3354 updateVisualBits.SetBit(PLAYER_FLAGS);
3355 updateVisualBits.SetBit(PLAYER_GUILDID);
3356 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3357 updateVisualBits.SetBit(PLAYER_BYTES);
3358 updateVisualBits.SetBit(PLAYER_BYTES_2);
3359 updateVisualBits.SetBit(PLAYER_BYTES_3);
3360 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3361 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3363 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3364 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3365 updateVisualBits.SetBit(i);
3367 // Players visible items are not inventory stuff
3368 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3370 uint32 offset = i * MAX_VISIBLE_ITEM_OFFSET;
3372 // item creator
3373 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 0 + offset);
3374 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 1 + offset);
3376 // item entry
3377 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 0 + offset);
3379 // item enchantments
3380 for(uint8 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
3381 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 1 + j + offset);
3383 // random properties
3384 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + offset);
3385 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_SEED + offset);
3386 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PAD + offset);
3389 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3392 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3394 for(int i = 0; i < EQUIPMENT_SLOT_END; i++)
3396 if(m_items[i] == NULL)
3397 continue;
3399 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3402 if(target == this)
3404 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3406 if(m_items[i] == NULL)
3407 continue;
3409 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3411 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3413 if(m_items[i] == NULL)
3414 continue;
3416 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3420 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3423 void Player::DestroyForPlayer( Player *target ) const
3425 Unit::DestroyForPlayer( target );
3427 for(int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
3429 if(m_items[i] == NULL)
3430 continue;
3432 m_items[i]->DestroyForPlayer( target );
3435 if(target == this)
3437 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3439 if(m_items[i] == NULL)
3440 continue;
3442 m_items[i]->DestroyForPlayer( target );
3444 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3446 if(m_items[i] == NULL)
3447 continue;
3449 m_items[i]->DestroyForPlayer( target );
3454 bool Player::HasSpell(uint32 spell) const
3456 PlayerSpellMap::const_iterator itr = m_spells.find((uint16)spell);
3457 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled);
3460 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3462 if (!trainer_spell)
3463 return TRAINER_SPELL_RED;
3465 if (!trainer_spell->spell)
3466 return TRAINER_SPELL_RED;
3468 // known spell
3469 if(HasSpell(trainer_spell->spell))
3470 return TRAINER_SPELL_GRAY;
3472 // check race/class requirement
3473 if(!IsSpellFitByClassAndRace(trainer_spell->spell))
3474 return TRAINER_SPELL_RED;
3476 // check level requirement
3477 if(getLevel() < trainer_spell->reqlevel)
3478 return TRAINER_SPELL_RED;
3480 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->spell))
3482 // check prev.rank requirement
3483 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3484 return TRAINER_SPELL_RED;
3486 // check additional spell requirement
3487 if(spell_chain->req && !HasSpell(spell_chain->req))
3488 return TRAINER_SPELL_RED;
3491 // check skill requirement
3492 if(trainer_spell->reqskill && GetBaseSkillValue(trainer_spell->reqskill) < trainer_spell->reqskillvalue)
3493 return TRAINER_SPELL_RED;
3495 // exist, already checked at loading
3496 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->spell);
3498 // secondary prof. or not prof. spell
3499 uint32 skill = spell->EffectMiscValue[1];
3501 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3502 return TRAINER_SPELL_GREEN;
3504 // check primary prof. limit
3505 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3506 return TRAINER_SPELL_RED;
3508 return TRAINER_SPELL_GREEN;
3511 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3513 uint32 guid = GUID_LOPART(playerguid);
3515 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3516 // bones will be deleted by corpse/bones deleting thread shortly
3517 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3519 // remove from guild
3520 uint32 guildId = GetGuildIdFromDB(playerguid);
3521 if(guildId != 0)
3523 Guild* guild = objmgr.GetGuildById(guildId);
3524 if(guild)
3525 guild->DelMember(guid);
3528 // remove from arena teams
3529 LeaveAllArenaTeams(playerguid);
3531 // the player was uninvited already on logout so just remove from group
3532 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3533 if(resultGroup)
3535 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3536 delete resultGroup;
3537 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3538 if(group)
3540 RemoveFromGroup(group, playerguid);
3544 // remove signs from petitions (also remove petitions if owner);
3545 RemovePetitionsAndSigns(playerguid, 10);
3547 // return back all mails with COD and Item 0 1 2 3 4 5 6
3548 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);
3549 if(resultMail)
3553 Field *fields = resultMail->Fetch();
3555 uint32 mail_id = fields[0].GetUInt32();
3556 uint16 mailTemplateId= fields[1].GetUInt16();
3557 uint32 sender = fields[2].GetUInt32();
3558 std::string subject = fields[3].GetCppString();
3559 uint32 itemTextId = fields[4].GetUInt32();
3560 uint32 money = fields[5].GetUInt32();
3561 bool has_items = fields[6].GetBool();
3563 //we can return mail now
3564 //so firstly delete the old one
3565 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3567 MailItemsInfo mi;
3568 if(has_items)
3570 // data needs to be at first place for Item::LoadFromDB
3571 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);
3572 if(resultItems)
3576 Field *fields2 = resultItems->Fetch();
3578 uint32 item_guidlow = fields2[1].GetUInt32();
3579 uint32 item_template = fields2[2].GetUInt32();
3581 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3582 if(!itemProto)
3584 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3585 continue;
3588 Item *pItem = NewItemOrBag(itemProto);
3589 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3591 pItem->FSetState(ITEM_REMOVED);
3592 pItem->SaveToDB(); // it also deletes item object !
3593 continue;
3596 mi.AddItem(item_guidlow, item_template, pItem);
3598 while (resultItems->NextRow());
3600 delete resultItems;
3604 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3606 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3608 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3610 while (resultMail->NextRow());
3612 delete resultMail;
3615 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3616 // Get guids of character's pets, will deleted in transaction
3617 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3619 // NOW we can finally clear other DB data related to character
3620 CharacterDatabase.BeginTransaction();
3621 if (resultPets)
3625 Field *fields3 = resultPets->Fetch();
3626 uint32 petguidlow = fields3[0].GetUInt32();
3627 Pet::DeleteFromDB(petguidlow);
3628 } while (resultPets->NextRow());
3629 delete resultPets;
3632 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3633 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3634 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3635 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3636 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3637 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3638 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3639 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3640 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3641 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3642 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3643 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3644 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3645 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3646 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3647 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3648 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3649 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3650 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3651 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3652 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3653 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3654 CharacterDatabase.CommitTransaction();
3656 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3657 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3660 void Player::SetMovement(PlayerMovementType pType)
3662 WorldPacket data;
3663 switch(pType)
3665 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3666 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3667 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3668 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3669 default:
3670 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3671 return;
3673 data.append(GetPackGUID());
3674 data << uint32(0);
3675 GetSession()->SendPacket( &data );
3678 /* Preconditions:
3679 - a resurrectable corpse must not be loaded for the player (only bones)
3680 - the player must be in world
3682 void Player::BuildPlayerRepop()
3684 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3685 data.append(GetPackGUID());
3686 GetSession()->SendPacket(&data);
3688 if(getRace() == RACE_NIGHTELF)
3689 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)
3690 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3692 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3693 // there must be SMSG.STOP_MIRROR_TIMER
3694 // there we must send 888 opcode
3696 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3697 if(GetCorpse())
3699 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3700 assert(false);
3703 // create a corpse and place it at the player's location
3704 CreateCorpse();
3705 Corpse *corpse = GetCorpse();
3706 if(!corpse)
3708 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3709 return;
3711 GetMap()->Add(corpse);
3713 // convert player body to ghost
3714 SetHealth( 1 );
3716 SetMovement(MOVE_WATER_WALK);
3717 if(!GetSession()->isLogingOut())
3718 SetMovement(MOVE_UNROOT);
3720 // BG - remove insignia related
3721 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3723 SendCorpseReclaimDelay();
3725 // to prevent cheating
3726 corpse->ResetGhostTime();
3728 StopMirrorTimers(); //disable timers(bars)
3730 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3732 SetByteValue(UNIT_FIELD_BYTES_1, 3, PLAYER_STATE_FLAG_ALWAYS_STAND);
3735 void Player::SendDelayResponse(const uint32 ml_seconds)
3737 //FIXME: is this delay time arg really need? 50msec by default in code
3738 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3739 data << (uint32)time(NULL);
3740 data << (uint32)0;
3741 GetSession()->SendPacket( &data );
3744 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
3746 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3747 data << uint32(-1);
3748 data << float(0);
3749 data << float(0);
3750 data << float(0);
3751 GetSession()->SendPacket(&data);
3753 // speed change, land walk
3755 // remove death flag + set aura
3756 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3757 if(getRace() == RACE_NIGHTELF)
3758 RemoveAurasDueToSpell(20584); // speed bonuses
3759 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3761 setDeathState(ALIVE);
3763 SetMovement(MOVE_LAND_WALK);
3764 SetMovement(MOVE_UNROOT);
3766 m_deathTimer = 0;
3768 // set health/powers (0- will be set in caller)
3769 if(restore_percent>0.0f)
3771 SetHealth(uint32(GetMaxHealth()*restore_percent));
3772 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3773 SetPower(POWER_RAGE, 0);
3774 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3777 // update visibility
3778 ObjectAccessor::UpdateVisibilityForPlayer(this);
3780 // some items limited to specific map
3781 DestroyZoneLimitedItem( true, GetZoneId());
3783 if(!applySickness)
3784 return;
3786 //Characters from level 1-10 are not affected by resurrection sickness.
3787 //Characters from level 11-19 will suffer from one minute of sickness
3788 //for each level they are above 10.
3789 //Characters level 20 and up suffer from ten minutes of sickness.
3790 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3792 if(int32(getLevel()) >= startLevel)
3794 // set resurrection sickness
3795 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
3797 // not full duration
3798 if(int32(getLevel()) < startLevel+9)
3800 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
3802 for(int i =0; i < 3; ++i)
3804 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
3806 Aur->SetAuraDuration(delta*1000);
3807 Aur->SendAuraUpdate(false);
3814 void Player::KillPlayer()
3816 SetMovement(MOVE_ROOT);
3818 StopMirrorTimers(); //disable timers(bars)
3820 setDeathState(CORPSE);
3821 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3823 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
3824 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
3826 // 6 minutes until repop at graveyard
3827 m_deathTimer = 6*MINUTE*1000;
3829 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3831 // don't create corpse at this moment, player might be falling
3833 // update visibility
3834 ObjectAccessor::UpdateObjectVisibility(this);
3837 void Player::CreateCorpse()
3839 // prevent existence 2 corpse for player
3840 SpawnCorpseBones();
3842 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
3844 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
3845 SetPvPDeath(false);
3847 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this, GetMapId(), GetPositionX(),
3848 GetPositionY(), GetPositionZ(), GetOrientation()))
3850 delete corpse;
3851 return;
3854 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
3855 _pb = GetUInt32Value(PLAYER_BYTES);
3856 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
3858 uint8 race = (uint8)(_uf);
3859 uint8 skin = (uint8)(_pb);
3860 uint8 face = (uint8)(_pb >> 8);
3861 uint8 hairstyle = (uint8)(_pb >> 16);
3862 uint8 haircolor = (uint8)(_pb >> 24);
3863 uint8 facialhair = (uint8)(_pb2);
3865 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
3866 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
3868 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
3869 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
3871 uint32 flags = CORPSE_FLAG_UNK2;
3872 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
3873 flags |= CORPSE_FLAG_HIDE_HELM;
3874 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
3875 flags |= CORPSE_FLAG_HIDE_CLOAK;
3876 if(InBattleGround())
3877 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
3878 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
3880 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
3882 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
3884 uint32 iDisplayID;
3885 uint16 iIventoryType;
3886 uint32 _cfi;
3887 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
3889 if(m_items[i])
3891 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
3892 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
3894 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
3895 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
3899 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
3900 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
3901 assert(entry);
3902 if(entry->map_type != MAP_BATTLEGROUND)
3903 corpse->SaveToDB();
3905 // register for player, but not show
3906 ObjectAccessor::Instance().AddCorpse(corpse);
3909 void Player::SpawnCorpseBones()
3911 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
3912 SaveToDB(); // prevent loading as ghost without corpse
3915 Corpse* Player::GetCorpse() const
3917 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
3920 void Player::DurabilityLossAll(double percent, bool inventory)
3922 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3923 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3924 DurabilityLoss(pItem,percent);
3926 if(inventory)
3928 // bags not have durability
3929 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3931 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3932 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3933 DurabilityLoss(pItem,percent);
3935 // keys not have durability
3936 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3938 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3939 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3940 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
3941 if(Item* pItem = GetItemByPos( i, j ))
3942 DurabilityLoss(pItem,percent);
3946 void Player::DurabilityLoss(Item* item, double percent)
3948 if(!item )
3949 return;
3951 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3953 if(!pMaxDurability)
3954 return;
3956 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
3958 if(pDurabilityLoss < 1 )
3959 pDurabilityLoss = 1;
3961 DurabilityPointsLoss(item,pDurabilityLoss);
3964 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
3966 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3967 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3968 DurabilityPointsLoss(pItem,points);
3970 if(inventory)
3972 // bags not have durability
3973 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3975 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3976 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3977 DurabilityPointsLoss(pItem,points);
3979 // keys not have durability
3980 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3982 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3983 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3984 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
3985 if(Item* pItem = GetItemByPos( i, j ))
3986 DurabilityPointsLoss(pItem,points);
3990 void Player::DurabilityPointsLoss(Item* item, int32 points)
3992 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3993 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
3994 int32 pNewDurability = pOldDurability - points;
3996 if (pNewDurability < 0)
3997 pNewDurability = 0;
3998 else if (pNewDurability > pMaxDurability)
3999 pNewDurability = pMaxDurability;
4001 if (pOldDurability != pNewDurability)
4003 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4004 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4005 _ApplyItemMods(item,item->GetSlot(), false);
4007 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4009 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4010 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4011 _ApplyItemMods(item,item->GetSlot(), true);
4013 item->SetState(ITEM_CHANGED, this);
4017 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4019 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4020 DurabilityPointsLoss(pItem,1);
4023 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4025 uint32 TotalCost = 0;
4026 // equipped, backpack, bags itself
4027 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
4028 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4030 // bank, buyback and keys not repaired
4032 // items in inventory bags
4033 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
4034 for(int i = 0; i < MAX_BAG_SIZE; i++)
4035 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4036 return TotalCost;
4039 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4041 Item* item = GetItemByPos(pos);
4043 uint32 TotalCost = 0;
4044 if(!item)
4045 return TotalCost;
4047 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4048 if(!maxDurability)
4049 return TotalCost;
4051 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4053 if(cost)
4055 uint32 LostDurability = maxDurability - curDurability;
4056 if(LostDurability>0)
4058 ItemPrototype const *ditemProto = item->GetProto();
4060 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4061 if(!dcost)
4063 sLog.outError("ERROR: RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4064 return TotalCost;
4067 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4068 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4069 if(!dQualitymodEntry)
4071 sLog.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4072 return TotalCost;
4075 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4076 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4078 costs = uint32(costs * discountMod);
4080 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4081 costs = 1;
4083 if (guildBank)
4085 if (GetGuildId()==0)
4087 DEBUG_LOG("You are not member of a guild");
4088 return TotalCost;
4091 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4092 if (!pGuild)
4093 return TotalCost;
4095 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4097 DEBUG_LOG("You do not have rights to withdraw for repairs");
4098 return TotalCost;
4101 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4103 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4104 return TotalCost;
4107 if (pGuild->GetGuildBankMoney() < costs)
4109 DEBUG_LOG("There is not enough money in bank");
4110 return TotalCost;
4113 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4114 TotalCost = costs;
4116 else if (GetMoney() < costs)
4118 DEBUG_LOG("You do not have enough money");
4119 return TotalCost;
4121 else
4122 ModifyMoney( -int32(costs) );
4126 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4127 item->SetState(ITEM_CHANGED, this);
4129 // reapply mods for total broken and repaired item if equipped
4130 if(IsEquipmentPos(pos) && !curDurability)
4131 _ApplyItemMods(item,pos & 255, true);
4132 return TotalCost;
4135 void Player::RepopAtGraveyard()
4137 // note: this can be called also when the player is alive
4138 // for example from WorldSession::HandleMovementOpcodes
4140 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4142 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4143 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4145 ResurrectPlayer(0.5f);
4146 SpawnCorpseBones();
4149 WorldSafeLocsEntry const *ClosestGrave = NULL;
4151 // Special handle for battleground maps
4152 BattleGround *bg = sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
4154 if(bg && (bg->GetTypeID() == BATTLEGROUND_AB || bg->GetTypeID() == BATTLEGROUND_EY))
4155 ClosestGrave = bg->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4156 else
4157 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4159 // stop countdown until repop
4160 m_deathTimer = 0;
4162 // if no grave found, stay at the current location
4163 // and don't show spirit healer location
4164 if(ClosestGrave)
4166 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4167 if(isDead()) // not send if alive, because it used in TeleportTo()
4169 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4170 data << ClosestGrave->map_id;
4171 data << ClosestGrave->x;
4172 data << ClosestGrave->y;
4173 data << ClosestGrave->z;
4174 GetSession()->SendPacket(&data);
4179 void Player::JoinedChannel(Channel *c)
4181 m_channels.push_back(c);
4184 void Player::LeftChannel(Channel *c)
4186 m_channels.remove(c);
4189 void Player::CleanupChannels()
4191 while(!m_channels.empty())
4193 Channel* ch = *m_channels.begin();
4194 m_channels.erase(m_channels.begin()); // remove from player's channel list
4195 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4196 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4197 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4200 sLog.outDebug("Player: channels cleaned up!");
4203 void Player::UpdateLocalChannels(uint32 newZone )
4205 if(m_channels.empty())
4206 return;
4208 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4209 if(!current_zone)
4210 return;
4212 ChannelMgr* cMgr = channelMgr(GetTeam());
4213 if(!cMgr)
4214 return;
4216 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4218 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4220 next = i; ++next;
4222 // skip non built-in channels
4223 if(!(*i)->IsConstant())
4224 continue;
4226 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4227 if(!ch)
4228 continue;
4230 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4231 continue;
4233 // new channel
4234 char new_channel_name_buf[100];
4235 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4236 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4238 if((*i)!=new_channel)
4240 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4242 // leave old channel
4243 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4244 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4245 LeftChannel(*i); // remove from player's channel list
4246 cMgr->LeftChannel(name); // delete if empty
4249 sLog.outDebug("Player: channels cleaned up!");
4252 void Player::LeaveLFGChannel()
4254 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4256 if((*i)->IsLFG())
4258 (*i)->Leave(GetGUID());
4259 break;
4264 void Player::UpdateDefense()
4266 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4268 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4270 // update dependent from defense skill part
4271 UpdateDefenseBonusesMod();
4275 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4277 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4279 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4280 return;
4283 float val = 1.0f;
4285 switch(modType)
4287 case FLAT_MOD:
4288 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4289 break;
4290 case PCT_MOD:
4291 if(amount <= -100.0f)
4292 amount = -200.0f;
4294 val = (100.0f + amount) / 100.0f;
4295 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4296 break;
4299 if(!CanModifyStats())
4300 return;
4302 switch(modGroup)
4304 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4305 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4306 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4307 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4308 default: break;
4312 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4314 if(modGroup >= BASEMOD_END || modType > MOD_END)
4316 sLog.outError("ERROR: trial to access non existed BaseModGroup or wrong BaseModType!");
4317 return 0.0f;
4320 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4321 return 0.0f;
4323 return m_auraBaseMod[modGroup][modType];
4326 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4328 if(modGroup >= BASEMOD_END)
4330 sLog.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4331 return 0.0f;
4334 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4335 return 0.0f;
4337 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4340 uint32 Player::GetShieldBlockValue() const
4342 BaseModGroup modGroup = SHIELD_BLOCK_VALUE;
4344 float value = GetTotalBaseModValue(modGroup) + GetStat(STAT_STRENGTH) * 0.5f - 10;
4346 value = (value < 0) ? 0 : value;
4348 return uint32(value);
4351 float Player::GetMeleeCritFromAgility()
4353 uint32 level = getLevel();
4354 uint32 pclass = getClass();
4356 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4358 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4359 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4360 if (critBase==NULL || critRatio==NULL)
4361 return 0.0f;
4363 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4364 return crit*100.0f;
4367 float Player::GetDodgeFromAgility()
4369 // Table for base dodge values
4370 float dodge_base[MAX_CLASSES] = {
4371 0.0075f, // Warrior
4372 0.00652f, // Paladin
4373 -0.0545f, // Hunter
4374 -0.0059f, // Rogue
4375 0.03183f, // Priest
4376 0.0114f, // DK
4377 0.0167f, // Shaman
4378 0.034575f, // Mage
4379 0.02011f, // Warlock
4380 0.0f, // ??
4381 -0.0187f // Druid
4383 // Crit/agility to dodge/agility coefficient multipliers
4384 float crit_to_dodge[MAX_CLASSES] = {
4385 1.1f, // Warrior
4386 1.0f, // Paladin
4387 1.6f, // Hunter
4388 2.0f, // Rogue
4389 1.0f, // Priest
4390 1.0f, // DK?
4391 1.0f, // Shaman
4392 1.0f, // Mage
4393 1.0f, // Warlock
4394 0.0f, // ??
4395 1.7f // Druid
4398 uint32 level = getLevel();
4399 uint32 pclass = getClass();
4401 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4403 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4404 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4405 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4406 return 0.0f;
4408 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4409 return dodge*100.0f;
4412 float Player::GetSpellCritFromIntellect()
4414 uint32 level = getLevel();
4415 uint32 pclass = getClass();
4417 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4419 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4420 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4421 if (critBase==NULL || critRatio==NULL)
4422 return 0.0f;
4424 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4425 return crit*100.0f;
4428 float Player::GetRatingCoefficient(CombatRating cr) const
4430 uint32 level = getLevel();
4432 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4434 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4435 if (Rating == NULL)
4436 return 1.0f; // By default use minimum coefficient (not must be called)
4438 return Rating->ratio;
4441 float Player::GetRatingBonusValue(CombatRating cr) const
4443 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4446 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4448 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.0f;
4449 if (melee>25.0f) melee = 25.0f;
4450 return uint32 (melee * damage /100.0f);
4453 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4455 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.0f;
4456 if (ranged>25.0f) ranged=25.0f;
4457 return uint32 (ranged * damage /100.0f);
4460 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4462 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.0f;
4463 // In wow script resilience limited to 25%
4464 if (spell>25.0f)
4465 spell = 25.0f;
4466 return uint32 (spell * damage / 100.0f);
4469 uint32 Player::GetDotDamageReduction(uint32 damage) const
4471 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4472 // Dot resilience not limited (limit it by 100%)
4473 if (spellDot > 100.0f)
4474 spellDot = 100.0f;
4475 return uint32 (spellDot * damage / 100.0f);
4478 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4480 switch (attType)
4482 case BASE_ATTACK:
4483 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4484 case OFF_ATTACK:
4485 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4486 default:
4487 break;
4489 return 0.0f;
4492 float Player::OCTRegenHPPerSpirit()
4494 uint32 level = getLevel();
4495 uint32 pclass = getClass();
4497 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4499 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4500 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4501 if (baseRatio==NULL || moreRatio==NULL)
4502 return 0.0f;
4504 // Formula from PaperDollFrame script
4505 float spirit = GetStat(STAT_SPIRIT);
4506 float baseSpirit = spirit;
4507 if (baseSpirit>50) baseSpirit = 50;
4508 float moreSpirit = spirit - baseSpirit;
4509 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4510 return regen;
4513 float Player::OCTRegenMPPerSpirit()
4515 uint32 level = getLevel();
4516 uint32 pclass = getClass();
4518 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4520 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4521 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4522 if (moreRatio==NULL)
4523 return 0.0f;
4525 // Formula get from PaperDollFrame script
4526 float spirit = GetStat(STAT_SPIRIT);
4527 float regen = spirit * moreRatio->ratio;
4528 return regen;
4531 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4533 m_baseRatingValue[cr]+=(apply ? value : -value);
4535 int32 amount = uint32(m_baseRatingValue[cr]);
4536 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4537 // stat used stored in miscValueB for this aura
4538 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4539 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4540 if ((*i)->GetMiscValue() & (1<<cr))
4541 amount += GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f;
4542 if (amount < 0)
4543 amount = 0;
4544 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4546 float RatingCoeffecient = GetRatingCoefficient(cr);
4547 float RatingChange = 0.0f;
4549 bool affectStats = CanModifyStats();
4551 switch (cr)
4553 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4554 case CR_DEFENSE_SKILL:
4555 UpdateDefenseBonusesMod();
4556 break;
4557 case CR_DODGE:
4558 UpdateDodgePercentage();
4559 break;
4560 case CR_PARRY:
4561 UpdateParryPercentage();
4562 break;
4563 case CR_BLOCK:
4564 UpdateBlockPercentage();
4565 break;
4566 case CR_HIT_MELEE:
4567 UpdateMeleeHitChances();
4568 break;
4569 case CR_HIT_RANGED:
4570 UpdateRangedHitChances();
4571 break;
4572 case CR_HIT_SPELL:
4573 UpdateSpellHitChances();
4574 break;
4575 case CR_CRIT_MELEE:
4576 if(affectStats)
4578 UpdateCritPercentage(BASE_ATTACK);
4579 UpdateCritPercentage(OFF_ATTACK);
4581 break;
4582 case CR_CRIT_RANGED:
4583 if(affectStats)
4584 UpdateCritPercentage(RANGED_ATTACK);
4585 break;
4586 case CR_CRIT_SPELL:
4587 if(affectStats)
4588 UpdateAllSpellCritChances();
4589 break;
4590 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4591 case CR_HIT_TAKEN_RANGED:
4592 break;
4593 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4594 break;
4595 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4596 case CR_CRIT_TAKEN_RANGED:
4597 break;
4598 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4599 break;
4600 case CR_HASTE_MELEE:
4601 RatingChange = value / RatingCoeffecient;
4602 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4603 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4604 break;
4605 case CR_HASTE_RANGED:
4606 RatingChange = value / RatingCoeffecient;
4607 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4608 break;
4609 case CR_HASTE_SPELL:
4610 RatingChange = value / RatingCoeffecient;
4611 ApplyCastTimePercentMod(RatingChange,apply);
4612 break;
4613 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4614 case CR_WEAPON_SKILL_OFFHAND:
4615 case CR_WEAPON_SKILL_RANGED:
4616 break;
4617 case CR_EXPERTISE:
4618 if(affectStats)
4620 UpdateExpertise(BASE_ATTACK);
4621 UpdateExpertise(OFF_ATTACK);
4623 break;
4627 void Player::SetRegularAttackTime()
4629 for(int i = 0; i < MAX_ATTACK; ++i)
4631 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4632 if(tmpitem && !tmpitem->IsBroken())
4634 ItemPrototype const *proto = tmpitem->GetProto();
4635 if(proto->Delay)
4636 SetAttackTime(WeaponAttackType(i), proto->Delay);
4637 else
4638 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4643 //skill+step, checking for max value
4644 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4646 if(!skill_id)
4647 return false;
4649 uint16 i=0;
4650 for (; i < PLAYER_MAX_SKILLS; i++)
4651 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4652 break;
4654 if(i>=PLAYER_MAX_SKILLS)
4655 return false;
4657 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4658 uint32 value = SKILL_VALUE(data);
4659 uint32 max = SKILL_MAX(data);
4661 if ((!max) || (!value) || (value >= max))
4662 return false;
4664 if (value*512 < max*urand(0,512))
4666 uint32 new_value = value+step;
4667 if(new_value > max)
4668 new_value = max;
4670 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4671 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4672 return true;
4675 return false;
4678 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4680 if ( SkillValue >= GrayLevel )
4681 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4682 if ( SkillValue >= GreenLevel )
4683 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4684 if ( SkillValue >= YellowLevel )
4685 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4686 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4689 bool Player::UpdateCraftSkill(uint32 spellid)
4691 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4693 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4694 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4696 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4698 if(_spell_idx->second->skillId)
4700 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4702 // Alchemy Discoveries here
4703 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4704 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4706 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4707 learnSpell(discoveredSpell);
4710 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4712 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4713 _spell_idx->second->max_value,
4714 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4715 _spell_idx->second->min_value),
4716 craft_skill_gain);
4719 return false;
4722 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4724 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4726 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4728 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4729 switch (SkillId)
4731 case SKILL_HERBALISM:
4732 case SKILL_LOCKPICKING:
4733 case SKILL_JEWELCRAFTING:
4734 case SKILL_INSCRIPTION:
4735 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4736 case SKILL_SKINNING:
4737 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4738 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4739 else
4740 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4741 case SKILL_MINING:
4742 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4743 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4744 else
4745 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4747 return false;
4750 bool Player::UpdateFishingSkill()
4752 sLog.outDebug("UpdateFishingSkill");
4754 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4756 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4758 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4760 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4763 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4765 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4766 if ( !SkillId )
4767 return false;
4769 if(Chance <= 0) // speedup in 0 chance case
4771 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4772 return false;
4775 uint16 i=0;
4776 for (; i < PLAYER_MAX_SKILLS; i++)
4777 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4778 if ( i >= PLAYER_MAX_SKILLS )
4779 return false;
4781 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4782 uint16 SkillValue = SKILL_VALUE(data);
4783 uint16 MaxValue = SKILL_MAX(data);
4785 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4786 return false;
4788 int32 Roll = irand(1,1000);
4790 if ( Roll <= Chance )
4792 uint32 new_value = SkillValue+step;
4793 if(new_value > MaxValue)
4794 new_value = MaxValue;
4796 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
4797 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4798 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
4799 return true;
4802 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4803 return false;
4806 void Player::UpdateWeaponSkill (WeaponAttackType attType)
4808 // no skill gain in pvp
4809 Unit *pVictim = getVictim();
4810 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
4811 return;
4813 if(IsInFeralForm())
4814 return; // always maximized SKILL_FERAL_COMBAT in fact
4816 if(m_form == FORM_TREE)
4817 return; // use weapon but not skill up
4819 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
4821 switch(attType)
4823 case BASE_ATTACK:
4825 Item *tmpitem = GetWeaponForAttack(attType,true);
4827 if (!tmpitem)
4828 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
4829 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
4830 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4831 break;
4833 case OFF_ATTACK:
4834 case RANGED_ATTACK:
4836 Item *tmpitem = GetWeaponForAttack(attType,true);
4837 if (tmpitem)
4838 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4839 break;
4842 UpdateAllCritPercentages();
4845 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, MeleeHitOutcome outcome, bool defence)
4847 /* Not need, this checked on call this func from trigger system
4848 switch(outcome)
4850 case MELEE_HIT_CRIT:
4851 case MELEE_HIT_DODGE:
4852 case MELEE_HIT_PARRY:
4853 case MELEE_HIT_BLOCK:
4854 case MELEE_HIT_BLOCK_CRIT:
4855 return;
4857 default:
4858 break;
4861 uint32 plevel = getLevel(); // if defense than pVictim == attacker
4862 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
4863 uint32 moblevel = pVictim->getLevelForTarget(this);
4864 if(moblevel < greylevel)
4865 return;
4867 if (moblevel > plevel + 5)
4868 moblevel = plevel + 5;
4870 uint32 lvldif = moblevel - greylevel;
4871 if(lvldif < 3)
4872 lvldif = 3;
4874 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
4875 if(skilldif <= 0)
4876 return;
4878 float chance = float(3 * lvldif * skilldif) / plevel;
4879 if(!defence)
4881 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
4882 chance *= 0.1f * GetStat(STAT_INTELLECT);
4885 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
4887 if(roll_chance_f(chance))
4889 if(defence)
4890 UpdateDefense();
4891 else
4892 UpdateWeaponSkill(attType);
4894 else
4895 return;
4898 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
4900 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4901 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
4903 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4904 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
4905 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
4907 if(talent) // permanent bonus stored in high part
4908 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
4909 else // temporary/item bonus stored in low part
4910 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
4911 return;
4915 void Player::UpdateSkillsForLevel()
4917 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
4918 uint32 maxSkill = GetMaxSkillValueForLevel();
4920 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
4922 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4923 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4925 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4927 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
4928 if(!pSkill)
4929 continue;
4931 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
4932 continue;
4934 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4935 uint32 max = SKILL_MAX(data);
4936 uint32 val = SKILL_VALUE(data);
4938 /// update only level dependent max skill values
4939 if(max!=1)
4941 /// miximize skill always
4942 if(alwaysMaxSkill)
4943 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
4944 /// update max skill value if current max skill not maximized
4945 else if(max != maxconfskill)
4946 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
4951 void Player::UpdateSkillsToMaxSkillsForLevel()
4953 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4954 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4956 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4957 if( IsProfessionSkill(pskill) || pskill == SKILL_RIDING )
4958 continue;
4959 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4961 uint32 max = SKILL_MAX(data);
4963 if(max > 1)
4964 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
4966 if(pskill == SKILL_DEFENSE)
4967 UpdateDefenseBonusesMod();
4971 // This functions sets a skill line value (and adds if doesn't exist yet)
4972 // To "remove" a skill line, set it's values to zero
4973 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
4975 if(!id)
4976 return;
4978 uint16 i=0;
4979 for (; i < PLAYER_MAX_SKILLS; i++)
4980 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
4982 if(i<PLAYER_MAX_SKILLS) //has skill
4984 if(currVal)
4986 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
4987 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4989 else //remove
4991 // clear skill fields
4992 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
4993 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
4994 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
4996 // remove spells that depend on this skill when removing the skill
4997 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
4999 ++next;
5000 if(itr->second->state == PLAYERSPELL_REMOVED)
5001 continue;
5003 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(itr->first);
5004 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(itr->first);
5006 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
5008 if (_spell_idx->second->skillId == id)
5010 // this may remove more than one spell (dependents)
5011 removeSpell(itr->first);
5012 next = m_spells.begin();
5013 break;
5019 else if(currVal) //add
5021 for (i=0; i < PLAYER_MAX_SKILLS; i++)
5022 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5024 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5025 if(!pSkill)
5027 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5028 return;
5030 // enable unlearn button for primary professions only
5031 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5032 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5033 else
5034 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5035 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5036 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
5038 // apply skill bonuses
5039 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5041 // temporary bonuses
5042 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5043 for(AuraList::const_iterator i = mModSkill.begin(); i != mModSkill.end(); ++i)
5044 if ((*i)->GetModifier()->m_miscvalue == int32(id))
5045 (*i)->ApplyModifier(true);
5047 // permanent bonuses
5048 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5049 for(AuraList::const_iterator i = mModSkillTalent.begin(); i != mModSkillTalent.end(); ++i)
5050 if ((*i)->GetModifier()->m_miscvalue == int32(id))
5051 (*i)->ApplyModifier(true);
5053 // Learn all spells for skill
5054 learnSkillRewardedSpells(id);
5055 return;
5060 bool Player::HasSkill(uint32 skill) const
5062 if(!skill)return false;
5063 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5065 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5067 return true;
5070 return false;
5073 uint16 Player::GetSkillValue(uint32 skill) const
5075 if(!skill)
5076 return 0;
5078 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5080 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5082 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5084 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5085 result += SKILL_TEMP_BONUS(bonus);
5086 result += SKILL_PERM_BONUS(bonus);
5087 return result < 0 ? 0 : result;
5090 return 0;
5093 uint16 Player::GetMaxSkillValue(uint32 skill) const
5095 if(!skill)return 0;
5096 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5098 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5100 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5102 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5103 result += SKILL_TEMP_BONUS(bonus);
5104 result += SKILL_PERM_BONUS(bonus);
5105 return result < 0 ? 0 : result;
5108 return 0;
5111 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5113 if(!skill)return 0;
5114 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5116 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5118 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5121 return 0;
5124 uint16 Player::GetBaseSkillValue(uint32 skill) const
5126 if(!skill)return 0;
5127 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5129 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5131 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5132 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5133 return result < 0 ? 0 : result;
5136 return 0;
5139 uint16 Player::GetPureSkillValue(uint32 skill) const
5141 if(!skill)return 0;
5142 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5144 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5146 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5149 return 0;
5152 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5154 if(!skill)
5155 return 0;
5157 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5159 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5161 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5165 return 0;
5168 void Player::SendInitialActionButtons()
5170 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5172 WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
5173 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5175 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5176 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5178 data << uint16(itr->second.action);
5179 data << uint8(itr->second.misc);
5180 data << uint8(itr->second.type);
5182 else
5184 data << uint32(0);
5188 GetSession()->SendPacket( &data );
5189 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5192 void Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5194 if(button >= MAX_ACTION_BUTTONS)
5196 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5197 return;
5200 // check cheating with adding non-known spells to action bar
5201 if(type==ACTION_BUTTON_SPELL)
5203 if(!sSpellStore.LookupEntry(action))
5205 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5206 return;
5209 if(!HasSpell(action))
5211 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5212 return;
5216 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5218 if (buttonItr==m_actionButtons.end())
5219 { // just add new button
5220 m_actionButtons[button] = ActionButton(action,type,misc);
5222 else
5223 { // change state of current button
5224 ActionButtonUpdateState uState = buttonItr->second.uState;
5225 buttonItr->second = ActionButton(action,type,misc);
5226 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5229 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5232 void Player::removeActionButton(uint8 button)
5234 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5235 if (buttonItr==m_actionButtons.end())
5236 return;
5238 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5239 m_actionButtons.erase(buttonItr); // new and not saved
5240 else
5241 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5243 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5246 void Player::SetDontMove(bool dontMove)
5248 m_dontMove = dontMove;
5251 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5253 // prevent crash when a bad coord is sent by the client
5254 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5256 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5257 return false;
5260 Map *m = GetMap();
5262 const float old_x = GetPositionX();
5263 const float old_y = GetPositionY();
5264 const float old_z = GetPositionZ();
5265 const float old_r = GetOrientation();
5267 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5269 if (teleport || old_x != x || old_y != y || old_z != z)
5270 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5271 else
5272 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5274 // move and update visible state if need
5275 m->PlayerRelocation(this, x, y, z, orientation);
5277 // reread after Map::Relocation
5278 m = GetMap();
5279 x = GetPositionX();
5280 y = GetPositionY();
5281 z = GetPositionZ();
5283 // group update
5284 if(GetGroup() && (old_x != x || old_y != y))
5285 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5288 // code block for underwater state update
5289 UpdateUnderwaterState(m, x, y, z);
5291 CheckExploreSystem();
5293 return true;
5296 void Player::SaveRecallPosition()
5298 m_recallMap = GetMapId();
5299 m_recallX = GetPositionX();
5300 m_recallY = GetPositionY();
5301 m_recallZ = GetPositionZ();
5302 m_recallO = GetOrientation();
5305 void Player::SendMessageToSet(WorldPacket *data, bool self)
5307 GetMap()->MessageBroadcast(this, data, self);
5310 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5312 GetMap()->MessageDistBroadcast(this, data, dist, self);
5315 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5317 GetMap()->MessageDistBroadcast(this, data, dist, self,own_team_only);
5320 void Player::SendDirectMessage(WorldPacket *data)
5322 GetSession()->SendPacket(data);
5325 void Player::CheckExploreSystem()
5327 if (!isAlive())
5328 return;
5330 if (isInFlight())
5331 return;
5333 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5334 if(areaFlag==0xffff)
5335 return;
5336 int offset = areaFlag / 32;
5338 if(offset >= 128)
5340 sLog.outError("ERROR: Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < 64 ).",areaFlag,GetPositionX(),GetPositionY(),offset,offset);
5341 return;
5344 uint32 val = (uint32)(1 << (areaFlag % 32));
5345 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5347 if( !(currFields & val) )
5349 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5351 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5353 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5354 if(!p)
5356 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5358 else if(p->area_level > 0)
5360 uint32 area = p->ID;
5361 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5363 SendExplorationExperience(area,0);
5365 else
5367 int32 diff = int32(getLevel()) - p->area_level;
5368 uint32 XP = 0;
5369 if (diff < -5)
5371 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5373 else if (diff > 5)
5375 int32 exploration_percent = (100-((diff-5)*5));
5376 if (exploration_percent > 100)
5377 exploration_percent = 100;
5378 else if (exploration_percent < 0)
5379 exploration_percent = 0;
5381 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5383 else
5385 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5388 GiveXP( XP, NULL );
5389 SendExplorationExperience(area,XP);
5391 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5396 uint32 Player::TeamForRace(uint8 race)
5398 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5399 if(!rEntry)
5401 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5402 return ALLIANCE;
5405 switch(rEntry->TeamID)
5407 case 7: return ALLIANCE;
5408 case 1: return HORDE;
5411 sLog.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5412 return ALLIANCE;
5415 uint32 Player::getFactionForRace(uint8 race)
5417 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5418 if(!rEntry)
5420 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5421 return 0;
5424 return rEntry->FactionID;
5427 void Player::setFactionForRace(uint8 race)
5429 m_team = TeamForRace(race);
5430 setFaction( getFactionForRace(race) );
5433 void Player::UpdateReputation() const
5435 sLog.outDetail( "WORLD: Player::UpdateReputation" );
5437 for(FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5439 SendFactionState(&(itr->second));
5443 void Player::SendFactionState(FactionState const* faction) const
5445 if(faction->Flags & FACTION_FLAG_VISIBLE) //If faction is visible then update it
5447 WorldPacket data(SMSG_SET_FACTION_STANDING, (16)); // last check 2.4.0
5448 data << (float) 0; // unk 2.4.0
5449 data << (uint8) 0; // wotlk 8634
5450 data << (uint32) 1; // count
5451 // for
5452 data << (uint32) faction->ReputationListID;
5453 data << (uint32) faction->Standing;
5454 // end for
5455 GetSession()->SendPacket(&data);
5459 void Player::SendInitialReputations()
5461 WorldPacket data(SMSG_INITIALIZE_FACTIONS, (4+128*5));
5462 data << uint32 (0x00000080);
5464 RepListID a = 0;
5466 for (FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5468 // fill in absent fields
5469 for (; a != itr->first; a++)
5471 data << uint8 (0x00);
5472 data << uint32 (0x00000000);
5475 // fill in encountered data
5476 data << uint8 (itr->second.Flags);
5477 data << uint32 (itr->second.Standing);
5479 ++a;
5482 // fill in absent fields
5483 for (; a != 128; a++)
5485 data << uint8 (0x00);
5486 data << uint32 (0x00000000);
5489 GetSession()->SendPacket(&data);
5492 FactionState const* Player::GetFactionState( FactionEntry const* factionEntry) const
5494 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5495 if (itr != m_factions.end())
5496 return &itr->second;
5498 return NULL;
5501 void Player::SetFactionAtWar(FactionState* faction, bool atWar)
5503 // not allow declare war to own faction
5504 if(atWar && (faction->Flags & FACTION_FLAG_PEACE_FORCED) )
5505 return;
5507 // already set
5508 if(((faction->Flags & FACTION_FLAG_AT_WAR) != 0) == atWar)
5509 return;
5511 if( atWar )
5512 faction->Flags |= FACTION_FLAG_AT_WAR;
5513 else
5514 faction->Flags &= ~FACTION_FLAG_AT_WAR;
5516 faction->Changed = true;
5519 void Player::SetFactionInactive(FactionState* faction, bool inactive)
5521 // always invisible or hidden faction can't be inactive
5522 if(inactive && ((faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN)) || !(faction->Flags & FACTION_FLAG_VISIBLE) ) )
5523 return;
5525 // already set
5526 if(((faction->Flags & FACTION_FLAG_INACTIVE) != 0) == inactive)
5527 return;
5529 if(inactive)
5530 faction->Flags |= FACTION_FLAG_INACTIVE;
5531 else
5532 faction->Flags &= ~FACTION_FLAG_INACTIVE;
5534 faction->Changed = true;
5537 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId)
5539 FactionTemplateEntry const*factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5541 if(!factionTemplateEntry)
5542 return;
5544 SetFactionVisibleForFactionId(factionTemplateEntry->faction);
5547 void Player::SetFactionVisibleForFactionId(uint32 FactionId)
5549 FactionEntry const *factionEntry = sFactionStore.LookupEntry(FactionId);
5550 if(!factionEntry)
5551 return;
5553 if(factionEntry->reputationListID < 0)
5554 return;
5556 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5557 if (itr == m_factions.end())
5558 return;
5560 SetFactionVisible(&itr->second);
5563 void Player::SetFactionVisible(FactionState* faction)
5565 // always invisible or hidden faction can't be make visible
5566 if(faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN))
5567 return;
5569 // already set
5570 if(faction->Flags & FACTION_FLAG_VISIBLE)
5571 return;
5573 faction->Flags |= FACTION_FLAG_VISIBLE;
5574 faction->Changed = true;
5576 if(!m_session->PlayerLoading())
5578 // make faction visible in reputation list at client
5579 WorldPacket data(SMSG_SET_FACTION_VISIBLE, 4);
5580 data << faction->ReputationListID;
5581 GetSession()->SendPacket(&data);
5585 void Player::SetInitialFactions()
5587 for(unsigned int i = 1; i < sFactionStore.GetNumRows(); i++)
5589 FactionEntry const *factionEntry = sFactionStore.LookupEntry(i);
5591 if( factionEntry && (factionEntry->reputationListID >= 0))
5593 FactionState newFaction;
5594 newFaction.ID = factionEntry->ID;
5595 newFaction.ReputationListID = factionEntry->reputationListID;
5596 newFaction.Standing = 0;
5597 newFaction.Flags = GetDefaultReputationFlags(factionEntry);
5598 newFaction.Changed = true;
5600 m_factions[newFaction.ReputationListID] = newFaction;
5605 uint32 Player::GetDefaultReputationFlags(const FactionEntry *factionEntry) const
5607 if (!factionEntry)
5608 return 0;
5610 uint32 raceMask = getRaceMask();
5611 uint32 classMask = getClassMask();
5612 for (int i=0; i < 4; i++)
5614 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5615 (factionEntry->BaseRepClassMask[i]==0 ||
5616 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5617 return factionEntry->ReputationFlags[i];
5619 return 0;
5622 int32 Player::GetBaseReputation(const FactionEntry *factionEntry) const
5624 if (!factionEntry)
5625 return 0;
5627 uint32 raceMask = getRaceMask();
5628 uint32 classMask = getClassMask();
5629 for (int i=0; i < 4; i++)
5631 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5632 (factionEntry->BaseRepClassMask[i]==0 ||
5633 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5634 return factionEntry->BaseRepValue[i];
5637 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5638 return 0;
5641 int32 Player::GetReputation(uint32 faction_id) const
5643 FactionEntry const *factionEntry = sFactionStore.LookupEntry(faction_id);
5645 if (!factionEntry)
5647 sLog.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id);
5648 return 0;
5651 return GetReputation(factionEntry);
5654 int32 Player::GetReputation(const FactionEntry *factionEntry) const
5656 // Faction without recorded reputation. Just ignore.
5657 if(!factionEntry)
5658 return 0;
5660 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5661 if (itr != m_factions.end())
5662 return GetBaseReputation(factionEntry) + itr->second.Standing;
5664 return 0;
5667 ReputationRank Player::GetReputationRank(uint32 faction) const
5669 FactionEntry const*factionEntry = sFactionStore.LookupEntry(faction);
5670 if(!factionEntry)
5671 return MIN_REPUTATION_RANK;
5673 return GetReputationRank(factionEntry);
5676 ReputationRank Player::ReputationToRank(int32 standing) const
5678 int32 Limit = Reputation_Cap + 1;
5679 for (int i = MAX_REPUTATION_RANK-1; i >= MIN_REPUTATION_RANK; --i)
5681 Limit -= ReputationRank_Length[i];
5682 if (standing >= Limit )
5683 return ReputationRank(i);
5685 return MIN_REPUTATION_RANK;
5688 ReputationRank Player::GetReputationRank(const FactionEntry *factionEntry) const
5690 int32 Reputation = GetReputation(factionEntry);
5691 return ReputationToRank(Reputation);
5694 ReputationRank Player::GetBaseReputationRank(const FactionEntry *factionEntry) const
5696 int32 Reputation = GetBaseReputation(factionEntry);
5697 return ReputationToRank(Reputation);
5700 bool Player::ModifyFactionReputation(uint32 FactionTemplateId, int32 DeltaReputation)
5702 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5704 if(!factionTemplateEntry)
5706 sLog.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5707 return false;
5710 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5712 // Faction without recorded reputation. Just ignore.
5713 if(!factionEntry)
5714 return false;
5716 return ModifyFactionReputation(factionEntry, DeltaReputation);
5719 bool Player::ModifyFactionReputation(FactionEntry const* factionEntry, int32 standing)
5721 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5722 if (flist)
5724 bool res = false;
5725 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5727 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5728 if(factionEntryCalc)
5729 res = ModifyOneFactionReputation(factionEntryCalc, standing);
5731 return res;
5733 else
5734 return ModifyOneFactionReputation(factionEntry, standing);
5737 bool Player::ModifyOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5739 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5740 if (itr != m_factions.end())
5742 int32 BaseRep = GetBaseReputation(factionEntry);
5743 int32 new_rep = BaseRep + itr->second.Standing + standing;
5745 if (new_rep > Reputation_Cap)
5746 new_rep = Reputation_Cap;
5747 else
5748 if (new_rep < Reputation_Bottom)
5749 new_rep = Reputation_Bottom;
5751 if(ReputationToRank(new_rep) <= REP_HOSTILE)
5752 SetFactionAtWar(&itr->second,true);
5754 itr->second.Standing = new_rep - BaseRep;
5755 itr->second.Changed = true;
5757 SetFactionVisible(&itr->second);
5759 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
5761 if(uint32 questid = GetQuestSlotQuestId(i))
5763 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
5764 if( qInfo && qInfo->GetRepObjectiveFaction() == factionEntry->ID )
5766 QuestStatusData& q_status = mQuestStatus[questid];
5767 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
5769 if(GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
5770 if ( CanCompleteQuest( questid ) )
5771 CompleteQuest( questid );
5773 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
5775 if(GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
5776 IncompleteQuest( questid );
5781 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION);
5782 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION);
5783 SendFactionState(&(itr->second));
5785 return true;
5787 return false;
5790 bool Player::SetFactionReputation(uint32 FactionTemplateId, int32 standing)
5792 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5794 if(!factionTemplateEntry)
5796 sLog.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5797 return false;
5800 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5802 // Faction without recorded reputation. Just ignore.
5803 if(!factionEntry)
5804 return false;
5806 return SetFactionReputation(factionEntry, standing);
5809 bool Player::SetFactionReputation(FactionEntry const* factionEntry, int32 standing)
5811 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5812 if (flist)
5814 bool res = false;
5815 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5817 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5818 if(factionEntryCalc)
5819 res = SetOneFactionReputation(factionEntryCalc, standing);
5821 return res;
5823 else
5824 return SetOneFactionReputation(factionEntry, standing);
5827 bool Player::SetOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5829 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5830 if (itr != m_factions.end())
5832 if (standing > Reputation_Cap)
5833 standing = Reputation_Cap;
5834 else
5835 if (standing < Reputation_Bottom)
5836 standing = Reputation_Bottom;
5838 int32 BaseRep = GetBaseReputation(factionEntry);
5839 itr->second.Standing = standing - BaseRep;
5840 itr->second.Changed = true;
5842 SetFactionVisible(&itr->second);
5844 if(ReputationToRank(standing) <= REP_HOSTILE)
5845 SetFactionAtWar(&itr->second,true);
5847 SendFactionState(&(itr->second));
5848 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION);
5849 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION);
5850 return true;
5852 return false;
5855 //Calculate total reputation percent player gain with quest/creature level
5856 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5858 // for grey creature kill received 20%, in other case 100.
5859 int32 percent = (!for_quest && (creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5861 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5863 percent += rep > 0 ? repMod : -repMod;
5865 if(percent <=0)
5866 return 0;
5868 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5871 //Calculates how many reputation points player gains in victim's enemy factions
5872 void Player::RewardReputation(Unit *pVictim, float rate)
5874 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5875 return;
5877 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5879 if(!Rep)
5880 return;
5882 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5884 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
5885 donerep1 = int32(donerep1*rate);
5886 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5887 uint32 current_reputation_rank1 = GetReputationRank(factionEntry1);
5888 if(factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5889 ModifyFactionReputation(factionEntry1, donerep1);
5891 // Wiki: Team factions value divided by 2
5892 if(Rep->is_teamaward1)
5894 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5895 if(team1_factionEntry)
5896 ModifyFactionReputation(team1_factionEntry, donerep1 / 2);
5900 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5902 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
5903 donerep2 = int32(donerep2*rate);
5904 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5905 uint32 current_reputation_rank2 = GetReputationRank(factionEntry2);
5906 if(factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5907 ModifyFactionReputation(factionEntry2, donerep2);
5909 // Wiki: Team factions value divided by 2
5910 if(Rep->is_teamaward2)
5912 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5913 if(team2_factionEntry)
5914 ModifyFactionReputation(team2_factionEntry, donerep2 / 2);
5919 //Calculate how many reputation points player gain with the quest
5920 void Player::RewardReputation(Quest const *pQuest)
5922 // quest reputation reward/loss
5923 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5925 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5927 int32 rep = CalculateReputationGain(pQuest->GetQuestLevel(),pQuest->RewRepValue[i],true);
5928 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5929 if(factionEntry)
5930 ModifyFactionReputation(factionEntry, rep);
5934 // TODO: implement reputation spillover
5937 void Player::UpdateArenaFields(void)
5939 /* arena calcs go here */
5942 void Player::UpdateHonorFields()
5944 /// called when rewarding honor and at each save
5945 uint64 now = time(NULL);
5946 uint64 today = uint64(time(NULL) / DAY) * DAY;
5948 if(m_lastHonorUpdateTime < today)
5950 uint64 yesterday = today - DAY;
5952 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5954 // update yesterday's contribution
5955 if(m_lastHonorUpdateTime >= yesterday )
5957 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5959 // this is the first update today, reset today's contribution
5960 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5961 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5963 else
5965 // no honor/kills yesterday or today, reset
5966 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5967 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5971 m_lastHonorUpdateTime = now;
5974 ///Calculate the amount of honor gained based on the victim
5975 ///and the size of the group for which the honor is divided
5976 ///An exact honor value can also be given (overriding the calcs)
5977 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5979 // do not reward honor in arenas, but enable onkill spellproc
5980 if(InArena())
5982 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
5983 return false;
5985 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
5986 return false;
5988 return true;
5991 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5992 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5993 return false;
5995 uint64 victim_guid = 0;
5996 uint32 victim_rank = 0;
5998 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5999 UpdateHonorFields();
6001 if(honor <= 0)
6003 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
6004 return false;
6006 victim_guid = uVictim->GetGUID();
6008 if( uVictim->GetTypeId() == TYPEID_PLAYER )
6010 Player *pVictim = (Player *)uVictim;
6012 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
6013 return false;
6015 float f = 1; //need for total kills (?? need more info)
6016 uint32 k_grey = 0;
6017 uint32 k_level = getLevel();
6018 uint32 v_level = pVictim->getLevel();
6021 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6022 // [0] Just name
6023 // [1..14] Alliance honor titles and player name
6024 // [15..28] Horde honor titles and player name
6025 // [29..38] Other title and player name
6026 // [39+] Nothing
6027 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
6028 // Get Killer titles, CharTitlesEntry::bit_index
6029 // Ranks:
6030 // title[1..14] -> rank[5..18]
6031 // title[15..28] -> rank[5..18]
6032 // title[other] -> 0
6033 if (victim_title == 0)
6034 victim_guid = 0; // Don't show HK: <rank> message, only log.
6035 else if (victim_title < 15)
6036 victim_rank = victim_title + 4;
6037 else if (victim_title < 29)
6038 victim_rank = victim_title - 14 + 4;
6039 else
6040 victim_guid = 0; // Don't show HK: <rank> message, only log.
6043 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
6045 if(v_level<=k_grey)
6046 return false;
6048 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
6050 int32 v_rank =1; //need more info
6052 honor = ((f * diff_level * (190 + v_rank*10))/6);
6053 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
6055 // count the number of playerkills in one day
6056 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
6057 // and those in a lifetime
6058 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
6060 else
6062 Creature *cVictim = (Creature *)uVictim;
6064 if (!cVictim->isRacialLeader())
6065 return false;
6067 honor = 100; // ??? need more info
6068 victim_rank = 19; // HK: Leader
6072 if (uVictim != NULL)
6074 honor *= sWorld.getRate(RATE_HONOR);
6076 if(groupsize > 1)
6077 honor /= groupsize;
6079 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6082 // honor - for show honor points in log
6083 // victim_guid - for show victim name in log
6084 // victim_rank [1..4] HK: <dishonored rank>
6085 // victim_rank [5..19] HK: <alliance\horde rank>
6086 // victim_rank [0,20+] HK: <>
6087 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
6088 data << (uint32) honor;
6089 data << (uint64) victim_guid;
6090 data << (uint32) victim_rank;
6092 GetSession()->SendPacket(&data);
6094 // add honor points
6095 ModifyHonorPoints(int32(honor));
6097 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
6098 return true;
6101 void Player::ModifyHonorPoints( int32 value )
6103 if(value < 0)
6105 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
6106 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
6107 else
6108 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6110 else
6111 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6114 void Player::ModifyArenaPoints( int32 value )
6116 if(value < 0)
6118 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6119 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6120 else
6121 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6123 else
6124 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6127 uint32 Player::GetGuildIdFromDB(uint64 guid)
6129 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
6130 if(!result)
6131 return 0;
6133 uint32 id = result->Fetch()[0].GetUInt32();
6134 delete result;
6135 return id;
6138 uint32 Player::GetRankFromDB(uint64 guid)
6140 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6141 if( result )
6143 uint32 v = result->Fetch()[0].GetUInt32();
6144 delete result;
6145 return v;
6147 else
6148 return 0;
6151 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6153 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);
6154 if(!result)
6155 return 0;
6157 uint32 id = (*result)[0].GetUInt32();
6158 delete result;
6159 return id;
6162 uint32 Player::GetZoneIdFromDB(uint64 guid)
6164 uint32 guidLow = GUID_LOPART(guid);
6165 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6166 if (!result)
6167 return 0;
6168 Field* fields = result->Fetch();
6169 uint32 zone = fields[0].GetUInt32();
6170 delete result;
6172 if (!zone)
6174 // stored zone is zero, use generic and slow zone detection
6175 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6176 if( !result )
6177 return 0;
6178 fields = result->Fetch();
6179 uint32 map = fields[0].GetUInt32();
6180 float posx = fields[1].GetFloat();
6181 float posy = fields[2].GetFloat();
6182 float posz = fields[3].GetFloat();
6183 delete result;
6185 zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
6187 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6190 return zone;
6193 void Player::UpdateArea(uint32 newArea)
6195 // FFA_PVP flags are area and not zone id dependent
6196 // so apply them accordingly
6197 m_areaUpdateId = newArea;
6199 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6201 if(area && (area->flags & AREA_FLAG_ARENA))
6203 if(!isGameMaster())
6204 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6206 else
6208 // remove ffa flag only if not ffapvp realm
6209 // removal in sanctuaries and capitals is handled in zone update
6210 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6211 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6214 UpdateAreaDependentAuras(newArea);
6217 void Player::UpdateZone(uint32 newZone)
6219 m_zoneUpdateId = newZone;
6220 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6222 // zone changed, so area changed as well, update it
6223 UpdateArea(GetAreaId());
6225 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6226 if(!zone)
6227 return;
6229 if (sWorld.getConfig(CONFIG_WEATHER))
6231 Weather *wth = sWorld.FindWeather(zone->ID);
6232 if(wth)
6234 wth->SendWeatherUpdateToPlayer(this);
6236 else
6238 if(!sWorld.AddWeather(zone->ID))
6240 // send fine weather packet to remove old zone's weather
6241 Weather::SendFineWeatherUpdateToPlayer(this);
6246 pvpInfo.inHostileArea =
6247 GetTeam() == ALLIANCE && zone->team == AREATEAM_HORDE ||
6248 GetTeam() == HORDE && zone->team == AREATEAM_ALLY ||
6249 sWorld.IsPvPRealm() && zone->team == AREATEAM_NONE ||
6250 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6252 if(pvpInfo.inHostileArea) // in hostile area
6254 if(!IsPvP() || pvpInfo.endTimer != 0)
6255 UpdatePvP(true, true);
6257 else // in friendly area
6259 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6260 pvpInfo.endTimer = time(0); // start toggle-off
6263 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6265 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6266 if(sWorld.IsFFAPvPRealm())
6267 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6269 else
6271 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6274 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6276 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6277 SetRestType(REST_TYPE_IN_CITY);
6278 InnEnter(time(0),GetMapId(),0,0,0);
6280 if(sWorld.IsFFAPvPRealm())
6281 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6283 else // anywhere else
6285 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6287 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6289 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6291 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6292 SetRestType(REST_TYPE_NO);
6294 if(sWorld.IsFFAPvPRealm())
6295 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6298 else // not in tavern (leave city then)
6300 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6301 SetRestType(REST_TYPE_NO);
6303 // Set player to FFA PVP when not in rested environment.
6304 if(sWorld.IsFFAPvPRealm())
6305 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6310 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6311 // if player resurrected at teleport this will be applied in resurrect code
6312 if(isAlive())
6313 DestroyZoneLimitedItem( true, newZone );
6315 // recent client version not send leave/join channel packets for built-in local channels
6316 UpdateLocalChannels( newZone );
6318 // group update
6319 if(GetGroup())
6320 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6322 UpdateZoneDependentAuras(newZone);
6325 //If players are too far way of duel flag... then player loose the duel
6326 void Player::CheckDuelDistance(time_t currTime)
6328 if(!duel)
6329 return;
6331 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6332 GameObject* obj = ObjectAccessor::GetGameObject(*this, duelFlagGUID);
6333 if(!obj)
6334 return;
6336 if(duel->outOfBound == 0)
6338 if(!IsWithinDistInMap(obj, 50))
6340 duel->outOfBound = currTime;
6342 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6343 GetSession()->SendPacket(&data);
6346 else
6348 if(IsWithinDistInMap(obj, 40))
6350 duel->outOfBound = 0;
6352 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6353 GetSession()->SendPacket(&data);
6355 else if(currTime >= (duel->outOfBound+10))
6357 DuelComplete(DUEL_FLED);
6362 void Player::DuelComplete(DuelCompleteType type)
6364 // duel not requested
6365 if(!duel)
6366 return;
6368 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6369 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6370 GetSession()->SendPacket(&data);
6371 duel->opponent->GetSession()->SendPacket(&data);
6373 if(type != DUEL_INTERUPTED)
6375 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6376 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6377 data << duel->opponent->GetName();
6378 data << GetName();
6379 SendMessageToSet(&data,true);
6382 // cool-down duel spell
6383 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6385 data<<GetGUID();
6386 data<<uint8(0x0);
6388 data<<(uint32)7266;
6389 data<<uint32(0x0);
6390 GetSession()->SendPacket(&data);
6391 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6392 data<<duel->opponent->GetGUID();
6393 data<<uint8(0x0);
6394 data<<(uint32)7266;
6395 data<<uint32(0x0);
6396 duel->opponent->GetSession()->SendPacket(&data);*/
6398 //Remove Duel Flag object
6399 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
6400 if(obj)
6401 duel->initiator->RemoveGameObject(obj,true);
6403 /* remove auras */
6404 std::vector<uint32> auras2remove;
6405 AuraMap const& vAuras = duel->opponent->GetAuras();
6406 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6408 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6409 auras2remove.push_back(i->second->GetId());
6412 for(size_t i=0; i<auras2remove.size(); i++)
6413 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6415 auras2remove.clear();
6416 AuraMap const& auras = GetAuras();
6417 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6419 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6420 auras2remove.push_back(i->second->GetId());
6422 for(size_t i=0; i<auras2remove.size(); i++)
6423 RemoveAurasDueToSpell(auras2remove[i]);
6425 // cleanup combo points
6426 if(GetComboTarget()==duel->opponent->GetGUID())
6427 ClearComboPoints();
6428 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6429 ClearComboPoints();
6431 if(duel->opponent->GetComboTarget()==GetGUID())
6432 duel->opponent->ClearComboPoints();
6433 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6434 duel->opponent->ClearComboPoints();
6436 //cleanups
6437 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6438 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6439 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6440 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6442 delete duel->opponent->duel;
6443 duel->opponent->duel = NULL;
6444 delete duel;
6445 duel = NULL;
6448 //---------------------------------------------------------//
6450 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6452 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6453 return;
6455 // not apply/remove mods for broken item
6456 if(item->IsBroken())
6457 return;
6459 ItemPrototype const *proto = item->GetProto();
6461 if(!proto)
6462 return;
6464 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6466 uint32 attacktype = Player::GetAttackBySlot(slot);
6467 if(attacktype < MAX_ATTACK)
6468 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6470 _ApplyItemBonuses(proto,slot,apply);
6472 if( slot==EQUIPMENT_SLOT_RANGED )
6473 _ApplyAmmoBonuses();
6475 ApplyItemEquipSpell(item,apply);
6476 ApplyEnchantment(item, apply);
6478 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6479 CorrectMetaGemEnchants(slot, apply);
6481 sLog.outDebug("_ApplyItemMods complete.");
6484 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6486 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6487 return;
6489 for (int i = 0; i < 10; i++)
6491 uint32 statType = 0;
6492 int32 val = 0;
6494 if(proto->ScalingStatDistribution)
6496 if(ScalingStatDistributionEntry const *ssd = sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution))
6498 statType = ssd->StatMod[i];
6500 if(uint32 modifier = ssd->Modifier[i])
6502 uint32 level = ((getLevel() > ssd->MaxLevel) ? ssd->MaxLevel : getLevel());
6503 if(ScalingStatValuesEntry const *ssv = sScalingStatValuesStore.LookupEntry(level))
6505 int multiplier = ssv->Multiplier[proto->GetScalingStatValuesColumn()];
6506 val = (multiplier * modifier) / 10000;
6511 else
6513 statType = proto->ItemStat[i].ItemStatType;
6514 val = float(proto->ItemStat[i].ItemStatValue);
6517 if(val == 0)
6518 continue;
6520 switch (statType)
6522 case ITEM_MOD_MANA:
6523 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6524 break;
6525 case ITEM_MOD_HEALTH: // modify HP
6526 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6527 break;
6528 case ITEM_MOD_AGILITY: // modify agility
6529 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6530 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6531 break;
6532 case ITEM_MOD_STRENGTH: //modify strength
6533 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6534 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6535 break;
6536 case ITEM_MOD_INTELLECT: //modify intellect
6537 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6538 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6539 break;
6540 case ITEM_MOD_SPIRIT: //modify spirit
6541 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6542 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6543 break;
6544 case ITEM_MOD_STAMINA: //modify stamina
6545 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6546 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6547 break;
6548 case ITEM_MOD_DEFENSE_SKILL_RATING:
6549 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6550 break;
6551 case ITEM_MOD_DODGE_RATING:
6552 ApplyRatingMod(CR_DODGE, int32(val), apply);
6553 break;
6554 case ITEM_MOD_PARRY_RATING:
6555 ApplyRatingMod(CR_PARRY, int32(val), apply);
6556 break;
6557 case ITEM_MOD_BLOCK_RATING:
6558 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6559 break;
6560 case ITEM_MOD_HIT_MELEE_RATING:
6561 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6562 break;
6563 case ITEM_MOD_HIT_RANGED_RATING:
6564 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6565 break;
6566 case ITEM_MOD_HIT_SPELL_RATING:
6567 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6568 break;
6569 case ITEM_MOD_CRIT_MELEE_RATING:
6570 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6571 break;
6572 case ITEM_MOD_CRIT_RANGED_RATING:
6573 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6574 break;
6575 case ITEM_MOD_CRIT_SPELL_RATING:
6576 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6577 break;
6578 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6579 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6580 break;
6581 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6582 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6583 break;
6584 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6585 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6586 break;
6587 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6588 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6589 break;
6590 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6591 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6592 break;
6593 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6594 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6595 break;
6596 case ITEM_MOD_HASTE_MELEE_RATING:
6597 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6598 break;
6599 case ITEM_MOD_HASTE_RANGED_RATING:
6600 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6601 break;
6602 case ITEM_MOD_HASTE_SPELL_RATING:
6603 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6604 break;
6605 case ITEM_MOD_HIT_RATING:
6606 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6607 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6608 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6609 break;
6610 case ITEM_MOD_CRIT_RATING:
6611 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6612 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6613 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6614 break;
6615 case ITEM_MOD_HIT_TAKEN_RATING:
6616 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6617 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6618 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6619 break;
6620 case ITEM_MOD_CRIT_TAKEN_RATING:
6621 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6622 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6623 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6624 break;
6625 case ITEM_MOD_RESILIENCE_RATING:
6626 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6627 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6628 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6629 break;
6630 case ITEM_MOD_HASTE_RATING:
6631 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6632 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6633 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6634 break;
6635 case ITEM_MOD_EXPERTISE_RATING:
6636 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6637 break;
6638 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6639 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6640 break;
6644 if (proto->Armor)
6645 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6647 if (proto->Block)
6648 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6650 if (proto->HolyRes)
6651 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6653 if (proto->FireRes)
6654 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6656 if (proto->NatureRes)
6657 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6659 if (proto->FrostRes)
6660 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6662 if (proto->ShadowRes)
6663 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6665 if (proto->ArcaneRes)
6666 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6668 WeaponAttackType attType = BASE_ATTACK;
6669 float damage = 0.0f;
6671 if( slot == EQUIPMENT_SLOT_RANGED && (
6672 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6673 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6675 attType = RANGED_ATTACK;
6677 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6679 attType = OFF_ATTACK;
6682 if (proto->Damage[0].DamageMin > 0 )
6684 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6685 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6686 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6689 if (proto->Damage[0].DamageMax > 0 )
6691 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6692 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6695 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6696 return;
6698 if (proto->Delay)
6700 if(slot == EQUIPMENT_SLOT_RANGED)
6701 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6702 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6703 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6704 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6705 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6708 if(CanModifyStats() && (damage || proto->Delay))
6709 UpdateDamagePhysical(attType);
6712 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6714 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6715 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6716 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6718 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6719 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6720 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6722 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6723 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6724 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6727 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6729 // generic not weapon specific case processes in aura code
6730 if(aura->GetSpellProto()->EquippedItemClass == -1)
6731 return;
6733 BaseModGroup mod = BASEMOD_END;
6734 switch(attackType)
6736 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6737 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6738 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6739 default: return;
6742 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6744 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6748 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6750 // ignore spell mods for not wands
6751 Modifier const* modifier = aura->GetModifier();
6752 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6753 return;
6755 // generic not weapon specific case processes in aura code
6756 if(aura->GetSpellProto()->EquippedItemClass == -1)
6757 return;
6759 UnitMods unitMod = UNIT_MOD_END;
6760 switch(attackType)
6762 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6763 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6764 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6765 default: return;
6768 UnitModifierType unitModType = TOTAL_VALUE;
6769 switch(modifier->m_auraname)
6771 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6772 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6773 default: return;
6776 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6778 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6782 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6784 if(!item)
6785 return;
6787 ItemPrototype const *proto = item->GetProto();
6788 if(!proto)
6789 return;
6791 for (int i = 0; i < 5; i++)
6793 _Spell const& spellData = proto->Spells[i];
6795 // no spell
6796 if(!spellData.SpellId )
6797 continue;
6799 // wrong triggering type
6800 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6801 continue;
6803 // check if it is valid spell
6804 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6805 if(!spellproto)
6806 continue;
6808 ApplyEquipSpell(spellproto,item,apply,form_change);
6812 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6814 if(apply)
6816 // Cannot be used in this stance/form
6817 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)!=0)
6818 return;
6820 if(form_change) // check aura active state from other form
6822 bool found = false;
6823 for (int k=0; k < 3; ++k)
6825 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6826 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6828 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6830 found = true;
6831 break;
6834 if(found)
6835 break;
6838 if(found) // and skip re-cast already active aura at form change
6839 return;
6842 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6844 CastSpell(this,spellInfo,true,item);
6846 else
6848 if(form_change) // check aura compatibility
6850 // Cannot be used in this stance/form
6851 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==0)
6852 return; // and remove only not compatible at form change
6855 if(item)
6856 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6857 else
6858 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6862 void Player::UpdateEquipSpellsAtFormChange()
6864 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6866 if(m_items[i] && !m_items[i]->IsBroken())
6868 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6869 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6873 // item set bonuses not dependent from item broken state
6874 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6876 ItemSetEffect* eff = ItemSetEff[setindex];
6877 if(!eff)
6878 continue;
6880 for(uint32 y=0;y<8; ++y)
6882 SpellEntry const* spellInfo = eff->spells[y];
6883 if(!spellInfo)
6884 continue;
6886 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6887 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6892 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
6894 if(!item || item->IsBroken())
6895 return;
6897 ItemPrototype const *proto = item->GetProto();
6898 if(!proto)
6899 return;
6901 if (!Target || Target == this )
6902 return;
6904 for (int i = 0; i < 5; i++)
6906 _Spell const& spellData = proto->Spells[i];
6908 // no spell
6909 if(!spellData.SpellId )
6910 continue;
6912 // wrong triggering type
6913 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6914 continue;
6916 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6917 if(!spellInfo)
6919 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6920 continue;
6923 // not allow proc extra attack spell at extra attack
6924 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6925 return;
6927 float chance = spellInfo->procChance;
6929 if(spellData.SpellPPMRate)
6931 uint32 WeaponSpeed = GetAttackTime(attType);
6932 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6934 else if(chance > 100.0f)
6936 chance = GetWeaponProcChance();
6939 if (roll_chance_f(chance))
6940 CastSpell(Target, spellInfo->Id, true, item);
6943 // item combat enchantments
6944 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6946 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6947 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6948 if(!pEnchant) continue;
6949 for (int s=0;s<3;s++)
6951 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6952 continue;
6954 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6955 if (!spellInfo)
6957 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6958 continue;
6961 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6962 if (roll_chance_f(chance))
6964 if(IsPositiveSpell(pEnchant->spellid[s]))
6965 CastSpell(this, pEnchant->spellid[s], true, item);
6966 else
6967 CastSpell(Target, pEnchant->spellid[s], true, item);
6973 void Player::_RemoveAllItemMods()
6975 sLog.outDebug("_RemoveAllItemMods start.");
6977 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6979 if(m_items[i])
6981 ItemPrototype const *proto = m_items[i]->GetProto();
6982 if(!proto)
6983 continue;
6985 // item set bonuses not dependent from item broken state
6986 if(proto->ItemSet)
6987 RemoveItemsSetItem(this,proto);
6989 if(m_items[i]->IsBroken())
6990 continue;
6992 ApplyItemEquipSpell(m_items[i],false);
6993 ApplyEnchantment(m_items[i], false);
6997 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6999 if(m_items[i])
7001 if(m_items[i]->IsBroken())
7002 continue;
7003 ItemPrototype const *proto = m_items[i]->GetProto();
7004 if(!proto)
7005 continue;
7007 uint32 attacktype = Player::GetAttackBySlot(i);
7008 if(attacktype < MAX_ATTACK)
7009 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7011 _ApplyItemBonuses(proto,i, false);
7013 if( i == EQUIPMENT_SLOT_RANGED )
7014 _ApplyAmmoBonuses();
7018 sLog.outDebug("_RemoveAllItemMods complete.");
7021 void Player::_ApplyAllItemMods()
7023 sLog.outDebug("_ApplyAllItemMods start.");
7025 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7027 if(m_items[i])
7029 if(m_items[i]->IsBroken())
7030 continue;
7032 ItemPrototype const *proto = m_items[i]->GetProto();
7033 if(!proto)
7034 continue;
7036 uint32 attacktype = Player::GetAttackBySlot(i);
7037 if(attacktype < MAX_ATTACK)
7038 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7040 _ApplyItemBonuses(proto,i, true);
7042 if( i == EQUIPMENT_SLOT_RANGED )
7043 _ApplyAmmoBonuses();
7047 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7049 if(m_items[i])
7051 ItemPrototype const *proto = m_items[i]->GetProto();
7052 if(!proto)
7053 continue;
7055 // item set bonuses not dependent from item broken state
7056 if(proto->ItemSet)
7057 AddItemsSetItem(this,m_items[i]);
7059 if(m_items[i]->IsBroken())
7060 continue;
7062 ApplyItemEquipSpell(m_items[i],true);
7063 ApplyEnchantment(m_items[i], true);
7067 sLog.outDebug("_ApplyAllItemMods complete.");
7070 void Player::_ApplyAmmoBonuses()
7072 // check ammo
7073 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7074 if(!ammo_id)
7075 return;
7077 float currentAmmoDPS;
7079 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
7080 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7081 currentAmmoDPS = 0.0f;
7082 else
7083 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7085 if(currentAmmoDPS == GetAmmoDPS())
7086 return;
7088 m_ammoDPS = currentAmmoDPS;
7090 if(CanModifyStats())
7091 UpdateDamagePhysical(RANGED_ATTACK);
7094 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7096 if(!ammo_proto)
7097 return false;
7099 // check ranged weapon
7100 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7101 if(!weapon || weapon->IsBroken() )
7102 return false;
7104 ItemPrototype const* weapon_proto = weapon->GetProto();
7105 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7106 return false;
7108 // check ammo ws. weapon compatibility
7109 switch(weapon_proto->SubClass)
7111 case ITEM_SUBCLASS_WEAPON_BOW:
7112 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7113 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7114 return false;
7115 break;
7116 case ITEM_SUBCLASS_WEAPON_GUN:
7117 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7118 return false;
7119 break;
7120 default:
7121 return false;
7124 return true;
7127 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7128 Called by remove insignia spell effect */
7129 void Player::RemovedInsignia(Player* looterPlr)
7131 if (!GetBattleGroundId())
7132 return;
7134 // If not released spirit, do it !
7135 if(m_deathTimer > 0)
7137 m_deathTimer = 0;
7138 BuildPlayerRepop();
7139 RepopAtGraveyard();
7142 Corpse *corpse = GetCorpse();
7143 if (!corpse)
7144 return;
7146 // We have to convert player corpse to bones, not to be able to resurrect there
7147 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7148 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
7149 if (!bones)
7150 return;
7152 // Now we must make bones lootable, and send player loot
7153 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7155 // We store the level of our player in the gold field
7156 // We retrieve this information at Player::SendLoot()
7157 bones->loot.gold = getLevel();
7158 bones->lootRecipient = looterPlr;
7159 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7162 /*Loot type MUST be
7163 1-corpse, go
7164 2-skinning
7165 3-Fishing
7168 void Player::SendLootRelease( uint64 guid )
7170 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7171 data << uint64(guid) << uint8(1);
7172 SendDirectMessage( &data );
7175 void Player::SendLoot(uint64 guid, LootType loot_type)
7177 Loot *loot = 0;
7178 PermissionTypes permission = ALL_PERMISSION;
7180 sLog.outDebug("Player::SendLoot");
7181 if (IS_GAMEOBJECT_GUID(guid))
7183 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7184 GameObject *go =
7185 ObjectAccessor::GetGameObject(*this, guid);
7187 // not check distance for GO in case owned GO (fishing bobber case, for example)
7188 // And permit out of range GO with no owner in case fishing hole
7189 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7191 SendLootRelease(guid);
7192 return;
7195 loot = &go->loot;
7197 if(go->getLootState() == GO_READY)
7199 uint32 lootid = go->GetLootId();
7201 if(lootid)
7203 sLog.outDebug(" if(lootid)");
7204 loot->clear();
7205 loot->FillLoot(lootid, LootTemplates_Gameobject, this);
7208 if(loot_type == LOOT_FISHING)
7209 go->getFishLoot(loot);
7211 go->SetLootState(GO_ACTIVATED);
7214 else if (IS_ITEM_GUID(guid))
7216 Item *item = GetItemByGuid( guid );
7218 if (!item)
7220 SendLootRelease(guid);
7221 return;
7224 if(loot_type == LOOT_DISENCHANTING)
7226 loot = &item->loot;
7228 if(!item->m_lootGenerated)
7230 item->m_lootGenerated = true;
7231 loot->clear();
7232 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this);
7235 else if(loot_type == LOOT_PROSPECTING)
7237 loot = &item->loot;
7239 if(!item->m_lootGenerated)
7241 item->m_lootGenerated = true;
7242 loot->clear();
7243 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this);
7246 else if(loot_type == LOOT_MILLING)
7248 loot = &item->loot;
7250 if(!item->m_lootGenerated)
7252 item->m_lootGenerated = true;
7253 loot->clear();
7254 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this);
7257 else
7259 loot = &item->loot;
7261 if(!item->m_lootGenerated)
7263 item->m_lootGenerated = true;
7264 loot->clear();
7265 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this);
7267 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7271 else if (IS_CORPSE_GUID(guid)) // remove insignia
7273 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7275 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7277 SendLootRelease(guid);
7278 return;
7281 loot = &bones->loot;
7283 if (!bones->lootForBody)
7285 bones->lootForBody = true;
7286 uint32 pLevel = bones->loot.gold;
7287 bones->loot.clear();
7288 // It may need a better formula
7289 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7290 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7293 if (bones->lootRecipient != this)
7294 permission = NONE_PERMISSION;
7296 else
7298 Creature *creature = ObjectAccessor::GetCreature(*this, guid);
7300 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7301 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7303 SendLootRelease(guid);
7304 return;
7307 if(loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7309 SendLootRelease(guid);
7310 return;
7313 loot = &creature->loot;
7315 if(loot_type == LOOT_PICKPOCKETING)
7317 if ( !creature->lootForPickPocketed )
7319 creature->lootForPickPocketed = true;
7320 loot->clear();
7322 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7323 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this);
7325 // Generate extra money for pick pocket loot
7326 const uint32 a = urand(0, creature->getLevel()/2);
7327 const uint32 b = urand(0, getLevel()/2);
7328 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7331 else
7333 // the player whose group may loot the corpse
7334 Player *recipient = creature->GetLootRecipient();
7335 if (!recipient)
7337 creature->SetLootRecipient(this);
7338 recipient = this;
7341 if (creature->lootForPickPocketed)
7343 creature->lootForPickPocketed = false;
7344 loot->clear();
7347 if(!creature->lootForBody)
7349 creature->lootForBody = true;
7350 loot->clear();
7352 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7353 loot->FillLoot(lootid, LootTemplates_Creature, recipient);
7355 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7357 if(Group* group = recipient->GetGroup())
7359 group->UpdateLooterGuid(creature,true);
7361 switch (group->GetLootMethod())
7363 case GROUP_LOOT:
7364 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7365 group->GroupLoot(recipient->GetGUID(), loot, creature);
7366 break;
7367 case NEED_BEFORE_GREED:
7368 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7369 break;
7370 case MASTER_LOOT:
7371 group->MasterLoot(recipient->GetGUID(), loot, creature);
7372 break;
7373 default:
7374 break;
7379 // possible only if creature->lootForBody && loot->empty() at spell cast check
7380 if (loot_type == LOOT_SKINNING)
7382 loot->clear();
7383 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this);
7385 // set group rights only for loot_type != LOOT_SKINNING
7386 else
7388 if(Group* group = GetGroup())
7390 if( group == recipient->GetGroup() )
7392 if(group->GetLootMethod() == FREE_FOR_ALL)
7393 permission = ALL_PERMISSION;
7394 else if(group->GetLooterGuid() == GetGUID())
7396 if(group->GetLootMethod() == MASTER_LOOT)
7397 permission = MASTER_PERMISSION;
7398 else
7399 permission = ALL_PERMISSION;
7401 else
7402 permission = GROUP_PERMISSION;
7404 else
7405 permission = NONE_PERMISSION;
7407 else if(recipient == this)
7408 permission = ALL_PERMISSION;
7409 else
7410 permission = NONE_PERMISSION;
7415 SetLootGUID(guid);
7417 QuestItemList *q_list = 0;
7418 if (permission != NONE_PERMISSION)
7420 QuestItemMap const& lootPlayerQuestItems = loot->GetPlayerQuestItems();
7421 QuestItemMap::const_iterator itr = lootPlayerQuestItems.find(GetGUIDLow());
7422 if (itr == lootPlayerQuestItems.end())
7423 q_list = loot->FillQuestLoot(this);
7424 else
7425 q_list = itr->second;
7428 QuestItemList *ffa_list = 0;
7429 if (permission != NONE_PERMISSION)
7431 QuestItemMap const& lootPlayerFFAItems = loot->GetPlayerFFAItems();
7432 QuestItemMap::const_iterator itr = lootPlayerFFAItems.find(GetGUIDLow());
7433 if (itr == lootPlayerFFAItems.end())
7434 ffa_list = loot->FillFFALoot(this);
7435 else
7436 ffa_list = itr->second;
7439 QuestItemList *conditional_list = 0;
7440 if (permission != NONE_PERMISSION)
7442 QuestItemMap const& lootPlayerNonQuestNonFFAConditionalItems = loot->GetPlayerNonQuestNonFFAConditionalItems();
7443 QuestItemMap::const_iterator itr = lootPlayerNonQuestNonFFAConditionalItems.find(GetGUIDLow());
7444 if (itr == lootPlayerNonQuestNonFFAConditionalItems.end())
7445 conditional_list = loot->FillNonQuestNonFFAConditionalLoot(this);
7446 else
7447 conditional_list = itr->second;
7450 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING, LOOT_INSIGNIA and LOOT_MILLING unsupported by client, sending LOOT_SKINNING instead
7451 if(loot_type == LOOT_PICKPOCKETING || loot_type == LOOT_DISENCHANTING || loot_type == LOOT_PROSPECTING || loot_type == LOOT_INSIGNIA || loot_type == LOOT_MILLING)
7452 loot_type = LOOT_SKINNING;
7454 if(loot_type == LOOT_FISHINGHOLE)
7455 loot_type = LOOT_FISHING;
7457 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7459 data << uint64(guid);
7460 data << uint8(loot_type);
7461 data << LootView(*loot, q_list, ffa_list, conditional_list, this, permission);
7463 SendDirectMessage(&data);
7465 // add 'this' player as one of the players that are looting 'loot'
7466 if (permission != NONE_PERMISSION)
7467 loot->AddLooter(GetGUID());
7469 if ( loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid) )
7470 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7473 void Player::SendNotifyLootMoneyRemoved()
7475 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7476 GetSession()->SendPacket( &data );
7479 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7481 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7482 data << uint8(lootSlot);
7483 GetSession()->SendPacket( &data );
7486 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7488 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7489 data << Field;
7490 data << Value;
7491 GetSession()->SendPacket(&data);
7494 void Player::SendInitWorldStates()
7496 // data depends on zoneid/mapid...
7497 BattleGround* bg = GetBattleGround();
7498 uint16 NumberOfFields = 0;
7499 uint32 mapid = GetMapId();
7500 uint32 zoneid = GetZoneId();
7501 uint32 areaid = GetAreaId();
7502 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7503 // may be exist better way to do this...
7504 switch(zoneid)
7506 case 0:
7507 case 1:
7508 case 4:
7509 case 8:
7510 case 10:
7511 case 11:
7512 case 12:
7513 case 36:
7514 case 38:
7515 case 40:
7516 case 41:
7517 case 51:
7518 case 267:
7519 case 1519:
7520 case 1537:
7521 case 2257:
7522 case 2918:
7523 NumberOfFields = 6;
7524 break;
7525 case 2597:
7526 NumberOfFields = 81;
7527 break;
7528 case 3277:
7529 NumberOfFields = 14;
7530 break;
7531 case 3358:
7532 case 3820:
7533 NumberOfFields = 38;
7534 break;
7535 case 3483:
7536 NumberOfFields = 22;
7537 break;
7538 case 3519:
7539 NumberOfFields = 36;
7540 break;
7541 case 3521:
7542 NumberOfFields = 35;
7543 break;
7544 case 3698:
7545 case 3702:
7546 case 3968:
7547 NumberOfFields = 9;
7548 break;
7549 case 3703:
7550 NumberOfFields = 9;
7551 break;
7552 default:
7553 NumberOfFields = 10;
7554 break;
7557 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7558 data << uint32(mapid); // mapid
7559 data << uint32(zoneid); // zone id
7560 data << uint32(areaid); // area id, new 2.1.0
7561 data << uint16(NumberOfFields); // count of uint64 blocks
7562 data << uint32(0x8d8) << uint32(0x0); // 1
7563 data << uint32(0x8d7) << uint32(0x0); // 2
7564 data << uint32(0x8d6) << uint32(0x0); // 3
7565 data << uint32(0x8d5) << uint32(0x0); // 4
7566 data << uint32(0x8d4) << uint32(0x0); // 5
7567 data << uint32(0x8d3) << uint32(0x0); // 6
7568 if(mapid == 530) // Outland
7570 data << uint32(0x9bf) << uint32(0x0); // 7
7571 data << uint32(0x9bd) << uint32(0xF); // 8
7572 data << uint32(0x9bb) << uint32(0xF); // 9
7574 switch(zoneid)
7576 case 1:
7577 case 11:
7578 case 12:
7579 case 38:
7580 case 40:
7581 case 51:
7582 case 1519:
7583 case 1537:
7584 case 2257:
7585 break;
7586 case 2597: // AV
7587 data << uint32(0x7ae) << uint32(0x1); // 7
7588 data << uint32(0x532) << uint32(0x1); // 8
7589 data << uint32(0x531) << uint32(0x0); // 9
7590 data << uint32(0x52e) << uint32(0x0); // 10
7591 data << uint32(0x571) << uint32(0x0); // 11
7592 data << uint32(0x570) << uint32(0x0); // 12
7593 data << uint32(0x567) << uint32(0x1); // 13
7594 data << uint32(0x566) << uint32(0x1); // 14
7595 data << uint32(0x550) << uint32(0x1); // 15
7596 data << uint32(0x544) << uint32(0x0); // 16
7597 data << uint32(0x536) << uint32(0x0); // 17
7598 data << uint32(0x535) << uint32(0x1); // 18
7599 data << uint32(0x518) << uint32(0x0); // 19
7600 data << uint32(0x517) << uint32(0x0); // 20
7601 data << uint32(0x574) << uint32(0x0); // 21
7602 data << uint32(0x573) << uint32(0x0); // 22
7603 data << uint32(0x572) << uint32(0x0); // 23
7604 data << uint32(0x56f) << uint32(0x0); // 24
7605 data << uint32(0x56e) << uint32(0x0); // 25
7606 data << uint32(0x56d) << uint32(0x0); // 26
7607 data << uint32(0x56c) << uint32(0x0); // 27
7608 data << uint32(0x56b) << uint32(0x0); // 28
7609 data << uint32(0x56a) << uint32(0x1); // 29
7610 data << uint32(0x569) << uint32(0x1); // 30
7611 data << uint32(0x568) << uint32(0x1); // 13
7612 data << uint32(0x565) << uint32(0x0); // 32
7613 data << uint32(0x564) << uint32(0x0); // 33
7614 data << uint32(0x563) << uint32(0x0); // 34
7615 data << uint32(0x562) << uint32(0x0); // 35
7616 data << uint32(0x561) << uint32(0x0); // 36
7617 data << uint32(0x560) << uint32(0x0); // 37
7618 data << uint32(0x55f) << uint32(0x0); // 38
7619 data << uint32(0x55e) << uint32(0x0); // 39
7620 data << uint32(0x55d) << uint32(0x0); // 40
7621 data << uint32(0x3c6) << uint32(0x4); // 41
7622 data << uint32(0x3c4) << uint32(0x6); // 42
7623 data << uint32(0x3c2) << uint32(0x4); // 43
7624 data << uint32(0x516) << uint32(0x1); // 44
7625 data << uint32(0x515) << uint32(0x0); // 45
7626 data << uint32(0x3b6) << uint32(0x6); // 46
7627 data << uint32(0x55c) << uint32(0x0); // 47
7628 data << uint32(0x55b) << uint32(0x0); // 48
7629 data << uint32(0x55a) << uint32(0x0); // 49
7630 data << uint32(0x559) << uint32(0x0); // 50
7631 data << uint32(0x558) << uint32(0x0); // 51
7632 data << uint32(0x557) << uint32(0x0); // 52
7633 data << uint32(0x556) << uint32(0x0); // 53
7634 data << uint32(0x555) << uint32(0x0); // 54
7635 data << uint32(0x554) << uint32(0x1); // 55
7636 data << uint32(0x553) << uint32(0x1); // 56
7637 data << uint32(0x552) << uint32(0x1); // 57
7638 data << uint32(0x551) << uint32(0x1); // 58
7639 data << uint32(0x54f) << uint32(0x0); // 59
7640 data << uint32(0x54e) << uint32(0x0); // 60
7641 data << uint32(0x54d) << uint32(0x1); // 61
7642 data << uint32(0x54c) << uint32(0x0); // 62
7643 data << uint32(0x54b) << uint32(0x0); // 63
7644 data << uint32(0x545) << uint32(0x0); // 64
7645 data << uint32(0x543) << uint32(0x1); // 65
7646 data << uint32(0x542) << uint32(0x0); // 66
7647 data << uint32(0x540) << uint32(0x0); // 67
7648 data << uint32(0x53f) << uint32(0x0); // 68
7649 data << uint32(0x53e) << uint32(0x0); // 69
7650 data << uint32(0x53d) << uint32(0x0); // 70
7651 data << uint32(0x53c) << uint32(0x0); // 71
7652 data << uint32(0x53b) << uint32(0x0); // 72
7653 data << uint32(0x53a) << uint32(0x1); // 73
7654 data << uint32(0x539) << uint32(0x0); // 74
7655 data << uint32(0x538) << uint32(0x0); // 75
7656 data << uint32(0x537) << uint32(0x0); // 76
7657 data << uint32(0x534) << uint32(0x0); // 77
7658 data << uint32(0x533) << uint32(0x0); // 78
7659 data << uint32(0x530) << uint32(0x0); // 79
7660 data << uint32(0x52f) << uint32(0x0); // 80
7661 data << uint32(0x52d) << uint32(0x1); // 81
7662 break;
7663 case 3277: // WS
7664 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7665 bg->FillInitialWorldStates(data);
7666 else
7668 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7669 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7670 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7671 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7672 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7673 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7674 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7675 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7677 break;
7678 case 3358: // AB
7679 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7680 bg->FillInitialWorldStates(data);
7681 else
7683 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7684 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7685 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7686 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7687 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7688 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7689 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7690 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7691 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7692 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7693 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7694 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7695 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7696 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7697 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7698 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7699 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7700 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7701 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7702 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7703 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7704 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7705 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7706 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7707 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7708 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7709 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7710 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7711 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7712 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7713 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7714 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7716 break;
7717 case 3820: // EY
7718 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7719 bg->FillInitialWorldStates(data);
7720 else
7722 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7723 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7724 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7725 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7726 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7727 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7728 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7729 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7730 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7731 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7732 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7733 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7734 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7735 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7736 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7737 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7738 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7739 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7740 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7741 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7742 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7743 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7744 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7745 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7746 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7747 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7748 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7749 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7750 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7751 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7752 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7753 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7754 // and some more ... unknown
7756 break;
7757 case 3483: // Hellfire Peninsula
7758 data << uint32(0x9ba) << uint32(0x1); // 10
7759 data << uint32(0x9b9) << uint32(0x1); // 11
7760 data << uint32(0x9b5) << uint32(0x0); // 12
7761 data << uint32(0x9b4) << uint32(0x1); // 13
7762 data << uint32(0x9b3) << uint32(0x0); // 14
7763 data << uint32(0x9b2) << uint32(0x0); // 15
7764 data << uint32(0x9b1) << uint32(0x1); // 16
7765 data << uint32(0x9b0) << uint32(0x0); // 17
7766 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7767 data << uint32(0x9ac) << uint32(0x0); // 19
7768 data << uint32(0x9a8) << uint32(0x0); // 20
7769 data << uint32(0x9a7) << uint32(0x0); // 21
7770 data << uint32(0x9a6) << uint32(0x1); // 22
7771 break;
7772 case 3519: // Terokkar Forest
7773 data << uint32(0xa41) << uint32(0x0); // 10
7774 data << uint32(0xa40) << uint32(0x14); // 11
7775 data << uint32(0xa3f) << uint32(0x0); // 12
7776 data << uint32(0xa3e) << uint32(0x0); // 13
7777 data << uint32(0xa3d) << uint32(0x5); // 14
7778 data << uint32(0xa3c) << uint32(0x0); // 15
7779 data << uint32(0xa87) << uint32(0x0); // 16
7780 data << uint32(0xa86) << uint32(0x0); // 17
7781 data << uint32(0xa85) << uint32(0x0); // 18
7782 data << uint32(0xa84) << uint32(0x0); // 19
7783 data << uint32(0xa83) << uint32(0x0); // 20
7784 data << uint32(0xa82) << uint32(0x0); // 21
7785 data << uint32(0xa81) << uint32(0x0); // 22
7786 data << uint32(0xa80) << uint32(0x0); // 23
7787 data << uint32(0xa7e) << uint32(0x0); // 24
7788 data << uint32(0xa7d) << uint32(0x0); // 25
7789 data << uint32(0xa7c) << uint32(0x0); // 26
7790 data << uint32(0xa7b) << uint32(0x0); // 27
7791 data << uint32(0xa7a) << uint32(0x0); // 28
7792 data << uint32(0xa79) << uint32(0x0); // 29
7793 data << uint32(0x9d0) << uint32(0x5); // 30
7794 data << uint32(0x9ce) << uint32(0x0); // 31
7795 data << uint32(0x9cd) << uint32(0x0); // 32
7796 data << uint32(0x9cc) << uint32(0x0); // 33
7797 data << uint32(0xa88) << uint32(0x0); // 34
7798 data << uint32(0xad0) << uint32(0x0); // 35
7799 data << uint32(0xacf) << uint32(0x1); // 36
7800 break;
7801 case 3521: // Zangarmarsh
7802 data << uint32(0x9e1) << uint32(0x0); // 10
7803 data << uint32(0x9e0) << uint32(0x0); // 11
7804 data << uint32(0x9df) << uint32(0x0); // 12
7805 data << uint32(0xa5d) << uint32(0x1); // 13
7806 data << uint32(0xa5c) << uint32(0x0); // 14
7807 data << uint32(0xa5b) << uint32(0x1); // 15
7808 data << uint32(0xa5a) << uint32(0x0); // 16
7809 data << uint32(0xa59) << uint32(0x1); // 17
7810 data << uint32(0xa58) << uint32(0x0); // 18
7811 data << uint32(0xa57) << uint32(0x0); // 19
7812 data << uint32(0xa56) << uint32(0x0); // 20
7813 data << uint32(0xa55) << uint32(0x1); // 21
7814 data << uint32(0xa54) << uint32(0x0); // 22
7815 data << uint32(0x9e7) << uint32(0x0); // 23
7816 data << uint32(0x9e6) << uint32(0x0); // 24
7817 data << uint32(0x9e5) << uint32(0x0); // 25
7818 data << uint32(0xa00) << uint32(0x0); // 26
7819 data << uint32(0x9ff) << uint32(0x1); // 27
7820 data << uint32(0x9fe) << uint32(0x0); // 28
7821 data << uint32(0x9fd) << uint32(0x0); // 29
7822 data << uint32(0x9fc) << uint32(0x1); // 30
7823 data << uint32(0x9fb) << uint32(0x0); // 31
7824 data << uint32(0xa62) << uint32(0x0); // 32
7825 data << uint32(0xa61) << uint32(0x1); // 33
7826 data << uint32(0xa60) << uint32(0x1); // 34
7827 data << uint32(0xa5f) << uint32(0x0); // 35
7828 break;
7829 case 3698: // Nagrand Arena
7830 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
7831 bg->FillInitialWorldStates(data);
7832 else
7834 data << uint32(0xa0f) << uint32(0x0); // 7
7835 data << uint32(0xa10) << uint32(0x0); // 8
7836 data << uint32(0xa11) << uint32(0x0); // 9 show
7838 break;
7839 case 3702: // Blade's Edge Arena
7840 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
7841 bg->FillInitialWorldStates(data);
7842 else
7844 data << uint32(0x9f0) << uint32(0x0); // 7 gold
7845 data << uint32(0x9f1) << uint32(0x0); // 8 green
7846 data << uint32(0x9f3) << uint32(0x0); // 9 show
7848 break;
7849 case 3968: // Ruins of Lordaeron
7850 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
7851 bg->FillInitialWorldStates(data);
7852 else
7854 data << uint32(0xbb8) << uint32(0x0); // 7 gold
7855 data << uint32(0xbb9) << uint32(0x0); // 8 green
7856 data << uint32(0xbba) << uint32(0x0); // 9 show
7858 break;
7859 case 3703: // Shattrath City
7860 break;
7861 default:
7862 data << uint32(0x914) << uint32(0x0); // 7
7863 data << uint32(0x913) << uint32(0x0); // 8
7864 data << uint32(0x912) << uint32(0x0); // 9
7865 data << uint32(0x915) << uint32(0x0); // 10
7866 break;
7868 GetSession()->SendPacket(&data);
7871 uint32 Player::GetXPRestBonus(uint32 xp)
7873 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7875 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7876 rested_bonus = xp;
7878 SetRestBonus( GetRestBonus() - rested_bonus);
7880 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7881 return rested_bonus;
7884 void Player::SetBindPoint(uint64 guid)
7886 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7887 data << uint64(guid);
7888 GetSession()->SendPacket( &data );
7891 void Player::SendTalentWipeConfirm(uint64 guid)
7893 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7894 data << uint64(guid);
7895 data << uint32(resetTalentsCost());
7896 GetSession()->SendPacket( &data );
7899 void Player::SendPetSkillWipeConfirm()
7901 Pet* pet = GetPet();
7902 if(!pet)
7903 return;
7904 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7905 data << pet->GetGUID();
7906 data << uint32(pet->resetTalentsCost());
7907 GetSession()->SendPacket( &data );
7910 /*********************************************************/
7911 /*** STORAGE SYSTEM ***/
7912 /*********************************************************/
7914 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7916 assert(i < 3);
7917 if(i < 2 && item)
7919 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7920 return;
7921 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7922 if(charges == 0)
7923 return;
7924 if(charges > 1)
7925 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7926 else if(charges <= 1)
7928 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7929 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7934 void Player::SetSheath( uint32 sheathed )
7936 switch (sheathed)
7938 case SHEATH_STATE_UNARMED: // no prepared weapon
7939 SetVirtualItemSlot(0,NULL);
7940 SetVirtualItemSlot(1,NULL);
7941 SetVirtualItemSlot(2,NULL);
7942 break;
7943 case SHEATH_STATE_MELEE: // prepared melee weapon
7945 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7946 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7947 SetVirtualItemSlot(2,NULL);
7948 }; break;
7949 case SHEATH_STATE_RANGED: // prepared ranged weapon
7950 SetVirtualItemSlot(0,NULL);
7951 SetVirtualItemSlot(1,NULL);
7952 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7953 break;
7954 default:
7955 SetVirtualItemSlot(0,NULL);
7956 SetVirtualItemSlot(1,NULL);
7957 SetVirtualItemSlot(2,NULL);
7958 break;
7960 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
7963 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7965 uint8 pClass = getClass();
7967 uint8 slots[4];
7968 slots[0] = NULL_SLOT;
7969 slots[1] = NULL_SLOT;
7970 slots[2] = NULL_SLOT;
7971 slots[3] = NULL_SLOT;
7972 switch( proto->InventoryType )
7974 case INVTYPE_HEAD:
7975 slots[0] = EQUIPMENT_SLOT_HEAD;
7976 break;
7977 case INVTYPE_NECK:
7978 slots[0] = EQUIPMENT_SLOT_NECK;
7979 break;
7980 case INVTYPE_SHOULDERS:
7981 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7982 break;
7983 case INVTYPE_BODY:
7984 slots[0] = EQUIPMENT_SLOT_BODY;
7985 break;
7986 case INVTYPE_CHEST:
7987 slots[0] = EQUIPMENT_SLOT_CHEST;
7988 break;
7989 case INVTYPE_ROBE:
7990 slots[0] = EQUIPMENT_SLOT_CHEST;
7991 break;
7992 case INVTYPE_WAIST:
7993 slots[0] = EQUIPMENT_SLOT_WAIST;
7994 break;
7995 case INVTYPE_LEGS:
7996 slots[0] = EQUIPMENT_SLOT_LEGS;
7997 break;
7998 case INVTYPE_FEET:
7999 slots[0] = EQUIPMENT_SLOT_FEET;
8000 break;
8001 case INVTYPE_WRISTS:
8002 slots[0] = EQUIPMENT_SLOT_WRISTS;
8003 break;
8004 case INVTYPE_HANDS:
8005 slots[0] = EQUIPMENT_SLOT_HANDS;
8006 break;
8007 case INVTYPE_FINGER:
8008 slots[0] = EQUIPMENT_SLOT_FINGER1;
8009 slots[1] = EQUIPMENT_SLOT_FINGER2;
8010 break;
8011 case INVTYPE_TRINKET:
8012 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8013 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8014 break;
8015 case INVTYPE_CLOAK:
8016 slots[0] = EQUIPMENT_SLOT_BACK;
8017 break;
8018 case INVTYPE_WEAPON:
8020 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8022 // suggest offhand slot only if know dual wielding
8023 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8024 if(CanDualWield())
8025 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8026 break;
8028 case INVTYPE_SHIELD:
8029 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8030 break;
8031 case INVTYPE_RANGED:
8032 slots[0] = EQUIPMENT_SLOT_RANGED;
8033 break;
8034 case INVTYPE_2HWEAPON:
8035 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8036 if (CanDualWield() && CanTitanGrip())
8037 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8038 break;
8039 case INVTYPE_TABARD:
8040 slots[0] = EQUIPMENT_SLOT_TABARD;
8041 break;
8042 case INVTYPE_WEAPONMAINHAND:
8043 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8044 break;
8045 case INVTYPE_WEAPONOFFHAND:
8046 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8047 break;
8048 case INVTYPE_HOLDABLE:
8049 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8050 break;
8051 case INVTYPE_THROWN:
8052 slots[0] = EQUIPMENT_SLOT_RANGED;
8053 break;
8054 case INVTYPE_RANGEDRIGHT:
8055 slots[0] = EQUIPMENT_SLOT_RANGED;
8056 break;
8057 case INVTYPE_BAG:
8058 slots[0] = INVENTORY_SLOT_BAG_1;
8059 slots[1] = INVENTORY_SLOT_BAG_2;
8060 slots[2] = INVENTORY_SLOT_BAG_3;
8061 slots[3] = INVENTORY_SLOT_BAG_4;
8062 break;
8063 case INVTYPE_RELIC:
8065 switch(proto->SubClass)
8067 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8068 if (pClass == CLASS_PALADIN)
8069 slots[0] = EQUIPMENT_SLOT_RANGED;
8070 break;
8071 case ITEM_SUBCLASS_ARMOR_IDOL:
8072 if (pClass == CLASS_DRUID)
8073 slots[0] = EQUIPMENT_SLOT_RANGED;
8074 break;
8075 case ITEM_SUBCLASS_ARMOR_TOTEM:
8076 if (pClass == CLASS_SHAMAN)
8077 slots[0] = EQUIPMENT_SLOT_RANGED;
8078 break;
8079 case ITEM_SUBCLASS_ARMOR_MISC:
8080 if (pClass == CLASS_WARLOCK)
8081 slots[0] = EQUIPMENT_SLOT_RANGED;
8082 break;
8083 case ITEM_SUBCLASS_ARMOR_SIGIL:
8084 if (pClass == CLASS_DEATH_KNIGHT)
8085 slots[0] = EQUIPMENT_SLOT_RANGED;
8086 break;
8088 break;
8090 default :
8091 return NULL_SLOT;
8094 if( slot != NULL_SLOT )
8096 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8098 for (int i = 0; i < 4; i++)
8100 if ( slots[i] == slot )
8101 return slot;
8105 else
8107 // search free slot at first
8108 for (int i = 0; i < 4; i++)
8110 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8112 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8113 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8114 return slots[i];
8118 // if not found free and can swap return first appropriate from used
8119 for (int i = 0; i < 4; i++)
8121 if ( slots[i] != NULL_SLOT && swap )
8122 return slots[i];
8126 // no free position
8127 return NULL_SLOT;
8130 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8132 Item *pItem;
8133 uint32 tempcount = 0;
8135 uint8 res = EQUIP_ERR_OK;
8137 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
8139 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8140 if( pItem && pItem->GetEntry() == item )
8142 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8143 if(ires==EQUIP_ERR_OK)
8145 tempcount += pItem->GetCount();
8146 if( tempcount >= count )
8147 return EQUIP_ERR_OK;
8149 else
8150 res = ires;
8153 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
8155 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8156 if( pItem && pItem->GetEntry() == item )
8158 tempcount += pItem->GetCount();
8159 if( tempcount >= count )
8160 return EQUIP_ERR_OK;
8163 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8165 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8166 if( pItem && pItem->GetEntry() == item )
8168 tempcount += pItem->GetCount();
8169 if( tempcount >= count )
8170 return EQUIP_ERR_OK;
8173 Bag *pBag;
8174 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8176 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8177 if( pBag )
8179 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8181 pItem = GetItemByPos( i, j );
8182 if( pItem && pItem->GetEntry() == item )
8184 tempcount += pItem->GetCount();
8185 if( tempcount >= count )
8186 return EQUIP_ERR_OK;
8192 // not found req. item count and have unequippable items
8193 return res;
8196 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8198 uint32 count = 0;
8199 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8201 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8202 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8203 count += pItem->GetCount();
8205 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8207 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8208 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8209 count += pItem->GetCount();
8211 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8213 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8214 if( pBag )
8215 count += pBag->GetItemCount(item,skipItem);
8218 if(skipItem && skipItem->GetProto()->GemProperties)
8220 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8222 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8223 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8224 count += pItem->GetGemCountWithID(item);
8228 if(inBankAlso)
8230 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8232 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8233 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8234 count += pItem->GetCount();
8236 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8238 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8239 if( pBag )
8240 count += pBag->GetItemCount(item,skipItem);
8243 if(skipItem && skipItem->GetProto()->GemProperties)
8245 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8247 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8248 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8249 count += pItem->GetGemCountWithID(item);
8254 return count;
8257 Item* Player::GetItemByGuid( uint64 guid ) const
8259 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8261 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8262 if( pItem && pItem->GetGUID() == guid )
8263 return pItem;
8265 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8267 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8268 if( pItem && pItem->GetGUID() == guid )
8269 return pItem;
8272 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8274 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8275 if( pBag )
8277 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8279 Item* pItem = pBag->GetItemByPos( j );
8280 if( pItem && pItem->GetGUID() == guid )
8281 return pItem;
8285 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8287 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8288 if( pBag )
8290 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8292 Item* pItem = pBag->GetItemByPos( j );
8293 if( pItem && pItem->GetGUID() == guid )
8294 return pItem;
8299 return NULL;
8302 Item* Player::GetItemByPos( uint16 pos ) const
8304 uint8 bag = pos >> 8;
8305 uint8 slot = pos & 255;
8306 return GetItemByPos( bag, slot );
8309 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8311 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8312 return m_items[slot];
8313 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8314 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8316 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8317 if ( pBag )
8318 return pBag->GetItemByPos(slot);
8320 return NULL;
8323 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8325 uint16 slot;
8326 switch (attackType)
8328 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8329 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8330 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8331 default: return NULL;
8334 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8335 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8336 return NULL;
8338 if(!useable)
8339 return item;
8341 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8342 return NULL;
8344 return item;
8347 Item* Player::GetShield(bool useable) const
8349 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8350 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8351 return NULL;
8353 if(!useable)
8354 return item;
8356 if( item->IsBroken())
8357 return NULL;
8359 return item;
8362 uint32 Player::GetAttackBySlot( uint8 slot )
8364 switch(slot)
8366 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8367 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8368 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8369 default: return MAX_ATTACK;
8373 bool Player::HasBankBagSlot( uint8 slot ) const
8375 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8376 if( slot < maxslot )
8377 return true;
8378 return false;
8381 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8383 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8384 return true;
8385 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8386 return true;
8387 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8388 return true;
8389 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8390 return true;
8391 return false;
8394 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8396 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8397 return true;
8398 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8399 return true;
8400 return false;
8403 bool Player::IsBankPos( uint8 bag, uint8 slot )
8405 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8406 return true;
8407 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8408 return true;
8409 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8410 return true;
8411 return false;
8414 bool Player::IsBagPos( uint16 pos )
8416 uint8 bag = pos >> 8;
8417 uint8 slot = pos & 255;
8418 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8419 return true;
8420 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8421 return true;
8422 return false;
8425 bool Player::IsValidPos( uint8 bag, uint8 slot )
8427 // post selected
8428 if(bag == NULL_BAG)
8429 return true;
8431 if (bag == INVENTORY_SLOT_BAG_0)
8433 // any post selected
8434 if (slot == NULL_SLOT)
8435 return true;
8437 // equipment
8438 if (slot < EQUIPMENT_SLOT_END)
8439 return true;
8441 // bag equip slots
8442 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8443 return true;
8445 // backpack slots
8446 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8447 return true;
8449 // keyring slots
8450 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8451 return true;
8453 // bank main slots
8454 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8455 return true;
8457 // bank bag slots
8458 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8459 return true;
8461 return false;
8464 // bag content slots
8465 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8467 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8468 if(!pBag)
8469 return false;
8471 // any post selected
8472 if (slot == NULL_SLOT)
8473 return true;
8475 return slot < pBag->GetBagSize();
8478 // bank bag content slots
8479 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8481 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8482 if(!pBag)
8483 return false;
8485 // any post selected
8486 if (slot == NULL_SLOT)
8487 return true;
8489 return slot < pBag->GetBagSize();
8492 // where this?
8493 return false;
8497 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8499 uint32 tempcount = 0;
8500 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8502 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8503 if( pItem && pItem->GetEntry() == item )
8505 tempcount += pItem->GetCount();
8506 if( tempcount >= count )
8507 return true;
8510 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8512 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8513 if( pItem && pItem->GetEntry() == item )
8515 tempcount += pItem->GetCount();
8516 if( tempcount >= count )
8517 return true;
8520 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8522 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8524 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8526 Item* pItem = GetItemByPos( i, j );
8527 if( pItem && pItem->GetEntry() == item )
8529 tempcount += pItem->GetCount();
8530 if( tempcount >= count )
8531 return true;
8537 if(inBankAlso)
8539 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8541 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8542 if( pItem && pItem->GetEntry() == item )
8544 tempcount += pItem->GetCount();
8545 if( tempcount >= count )
8546 return true;
8549 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8551 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8553 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8555 Item* pItem = GetItemByPos( i, j );
8556 if( pItem && pItem->GetEntry() == item )
8558 tempcount += pItem->GetCount();
8559 if( tempcount >= count )
8560 return true;
8567 return false;
8570 Item* Player::GetItemOrItemWithGemEquipped( uint32 item ) const
8572 Item *pItem;
8573 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8575 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8576 if( pItem && pItem->GetEntry() == item )
8577 return pItem;
8580 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8581 if (pProto && pProto->GemProperties)
8583 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8585 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8586 if( pItem && pItem->GetProto()->Socket[0].Color )
8588 if (pItem->GetGemCountWithID(item) > 0 )
8589 return pItem;
8594 return NULL;
8597 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8599 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8600 if( !pProto )
8602 if(no_space_count)
8603 *no_space_count = count;
8604 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8607 // no maximum
8608 if(pProto->MaxCount <= 0)
8609 return EQUIP_ERR_OK;
8611 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8613 if (curcount + count > uint32(pProto->MaxCount))
8615 if(no_space_count)
8616 *no_space_count = count +curcount - pProto->MaxCount;
8617 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8620 return EQUIP_ERR_OK;
8623 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8625 Item *pItem;
8626 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8628 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8629 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8630 return true;
8632 for(uint8 i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8634 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8635 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8636 return true;
8638 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8640 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8642 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8644 pItem = GetItemByPos( i, j );
8645 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8646 return true;
8650 return false;
8653 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8655 Item* pItem2 = GetItemByPos( bag, slot );
8657 // ignore move item (this slot will be empty at move)
8658 if(pItem2==pSrcItem)
8659 pItem2 = NULL;
8661 uint32 need_space;
8663 // empty specific slot - check item fit to slot
8664 if( !pItem2 || swap )
8666 if( bag == INVENTORY_SLOT_BAG_0 )
8668 // keyring case
8669 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8670 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8672 // vanitypet case (disabled until proper implement)
8673 if(slot >= VANITYPET_SLOT_START && slot < VANITYPET_SLOT_END && !(false /*pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS*/))
8674 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8676 // currencytoken case (disabled until proper implement)
8677 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(false /*pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS*/))
8678 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8680 // guestbag case (disabled until proper implement)
8681 if(slot >= QUESTBAG_SLOT_START && slot < QUESTBAG_SLOT_END && !(false /*pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS*/))
8682 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8684 // prevent cheating
8685 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8686 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8688 else
8690 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8691 if( !pBag )
8692 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8694 ItemPrototype const* pBagProto = pBag->GetProto();
8695 if( !pBagProto )
8696 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8698 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8699 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8702 // non empty stack with space
8703 need_space = pProto->GetMaxStackSize();
8705 // non empty slot, check item type
8706 else
8708 // check item type
8709 if(pItem2->GetEntry() != pProto->ItemId)
8710 return EQUIP_ERR_ITEM_CANT_STACK;
8712 // check free space
8713 if(pItem2->GetCount() >= pProto->GetMaxStackSize())
8714 return EQUIP_ERR_ITEM_CANT_STACK;
8716 // free stack space or infinity
8717 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8720 if(need_space > count)
8721 need_space = count;
8723 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8724 if(!newPosition.isContainedIn(dest))
8726 dest.push_back(newPosition);
8727 count -= need_space;
8729 return EQUIP_ERR_OK;
8732 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
8734 // skip specific bag already processed in first called _CanStoreItem_InBag
8735 if(bag==skip_bag)
8736 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8738 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8739 if( !pBag )
8740 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8742 ItemPrototype const* pBagProto = pBag->GetProto();
8743 if( !pBagProto )
8744 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8746 // specialized bag mode or non-specilized
8747 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8748 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8750 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8751 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8753 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8755 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8756 if(j==skip_slot)
8757 continue;
8759 Item* pItem2 = GetItemByPos( bag, j );
8761 // ignore move item (this slot will be empty at move)
8762 if(pItem2==pSrcItem)
8763 pItem2 = NULL;
8765 // if merge skip empty, if !merge skip non-empty
8766 if((pItem2!=NULL)!=merge)
8767 continue;
8769 if( pItem2 )
8771 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8773 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8774 if(need_space > count)
8775 need_space = count;
8777 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8778 if(!newPosition.isContainedIn(dest))
8780 dest.push_back(newPosition);
8781 count -= need_space;
8783 if(count==0)
8784 return EQUIP_ERR_OK;
8788 else
8790 uint32 need_space = pProto->GetMaxStackSize();
8791 if(need_space > count)
8792 need_space = count;
8794 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8795 if(!newPosition.isContainedIn(dest))
8797 dest.push_back(newPosition);
8798 count -= need_space;
8800 if(count==0)
8801 return EQUIP_ERR_OK;
8805 return EQUIP_ERR_OK;
8808 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
8810 for(uint32 j = slot_begin; j < slot_end; j++)
8812 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8813 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8814 continue;
8816 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8818 // ignore move item (this slot will be empty at move)
8819 if(pItem2==pSrcItem)
8820 pItem2 = NULL;
8822 // if merge skip empty, if !merge skip non-empty
8823 if((pItem2!=NULL)!=merge)
8824 continue;
8826 if( pItem2 )
8828 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8830 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8831 if(need_space > count)
8832 need_space = count;
8833 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8834 if(!newPosition.isContainedIn(dest))
8836 dest.push_back(newPosition);
8837 count -= need_space;
8839 if(count==0)
8840 return EQUIP_ERR_OK;
8844 else
8846 uint32 need_space = pProto->GetMaxStackSize();
8847 if(need_space > count)
8848 need_space = count;
8850 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8851 if(!newPosition.isContainedIn(dest))
8853 dest.push_back(newPosition);
8854 count -= need_space;
8856 if(count==0)
8857 return EQUIP_ERR_OK;
8861 return EQUIP_ERR_OK;
8864 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8866 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8868 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8869 if( !pProto )
8871 if(no_space_count)
8872 *no_space_count = count;
8873 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8876 if(pItem && pItem->IsBindedNotWith(GetGUID()))
8878 if(no_space_count)
8879 *no_space_count = count;
8880 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8883 // check count of items (skip for auto move for same player from bank)
8884 uint32 no_similar_count = 0; // can't store this amount similar items
8885 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8886 if(res!=EQUIP_ERR_OK)
8888 if(count==no_similar_count)
8890 if(no_space_count)
8891 *no_space_count = no_similar_count;
8892 return res;
8894 count -= no_similar_count;
8897 // in specific slot
8898 if( bag != NULL_BAG && slot != NULL_SLOT )
8900 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8901 if(res!=EQUIP_ERR_OK)
8903 if(no_space_count)
8904 *no_space_count = count + no_similar_count;
8905 return res;
8908 if(count==0)
8910 if(no_similar_count==0)
8911 return EQUIP_ERR_OK;
8913 if(no_space_count)
8914 *no_space_count = count + no_similar_count;
8915 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8919 // not specific slot or have space for partly store only in specific slot
8921 // in specific bag
8922 if( bag != NULL_BAG )
8924 // search stack in bag for merge to
8925 if( pProto->Stackable != 1 )
8927 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8929 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8930 if(res!=EQUIP_ERR_OK)
8932 if(no_space_count)
8933 *no_space_count = count + no_similar_count;
8934 return res;
8937 if(count==0)
8939 if(no_similar_count==0)
8940 return EQUIP_ERR_OK;
8942 if(no_space_count)
8943 *no_space_count = count + no_similar_count;
8944 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8947 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8948 if(res!=EQUIP_ERR_OK)
8950 if(no_space_count)
8951 *no_space_count = count + no_similar_count;
8952 return res;
8955 if(count==0)
8957 if(no_similar_count==0)
8958 return EQUIP_ERR_OK;
8960 if(no_space_count)
8961 *no_space_count = count + no_similar_count;
8962 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8965 else // equipped bag
8967 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8968 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
8969 if(res!=EQUIP_ERR_OK)
8970 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
8972 if(res!=EQUIP_ERR_OK)
8974 if(no_space_count)
8975 *no_space_count = count + no_similar_count;
8976 return res;
8979 if(count==0)
8981 if(no_similar_count==0)
8982 return EQUIP_ERR_OK;
8984 if(no_space_count)
8985 *no_space_count = count + no_similar_count;
8986 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8991 // search free slot in bag for place to
8992 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8994 // search free slot - keyring case
8995 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
8997 uint32 keyringSize = GetMaxKeyringSize();
8998 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
8999 if(res!=EQUIP_ERR_OK)
9001 if(no_space_count)
9002 *no_space_count = count + no_similar_count;
9003 return res;
9006 if(count==0)
9008 if(no_similar_count==0)
9009 return EQUIP_ERR_OK;
9011 if(no_space_count)
9012 *no_space_count = count + no_similar_count;
9013 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9016 /* until proper implementation
9017 else if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9019 res = _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START,VANITYPET_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9020 if(res!=EQUIP_ERR_OK)
9022 if(no_space_count)
9023 *no_space_count = count + no_similar_count;
9024 return res;
9027 if(count==0)
9029 if(no_similar_count==0)
9030 return EQUIP_ERR_OK;
9032 if(no_space_count)
9033 *no_space_count = count + no_similar_count;
9034 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9038 /* until proper implementation
9039 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9041 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9042 if(res!=EQUIP_ERR_OK)
9044 if(no_space_count)
9045 *no_space_count = count + no_similar_count;
9046 return res;
9049 if(count==0)
9051 if(no_similar_count==0)
9052 return EQUIP_ERR_OK;
9054 if(no_space_count)
9055 *no_space_count = count + no_similar_count;
9056 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9060 /* until proper implementation
9061 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9063 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9064 if(res!=EQUIP_ERR_OK)
9066 if(no_space_count)
9067 *no_space_count = count + no_similar_count;
9068 return res;
9071 if(count==0)
9073 if(no_similar_count==0)
9074 return EQUIP_ERR_OK;
9076 if(no_space_count)
9077 *no_space_count = count + no_similar_count;
9078 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9083 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9084 if(res!=EQUIP_ERR_OK)
9086 if(no_space_count)
9087 *no_space_count = count + no_similar_count;
9088 return res;
9091 if(count==0)
9093 if(no_similar_count==0)
9094 return EQUIP_ERR_OK;
9096 if(no_space_count)
9097 *no_space_count = count + no_similar_count;
9098 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9101 else // equipped bag
9103 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9104 if(res!=EQUIP_ERR_OK)
9105 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9107 if(res!=EQUIP_ERR_OK)
9109 if(no_space_count)
9110 *no_space_count = count + no_similar_count;
9111 return res;
9114 if(count==0)
9116 if(no_similar_count==0)
9117 return EQUIP_ERR_OK;
9119 if(no_space_count)
9120 *no_space_count = count + no_similar_count;
9121 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9126 // not specific bag or have space for partly store only in specific bag
9128 // search stack for merge to
9129 if( pProto->Stackable != 1 )
9131 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9132 if(res!=EQUIP_ERR_OK)
9134 if(no_space_count)
9135 *no_space_count = count + no_similar_count;
9136 return res;
9139 if(count==0)
9141 if(no_similar_count==0)
9142 return EQUIP_ERR_OK;
9144 if(no_space_count)
9145 *no_space_count = count + no_similar_count;
9146 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9149 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9150 if(res!=EQUIP_ERR_OK)
9152 if(no_space_count)
9153 *no_space_count = count + no_similar_count;
9154 return res;
9157 if(count==0)
9159 if(no_similar_count==0)
9160 return EQUIP_ERR_OK;
9162 if(no_space_count)
9163 *no_space_count = count + no_similar_count;
9164 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9167 if( pProto->BagFamily )
9169 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9171 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9172 if(res!=EQUIP_ERR_OK)
9173 continue;
9175 if(count==0)
9177 if(no_similar_count==0)
9178 return EQUIP_ERR_OK;
9180 if(no_space_count)
9181 *no_space_count = count + no_similar_count;
9182 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9187 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9189 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9190 if(res!=EQUIP_ERR_OK)
9191 continue;
9193 if(count==0)
9195 if(no_similar_count==0)
9196 return EQUIP_ERR_OK;
9198 if(no_space_count)
9199 *no_space_count = count + no_similar_count;
9200 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9205 // search free slot - special bag case
9206 if( pProto->BagFamily )
9208 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9210 uint32 keyringSize = GetMaxKeyringSize();
9211 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9212 if(res!=EQUIP_ERR_OK)
9214 if(no_space_count)
9215 *no_space_count = count + no_similar_count;
9216 return res;
9219 if(count==0)
9221 if(no_similar_count==0)
9222 return EQUIP_ERR_OK;
9224 if(no_space_count)
9225 *no_space_count = count + no_similar_count;
9226 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9229 /* until proper implementation
9230 else if(false pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9232 res = _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START,VANITYPET_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9233 if(res!=EQUIP_ERR_OK)
9235 if(no_space_count)
9236 *no_space_count = count + no_similar_count;
9237 return res;
9240 if(count==0)
9242 if(no_similar_count==0)
9243 return EQUIP_ERR_OK;
9245 if(no_space_count)
9246 *no_space_count = count + no_similar_count;
9247 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9251 /* until proper implementation
9252 else if(false pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9254 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9255 if(res!=EQUIP_ERR_OK)
9257 if(no_space_count)
9258 *no_space_count = count + no_similar_count;
9259 return res;
9262 if(count==0)
9264 if(no_similar_count==0)
9265 return EQUIP_ERR_OK;
9267 if(no_space_count)
9268 *no_space_count = count + no_similar_count;
9269 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9273 /* until proper implementation
9274 else if(false pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9276 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,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 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9298 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9299 if(res!=EQUIP_ERR_OK)
9300 continue;
9302 if(count==0)
9304 if(no_similar_count==0)
9305 return EQUIP_ERR_OK;
9307 if(no_space_count)
9308 *no_space_count = count + no_similar_count;
9309 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9314 // search free slot
9315 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9316 if(res!=EQUIP_ERR_OK)
9318 if(no_space_count)
9319 *no_space_count = count + no_similar_count;
9320 return res;
9323 if(count==0)
9325 if(no_similar_count==0)
9326 return EQUIP_ERR_OK;
9328 if(no_space_count)
9329 *no_space_count = count + no_similar_count;
9330 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9333 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9335 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9336 if(res!=EQUIP_ERR_OK)
9337 continue;
9339 if(count==0)
9341 if(no_similar_count==0)
9342 return EQUIP_ERR_OK;
9344 if(no_space_count)
9345 *no_space_count = count + no_similar_count;
9346 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9350 if(no_space_count)
9351 *no_space_count = count + no_similar_count;
9353 return EQUIP_ERR_INVENTORY_FULL;
9356 //////////////////////////////////////////////////////////////////////////
9357 uint8 Player::CanStoreItems( Item **pItems,int count) const
9359 Item *pItem2;
9361 // fill space table
9362 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9363 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9364 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9365 int inv_pets[VANITYPET_SLOT_END-VANITYPET_SLOT_START];
9366 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9367 int inv_quests[QUESTBAG_SLOT_END-QUESTBAG_SLOT_START];
9369 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9370 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9371 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9372 memset(inv_pets,0,sizeof(int)*(VANITYPET_SLOT_END-VANITYPET_SLOT_START));
9373 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9374 memset(inv_quests,0,sizeof(int)*(QUESTBAG_SLOT_END-QUESTBAG_SLOT_START));
9376 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
9378 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9380 if (pItem2 && !pItem2->IsInTrade())
9382 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9386 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
9388 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9390 if (pItem2 && !pItem2->IsInTrade())
9392 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9396 for(int i = VANITYPET_SLOT_START; i < VANITYPET_SLOT_END; i++)
9398 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9400 if (pItem2 && !pItem2->IsInTrade())
9402 inv_pets[i-VANITYPET_SLOT_START] = pItem2->GetCount();
9406 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; i++)
9408 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9410 if (pItem2 && !pItem2->IsInTrade())
9412 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9416 for(int i = QUESTBAG_SLOT_START; i < QUESTBAG_SLOT_END; i++)
9418 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9420 if (pItem2 && !pItem2->IsInTrade())
9422 inv_quests[i-QUESTBAG_SLOT_START] = pItem2->GetCount();
9426 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9428 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9430 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9432 pItem2 = GetItemByPos( i, j );
9433 if (pItem2 && !pItem2->IsInTrade())
9435 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9441 // check free space for all items
9442 for (int k=0;k<count;k++)
9444 Item *pItem = pItems[k];
9446 // no item
9447 if (!pItem) continue;
9449 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9450 ItemPrototype const *pProto = pItem->GetProto();
9452 // strange item
9453 if( !pProto )
9454 return EQUIP_ERR_ITEM_NOT_FOUND;
9456 // item it 'bind'
9457 if(pItem->IsBindedNotWith(GetGUID()))
9458 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9460 Bag *pBag;
9461 ItemPrototype const *pBagProto;
9463 // item is 'one item only'
9464 uint8 res = CanTakeMoreSimilarItems(pItem);
9465 if(res != EQUIP_ERR_OK)
9466 return res;
9468 // search stack for merge to
9469 if( pProto->Stackable != 1 )
9471 bool b_found = false;
9473 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
9475 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9476 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9478 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9479 b_found = true;
9480 break;
9483 if (b_found) continue;
9485 for(int t = VANITYPET_SLOT_START; t < VANITYPET_SLOT_END; t++)
9487 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9488 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_pets[t-VANITYPET_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9490 inv_pets[t-VANITYPET_SLOT_START] += pItem->GetCount();
9491 b_found = true;
9492 break;
9495 if (b_found) continue;
9497 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; t++)
9499 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9500 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9502 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9503 b_found = true;
9504 break;
9507 if (b_found) continue;
9509 for(int t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; t++)
9511 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9512 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_quests[t-QUESTBAG_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9514 inv_quests[t-QUESTBAG_SLOT_START] += pItem->GetCount();
9515 b_found = true;
9516 break;
9519 if (b_found) continue;
9521 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9523 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9524 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9526 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9527 b_found = true;
9528 break;
9531 if (b_found) continue;
9533 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9535 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9536 if( pBag )
9538 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9540 pItem2 = GetItemByPos( t, j );
9541 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9543 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9544 b_found = true;
9545 break;
9550 if (b_found) continue;
9553 // special bag case
9554 if( pProto->BagFamily )
9556 bool b_found = false;
9557 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9559 uint32 keyringSize = GetMaxKeyringSize();
9560 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9562 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9564 inv_keys[t-KEYRING_SLOT_START] = 1;
9565 b_found = true;
9566 break;
9571 if (b_found) continue;
9573 /* until proper implementation
9574 if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9576 for(uint32 t = VANITYPET_SLOT_START; t < VANITYPET_SLOT_END; ++t)
9578 if( inv_pets[t-VANITYPET_SLOT_START] == 0 )
9580 inv_pets[t-VANITYPET_SLOT_START] = 1;
9581 b_found = true;
9582 break;
9587 if (b_found) continue;
9589 /* until proper implementation
9590 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9592 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9594 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9596 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9597 b_found = true;
9598 break;
9603 if (b_found) continue;
9605 /* until proper implementation
9606 if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9608 for(uint32 t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; ++t)
9610 if( inv_quests[t-QUESTBAG_SLOT_START] == 0 )
9612 inv_quests[t-QUESTBAG_SLOT_START] = 1;
9613 b_found = true;
9614 break;
9619 if (b_found) continue;
9622 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9624 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9625 if( pBag )
9627 pBagProto = pBag->GetProto();
9629 // not plain container check
9630 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9631 ItemCanGoIntoBag(pProto,pBagProto) )
9633 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9635 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9637 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9638 b_found = true;
9639 break;
9645 if (b_found) continue;
9648 // search free slot
9649 bool b_found = false;
9650 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9652 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9654 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9655 b_found = true;
9656 break;
9659 if (b_found) continue;
9661 // search free slot in bags
9662 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9664 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9665 if( pBag )
9667 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9669 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9671 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9672 b_found = true;
9673 break;
9679 // no free slot found?
9680 if (!b_found)
9681 return EQUIP_ERR_INVENTORY_FULL;
9684 return EQUIP_ERR_OK;
9687 //////////////////////////////////////////////////////////////////////////
9688 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9690 dest = 0;
9691 Item *pItem = Item::CreateItem( item, 1, this );
9692 if( pItem )
9694 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9695 delete pItem;
9696 return result;
9699 return EQUIP_ERR_ITEM_NOT_FOUND;
9702 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9704 dest = 0;
9705 if( pItem )
9707 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9708 ItemPrototype const *pProto = pItem->GetProto();
9709 if( pProto )
9711 // May be here should be more stronger checks; STUNNED checked
9712 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9713 if (not_loading && hasUnitState(UNIT_STAT_STUNNED))
9714 return EQUIP_ERR_YOU_ARE_STUNNED;
9716 if(pItem->IsBindedNotWith(GetGUID()))
9717 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9719 // check count of items (skip for auto move for same player from bank)
9720 uint8 res = CanTakeMoreSimilarItems(pItem);
9721 if(res != EQUIP_ERR_OK)
9722 return res;
9724 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9725 // - combat
9726 // - in-progress arenas
9727 if( !pProto->CanChangeEquipStateInCombat() )
9729 if( isInCombat() )
9730 return EQUIP_ERR_NOT_IN_COMBAT;
9732 if(BattleGround* bg = GetBattleGround())
9733 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9734 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9737 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9738 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9740 if(IsNonMeleeSpellCasted(false))
9741 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9743 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9744 if( eslot == NULL_SLOT )
9745 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9747 uint8 msg = CanUseItem( pItem , not_loading );
9748 if( msg != EQUIP_ERR_OK )
9749 return msg;
9750 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9751 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9753 // check unique-equipped on item
9754 if (pProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
9756 // there is an equip limit on this item
9757 Item* tItem = GetItemOrItemWithGemEquipped(pProto->ItemId);
9758 if (tItem && (!swap || tItem->GetSlot() != eslot ) )
9759 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9762 // check unique-equipped on gems
9763 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
9765 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
9766 if(!enchant_id)
9767 continue;
9768 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
9769 if(!enchantEntry)
9770 continue;
9772 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
9773 if(pGem && (pGem->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED))
9775 Item* tItem = GetItemOrItemWithGemEquipped(enchantEntry->GemID);
9776 if(tItem && (!swap || tItem->GetSlot() != eslot ))
9777 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9781 // check unique-equipped special item classes
9782 if (pProto->Class == ITEM_CLASS_QUIVER)
9784 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9786 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9788 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9790 if( pBagProto->Class==pProto->Class && pBagProto->SubClass==pProto->SubClass &&
9791 (!swap || pBag->GetSlot() != eslot ) )
9793 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9794 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9795 else
9796 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9803 uint32 type = pProto->InventoryType;
9805 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9807 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9809 if(!CanDualWield())
9810 return EQUIP_ERR_CANT_DUAL_WIELD;
9812 else if (type == INVTYPE_2HWEAPON)
9814 if(!CanDualWield() || !CanTitanGrip())
9815 return EQUIP_ERR_CANT_DUAL_WIELD;
9818 if(IsTwoHandUsed())
9819 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9822 // equip two-hand weapon case (with possible unequip 2 items)
9823 if( type == INVTYPE_2HWEAPON )
9825 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9827 if (!CanTitanGrip())
9828 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9830 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9831 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9833 if (!CanTitanGrip())
9835 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9836 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9837 ItemPosCountVec off_dest;
9838 if( offItem && (!not_loading ||
9839 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9840 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
9841 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9844 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9845 return EQUIP_ERR_OK;
9848 if( !swap )
9849 return EQUIP_ERR_ITEM_NOT_FOUND;
9850 else
9851 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9854 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9856 // Applied only to equipped items and bank bags
9857 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9858 return EQUIP_ERR_OK;
9860 Item* pItem = GetItemByPos(pos);
9862 // Applied only to existed equipped item
9863 if( !pItem )
9864 return EQUIP_ERR_OK;
9866 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9868 ItemPrototype const *pProto = pItem->GetProto();
9869 if( !pProto )
9870 return EQUIP_ERR_ITEM_NOT_FOUND;
9872 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9873 // - combat
9874 // - in-progress arenas
9875 if( !pProto->CanChangeEquipStateInCombat() )
9877 if( isInCombat() )
9878 return EQUIP_ERR_NOT_IN_COMBAT;
9880 if(BattleGround* bg = GetBattleGround())
9881 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9882 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9885 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9886 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9888 return EQUIP_ERR_OK;
9891 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9893 if( !pItem )
9894 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9896 uint32 count = pItem->GetCount();
9898 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9899 ItemPrototype const *pProto = pItem->GetProto();
9900 if( !pProto )
9901 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9903 if( pItem->IsBindedNotWith(GetGUID()) )
9904 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9906 // check count of items (skip for auto move for same player from bank)
9907 uint8 res = CanTakeMoreSimilarItems(pItem);
9908 if(res != EQUIP_ERR_OK)
9909 return res;
9911 // in specific slot
9912 if( bag != NULL_BAG && slot != NULL_SLOT )
9914 if( pProto->InventoryType == INVTYPE_BAG )
9916 Bag *pBag = (Bag*)pItem;
9917 if( pBag )
9919 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9921 if( !HasBankBagSlot( slot ) )
9922 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9923 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
9924 return cantuse;
9926 else
9928 if( !pBag->IsEmpty() )
9929 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9933 else
9935 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9936 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9939 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9940 if(res!=EQUIP_ERR_OK)
9941 return res;
9943 if(count==0)
9944 return EQUIP_ERR_OK;
9947 // not specific slot or have space for partly store only in specific slot
9949 // in specific bag
9950 if( bag != NULL_BAG )
9952 if( pProto->InventoryType == INVTYPE_BAG )
9954 Bag *pBag = (Bag*)pItem;
9955 if( pBag && !pBag->IsEmpty() )
9956 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9959 // search stack in bag for merge to
9960 if( pProto->Stackable != 1 )
9962 if( bag == INVENTORY_SLOT_BAG_0 )
9964 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9965 if(res!=EQUIP_ERR_OK)
9966 return res;
9968 if(count==0)
9969 return EQUIP_ERR_OK;
9971 else
9973 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9974 if(res!=EQUIP_ERR_OK)
9975 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9977 if(res!=EQUIP_ERR_OK)
9978 return res;
9980 if(count==0)
9981 return EQUIP_ERR_OK;
9985 // search free slot in bag
9986 if( bag == INVENTORY_SLOT_BAG_0 )
9988 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9989 if(res!=EQUIP_ERR_OK)
9990 return res;
9992 if(count==0)
9993 return EQUIP_ERR_OK;
9995 else
9997 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9998 if(res!=EQUIP_ERR_OK)
9999 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
10001 if(res!=EQUIP_ERR_OK)
10002 return res;
10004 if(count==0)
10005 return EQUIP_ERR_OK;
10009 // not specific bag or have space for partly store only in specific bag
10011 // search stack for merge to
10012 if( pProto->Stackable != 1 )
10014 // in slots
10015 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10016 if(res!=EQUIP_ERR_OK)
10017 return res;
10019 if(count==0)
10020 return EQUIP_ERR_OK;
10022 // in special bags
10023 if( pProto->BagFamily )
10025 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10027 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
10028 if(res!=EQUIP_ERR_OK)
10029 continue;
10031 if(count==0)
10032 return EQUIP_ERR_OK;
10036 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10038 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
10039 if(res!=EQUIP_ERR_OK)
10040 continue;
10042 if(count==0)
10043 return EQUIP_ERR_OK;
10047 // search free place in special bag
10048 if( pProto->BagFamily )
10050 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10052 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
10053 if(res!=EQUIP_ERR_OK)
10054 continue;
10056 if(count==0)
10057 return EQUIP_ERR_OK;
10061 // search free space
10062 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10063 if(res!=EQUIP_ERR_OK)
10064 return res;
10066 if(count==0)
10067 return EQUIP_ERR_OK;
10069 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10071 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
10072 if(res!=EQUIP_ERR_OK)
10073 continue;
10075 if(count==0)
10076 return EQUIP_ERR_OK;
10078 return EQUIP_ERR_BANK_FULL;
10081 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
10083 if( pItem )
10085 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
10086 if( !isAlive() && not_loading )
10087 return EQUIP_ERR_YOU_ARE_DEAD;
10088 //if( isStunned() )
10089 // return EQUIP_ERR_YOU_ARE_STUNNED;
10090 ItemPrototype const *pProto = pItem->GetProto();
10091 if( pProto )
10093 if( pItem->IsBindedNotWith(GetGUID()) )
10094 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10095 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10096 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10097 if( pItem->GetSkill() != 0 )
10099 if( GetSkillValue( pItem->GetSkill() ) == 0 )
10100 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10102 if( pProto->RequiredSkill != 0 )
10104 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10105 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10106 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10107 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10109 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10110 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10111 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
10112 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10113 if( getLevel() < pProto->RequiredLevel )
10114 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10115 return EQUIP_ERR_OK;
10118 return EQUIP_ERR_ITEM_NOT_FOUND;
10121 bool Player::CanUseItem( ItemPrototype const *pProto )
10123 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10125 if( pProto )
10127 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10128 return false;
10129 if( pProto->RequiredSkill != 0 )
10131 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10132 return false;
10133 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10134 return false;
10136 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10137 return false;
10138 if( getLevel() < pProto->RequiredLevel )
10139 return false;
10140 return true;
10142 return false;
10145 uint8 Player::CanUseAmmo( uint32 item ) const
10147 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10148 if( !isAlive() )
10149 return EQUIP_ERR_YOU_ARE_DEAD;
10150 //if( isStunned() )
10151 // return EQUIP_ERR_YOU_ARE_STUNNED;
10152 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
10153 if( pProto )
10155 if( pProto->InventoryType!= INVTYPE_AMMO )
10156 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10157 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10158 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10159 if( pProto->RequiredSkill != 0 )
10161 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10162 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10163 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10164 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10166 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10167 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10168 /*if( GetReputation() < pProto->RequiredReputation )
10169 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10171 if( getLevel() < pProto->RequiredLevel )
10172 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10174 // Requires No Ammo
10175 if(GetDummyAura(46699))
10176 return EQUIP_ERR_BAG_FULL6;
10178 return EQUIP_ERR_OK;
10180 return EQUIP_ERR_ITEM_NOT_FOUND;
10183 void Player::SetAmmo( uint32 item )
10185 if(!item)
10186 return;
10188 // already set
10189 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10190 return;
10192 // check ammo
10193 if(item)
10195 uint8 msg = CanUseAmmo( item );
10196 if( msg != EQUIP_ERR_OK )
10198 SendEquipError( msg, NULL, NULL );
10199 return;
10203 SetUInt32Value(PLAYER_AMMO_ID, item);
10205 _ApplyAmmoBonuses();
10208 void Player::RemoveAmmo()
10210 SetUInt32Value(PLAYER_AMMO_ID, 0);
10212 m_ammoDPS = 0.0f;
10214 if(CanModifyStats())
10215 UpdateDamagePhysical(RANGED_ATTACK);
10218 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10219 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10221 uint32 count = 0;
10222 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10223 count += itr->count;
10225 Item *pItem = Item::CreateItem( item, count, this );
10226 if( pItem )
10228 ItemAddedQuestCheck( item, count );
10229 if(randomPropertyId)
10230 pItem->SetItemRandomProperties(randomPropertyId);
10231 pItem = StoreItem( dest, pItem, update );
10233 return pItem;
10236 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10238 if( !pItem )
10239 return NULL;
10241 Item* lastItem = pItem;
10243 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10245 uint16 pos = itr->pos;
10246 uint32 count = itr->count;
10248 ++itr;
10250 if(itr == dest.end())
10252 lastItem = _StoreItem(pos,pItem,count,false,update);
10253 break;
10256 lastItem = _StoreItem(pos,pItem,count,true,update);
10259 return lastItem;
10262 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10263 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10265 if( !pItem )
10266 return NULL;
10268 uint8 bag = pos >> 8;
10269 uint8 slot = pos & 255;
10271 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10273 Item *pItem2 = GetItemByPos( bag, slot );
10275 if( !pItem2 )
10277 if(clone)
10278 pItem = pItem->CloneItem(count,this);
10279 else
10280 pItem->SetCount(count);
10282 if(!pItem)
10283 return NULL;
10285 if( pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10286 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10287 pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10288 pItem->SetBinding( true );
10290 if( bag == INVENTORY_SLOT_BAG_0 )
10292 m_items[slot] = pItem;
10293 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10294 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10295 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10297 pItem->SetSlot( slot );
10298 pItem->SetContainer( NULL );
10300 if( IsInWorld() && update )
10302 pItem->AddToWorld();
10303 pItem->SendUpdateToPlayer( this );
10306 pItem->SetState(ITEM_CHANGED, this);
10308 else
10310 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10311 if( pBag )
10313 pBag->StoreItem( slot, pItem, update );
10314 if( IsInWorld() && update )
10316 pItem->AddToWorld();
10317 pItem->SendUpdateToPlayer( this );
10319 pItem->SetState(ITEM_CHANGED, this);
10320 pBag->SetState(ITEM_CHANGED, this);
10324 AddEnchantmentDurations(pItem);
10325 AddItemDurations(pItem);
10327 return pItem;
10329 else
10331 if( pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10332 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10333 pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10334 pItem2->SetBinding( true );
10336 pItem2->SetCount( pItem2->GetCount() + count );
10337 if( IsInWorld() && update )
10338 pItem2->SendUpdateToPlayer( this );
10340 if(!clone)
10342 // delete item (it not in any slot currently)
10343 if( IsInWorld() && update )
10345 pItem->RemoveFromWorld();
10346 pItem->DestroyForPlayer( this );
10349 RemoveEnchantmentDurations(pItem);
10350 RemoveItemDurations(pItem);
10352 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10353 pItem->SetState(ITEM_REMOVED, this);
10355 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10356 AddEnchantmentDurations(pItem2);
10358 pItem2->SetState(ITEM_CHANGED, this);
10360 return pItem2;
10364 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10366 Item *pItem = Item::CreateItem( item, 1, this );
10367 if( pItem )
10369 ItemAddedQuestCheck( item, 1 );
10370 Item * retItem = EquipItem( pos, pItem, update );
10372 return retItem;
10374 return NULL;
10377 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10379 if( pItem )
10381 AddEnchantmentDurations(pItem);
10382 AddItemDurations(pItem);
10384 uint8 bag = pos >> 8;
10385 uint8 slot = pos & 255;
10387 Item *pItem2 = GetItemByPos( bag, slot );
10389 if( !pItem2 )
10391 VisualizeItem( slot, pItem);
10393 if(isAlive())
10395 ItemPrototype const *pProto = pItem->GetProto();
10397 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10398 if(pProto && pProto->ItemSet)
10399 AddItemsSetItem(this,pItem);
10401 _ApplyItemMods(pItem, slot, true);
10403 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10405 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10407 if (getClass() == CLASS_ROGUE)
10408 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10410 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10412 if (!spellProto)
10413 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10414 else
10416 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10418 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10419 data << uint64(GetGUID());
10420 data << uint8(1);
10421 data << uint32(cooldownSpell);
10422 data << uint32(0);
10423 GetSession()->SendPacket(&data);
10428 if( IsInWorld() && update )
10430 pItem->AddToWorld();
10431 pItem->SendUpdateToPlayer( this );
10434 ApplyEquipCooldown(pItem);
10436 if( slot == EQUIPMENT_SLOT_MAINHAND )
10437 UpdateExpertise(BASE_ATTACK);
10438 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10439 UpdateExpertise(OFF_ATTACK);
10441 else
10443 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10444 if( IsInWorld() && update )
10445 pItem2->SendUpdateToPlayer( this );
10447 // delete item (it not in any slot currently)
10448 //pItem->DeleteFromDB();
10449 if( IsInWorld() && update )
10451 pItem->RemoveFromWorld();
10452 pItem->DestroyForPlayer( this );
10455 RemoveEnchantmentDurations(pItem);
10456 RemoveItemDurations(pItem);
10458 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10459 pItem->SetState(ITEM_REMOVED, this);
10460 pItem2->SetState(ITEM_CHANGED, this);
10462 ApplyEquipCooldown(pItem2);
10464 return pItem2;
10468 return pItem;
10471 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10473 if( pItem )
10475 AddEnchantmentDurations(pItem);
10476 AddItemDurations(pItem);
10478 uint8 slot = pos & 255;
10479 VisualizeItem( slot, pItem);
10481 if( IsInWorld() )
10483 pItem->AddToWorld();
10484 pItem->SendUpdateToPlayer( this );
10489 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10491 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10492 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10493 // entry // Size: 1
10494 // inspected enchantments // Size: 6
10495 // ? // Size: 5
10496 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10497 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10498 // // = 16
10500 if(pItem)
10502 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10504 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10505 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10507 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10508 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10510 // Use SetInt16Value to prevent set high part to FFFF for negative value
10511 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10512 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10514 else
10516 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10518 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10519 SetUInt32Value(VisibleBase + 0, 0);
10521 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10522 SetUInt32Value(VisibleBase + 1 + i, 0);
10524 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10525 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10529 void Player::VisualizeItem( uint8 slot, Item *pItem)
10531 if(!pItem)
10532 return;
10534 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10535 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10536 pItem->SetBinding( true );
10538 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10540 m_items[slot] = pItem;
10541 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10542 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10543 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10544 pItem->SetSlot( slot );
10545 pItem->SetContainer( NULL );
10547 if( slot < EQUIPMENT_SLOT_END )
10548 SetVisibleItemSlot(slot,pItem);
10550 pItem->SetState(ITEM_CHANGED, this);
10553 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10555 // note: removeitem does not actually change the item
10556 // it only takes the item out of storage temporarily
10557 // note2: if removeitem is to be used for delinking
10558 // the item must be removed from the player's updatequeue
10560 Item *pItem = GetItemByPos( bag, slot );
10561 if( pItem )
10563 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10565 RemoveEnchantmentDurations(pItem);
10566 RemoveItemDurations(pItem);
10568 if( bag == INVENTORY_SLOT_BAG_0 )
10570 if ( slot < INVENTORY_SLOT_BAG_END )
10572 ItemPrototype const *pProto = pItem->GetProto();
10573 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10575 if(pProto && pProto->ItemSet)
10576 RemoveItemsSetItem(this,pProto);
10578 _ApplyItemMods(pItem, slot, false);
10580 // remove item dependent auras and casts (only weapon and armor slots)
10581 if(slot < EQUIPMENT_SLOT_END)
10582 RemoveItemDependentAurasAndCasts(pItem);
10584 // remove held enchantments
10585 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10587 if (pItem->GetItemSuffixFactor())
10589 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10590 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10592 else
10594 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10595 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10600 m_items[slot] = NULL;
10601 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10603 if ( slot < EQUIPMENT_SLOT_END )
10604 SetVisibleItemSlot(slot,NULL);
10606 else
10608 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10609 if( pBag )
10610 pBag->RemoveItem(slot, update);
10612 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10613 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10614 pItem->SetSlot( NULL_SLOT );
10615 if( IsInWorld() && update )
10616 pItem->SendUpdateToPlayer( this );
10618 if( slot == EQUIPMENT_SLOT_MAINHAND )
10619 UpdateExpertise(BASE_ATTACK);
10620 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10621 UpdateExpertise(OFF_ATTACK);
10625 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10626 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10628 if(Item* it = GetItemByPos(bag,slot))
10630 ItemRemovedQuestCheck(it->GetEntry(),it->GetCount());
10631 RemoveItem( bag,slot,update);
10632 it->RemoveFromUpdateQueueOf(this);
10633 if(it->IsInWorld())
10635 it->RemoveFromWorld();
10636 it->DestroyForPlayer( this );
10641 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10642 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10644 // update quest counters
10645 ItemAddedQuestCheck(pItem->GetEntry(),pItem->GetCount());
10647 // store item
10648 Item* pLastItem = StoreItem( dest, pItem, update);
10650 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10651 if(pLastItem==pItem)
10653 // update owner for last item (this can be original item with wrong owner
10654 if(pLastItem->GetOwnerGUID() != GetGUID())
10655 pLastItem->SetOwnerGUID(GetGUID());
10657 // if this original item then it need create record in inventory
10658 // in case trade we already have item in other player inventory
10659 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10663 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10665 Item *pItem = GetItemByPos( bag, slot );
10666 if( pItem )
10668 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10670 // start from destroy contained items (only equipped bag can have its)
10671 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10673 for (int i = 0; i < MAX_BAG_SIZE; i++)
10674 DestroyItem(slot,i,update);
10677 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10678 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10680 RemoveEnchantmentDurations(pItem);
10681 RemoveItemDurations(pItem);
10683 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10685 if( bag == INVENTORY_SLOT_BAG_0 )
10687 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10689 // equipment and equipped bags can have applied bonuses
10690 if ( slot < INVENTORY_SLOT_BAG_END )
10692 ItemPrototype const *pProto = pItem->GetProto();
10694 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10695 if(pProto && pProto->ItemSet)
10696 RemoveItemsSetItem(this,pProto);
10698 _ApplyItemMods(pItem, slot, false);
10701 if ( slot < EQUIPMENT_SLOT_END )
10703 // remove item dependent auras and casts (only weapon and armor slots)
10704 RemoveItemDependentAurasAndCasts(pItem);
10706 // equipment visual show
10707 SetVisibleItemSlot(slot,NULL);
10710 m_items[slot] = NULL;
10712 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10713 pBag->RemoveItem(slot, update);
10715 if( IsInWorld() && update )
10717 pItem->RemoveFromWorld();
10718 pItem->DestroyForPlayer(this);
10721 //pItem->SetOwnerGUID(0);
10722 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10723 pItem->SetSlot( NULL_SLOT );
10724 pItem->SetState(ITEM_REMOVED, this);
10728 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10730 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10731 Item *pItem;
10732 ItemPrototype const *pProto;
10733 uint32 remcount = 0;
10735 // in inventory
10736 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10738 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10739 if( pItem && pItem->GetEntry() == item )
10741 if( pItem->GetCount() + remcount <= count )
10743 // all items in inventory can unequipped
10744 remcount += pItem->GetCount();
10745 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10747 if(remcount >=count)
10748 return;
10750 else
10752 pProto = pItem->GetProto();
10753 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10754 pItem->SetCount( pItem->GetCount() - count + remcount );
10755 if( IsInWorld() & update )
10756 pItem->SendUpdateToPlayer( this );
10757 pItem->SetState(ITEM_CHANGED, this);
10758 return;
10762 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10764 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10765 if( pItem && pItem->GetEntry() == item )
10767 if( pItem->GetCount() + remcount <= count )
10769 // all keys can be unequipped
10770 remcount += pItem->GetCount();
10771 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10773 if(remcount >=count)
10774 return;
10776 else
10778 pProto = pItem->GetProto();
10779 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10780 pItem->SetCount( pItem->GetCount() - count + remcount );
10781 if( IsInWorld() & update )
10782 pItem->SendUpdateToPlayer( this );
10783 pItem->SetState(ITEM_CHANGED, this);
10784 return;
10789 // in inventory bags
10790 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10792 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10794 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10796 pItem = pBag->GetItemByPos(j);
10797 if( pItem && pItem->GetEntry() == item )
10799 // all items in bags can be unequipped
10800 if( pItem->GetCount() + remcount <= count )
10802 remcount += pItem->GetCount();
10803 DestroyItem( i, j, update );
10805 if(remcount >=count)
10806 return;
10808 else
10810 pProto = pItem->GetProto();
10811 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10812 pItem->SetCount( pItem->GetCount() - count + remcount );
10813 if( IsInWorld() && update )
10814 pItem->SendUpdateToPlayer( this );
10815 pItem->SetState(ITEM_CHANGED, this);
10816 return;
10823 // in equipment and bag list
10824 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10826 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10827 if( pItem && pItem->GetEntry() == item )
10829 if( pItem->GetCount() + remcount <= count )
10831 if(!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
10833 remcount += pItem->GetCount();
10834 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10836 if(remcount >=count)
10837 return;
10840 else
10842 pProto = pItem->GetProto();
10843 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10844 pItem->SetCount( pItem->GetCount() - count + remcount );
10845 if( IsInWorld() & update )
10846 pItem->SendUpdateToPlayer( this );
10847 pItem->SetState(ITEM_CHANGED, this);
10848 return;
10854 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10856 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10858 // in inventory
10859 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10861 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10862 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10863 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10865 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10867 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10868 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10869 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10872 // in inventory bags
10873 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10875 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10876 if( pBag )
10878 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10880 Item* pItem = pBag->GetItemByPos(j);
10881 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10882 DestroyItem( i, j, update);
10887 // in equipment and bag list
10888 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10890 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10891 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10892 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10896 void Player::DestroyConjuredItems( bool update )
10898 // used when entering arena
10899 // destroys all conjured items
10900 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10902 // in inventory
10903 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10905 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10906 if( pItem && pItem->GetProto() &&
10907 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10908 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10909 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10912 // in inventory bags
10913 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10915 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10916 if( pBag )
10918 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10920 Item* pItem = pBag->GetItemByPos(j);
10921 if( pItem && pItem->GetProto() &&
10922 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10923 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10924 DestroyItem( i, j, update);
10929 // in equipment and bag list
10930 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10932 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10933 if( pItem && pItem->GetProto() &&
10934 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10935 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10936 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10940 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10942 if(!pItem)
10943 return;
10945 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10947 if( pItem->GetCount() <= count )
10949 count-= pItem->GetCount();
10951 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10953 else
10955 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10956 pItem->SetCount( pItem->GetCount() - count );
10957 count = 0;
10958 if( IsInWorld() & update )
10959 pItem->SendUpdateToPlayer( this );
10960 pItem->SetState(ITEM_CHANGED, this);
10964 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10966 uint8 srcbag = src >> 8;
10967 uint8 srcslot = src & 255;
10969 uint8 dstbag = dst >> 8;
10970 uint8 dstslot = dst & 255;
10972 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10973 if( !pSrcItem )
10975 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10976 return;
10979 // not let split all items (can be only at cheating)
10980 if(pSrcItem->GetCount() == count)
10982 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10983 return;
10986 // not let split more existed items (can be only at cheating)
10987 if(pSrcItem->GetCount() < count)
10989 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10990 return;
10993 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10995 //best error message found for attempting to split while looting
10996 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10997 return;
11000 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
11001 Item *pNewItem = pSrcItem->CloneItem( count, this );
11002 if( !pNewItem )
11004 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11005 return;
11008 if( IsInventoryPos( dst ) )
11010 // change item amount before check (for unique max count check)
11011 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11013 ItemPosCountVec dest;
11014 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
11015 if( msg != EQUIP_ERR_OK )
11017 delete pNewItem;
11018 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11019 SendEquipError( msg, pSrcItem, NULL );
11020 return;
11023 if( IsInWorld() )
11024 pSrcItem->SendUpdateToPlayer( this );
11025 pSrcItem->SetState(ITEM_CHANGED, this);
11026 StoreItem( dest, pNewItem, true);
11028 else if( IsBankPos ( dst ) )
11030 // change item amount before check (for unique max count check)
11031 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11033 ItemPosCountVec dest;
11034 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
11035 if( msg != EQUIP_ERR_OK )
11037 delete pNewItem;
11038 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11039 SendEquipError( msg, pSrcItem, NULL );
11040 return;
11043 if( IsInWorld() )
11044 pSrcItem->SendUpdateToPlayer( this );
11045 pSrcItem->SetState(ITEM_CHANGED, this);
11046 BankItem( dest, pNewItem, true);
11048 else if( IsEquipmentPos ( dst ) )
11050 // change item amount before check (for unique max count check), provide space for splitted items
11051 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11053 uint16 dest;
11054 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
11055 if( msg != EQUIP_ERR_OK )
11057 delete pNewItem;
11058 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11059 SendEquipError( msg, pSrcItem, NULL );
11060 return;
11063 if( IsInWorld() )
11064 pSrcItem->SendUpdateToPlayer( this );
11065 pSrcItem->SetState(ITEM_CHANGED, this);
11066 EquipItem( dest, pNewItem, true);
11067 AutoUnequipOffhandIfNeed();
11071 void Player::SwapItem( uint16 src, uint16 dst )
11073 uint8 srcbag = src >> 8;
11074 uint8 srcslot = src & 255;
11076 uint8 dstbag = dst >> 8;
11077 uint8 dstslot = dst & 255;
11079 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11080 Item *pDstItem = GetItemByPos( dstbag, dstslot );
11082 if( !pSrcItem )
11083 return;
11085 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
11087 if(!isAlive() )
11089 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
11090 return;
11093 if(pSrcItem->m_lootGenerated) // prevent swap looting item
11095 //best error message found for attempting to swap while looting
11096 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
11097 return;
11100 // check unequip potability for equipped items and bank bags
11101 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
11103 // bags can be swapped with empty bag slots
11104 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ));
11105 if(msg != EQUIP_ERR_OK)
11107 SendEquipError( msg, pSrcItem, pDstItem );
11108 return;
11112 // prevent put equipped/bank bag in self
11113 if( IsBagPos ( src ) && srcslot == dstbag)
11115 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11116 return;
11119 if( !pDstItem )
11121 if( IsInventoryPos( dst ) )
11123 ItemPosCountVec dest;
11124 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
11125 if( msg != EQUIP_ERR_OK )
11127 SendEquipError( msg, pSrcItem, NULL );
11128 return;
11131 RemoveItem(srcbag, srcslot, true);
11132 StoreItem( dest, pSrcItem, true);
11134 else if( IsBankPos ( dst ) )
11136 ItemPosCountVec dest;
11137 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11138 if( msg != EQUIP_ERR_OK )
11140 SendEquipError( msg, pSrcItem, NULL );
11141 return;
11144 RemoveItem(srcbag, srcslot, true);
11145 BankItem( dest, pSrcItem, true);
11147 else if( IsEquipmentPos ( dst ) )
11149 uint16 dest;
11150 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11151 if( msg != EQUIP_ERR_OK )
11153 SendEquipError( msg, pSrcItem, NULL );
11154 return;
11157 RemoveItem(srcbag, srcslot, true);
11158 EquipItem( dest, pSrcItem, true);
11159 AutoUnequipOffhandIfNeed();
11162 else // if (!pDstItem)
11164 if(pDstItem->m_lootGenerated) // prevent swap looting item
11166 //best error message found for attempting to swap while looting
11167 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
11168 return;
11171 // check unequip potability for equipped items and bank bags
11172 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11174 // bags can be swapped with empty bag slots
11175 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) );
11176 if(msg != EQUIP_ERR_OK)
11178 SendEquipError( msg, pSrcItem, pDstItem );
11179 return;
11183 // attempt merge to / fill target item
11185 uint8 msg;
11186 ItemPosCountVec sDest;
11187 uint16 eDest;
11188 if( IsInventoryPos( dst ) )
11189 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11190 else if( IsBankPos ( dst ) )
11191 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11192 else if( IsEquipmentPos ( dst ) )
11193 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11194 else
11195 return;
11197 // can be merge/fill
11198 if(msg == EQUIP_ERR_OK)
11200 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11202 RemoveItem(srcbag, srcslot, true);
11204 if( IsInventoryPos( dst ) )
11205 StoreItem( sDest, pSrcItem, true);
11206 else if( IsBankPos ( dst ) )
11207 BankItem( sDest, pSrcItem, true);
11208 else if( IsEquipmentPos ( dst ) )
11210 EquipItem( eDest, pSrcItem, true);
11211 AutoUnequipOffhandIfNeed();
11214 else
11216 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11217 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11218 pSrcItem->SetState(ITEM_CHANGED, this);
11219 pDstItem->SetState(ITEM_CHANGED, this);
11220 if( IsInWorld() )
11222 pSrcItem->SendUpdateToPlayer( this );
11223 pDstItem->SendUpdateToPlayer( this );
11226 return;
11230 // impossible merge/fill, do real swap
11231 uint8 msg;
11233 // check src->dest move possibility
11234 ItemPosCountVec sDest;
11235 uint16 eDest;
11236 if( IsInventoryPos( dst ) )
11237 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11238 else if( IsBankPos( dst ) )
11239 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11240 else if( IsEquipmentPos( dst ) )
11242 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11243 if( msg == EQUIP_ERR_OK )
11244 msg = CanUnequipItem( eDest, true );
11247 if( msg != EQUIP_ERR_OK )
11249 SendEquipError( msg, pSrcItem, pDstItem );
11250 return;
11253 // check dest->src move possibility
11254 ItemPosCountVec sDest2;
11255 uint16 eDest2;
11256 if( IsInventoryPos( src ) )
11257 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11258 else if( IsBankPos( src ) )
11259 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11260 else if( IsEquipmentPos( src ) )
11262 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11263 if( msg == EQUIP_ERR_OK )
11264 msg = CanUnequipItem( eDest2, true);
11267 if( msg != EQUIP_ERR_OK )
11269 SendEquipError( msg, pDstItem, pSrcItem );
11270 return;
11273 // now do moves, remove...
11274 RemoveItem(dstbag, dstslot, false);
11275 RemoveItem(srcbag, srcslot, false);
11277 // add to dest
11278 if( IsInventoryPos( dst ) )
11279 StoreItem(sDest, pSrcItem, true);
11280 else if( IsBankPos( dst ) )
11281 BankItem(sDest, pSrcItem, true);
11282 else if( IsEquipmentPos( dst ) )
11283 EquipItem(eDest, pSrcItem, true);
11285 // add to src
11286 if( IsInventoryPos( src ) )
11287 StoreItem(sDest2, pDstItem, true);
11288 else if( IsBankPos( src ) )
11289 BankItem(sDest2, pDstItem, true);
11290 else if( IsEquipmentPos( src ) )
11291 EquipItem(eDest2, pDstItem, true);
11293 AutoUnequipOffhandIfNeed();
11297 void Player::AddItemToBuyBackSlot( Item *pItem )
11299 if( pItem )
11301 uint32 slot = m_currentBuybackSlot;
11302 // if current back slot non-empty search oldest or free
11303 if(m_items[slot])
11305 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11306 uint32 oldest_slot = BUYBACK_SLOT_START;
11308 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11310 // found empty
11311 if(!m_items[i])
11313 slot = i;
11314 break;
11317 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11319 if(oldest_time > i_time)
11321 oldest_time = i_time;
11322 oldest_slot = i;
11326 // find oldest
11327 slot = oldest_slot;
11330 RemoveItemFromBuyBackSlot( slot, true );
11331 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11333 m_items[slot] = pItem;
11334 time_t base = time(NULL);
11335 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11336 uint32 eslot = slot - BUYBACK_SLOT_START;
11338 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
11339 ItemPrototype const *pProto = pItem->GetProto();
11340 if( pProto )
11341 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11342 else
11343 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11344 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11346 // move to next (for non filled list is move most optimized choice)
11347 if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
11348 ++m_currentBuybackSlot;
11352 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11354 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11355 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11356 return m_items[slot];
11357 return NULL;
11360 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11362 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11363 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11365 Item *pItem = m_items[slot];
11366 if( pItem )
11368 pItem->RemoveFromWorld();
11369 if(del) pItem->SetState(ITEM_REMOVED, this);
11372 m_items[slot] = NULL;
11374 uint32 eslot = slot - BUYBACK_SLOT_START;
11375 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
11376 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11377 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11379 // if current backslot is filled set to now free slot
11380 if(m_items[m_currentBuybackSlot])
11381 m_currentBuybackSlot = slot;
11385 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11387 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg);
11388 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11389 data << uint8(msg);
11391 if(msg)
11393 data << uint64(pItem ? pItem->GetGUID() : 0);
11394 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11395 data << uint8(0); // not 0 there...
11397 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11399 uint32 level = 0;
11401 if(pItem)
11402 if(ItemPrototype const* proto = pItem->GetProto())
11403 level = proto->RequiredLevel;
11405 data << uint32(level); // new 2.4.0
11408 GetSession()->SendPacket(&data);
11411 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11413 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11414 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11415 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11416 data << uint32(item);
11417 if( param > 0 )
11418 data << uint32(param);
11419 data << uint8(msg);
11420 GetSession()->SendPacket(&data);
11423 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11425 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11426 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11427 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11428 data << uint64(guid);
11429 if( param > 0 )
11430 data << uint32(param);
11431 data << uint8(msg);
11432 GetSession()->SendPacket(&data);
11435 void Player::ClearTrade()
11437 tradeGold = 0;
11438 acceptTrade = false;
11439 for(int i = 0; i < TRADE_SLOT_COUNT; i++)
11440 tradeItems[i] = NULL_SLOT;
11443 void Player::TradeCancel(bool sendback)
11445 if(pTrader)
11447 // send yellow "Trade canceled" message to both traders
11448 WorldSession* ws;
11449 ws = GetSession();
11450 if(sendback)
11451 ws->SendCancelTrade();
11452 ws = pTrader->GetSession();
11453 if(!ws->PlayerLogout())
11454 ws->SendCancelTrade();
11456 // cleanup
11457 ClearTrade();
11458 pTrader->ClearTrade();
11459 // prevent loss of reference
11460 pTrader->pTrader = NULL;
11461 pTrader = NULL;
11465 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11467 if(m_itemDuration.empty())
11468 return;
11470 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);
11472 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
11474 Item* item = *itr;
11475 ++itr; // current element can be erased in UpdateDuration
11477 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11478 item->UpdateDuration(this,time);
11482 void Player::UpdateEnchantTime(uint32 time)
11484 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11486 assert(itr->item);
11487 next=itr;
11488 if(!itr->item->GetEnchantmentId(itr->slot))
11490 next = m_enchantDuration.erase(itr);
11492 else if(itr->leftduration <= time)
11494 ApplyEnchantment(itr->item,itr->slot,false,false);
11495 itr->item->ClearEnchantment(itr->slot);
11496 next = m_enchantDuration.erase(itr);
11498 else if(itr->leftduration > time)
11500 itr->leftduration -= time;
11501 ++next;
11506 void Player::AddEnchantmentDurations(Item *item)
11508 for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
11510 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11511 continue;
11513 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11514 if( duration > 0 )
11515 AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
11519 void Player::RemoveEnchantmentDurations(Item *item)
11521 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
11523 if(itr->item == item)
11525 // save duration in item
11526 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
11527 itr = m_enchantDuration.erase(itr);
11529 else
11530 ++itr;
11534 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11536 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11537 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11539 next = itr;
11540 if(itr->slot==slot)
11542 if(itr->item && itr->item->GetEnchantmentId(slot))
11544 // remove from stats
11545 ApplyEnchantment(itr->item,slot,false,false);
11546 // remove visual
11547 itr->item->ClearEnchantment(slot);
11549 // remove from update list
11550 next = m_enchantDuration.erase(itr);
11552 else
11553 ++next;
11556 // remove enchants from inventory items
11557 // NOTE: no need to remove these from stats, since these aren't equipped
11558 // in inventory
11559 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11561 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11562 if( pItem && pItem->GetEnchantmentId(slot) )
11563 pItem->ClearEnchantment(slot);
11566 // in inventory bags
11567 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11569 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11570 if( pBag )
11572 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11574 Item* pItem = pBag->GetItemByPos(j);
11575 if( pItem && pItem->GetEnchantmentId(slot) )
11576 pItem->ClearEnchantment(slot);
11582 // duration == 0 will remove item enchant
11583 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11585 if(!item)
11586 return;
11588 if(slot >= MAX_ENCHANTMENT_SLOT)
11589 return;
11591 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11593 if(itr->item == item && itr->slot == slot)
11595 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
11596 m_enchantDuration.erase(itr);
11597 break;
11600 if(item && duration > 0 )
11602 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
11603 m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
11607 void Player::ApplyEnchantment(Item *item,bool apply)
11609 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11610 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11613 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
11615 if(!item)
11616 return;
11618 if(!item->IsEquipped())
11619 return;
11621 if(slot >= MAX_ENCHANTMENT_SLOT)
11622 return;
11624 uint32 enchant_id = item->GetEnchantmentId(slot);
11625 if(!enchant_id)
11626 return;
11628 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11629 if(!pEnchant)
11630 return;
11632 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11633 return;
11635 for (int s=0; s<3; s++)
11637 uint32 enchant_display_type = pEnchant->type[s];
11638 uint32 enchant_amount = pEnchant->amount[s];
11639 uint32 enchant_spell_id = pEnchant->spellid[s];
11641 switch(enchant_display_type)
11643 case ITEM_ENCHANTMENT_TYPE_NONE:
11644 break;
11645 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11646 // processed in Player::CastItemCombatSpell
11647 break;
11648 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11649 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11650 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11651 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11652 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11653 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11654 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11655 break;
11656 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11657 if(enchant_spell_id)
11659 if(apply)
11661 int32 basepoints = 0;
11662 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11663 if (item->GetItemRandomPropertyId())
11665 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11666 if (item_rand)
11668 // Search enchant_amount
11669 for (int k=0; k<3; k++)
11671 if(item_rand->enchant_id[k] == enchant_id)
11673 basepoints = int32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11674 break;
11679 // Cast custom spell vs all equal basepoints getted from enchant_amount
11680 if (basepoints)
11681 CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
11682 else
11683 CastSpell(this,enchant_spell_id,true,item);
11685 else
11686 RemoveAurasDueToItemSpell(item,enchant_spell_id);
11688 break;
11689 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11690 if (!enchant_amount)
11692 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11693 if(item_rand)
11695 for (int k=0; k<3; k++)
11697 if(item_rand->enchant_id[k] == enchant_id)
11699 enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11700 break;
11706 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11707 break;
11708 case ITEM_ENCHANTMENT_TYPE_STAT:
11710 if (!enchant_amount)
11712 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11713 if(item_rand_suffix)
11715 for (int k=0; k<3; k++)
11717 if(item_rand_suffix->enchant_id[k] == enchant_id)
11719 enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11720 break;
11726 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11727 switch (enchant_spell_id)
11729 case ITEM_MOD_AGILITY:
11730 sLog.outDebug("+ %u AGILITY",enchant_amount);
11731 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11732 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11733 break;
11734 case ITEM_MOD_STRENGTH:
11735 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11736 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11737 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11738 break;
11739 case ITEM_MOD_INTELLECT:
11740 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11741 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11742 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11743 break;
11744 case ITEM_MOD_SPIRIT:
11745 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11746 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11747 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11748 break;
11749 case ITEM_MOD_STAMINA:
11750 sLog.outDebug("+ %u STAMINA",enchant_amount);
11751 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11752 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11753 break;
11754 case ITEM_MOD_DEFENSE_SKILL_RATING:
11755 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11756 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11757 break;
11758 case ITEM_MOD_DODGE_RATING:
11759 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11760 sLog.outDebug("+ %u DODGE", enchant_amount);
11761 break;
11762 case ITEM_MOD_PARRY_RATING:
11763 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11764 sLog.outDebug("+ %u PARRY", enchant_amount);
11765 break;
11766 case ITEM_MOD_BLOCK_RATING:
11767 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11768 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11769 break;
11770 case ITEM_MOD_HIT_MELEE_RATING:
11771 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11772 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11773 break;
11774 case ITEM_MOD_HIT_RANGED_RATING:
11775 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11776 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11777 break;
11778 case ITEM_MOD_HIT_SPELL_RATING:
11779 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11780 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11781 break;
11782 case ITEM_MOD_CRIT_MELEE_RATING:
11783 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11784 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11785 break;
11786 case ITEM_MOD_CRIT_RANGED_RATING:
11787 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11788 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11789 break;
11790 case ITEM_MOD_CRIT_SPELL_RATING:
11791 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11792 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11793 break;
11794 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11795 // in Enchantments
11796 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11797 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11798 // break;
11799 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11800 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11801 // break;
11802 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11803 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11804 // break;
11805 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11806 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11807 // break;
11808 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11809 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11810 // break;
11811 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11812 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11813 // break;
11814 // case ITEM_MOD_HASTE_MELEE_RATING:
11815 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11816 // break;
11817 // case ITEM_MOD_HASTE_RANGED_RATING:
11818 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11819 // break;
11820 case ITEM_MOD_HASTE_SPELL_RATING:
11821 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11822 break;
11823 case ITEM_MOD_HIT_RATING:
11824 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11825 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11826 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11827 sLog.outDebug("+ %u HIT", enchant_amount);
11828 break;
11829 case ITEM_MOD_CRIT_RATING:
11830 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11831 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11832 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11833 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11834 break;
11835 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11836 // case ITEM_MOD_HIT_TAKEN_RATING:
11837 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11838 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11839 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11840 // break;
11841 // case ITEM_MOD_CRIT_TAKEN_RATING:
11842 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11843 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11844 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11845 // break;
11846 case ITEM_MOD_RESILIENCE_RATING:
11847 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11848 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11849 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11850 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11851 break;
11852 case ITEM_MOD_HASTE_RATING:
11853 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11854 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11855 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11856 sLog.outDebug("+ %u HASTE", enchant_amount);
11857 break;
11858 case ITEM_MOD_EXPERTISE_RATING:
11859 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11860 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11861 break;
11862 case ITEM_MOD_ARMOR_PENETRATION_RATING:
11863 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
11864 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
11865 break;
11866 default:
11867 break;
11869 break;
11871 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11873 if(getClass() == CLASS_SHAMAN)
11875 float addValue = 0.0f;
11876 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11878 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11879 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11881 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11883 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11884 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11887 break;
11889 default:
11890 sLog.outError("Unknown item enchantment display type: %d",enchant_display_type);
11891 break;
11892 } /*switch(enchant_display_type)*/
11893 } /*for*/
11895 // visualize enchantment at player and equipped items
11896 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
11898 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
11899 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
11902 if(apply_dur)
11904 if(apply)
11906 // set duration
11907 uint32 duration = item->GetEnchantmentDuration(slot);
11908 if(duration > 0)
11909 AddEnchantmentDuration(item,slot,duration);
11911 else
11913 // duration == 0 will remove EnchantDuration
11914 AddEnchantmentDuration(item,slot,0);
11919 void Player::SendEnchantmentDurations()
11921 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11923 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
11927 void Player::SendItemDurations()
11929 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
11931 (*itr)->SendTimeUpdate(this);
11935 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11937 if(!item) // prevent crash
11938 return;
11940 // last check 2.0.10
11941 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11942 data << GetGUID(); // player GUID
11943 data << uint32(received); // 0=looted, 1=from npc
11944 data << uint32(created); // 0=received, 1=created
11945 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11946 data << (uint8)item->GetBagSlot(); // bagslot
11947 // item slot, but when added to stack: 0xFFFFFFFF
11948 data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
11949 data << uint32(item->GetEntry()); // item id
11950 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11951 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11952 data << uint32(count); // count of items
11953 data << GetItemCount(item->GetEntry()); // count of items in inventory
11955 if (broadcast && GetGroup())
11956 GetGroup()->BroadcastPacket(&data);
11957 else
11958 GetSession()->SendPacket(&data);
11961 /*********************************************************/
11962 /*** QUEST SYSTEM ***/
11963 /*********************************************************/
11965 void Player::PrepareQuestMenu( uint64 guid )
11967 Object *pObject;
11968 QuestRelations* pObjectQR;
11969 QuestRelations* pObjectQIR;
11970 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11971 if( pCreature )
11973 pObject = (Object*)pCreature;
11974 pObjectQR = &objmgr.mCreatureQuestRelations;
11975 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11977 else
11979 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
11980 if( pGameObject )
11982 pObject = (Object*)pGameObject;
11983 pObjectQR = &objmgr.mGOQuestRelations;
11984 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11986 else
11987 return;
11990 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11991 qm.ClearMenu();
11993 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
11995 uint32 quest_id = i->second;
11996 QuestStatus status = GetQuestStatus( quest_id );
11997 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
11998 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11999 else if ( status == QUEST_STATUS_INCOMPLETE )
12000 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
12001 else if (status == QUEST_STATUS_AVAILABLE )
12002 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12005 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
12007 uint32 quest_id = i->second;
12008 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12009 if(!pQuest) continue;
12011 QuestStatus status = GetQuestStatus( quest_id );
12013 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
12014 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
12015 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
12016 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
12020 void Player::SendPreparedQuest( uint64 guid )
12022 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
12023 if( questMenu.Empty() )
12024 return;
12026 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
12028 uint32 status = qmi0.m_qIcon;
12030 // single element case
12031 if ( questMenu.MenuItemCount() == 1 )
12033 // Auto open -- maybe also should verify there is no greeting
12034 uint32 quest_id = qmi0.m_qId;
12035 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12036 if ( pQuest )
12038 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
12039 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
12040 else if( status == DIALOG_STATUS_INCOMPLETE )
12041 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
12042 // Send completable on repeatable quest if player don't have quest
12043 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
12044 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
12045 else
12046 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
12049 // multiply entries
12050 else
12052 QEmote qe;
12053 qe._Delay = 0;
12054 qe._Emote = 0;
12055 std::string title = "";
12056 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12057 if( pCreature )
12059 uint32 textid = pCreature->GetNpcTextId();
12060 GossipText * gossiptext = objmgr.GetGossipText(textid);
12061 if( !gossiptext )
12063 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12064 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12065 title = "";
12067 else
12069 qe = gossiptext->Options[0].Emotes[0];
12071 if(!gossiptext->Options[0].Text_0.empty())
12073 title = gossiptext->Options[0].Text_0;
12075 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12076 if (loc_idx >= 0)
12078 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12079 if (nl)
12081 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12082 title = nl->Text_0[0][loc_idx];
12086 else
12088 title = gossiptext->Options[0].Text_1;
12090 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12091 if (loc_idx >= 0)
12093 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12094 if (nl)
12096 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12097 title = nl->Text_1[0][loc_idx];
12103 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
12107 bool Player::IsActiveQuest( uint32 quest_id ) const
12109 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12111 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12114 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12116 Object *pObject;
12117 QuestRelations* pObjectQR;
12118 QuestRelations* pObjectQIR;
12120 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12121 if( pCreature )
12123 pObject = (Object*)pCreature;
12124 pObjectQR = &objmgr.mCreatureQuestRelations;
12125 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12127 else
12129 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
12130 if( pGameObject )
12132 pObject = (Object*)pGameObject;
12133 pObjectQR = &objmgr.mGOQuestRelations;
12134 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12136 else
12137 return NULL;
12140 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12141 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12143 if (itr->second == nextQuestID)
12144 return objmgr.GetQuestTemplate(nextQuestID);
12147 return NULL;
12150 bool Player::CanSeeStartQuest( Quest const *pQuest )
12152 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12153 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12154 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12155 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12157 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12160 return false;
12163 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12165 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12166 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12167 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12168 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12169 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12170 && SatisfyQuestDay( pQuest, msg );
12173 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12175 if( !SatisfyQuestLog( msg ) )
12176 return false;
12178 uint32 srcitem = pQuest->GetSrcItemId();
12179 if( srcitem > 0 )
12181 uint32 count = pQuest->GetSrcItemCount();
12182 ItemPosCountVec dest;
12183 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12185 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12186 if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12187 return true;
12188 else if( msg != EQUIP_ERR_OK )
12190 SendEquipError( msg, NULL, NULL );
12191 return false;
12194 return true;
12197 bool Player::CanCompleteQuest( uint32 quest_id )
12199 if( quest_id )
12201 QuestStatusData& q_status = mQuestStatus[quest_id];
12202 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12203 return false; // not allow re-complete quest
12205 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12207 if(!qInfo)
12208 return false;
12210 // auto complete quest
12211 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12212 return true;
12214 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12217 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12219 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12221 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12222 return false;
12226 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12228 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12230 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12231 continue;
12233 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12234 return false;
12238 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12239 return false;
12241 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12242 return false;
12244 if ( qInfo->GetRewOrReqMoney() < 0 )
12246 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12247 return false;
12250 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12251 if ( repFacId && GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12252 return false;
12254 return true;
12257 return false;
12260 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12262 // Solve problem that player don't have the quest and try complete it.
12263 // if repeatable she must be able to complete event if player don't have it.
12264 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12265 if( !CanTakeQuest(pQuest, false) )
12266 return false;
12268 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12269 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12270 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12271 return false;
12273 if( !CanRewardQuest(pQuest, false) )
12274 return false;
12276 return true;
12279 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12281 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12282 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12283 return false;
12285 // daily quest can't be rewarded (25 daily quest already completed)
12286 if(!SatisfyQuestDay(pQuest,true))
12287 return false;
12289 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12290 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12291 return false;
12293 // prevent receive reward with quest items in bank
12294 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12296 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12298 if( pQuest->ReqItemCount[i]!= 0 &&
12299 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12301 if(msg)
12302 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12303 return false;
12308 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12309 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12310 return false;
12312 return true;
12315 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12317 // prevent receive reward with quest items in bank or for not completed quest
12318 if(!CanRewardQuest(pQuest,msg))
12319 return false;
12321 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12323 if( pQuest->RewChoiceItemId[reward] )
12325 ItemPosCountVec dest;
12326 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12327 if( res != EQUIP_ERR_OK )
12329 SendEquipError( res, NULL, NULL );
12330 return false;
12335 if ( pQuest->GetRewItemsCount() > 0 )
12337 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12339 if( pQuest->RewItemId[i] )
12341 ItemPosCountVec dest;
12342 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12343 if( res != EQUIP_ERR_OK )
12345 SendEquipError( res, NULL, NULL );
12346 return false;
12352 return true;
12355 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12357 uint16 log_slot = FindQuestSlot( 0 );
12358 assert(log_slot < MAX_QUEST_LOG_SIZE);
12360 uint32 quest_id = pQuest->GetQuestId();
12362 // if not exist then created with set uState==NEW and rewarded=false
12363 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12364 if (questStatusData.uState != QUEST_NEW)
12365 questStatusData.uState = QUEST_CHANGED;
12367 // check for repeatable quests status reset
12368 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12369 questStatusData.m_explored = false;
12371 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12373 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12374 questStatusData.m_itemcount[i] = 0;
12377 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12379 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12380 questStatusData.m_creatureOrGOcount[i] = 0;
12383 GiveQuestSourceItem( pQuest );
12384 AdjustQuestReqItemCount( pQuest );
12386 if( pQuest->GetRepObjectiveFaction() )
12387 SetFactionVisibleForFactionId(pQuest->GetRepObjectiveFaction());
12389 uint32 qtime = 0;
12390 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12392 uint32 limittime = pQuest->GetLimitTime();
12394 // shared timed quest
12395 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12396 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / 1000;
12398 AddTimedQuest( quest_id );
12399 questStatusData.m_timer = limittime * 1000;
12400 qtime = static_cast<uint32>(time(NULL)) + limittime;
12402 else
12403 questStatusData.m_timer = 0;
12405 SetQuestSlot(log_slot, quest_id, qtime);
12407 //starting initial quest script
12408 if(questGiver && pQuest->GetQuestStartScript()!=0)
12409 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12411 UpdateForQuestsGO();
12414 void Player::CompleteQuest( uint32 quest_id )
12416 if( quest_id )
12418 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12420 uint16 log_slot = FindQuestSlot( quest_id );
12421 if( log_slot < MAX_QUEST_LOG_SIZE)
12422 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12424 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12426 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12427 RewardQuest(qInfo,0,this,false);
12428 else
12429 SendQuestComplete( quest_id );
12434 void Player::IncompleteQuest( uint32 quest_id )
12436 if( quest_id )
12438 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12440 uint16 log_slot = FindQuestSlot( quest_id );
12441 if( log_slot < MAX_QUEST_LOG_SIZE)
12442 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12446 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12448 uint32 quest_id = pQuest->GetQuestId();
12450 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; i++ )
12452 if ( pQuest->ReqItemId[i] )
12453 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12456 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12457 // SetTimedQuest( 0 );
12458 m_timedquests.erase(pQuest->GetQuestId());
12460 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12462 if( pQuest->RewChoiceItemId[reward] )
12464 ItemPosCountVec dest;
12465 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12467 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12468 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12473 if ( pQuest->GetRewItemsCount() > 0 )
12475 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12477 if( pQuest->RewItemId[i] )
12479 ItemPosCountVec dest;
12480 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12482 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12483 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12489 RewardReputation( pQuest );
12491 if( pQuest->GetRewSpellCast() > 0 )
12492 CastSpell( this, pQuest->GetRewSpellCast(), true);
12493 else if( pQuest->GetRewSpell() > 0)
12494 CastSpell( this, pQuest->GetRewSpell(), true);
12496 uint16 log_slot = FindQuestSlot( quest_id );
12497 if( log_slot < MAX_QUEST_LOG_SIZE)
12498 SetQuestSlot(log_slot,0);
12500 QuestStatusData& q_status = mQuestStatus[quest_id];
12502 // Not give XP in case already completed once repeatable quest
12503 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12505 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12506 GiveXP( XP , NULL );
12507 else
12508 ModifyMoney( int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)) );
12510 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12511 ModifyMoney( pQuest->GetRewOrReqMoney() );
12513 // honor reward
12514 if(pQuest->GetRewHonorableKills())
12515 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12517 // title reward
12518 if(pQuest->GetCharTitleId())
12520 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12521 SetTitle(titleEntry);
12524 // Send reward mail
12525 if(pQuest->GetRewMailTemplateId())
12527 MailMessageType mailType;
12528 uint32 senderGuidOrEntry;
12529 switch(questGiver->GetTypeId())
12531 case TYPEID_UNIT:
12532 mailType = MAIL_CREATURE;
12533 senderGuidOrEntry = questGiver->GetEntry();
12534 break;
12535 case TYPEID_GAMEOBJECT:
12536 mailType = MAIL_GAMEOBJECT;
12537 senderGuidOrEntry = questGiver->GetEntry();
12538 break;
12539 case TYPEID_ITEM:
12540 mailType = MAIL_ITEM;
12541 senderGuidOrEntry = questGiver->GetEntry();
12542 break;
12543 case TYPEID_PLAYER:
12544 mailType = MAIL_NORMAL;
12545 senderGuidOrEntry = questGiver->GetGUIDLow();
12546 break;
12547 default:
12548 mailType = MAIL_NORMAL;
12549 senderGuidOrEntry = GetGUIDLow();
12550 break;
12553 Loot questMailLoot;
12555 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this);
12557 // fill mail
12558 MailItemsInfo mi; // item list preparing
12560 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.items.size(); ++i)
12562 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12564 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12566 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12567 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12572 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.quest_items.size(); ++i)
12574 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i+questMailLoot.items.size(),this))
12576 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12578 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12579 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12584 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12587 if(pQuest->IsDaily())
12589 SetDailyQuestStatus(quest_id);
12590 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12593 if ( !pQuest->IsRepeatable() )
12594 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12595 else
12596 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12598 q_status.m_rewarded = true;
12600 if(announce)
12601 SendQuestReward( pQuest, XP, questGiver );
12603 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12604 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12605 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST);
12608 void Player::FailQuest( uint32 quest_id )
12610 if( quest_id )
12612 IncompleteQuest( quest_id );
12614 uint16 log_slot = FindQuestSlot( quest_id );
12615 if( log_slot < MAX_QUEST_LOG_SIZE)
12617 SetQuestSlotTimer(log_slot, 1 );
12618 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12620 SendQuestFailed( quest_id );
12624 void Player::FailTimedQuest( uint32 quest_id )
12626 if( quest_id )
12628 QuestStatusData& q_status = mQuestStatus[quest_id];
12630 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12631 q_status.m_timer = 0;
12633 IncompleteQuest( quest_id );
12635 uint16 log_slot = FindQuestSlot( quest_id );
12636 if( log_slot < MAX_QUEST_LOG_SIZE)
12638 SetQuestSlotTimer(log_slot, 1 );
12639 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12641 SendQuestTimerFailed( quest_id );
12645 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12647 int32 zoneOrSort = qInfo->GetZoneOrSort();
12648 int32 skillOrClass = qInfo->GetSkillOrClass();
12650 // skip zone zoneOrSort and 0 case skillOrClass
12651 if( zoneOrSort >= 0 && skillOrClass == 0 )
12652 return true;
12654 int32 questSort = -zoneOrSort;
12655 uint8 reqSortClass = ClassByQuestSort(questSort);
12657 // check class sort cases in zoneOrSort
12658 if( reqSortClass != 0 && getClass() != reqSortClass)
12660 if( msg )
12661 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12662 return false;
12665 // check class
12666 if( skillOrClass < 0 )
12668 uint8 reqClass = -int32(skillOrClass);
12669 if(getClass() != reqClass)
12671 if( msg )
12672 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12673 return false;
12676 // check skill
12677 else if( skillOrClass > 0 )
12679 uint32 reqSkill = skillOrClass;
12680 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12682 if( msg )
12683 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12684 return false;
12688 return true;
12691 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12693 if( getLevel() < qInfo->GetMinLevel() )
12695 if( msg )
12696 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12697 return false;
12699 return true;
12702 bool Player::SatisfyQuestLog( bool msg )
12704 // exist free slot
12705 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12706 return true;
12708 if( msg )
12710 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12711 GetSession()->SendPacket( &data );
12712 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12714 return false;
12717 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12719 // No previous quest (might be first quest in a series)
12720 if( qInfo->prevQuests.empty())
12721 return true;
12723 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12725 uint32 prevId = abs(*iter);
12727 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12728 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12730 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12732 // If any of the positive previous quests completed, return true
12733 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12735 // skip one-from-all exclusive group
12736 if(qPrevInfo->GetExclusiveGroup() >= 0)
12737 return true;
12739 // each-from-all exclusive group ( < 0)
12740 // can be start if only all quests in prev quest exclusive group completed and rewarded
12741 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12742 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12744 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12746 for(; iter != end; ++iter)
12748 uint32 exclude_Id = iter->second;
12750 // skip checked quest id, only state of other quests in group is interesting
12751 if(exclude_Id == prevId)
12752 continue;
12754 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12756 // alternative quest from group also must be completed and rewarded(reported)
12757 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12759 if( msg )
12760 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12761 return false;
12764 return true;
12766 // If any of the negative previous quests active, return true
12767 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12768 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12770 // skip one-from-all exclusive group
12771 if(qPrevInfo->GetExclusiveGroup() >= 0)
12772 return true;
12774 // each-from-all exclusive group ( < 0)
12775 // can be start if only all quests in prev quest exclusive group active
12776 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12777 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12779 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12781 for(; iter != end; ++iter)
12783 uint32 exclude_Id = iter->second;
12785 // skip checked quest id, only state of other quests in group is interesting
12786 if(exclude_Id == prevId)
12787 continue;
12789 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12791 // alternative quest from group also must be active
12792 if( i_exstatus == mQuestStatus.end() ||
12793 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12794 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12796 if( msg )
12797 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12798 return false;
12801 return true;
12806 // Has only positive prev. quests in non-rewarded state
12807 // and negative prev. quests in non-active state
12808 if( msg )
12809 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12811 return false;
12814 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12816 uint32 reqraces = qInfo->GetRequiredRaces();
12817 if ( reqraces == 0 )
12818 return true;
12819 if( (reqraces & getRaceMask()) == 0 )
12821 if( msg )
12822 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12823 return false;
12825 return true;
12828 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12830 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12831 if(fIdMin && GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12833 if( msg )
12834 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12835 return false;
12838 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12839 if(fIdMax && GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12841 if( msg )
12842 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12843 return false;
12846 return true;
12849 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12851 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12852 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12854 if( msg )
12855 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12856 return false;
12858 return true;
12861 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12863 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12865 if( msg )
12866 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12867 return false;
12869 return true;
12872 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12874 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12875 if(qInfo->GetExclusiveGroup() <= 0)
12876 return true;
12878 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12879 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12881 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12883 for(; iter != end; ++iter)
12885 uint32 exclude_Id = iter->second;
12887 // skip checked quest id, only state of other quests in group is interesting
12888 if(exclude_Id == qInfo->GetQuestId())
12889 continue;
12891 // not allow have daily quest if daily quest from exclusive group already recently completed
12892 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
12893 if( !SatisfyQuestDay(Nquest, false) )
12895 if( msg )
12896 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12897 return false;
12900 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12902 // alternative quest already started or completed
12903 if( i_exstatus != mQuestStatus.end()
12904 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12906 if( msg )
12907 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12908 return false;
12911 return true;
12914 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12916 if(!qInfo->GetNextQuestInChain())
12917 return true;
12919 // next quest in chain already started or completed
12920 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12921 if( itr != mQuestStatus.end()
12922 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12924 if( msg )
12925 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12926 return false;
12929 // check for all quests further up the chain
12930 // only necessary if there are quest chains with more than one quest that can be skipped
12931 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12932 return true;
12935 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12937 // No previous quest in chain
12938 if( qInfo->prevChainQuests.empty())
12939 return true;
12941 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12943 uint32 prevId = *iter;
12945 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12947 if( i_prevstatus != mQuestStatus.end() )
12949 // If any of the previous quests in chain active, return false
12950 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12951 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12953 if( msg )
12954 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12955 return false;
12959 // check for all quests further down the chain
12960 // only necessary if there are quest chains with more than one quest that can be skipped
12961 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12962 // return false;
12965 // No previous quest in chain active
12966 return true;
12969 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12971 if(!qInfo->IsDaily())
12972 return true;
12974 bool have_slot = false;
12975 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12977 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12978 if(qInfo->GetQuestId()==id)
12979 return false;
12981 if(!id)
12982 have_slot = true;
12985 if(!have_slot)
12987 if( msg )
12988 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
12989 return false;
12992 return true;
12995 bool Player::GiveQuestSourceItem( Quest const *pQuest )
12997 uint32 srcitem = pQuest->GetSrcItemId();
12998 if( srcitem > 0 )
13000 uint32 count = pQuest->GetSrcItemCount();
13001 if( count <= 0 )
13002 count = 1;
13004 ItemPosCountVec dest;
13005 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13006 if( msg == EQUIP_ERR_OK )
13008 Item * item = StoreNewItem(dest, srcitem, true);
13009 SendNewItem(item, count, true, false);
13010 return true;
13012 // player already have max amount required item, just report success
13013 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13014 return true;
13015 else
13016 SendEquipError( msg, NULL, NULL );
13017 return false;
13020 return true;
13023 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13025 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13026 if( qInfo )
13028 uint32 srcitem = qInfo->GetSrcItemId();
13029 if( srcitem > 0 )
13031 uint32 count = qInfo->GetSrcItemCount();
13032 if( count <= 0 )
13033 count = 1;
13035 // exist one case when destroy source quest item not possible:
13036 // non un-equippable item (equipped non-empty bag, for example)
13037 uint8 res = CanUnequipItems(srcitem,count);
13038 if(res != EQUIP_ERR_OK)
13040 if(msg)
13041 SendEquipError( res, NULL, NULL );
13042 return false;
13045 DestroyItemCount(srcitem, count, true, true);
13048 return true;
13051 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13053 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13054 if( qInfo )
13056 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13057 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13058 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13059 && !qInfo->IsRepeatable() )
13060 return itr->second.m_rewarded;
13062 return false;
13064 return false;
13067 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13069 if( quest_id )
13071 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13072 if( itr != mQuestStatus.end() )
13073 return itr->second.m_status;
13075 return QUEST_STATUS_NONE;
13078 bool Player::CanShareQuest(uint32 quest_id) const
13080 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13081 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13083 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13084 if( itr != mQuestStatus.end() )
13085 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13087 return false;
13090 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
13092 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13093 if( qInfo )
13095 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
13097 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13098 m_timedquests.erase(qInfo->GetQuestId());
13101 QuestStatusData& q_status = mQuestStatus[quest_id];
13103 q_status.m_status = status;
13104 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13107 UpdateForQuestsGO();
13110 // not used in MaNGOS, but used in scripting code
13111 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13113 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13114 if( !qInfo )
13115 return 0;
13117 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13118 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13119 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13121 return 0;
13124 void Player::AdjustQuestReqItemCount( Quest const* pQuest )
13126 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13128 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
13130 uint32 reqitemcount = pQuest->ReqItemCount[i];
13131 if( reqitemcount != 0 )
13133 uint32 quest_id = pQuest->GetQuestId();
13134 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13136 QuestStatusData& q_status = mQuestStatus[quest_id];
13137 q_status.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13138 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13144 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13146 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13147 if ( GetQuestSlotQuestId(i) == quest_id )
13148 return i;
13150 return MAX_QUEST_LOG_SIZE;
13153 void Player::AreaExploredOrEventHappens( uint32 questId )
13155 if( questId )
13157 uint16 log_slot = FindQuestSlot( questId );
13158 if( log_slot < MAX_QUEST_LOG_SIZE)
13160 QuestStatusData& q_status = mQuestStatus[questId];
13162 if(!q_status.m_explored)
13164 q_status.m_explored = true;
13165 if (q_status.uState != QUEST_NEW)
13166 q_status.uState = QUEST_CHANGED;
13169 if( CanCompleteQuest( questId ) )
13170 CompleteQuest( questId );
13174 //not used in mangosd, function for external script library
13175 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13177 if( Group *pGroup = GetGroup() )
13179 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13181 Player *pGroupGuy = itr->getSource();
13183 // for any leave or dead (with not released body) group member at appropriate distance
13184 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13185 pGroupGuy->AreaExploredOrEventHappens(questId);
13188 else
13189 AreaExploredOrEventHappens(questId);
13192 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13194 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13196 uint32 questid = GetQuestSlotQuestId(i);
13197 if ( questid == 0 )
13198 continue;
13200 QuestStatusData& q_status = mQuestStatus[questid];
13202 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13203 continue;
13205 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13206 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13207 continue;
13209 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13211 uint32 reqitem = qInfo->ReqItemId[j];
13212 if ( reqitem == entry )
13214 uint32 reqitemcount = qInfo->ReqItemCount[j];
13215 uint32 curitemcount = q_status.m_itemcount[j];
13216 if ( curitemcount < reqitemcount )
13218 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13219 q_status.m_itemcount[j] += additemcount;
13220 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13222 SendQuestUpdateAddItem( qInfo, j, additemcount );
13224 if ( CanCompleteQuest( questid ) )
13225 CompleteQuest( questid );
13226 return;
13230 UpdateForQuestsGO();
13231 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
13234 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13236 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13238 uint32 questid = GetQuestSlotQuestId(i);
13239 if(!questid)
13240 continue;
13241 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13242 if ( !qInfo )
13243 continue;
13244 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13245 continue;
13247 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13249 uint32 reqitem = qInfo->ReqItemId[j];
13250 if ( reqitem == entry )
13252 QuestStatusData& q_status = mQuestStatus[questid];
13254 uint32 reqitemcount = qInfo->ReqItemCount[j];
13255 uint32 curitemcount;
13256 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13257 curitemcount = q_status.m_itemcount[j];
13258 else
13259 curitemcount = GetItemCount(entry,true);
13260 if ( curitemcount < reqitemcount + count )
13262 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13263 q_status.m_itemcount[j] = curitemcount - remitemcount;
13264 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13266 IncompleteQuest( questid );
13268 return;
13272 UpdateForQuestsGO();
13275 void Player::KilledMonster( uint32 entry, uint64 guid )
13277 uint32 addkillcount = 1;
13278 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13279 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13281 uint32 questid = GetQuestSlotQuestId(i);
13282 if(!questid)
13283 continue;
13285 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13286 if( !qInfo )
13287 continue;
13288 // just if !ingroup || !noraidgroup || raidgroup
13289 QuestStatusData& q_status = mQuestStatus[questid];
13290 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13292 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13294 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13296 // skip GO activate objective or none
13297 if(qInfo->ReqCreatureOrGOId[j] <=0)
13298 continue;
13300 // skip Cast at creature objective
13301 if(qInfo->ReqSpell[j] !=0 )
13302 continue;
13304 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13306 if ( reqkill == entry )
13308 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13309 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13310 if ( curkillcount < reqkillcount )
13312 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13313 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13315 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13317 if ( CanCompleteQuest( questid ) )
13318 CompleteQuest( questid );
13320 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13321 continue;
13329 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13331 bool isCreature = IS_CREATURE_GUID(guid);
13333 uint32 addCastCount = 1;
13334 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13336 uint32 questid = GetQuestSlotQuestId(i);
13337 if(!questid)
13338 continue;
13340 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13341 if ( !qInfo )
13342 continue;
13344 QuestStatusData& q_status = mQuestStatus[questid];
13346 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13348 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13350 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13352 // skip kill creature objective (0) or wrong spell casts
13353 if(qInfo->ReqSpell[j] != spell_id )
13354 continue;
13356 uint32 reqTarget = 0;
13358 if(isCreature)
13360 // creature activate objectives
13361 if(qInfo->ReqCreatureOrGOId[j] > 0)
13362 // checked at quest_template loading
13363 reqTarget = qInfo->ReqCreatureOrGOId[j];
13365 else
13367 // GO activate objective
13368 if(qInfo->ReqCreatureOrGOId[j] < 0)
13369 // checked at quest_template loading
13370 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13373 // other not this creature/GO related objectives
13374 if( reqTarget != entry )
13375 continue;
13377 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13378 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13379 if ( curCastCount < reqCastCount )
13381 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13382 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13384 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13387 if ( CanCompleteQuest( questid ) )
13388 CompleteQuest( questid );
13390 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13391 break;
13398 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13400 uint32 addTalkCount = 1;
13401 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13403 uint32 questid = GetQuestSlotQuestId(i);
13404 if(!questid)
13405 continue;
13407 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13408 if ( !qInfo )
13409 continue;
13411 QuestStatusData& q_status = mQuestStatus[questid];
13413 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13415 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13417 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13419 // skip spell casts and Gameobject objectives
13420 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13421 continue;
13423 uint32 reqTarget = 0;
13425 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13426 // checked at quest_template loading
13427 reqTarget = qInfo->ReqCreatureOrGOId[j];
13428 else
13429 continue;
13431 if ( reqTarget == entry )
13433 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13434 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13435 if ( curTalkCount < reqTalkCount )
13437 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13438 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13440 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13442 if ( CanCompleteQuest( questid ) )
13443 CompleteQuest( questid );
13445 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13446 continue;
13454 void Player::MoneyChanged( uint32 count )
13456 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13458 uint32 questid = GetQuestSlotQuestId(i);
13459 if (!questid)
13460 continue;
13462 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13463 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13465 QuestStatusData& q_status = mQuestStatus[questid];
13467 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13469 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13471 if ( CanCompleteQuest( questid ) )
13472 CompleteQuest( questid );
13475 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13477 if(int32(count) < -qInfo->GetRewOrReqMoney())
13478 IncompleteQuest( questid );
13484 bool Player::HasQuestForItem( uint32 itemid ) const
13486 for( QuestStatusMap::const_iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
13488 QuestStatusData const& q_status = i->second;
13490 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13492 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
13493 if(!qinfo)
13494 continue;
13496 // hide quest if player is in raid-group and quest is no raid quest
13497 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13498 continue;
13500 // There should be no mixed ReqItem/ReqSource drop
13501 // This part for ReqItem drop
13502 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13504 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13505 return true;
13507 // This part - for ReqSource
13508 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; j++)
13510 // examined item is a source item
13511 if (qinfo->ReqSourceId[j] == itemid && qinfo->ReqSourceRef[j] > 0 && qinfo->ReqSourceRef[j] <= QUEST_OBJECTIVES_COUNT)
13513 uint32 idx = qinfo->ReqSourceRef[j]-1;
13515 // total count of created ReqItems and SourceItems is less than ReqItemCount
13516 if(qinfo->ReqItemId[idx] != 0 &&
13517 q_status.m_itemcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqItemCount[idx] * qinfo->ReqSourceCount[j])
13518 return true;
13520 // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
13521 if (qinfo->ReqCreatureOrGOId[idx] != 0)
13523 if(q_status.m_creatureOrGOcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqCreatureOrGOCount[idx] * qinfo->ReqSourceCount[j])
13524 return true;
13526 // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
13527 else if(qinfo->ReqSpell[idx] != 0)
13529 // not casted and need more reagents/item for use.
13530 if(!q_status.m_explored && GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13531 return true;
13537 return false;
13540 void Player::SendQuestComplete( uint32 quest_id )
13542 if( quest_id )
13544 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13545 data << uint32(quest_id);
13546 GetSession()->SendPacket( &data );
13547 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13551 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13553 uint32 questid = pQuest->GetQuestId();
13554 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13555 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13556 data << uint32(questid);
13558 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13560 data << uint32(XP);
13561 data << uint32(pQuest->GetRewOrReqMoney());
13563 else
13565 data << uint32(0);
13566 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13569 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13570 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13571 GetSession()->SendPacket( &data );
13573 if (pQuest->GetQuestCompleteScript() != 0)
13574 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13577 void Player::SendQuestFailed( uint32 quest_id )
13579 if( quest_id )
13581 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13582 data << quest_id;
13583 data << uint32(0); // failed reason (4 for inventory is full)
13584 GetSession()->SendPacket( &data );
13585 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13589 void Player::SendQuestTimerFailed( uint32 quest_id )
13591 if( quest_id )
13593 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13594 data << quest_id;
13595 GetSession()->SendPacket( &data );
13596 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13600 void Player::SendCanTakeQuestResponse( uint32 msg )
13602 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13603 data << uint32(msg);
13604 GetSession()->SendPacket( &data );
13605 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13608 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13610 if( pPlayer )
13612 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13613 data << uint64(pPlayer->GetGUID());
13614 data << uint8(msg); // valid values: 0-8
13615 GetSession()->SendPacket( &data );
13616 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13620 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13622 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13623 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13624 //data << pQuest->ReqItemId[item_idx];
13625 //data << count;
13626 GetSession()->SendPacket( &data );
13629 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13631 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13633 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13634 if (entry < 0)
13635 // client expected gameobject template id in form (id|0x80000000)
13636 entry = (-entry) | 0x80000000;
13638 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13639 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13640 data << uint32(pQuest->GetQuestId());
13641 data << uint32(entry);
13642 data << uint32(old_count + add_count);
13643 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13644 data << uint64(guid);
13645 GetSession()->SendPacket(&data);
13647 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13648 if( log_slot < MAX_QUEST_LOG_SIZE)
13649 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13652 /*********************************************************/
13653 /*** LOAD SYSTEM ***/
13654 /*********************************************************/
13656 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13658 bool delete_result = true;
13659 if(!result)
13661 // 0 1 2 3 4 5 6 7 8 9
13662 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13663 if(!result) return false;
13665 else delete_result = false;
13667 Field *fields = result->Fetch();
13669 if(!LoadValues( fields[1].GetString()))
13671 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
13672 if(delete_result) delete result;
13673 return false;
13676 // overwrite possible wrong/corrupted guid
13677 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13679 m_name = fields[2].GetCppString();
13681 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13682 SetMapId(fields[6].GetUInt32());
13683 // the instance id is not needed at character enum
13685 m_Played_time[0] = fields[7].GetUInt32();
13686 m_Played_time[1] = fields[8].GetUInt32();
13688 m_atLoginFlags = fields[9].GetUInt32();
13690 // I don't see these used anywhere ..
13691 /*_LoadGroup();
13693 _LoadBoundInstances();*/
13695 if (delete_result) delete result;
13697 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
13698 m_items[i] = NULL;
13700 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13701 m_deathState = DEAD;
13703 return true;
13706 void Player::_LoadDeclinedNames(QueryResult* result)
13708 if(!result)
13709 return;
13711 if(m_declinedname)
13712 delete m_declinedname;
13714 m_declinedname = new DeclinedName;
13715 Field *fields = result->Fetch();
13716 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13717 m_declinedname->name[i] = fields[i].GetCppString();
13719 delete result;
13722 void Player::_LoadArenaTeamInfo(QueryResult *result)
13724 // arenateamid, played_week, played_season, personal_rating
13725 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
13726 if (!result)
13727 return;
13731 Field *fields = result->Fetch();
13733 uint32 arenateamid = fields[0].GetUInt32();
13734 uint32 played_week = fields[1].GetUInt32();
13735 uint32 played_season = fields[2].GetUInt32();
13736 uint32 personal_rating = fields[3].GetUInt32();
13738 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
13739 if(!aTeam)
13741 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
13742 continue;
13744 uint8 arenaSlot = aTeam->GetSlot();
13746 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
13747 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
13748 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
13749 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
13750 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
13751 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
13753 }while (result->NextRow());
13754 delete result;
13757 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13759 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13760 if(!result)
13761 return false;
13763 Field *fields = result->Fetch();
13765 x = fields[0].GetFloat();
13766 y = fields[1].GetFloat();
13767 z = fields[2].GetFloat();
13768 o = fields[3].GetFloat();
13769 mapid = fields[4].GetUInt32();
13770 in_flight = !fields[5].GetCppString().empty();
13772 delete result;
13773 return true;
13776 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13778 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13779 if( !result )
13780 return false;
13782 Field *fields = result->Fetch();
13784 data = StrSplit(fields[0].GetCppString(), " ");
13786 delete result;
13788 return true;
13791 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13793 if(index >= data.size())
13794 return 0;
13796 return (uint32)atoi(data[index].c_str());
13799 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13801 float result;
13802 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13803 memcpy(&result, &temp, sizeof(result));
13805 return result;
13808 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13810 Tokens data;
13811 if(!LoadValuesArrayFromDB(data,guid))
13812 return 0;
13814 return GetUInt32ValueFromArray(data,index);
13817 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13819 float result;
13820 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13821 memcpy(&result, &temp, sizeof(result));
13823 return result;
13826 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
13828 //// 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
13829 //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty, arena_pending_points FROM characters WHERE guid = '%u'", guid);
13830 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
13832 if(!result)
13834 sLog.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid);
13835 return false;
13838 Field *fields = result->Fetch();
13840 uint32 dbAccountId = fields[1].GetUInt32();
13842 // check if the character's account in the db and the logged in account match.
13843 // player should be able to load/delete character only with correct account!
13844 if( dbAccountId != GetSession()->GetAccountId() )
13846 sLog.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
13847 delete result;
13848 return false;
13851 Object::_Create( guid, 0, HIGHGUID_PLAYER );
13853 m_name = fields[3].GetCppString();
13855 // check name limitations
13856 if(!ObjectMgr::IsValidName(m_name) || GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name))
13858 delete result;
13859 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
13860 return false;
13863 if(!LoadValues( fields[2].GetString()))
13865 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13866 delete result;
13867 return false;
13870 // overwrite possible wrong/corrupted guid
13871 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13873 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13874 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
13876 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), 0 );
13877 SetVisibleItemSlot(slot,NULL);
13879 if (m_items[slot])
13881 delete m_items[slot];
13882 m_items[slot] = NULL;
13886 // update money limits
13887 if(GetMoney() > MAX_MONEY_AMOUNT)
13888 SetMoney(MAX_MONEY_AMOUNT);
13890 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
13891 outDebugValues();
13893 m_race = fields[4].GetUInt8();
13894 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13895 //Other way is to saves m_team into characters table.
13896 setFactionForRace(m_race);
13897 SetCharm(0);
13899 m_class = fields[5].GetUInt8();
13901 PlayerInfo const *info = objmgr.GetPlayerInfo(m_race, m_class);
13902 if(!info)
13904 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
13905 delete result;
13906 return false;
13909 InitPrimaryProffesions(); // to max set before any spell loaded
13911 uint32 transGUID = fields[24].GetUInt32();
13912 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
13913 SetMapId(fields[9].GetUInt32());
13914 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
13916 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
13918 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
13920 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[33].GetUInt32();
13921 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
13922 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
13924 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
13926 // check arena teams integrity
13927 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
13929 uint32 arena_team_id = GetArenaTeamId(arena_slot);
13930 if(!arena_team_id)
13931 continue;
13933 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
13934 if(at->HaveMember(GetGUID()))
13935 continue;
13937 // arena team not exist or not member, cleanup fields
13938 for(int j =0; j < 6; ++j)
13939 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
13942 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
13944 if(!IsPositionValid())
13946 sLog.outError("ERROR: 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());
13948 SetMapId(info->mapId);
13949 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13951 transGUID = 0;
13953 m_movementInfo.t_x = 0.0f;
13954 m_movementInfo.t_y = 0.0f;
13955 m_movementInfo.t_z = 0.0f;
13956 m_movementInfo.t_o = 0.0f;
13959 // load the player's map here if it's not already loaded
13960 Map *map = GetMap();
13961 // since the player may not be bound to the map yet, make sure subsequent
13962 // getmap calls won't create new maps
13963 SetInstanceId(map->GetInstanceId());
13965 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
13966 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
13968 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
13969 if(at)
13970 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
13971 else
13972 sLog.outError("Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no aretrigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), GetMapId());
13975 SaveRecallPosition();
13977 if (transGUID != 0)
13979 m_movementInfo.t_x = fields[20].GetFloat();
13980 m_movementInfo.t_y = fields[21].GetFloat();
13981 m_movementInfo.t_z = fields[22].GetFloat();
13982 m_movementInfo.t_o = fields[23].GetFloat();
13984 if( !MaNGOS::IsValidMapCoord(
13985 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13986 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
13987 // transport size limited
13988 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
13990 sLog.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13991 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13992 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
13994 SetMapId(info->mapId);
13995 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13997 m_movementInfo.t_x = 0.0f;
13998 m_movementInfo.t_y = 0.0f;
13999 m_movementInfo.t_z = 0.0f;
14000 m_movementInfo.t_o = 0.0f;
14002 transGUID = 0;
14006 if (transGUID != 0)
14008 for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
14010 if( (*iter)->GetGUIDLow() == transGUID)
14012 m_transport = *iter;
14013 m_transport->AddPassenger(this);
14014 SetMapId(m_transport->GetMapId());
14015 break;
14019 if(!m_transport)
14021 sLog.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
14022 guid,transGUID);
14024 SetMapId(info->mapId);
14025 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
14027 m_movementInfo.t_x = 0.0f;
14028 m_movementInfo.t_y = 0.0f;
14029 m_movementInfo.t_z = 0.0f;
14030 m_movementInfo.t_o = 0.0f;
14032 transGUID = 0;
14036 time_t now = time(NULL);
14037 time_t logoutTime = time_t(fields[16].GetUInt64());
14039 // since last logout (in seconds)
14040 uint64 time_diff = uint64(now - logoutTime);
14042 // set value, including drunk invisibility detection
14043 // calculate sobering. after 15 minutes logged out, the player will be sober again
14044 float soberFactor;
14045 if(time_diff > 15*MINUTE)
14046 soberFactor = 0;
14047 else
14048 soberFactor = 1-time_diff/(15.0f*MINUTE);
14049 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14050 SetDrunkValue(newDrunkenValue);
14052 m_rest_bonus = fields[15].GetFloat();
14053 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14054 float bubble0 = 0.031;
14055 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14056 float bubble1 = 0.125;
14058 if((int32)fields[16].GetUInt32() > 0)
14060 float bubble = fields[17].GetUInt32() > 0
14061 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14062 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14064 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14067 m_cinematic = fields[12].GetUInt32();
14068 m_Played_time[0]= fields[13].GetUInt32();
14069 m_Played_time[1]= fields[14].GetUInt32();
14071 m_resetTalentsCost = fields[18].GetUInt32();
14072 m_resetTalentsTime = time_t(fields[19].GetUInt64());
14074 // reserve some flags
14075 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14077 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14078 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14080 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
14082 uint32 extraflags = fields[25].GetUInt32();
14084 m_stableSlots = fields[26].GetUInt32();
14085 if(m_stableSlots > 4)
14087 sLog.outError("Player can have not more 4 stable slots, but have in DB %u",uint32(m_stableSlots));
14088 m_stableSlots = 4;
14091 m_atLoginFlags = fields[27].GetUInt32();
14093 // Honor system
14094 // Update Honor kills data
14095 m_lastHonorUpdateTime = logoutTime;
14096 UpdateHonorFields();
14098 m_deathExpireTime = (time_t)fields[30].GetUInt64();
14099 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14100 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14102 std::string taxi_nodes = fields[31].GetCppString();
14104 delete result;
14106 // clear channel spell data (if saved at channel spell casting)
14107 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14108 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14110 // clear charm/summon related fields
14111 SetCharm(NULL);
14112 SetPet(NULL);
14113 SetCharmerGUID(NULL);
14114 SetOwnerGUID(NULL);
14115 SetCreatorGUID(NULL);
14117 // reset some aura modifiers before aura apply
14118 SetFarSight(NULL);
14119 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14120 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14122 // reset skill modifiers and set correct unlearn flags
14123 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; i++)
14125 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
14127 // set correct unlearn bit
14128 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
14129 if(!id) continue;
14131 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
14132 if(!pSkill) continue;
14134 // enable unlearn button for primary professions only
14135 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
14136 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
14137 else
14138 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
14141 // make sure the unit is considered out of combat for proper loading
14142 ClearInCombat();
14144 // make sure the unit is considered not in duel for proper loading
14145 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14146 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14148 // remember loaded power/health values to restore after stats initialization and modifier applying
14149 uint32 savedHealth = GetHealth();
14150 uint32 savedPower[MAX_POWERS];
14151 for(uint32 i = 0; i < MAX_POWERS; ++i)
14152 savedPower[i] = GetPower(Powers(i));
14154 // reset stats before loading any modifiers
14155 InitStatsForLevel();
14156 InitTaxiNodesForLevel();
14157 InitGlyphsForLevel();
14158 InitRunes();
14160 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14162 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14163 //_LoadMail();
14165 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14167 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14168 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14169 m_deathState = DEAD;
14171 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14173 // after spell load
14174 InitTalentForLevel();
14175 learnSkillRewardedSpells();
14177 // after spell load, learn rewarded spell if need also
14178 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14179 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14181 _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));
14183 // must be before inventory (some items required reputation check)
14184 _LoadReputation(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14186 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14188 // update items with duration and realtime
14189 UpdateItemDuration(time_diff, true);
14191 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14193 // unread mails and next delivery time, actual mails not loaded
14194 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14196 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14198 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
14199 return false;
14201 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14202 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14203 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14205 if(!HasTitle(curTitle))
14206 SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
14209 // Not finish taxi flight path
14210 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes))
14212 // problems with taxi path loading
14213 TaxiNodesEntry const* nodeEntry = NULL;
14214 if(uint32 node_id = m_taxi.GetTaxiSource())
14215 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14217 if(!nodeEntry) // don't know taxi start node, to homebind
14219 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14220 SetMapId(m_homebindMapId);
14221 Relocate( m_homebindX, m_homebindY, m_homebindZ,0.0f);
14222 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14224 else // have start node, to it
14226 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14227 SetMapId(nodeEntry->map_id);
14228 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14229 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14231 m_taxi.ClearTaxiDestinations();
14233 else if(uint32 node_id = m_taxi.GetTaxiSource())
14235 // save source node as recall coord to prevent recall and fall from sky
14236 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14237 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14238 m_recallMap = nodeEntry->map_id;
14239 m_recallX = nodeEntry->x;
14240 m_recallY = nodeEntry->y;
14241 m_recallZ = nodeEntry->z;
14243 // flight will started later
14246 // has to be called after last Relocate() in Player::LoadFromDB
14247 SetFallInformation(0, GetPositionZ());
14249 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14251 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14252 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14253 if(!isAlive())
14254 RemoveAllAurasOnDeath();
14256 //apply all stat bonuses from items and auras
14257 SetCanModifyStats(true);
14258 UpdateAllStats();
14260 // restore remembered power/health values (but not more max values)
14261 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14262 for(uint32 i = 0; i < MAX_POWERS; ++i)
14263 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14265 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14266 outDebugValues();
14268 // GM state
14269 if(GetSession()->GetSecurity() > SEC_PLAYER)
14271 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14273 default:
14274 case 0: break; // disable
14275 case 1: SetGameMaster(true); break; // enable
14276 case 2: // save state
14277 if(extraflags & PLAYER_EXTRA_GM_ON)
14278 SetGameMaster(true);
14279 break;
14282 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14284 default:
14285 case 0: break; // disable
14286 case 1: SetAcceptTicket(true); break; // enable
14287 case 2: // save state
14288 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14289 SetAcceptTicket(true);
14290 break;
14293 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14295 default:
14296 case 0: break; // disable
14297 case 1: SetGMChat(true); break; // enable
14298 case 2: // save state
14299 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14300 SetGMChat(true);
14301 break;
14304 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14306 default:
14307 case 0: break; // disable
14308 case 1: SetAcceptWhispers(true); break; // enable
14309 case 2: // save state
14310 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14311 SetAcceptWhispers(true);
14312 break;
14316 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14318 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14319 m_achievementMgr.CheckAllAchievementCriteria();
14320 return true;
14323 bool Player::isAllowedToLoot(Creature* creature)
14325 if(Player* recipient = creature->GetLootRecipient())
14327 if (recipient == this)
14328 return true;
14329 if( Group* otherGroup = recipient->GetGroup())
14331 Group* thisGroup = GetGroup();
14332 if(!thisGroup)
14333 return false;
14334 return thisGroup == otherGroup;
14336 return false;
14338 else
14339 // prevent other players from looting if the recipient got disconnected
14340 return !creature->hasLootRecipient();
14343 void Player::_LoadActions(QueryResult *result)
14345 m_actionButtons.clear();
14347 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14349 if(result)
14353 Field *fields = result->Fetch();
14355 uint8 button = fields[0].GetUInt8();
14357 addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8());
14359 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14361 while( result->NextRow() );
14363 delete result;
14367 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14369 m_Auras.clear();
14370 for (int i = 0; i < TOTAL_AURAS; i++)
14371 m_modAuras[i].clear();
14373 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14375 if(result)
14379 Field *fields = result->Fetch();
14380 uint64 caster_guid = fields[0].GetUInt64();
14381 uint32 spellid = fields[1].GetUInt32();
14382 uint32 effindex = fields[2].GetUInt32();
14383 uint32 stackcount = fields[3].GetUInt32();
14384 int32 damage = (int32)fields[4].GetUInt32();
14385 int32 maxduration = (int32)fields[5].GetUInt32();
14386 int32 remaintime = (int32)fields[6].GetUInt32();
14387 int32 remaincharges = (int32)fields[7].GetUInt32();
14389 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14390 if(!spellproto)
14392 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14393 continue;
14396 if(effindex >= 3)
14398 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14399 continue;
14402 // negative effects should continue counting down after logout
14403 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14405 if(remaintime <= int32(timediff))
14406 continue;
14408 remaintime -= timediff;
14411 // prevent wrong values of remaincharges
14412 if(spellproto->procCharges)
14414 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14415 remaincharges = spellproto->procCharges;
14417 else
14418 remaincharges = -1;
14420 //do not load single target auras (unless they were cast by the player)
14421 if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
14422 continue;
14424 for(uint32 i=0; i<stackcount; i++)
14426 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14427 if(!damage)
14428 damage = aura->GetModifier()->m_amount;
14429 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14430 AddAura(aura);
14431 sLog.outString("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14434 while( result->NextRow() );
14436 delete result;
14439 if(m_class == CLASS_WARRIOR)
14440 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14443 void Player::LoadCorpse()
14445 if( isAlive() )
14447 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14449 else
14451 if(Corpse *corpse = GetCorpse())
14453 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14455 else
14457 //Prevent Dead Player login without corpse
14458 ResurrectPlayer(0.5f);
14463 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14465 //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());
14466 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14467 //NOTE: the "order by `bag`" is important because it makes sure
14468 //the bagMap is filled before items in the bags are loaded
14469 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14470 //expected to be equipped before offhand items (TODO: fixme)
14472 uint32 zone = GetZoneId();
14474 if (result)
14476 std::list<Item*> problematicItems;
14478 // prevent items from being added to the queue when stored
14479 m_itemUpdateQueueBlocked = true;
14482 Field *fields = result->Fetch();
14483 uint32 bag_guid = fields[1].GetUInt32();
14484 uint8 slot = fields[2].GetUInt8();
14485 uint32 item_guid = fields[3].GetUInt32();
14486 uint32 item_id = fields[4].GetUInt32();
14488 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14490 if(!proto)
14492 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14493 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14494 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14495 continue;
14498 Item *item = NewItemOrBag(proto);
14500 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14502 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14503 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14504 item->FSetState(ITEM_REMOVED);
14505 item->SaveToDB(); // it also deletes item object !
14506 continue;
14509 // not allow have in alive state item limited to another map/zone
14510 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14512 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14513 item->FSetState(ITEM_REMOVED);
14514 item->SaveToDB(); // it also deletes item object !
14515 continue;
14518 // "Conjured items disappear if you are logged out for more than 15 minutes"
14519 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14521 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14522 item->FSetState(ITEM_REMOVED);
14523 item->SaveToDB(); // it also deletes item object !
14524 continue;
14527 bool success = true;
14529 if (!bag_guid)
14531 // the item is not in a bag
14532 item->SetContainer( NULL );
14533 item->SetSlot(slot);
14535 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14537 ItemPosCountVec dest;
14538 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14539 item = StoreItem(dest, item, true);
14540 else
14541 success = false;
14543 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14545 uint16 dest;
14546 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14547 QuickEquipItem(dest, item);
14548 else
14549 success = false;
14551 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14553 ItemPosCountVec dest;
14554 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14555 item = BankItem(dest, item, true);
14556 else
14557 success = false;
14560 if(success)
14562 // store bags that may contain items in them
14563 if(item->IsBag() && IsBagPos(item->GetPos()))
14564 bagMap[item_guid] = (Bag*)item;
14567 else
14569 item->SetSlot(NULL_SLOT);
14570 // the item is in a bag, find the bag
14571 std::map<uint64, Bag*>::iterator itr = bagMap.find(bag_guid);
14572 if(itr != bagMap.end())
14573 itr->second->StoreItem(slot, item, true );
14574 else
14575 success = false;
14578 // item's state may have changed after stored
14579 if (success)
14580 item->SetState(ITEM_UNCHANGED, this);
14581 else
14583 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);
14584 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14585 problematicItems.push_back(item);
14587 } while (result->NextRow());
14589 delete result;
14590 m_itemUpdateQueueBlocked = false;
14592 // send by mail problematic items
14593 while(!problematicItems.empty())
14595 // fill mail
14596 MailItemsInfo mi; // item list preparing
14598 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14600 Item* item = problematicItems.front();
14601 problematicItems.pop_front();
14603 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14606 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14608 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14611 //if(isAlive())
14612 _ApplyAllItemMods();
14615 // load mailed item which should receive current player
14616 void Player::_LoadMailedItems(Mail *mail)
14618 // data needs to be at first place for Item::LoadFromDB
14619 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);
14620 if(!result)
14621 return;
14625 Field *fields = result->Fetch();
14626 uint32 item_guid_low = fields[1].GetUInt32();
14627 uint32 item_template = fields[2].GetUInt32();
14629 mail->AddItem(item_guid_low, item_template);
14631 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14633 if(!proto)
14635 sLog.outError( "Player %u have unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), item_guid_low, item_template,mail->messageID);
14636 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14637 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14638 continue;
14641 Item *item = NewItemOrBag(proto);
14643 if(!item->LoadFromDB(item_guid_low, 0, result))
14645 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14646 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14647 item->FSetState(ITEM_REMOVED);
14648 item->SaveToDB(); // it also deletes item object !
14649 continue;
14652 AddMItem(item);
14653 } while (result->NextRow());
14655 delete result;
14658 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14660 //set a count of unread mails
14661 //QueryResult *resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" I64FMTD "'", GUID_LOPART(playerGuid),(uint64)cTime);
14662 if (resultUnread)
14664 Field *fieldMail = resultUnread->Fetch();
14665 unReadMails = fieldMail[0].GetUInt8();
14666 delete resultUnread;
14669 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14670 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14671 if (resultDelivery)
14673 Field *fieldMail = resultDelivery->Fetch();
14674 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14675 delete resultDelivery;
14679 void Player::_LoadMail()
14681 m_mail.clear();
14682 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14683 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());
14684 if(result)
14688 Field *fields = result->Fetch();
14689 Mail *m = new Mail;
14690 m->messageID = fields[0].GetUInt32();
14691 m->messageType = fields[1].GetUInt8();
14692 m->sender = fields[2].GetUInt32();
14693 m->receiver = fields[3].GetUInt32();
14694 m->subject = fields[4].GetCppString();
14695 m->itemTextId = fields[5].GetUInt32();
14696 bool has_items = fields[6].GetBool();
14697 m->expire_time = (time_t)fields[7].GetUInt64();
14698 m->deliver_time = (time_t)fields[8].GetUInt64();
14699 m->money = fields[9].GetUInt32();
14700 m->COD = fields[10].GetUInt32();
14701 m->checked = fields[11].GetUInt32();
14702 m->stationery = fields[12].GetUInt8();
14703 m->mailTemplateId = fields[13].GetInt16();
14705 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14707 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14708 m->mailTemplateId = 0;
14711 m->state = MAIL_STATE_UNCHANGED;
14713 if (has_items)
14714 _LoadMailedItems(m);
14716 m_mail.push_back(m);
14717 } while( result->NextRow() );
14718 delete result;
14720 m_mailsLoaded = true;
14723 void Player::LoadPet()
14725 //fixme: the pet should still be loaded if the player is not in world
14726 // just not added to the map
14727 if(IsInWorld())
14729 Pet *pet = new Pet;
14730 if(!pet->LoadPetFromDB(this,0,0,true))
14731 delete pet;
14735 void Player::_LoadQuestStatus(QueryResult *result)
14737 mQuestStatus.clear();
14739 uint32 slot = 0;
14741 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14742 //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());
14744 if(result)
14748 Field *fields = result->Fetch();
14750 uint32 quest_id = fields[0].GetUInt32();
14751 // used to be new, no delete?
14752 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14753 if( pQuest )
14755 // find or create
14756 QuestStatusData& questStatusData = mQuestStatus[quest_id];
14758 uint32 qstatus = fields[1].GetUInt32();
14759 if(qstatus < MAX_QUEST_STATUS)
14760 questStatusData.m_status = QuestStatus(qstatus);
14761 else
14763 questStatusData.m_status = QUEST_STATUS_NONE;
14764 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
14767 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
14768 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
14770 time_t quest_time = time_t(fields[4].GetUInt64());
14772 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
14774 AddTimedQuest( quest_id );
14776 if (quest_time <= sWorld.GetGameTime())
14777 questStatusData.m_timer = 1;
14778 else
14779 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * 1000;
14781 else
14782 quest_time = 0;
14784 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
14785 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
14786 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
14787 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
14788 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
14789 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
14790 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
14791 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
14793 questStatusData.uState = QUEST_UNCHANGED;
14795 // add to quest log
14796 if( slot < MAX_QUEST_LOG_SIZE &&
14797 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
14798 questStatusData.m_status==QUEST_STATUS_COMPLETE &&
14799 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
14801 SetQuestSlot(slot,quest_id,quest_time);
14803 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
14804 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
14806 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
14807 if(questStatusData.m_creatureOrGOcount[idx])
14808 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
14810 ++slot;
14813 if(questStatusData.m_rewarded)
14815 // learn rewarded spell if unknown
14816 learnQuestRewardedSpells(pQuest);
14818 // set rewarded title if any
14819 if(pQuest->GetCharTitleId())
14821 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
14822 SetTitle(titleEntry);
14826 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
14829 while( result->NextRow() );
14831 delete result;
14834 // clear quest log tail
14835 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
14836 SetQuestSlot(i,0);
14839 void Player::_LoadDailyQuestStatus(QueryResult *result)
14841 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
14842 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
14844 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14846 if(result)
14848 uint32 quest_daily_idx = 0;
14852 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
14854 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14855 break;
14858 Field *fields = result->Fetch();
14860 uint32 quest_id = fields[0].GetUInt32();
14862 // save _any_ from daily quest times (it must be after last reset anyway)
14863 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
14865 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14866 if( !pQuest )
14867 continue;
14869 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
14870 ++quest_daily_idx;
14872 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
14874 while( result->NextRow() );
14876 delete result;
14879 m_DailyQuestChanged = false;
14882 void Player::_LoadReputation(QueryResult *result)
14884 m_factions.clear();
14886 // Set initial reputations (so everything is nifty before DB data load)
14887 SetInitialFactions();
14889 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
14891 if(result)
14895 Field *fields = result->Fetch();
14897 FactionEntry const *factionEntry = sFactionStore.LookupEntry(fields[0].GetUInt32());
14898 if( factionEntry && (factionEntry->reputationListID >= 0))
14900 FactionState* faction = &m_factions[factionEntry->reputationListID];
14902 // update standing to current
14903 faction->Standing = int32(fields[1].GetUInt32());
14905 uint32 dbFactionFlags = fields[2].GetUInt32();
14907 if( dbFactionFlags & FACTION_FLAG_VISIBLE )
14908 SetFactionVisible(faction); // have internal checks for forced invisibility
14910 if( dbFactionFlags & FACTION_FLAG_INACTIVE)
14911 SetFactionInactive(faction,true); // have internal checks for visibility requirement
14913 if( dbFactionFlags & FACTION_FLAG_AT_WAR ) // DB at war
14914 SetFactionAtWar(faction,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
14915 else // DB not at war
14917 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
14918 if( faction->Flags & FACTION_FLAG_VISIBLE )
14919 SetFactionAtWar(faction,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
14922 // set atWar for hostile
14923 if(GetReputationRank(factionEntry) <= REP_HOSTILE)
14924 SetFactionAtWar(faction,true);
14926 // reset changed flag if values similar to saved in DB
14927 if(faction->Flags==dbFactionFlags)
14928 faction->Changed = false;
14931 while( result->NextRow() );
14933 delete result;
14937 void Player::_LoadSpells(QueryResult *result)
14939 for (PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
14940 delete itr->second;
14941 m_spells.clear();
14943 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,slot,active FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14945 if(result)
14949 Field *fields = result->Fetch();
14951 addSpell(fields[0].GetUInt16(), fields[2].GetBool(), false, true, fields[1].GetUInt16(), fields[3].GetBool());
14953 while( result->NextRow() );
14955 delete result;
14959 void Player::_LoadTutorials(QueryResult *result)
14961 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14963 if(result)
14967 Field *fields = result->Fetch();
14969 for (int iI=0; iI<8; iI++)
14970 m_Tutorials[iI] = fields[iI].GetUInt32();
14972 while( result->NextRow() );
14974 delete result;
14977 m_TutorialsChanged = false;
14980 void Player::_LoadGroup(QueryResult *result)
14982 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14983 if(result)
14985 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
14986 delete result;
14987 Group* group = objmgr.GetGroupByLeader(leaderGuid);
14988 if(group)
14990 uint8 subgroup = group->GetMemberGroup(GetGUID());
14991 SetGroup(group, subgroup);
14992 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
14994 // the group leader may change the instance difficulty while the player is offline
14995 SetDifficulty(group->GetDifficulty());
15001 void Player::_LoadBoundInstances(QueryResult *result)
15003 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15004 m_boundInstances[i].clear();
15006 Group *group = GetGroup();
15008 //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));
15009 if(result)
15013 Field *fields = result->Fetch();
15014 bool perm = fields[1].GetBool();
15015 uint32 mapId = fields[2].GetUInt32();
15016 uint32 instanceId = fields[0].GetUInt32();
15017 uint8 difficulty = fields[3].GetUInt8();
15018 time_t resetTime = (time_t)fields[4].GetUInt64();
15019 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15020 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15021 // and in that case it is not used
15023 if(!perm && group)
15025 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);
15026 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15027 continue;
15030 // since non permanent binds are always solo bind, they can always be reset
15031 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
15032 if(save) BindToInstance(save, perm, true);
15033 } while(result->NextRow());
15034 delete result;
15038 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
15040 // some instances only have one difficulty
15041 const MapEntry* entry = sMapStore.LookupEntry(mapid);
15042 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
15044 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15045 if(itr != m_boundInstances[difficulty].end())
15046 return &itr->second;
15047 else
15048 return NULL;
15051 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
15053 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15054 UnbindInstance(itr, difficulty, unload);
15057 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
15059 if(itr != m_boundInstances[difficulty].end())
15061 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15062 itr->second.save->RemovePlayer(this); // save can become invalid
15063 m_boundInstances[difficulty].erase(itr++);
15067 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15069 if(save)
15071 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15072 if(bind.save)
15074 // update the save when the group kills a boss
15075 if(permanent != bind.perm || save != bind.save)
15076 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());
15078 else
15079 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15081 if(bind.save != save)
15083 if(bind.save) bind.save->RemovePlayer(this);
15084 save->AddPlayer(this);
15087 if(permanent) save->SetCanReset(false);
15089 bind.save = save;
15090 bind.perm = permanent;
15091 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());
15092 return &bind;
15094 else
15095 return NULL;
15098 void Player::SendRaidInfo()
15100 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15102 uint32 counter = 0, i;
15103 for(i = 0; i < TOTAL_DIFFICULTIES; i++)
15104 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15105 if(itr->second.perm) counter++;
15107 data << counter;
15108 for(i = 0; i < TOTAL_DIFFICULTIES; i++)
15110 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15112 if(itr->second.perm)
15114 InstanceSave *save = itr->second.save;
15115 data << (save->GetMapId());
15116 data << (uint32)(save->GetResetTime() - time(NULL));
15117 data << save->GetInstanceId();
15118 data << uint32(counter);
15119 counter--;
15123 GetSession()->SendPacket(&data);
15127 - called on every successful teleportation to a map
15129 void Player::SendSavedInstances()
15131 bool hasBeenSaved = false;
15132 WorldPacket data;
15134 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15136 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15138 if(itr->second.perm) // only permanent binds are sent
15140 hasBeenSaved = true;
15141 break;
15146 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15147 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15148 data << uint32(hasBeenSaved);
15149 GetSession()->SendPacket(&data);
15151 if(!hasBeenSaved)
15152 return;
15154 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15156 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15158 if(itr->second.perm)
15160 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15161 data << uint32(itr->second.save->GetMapId());
15162 GetSession()->SendPacket(&data);
15168 /// convert the player's binds to the group
15169 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15171 bool has_binds = false;
15172 bool has_solo = false;
15174 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15175 assert(player_guid);
15177 // copy all binds to the group, when changing leader it's assumed the character
15178 // will not have any solo binds
15180 if(player)
15182 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15184 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15186 has_binds = true;
15187 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15188 // permanent binds are not removed
15189 if(!itr->second.perm)
15191 player->UnbindInstance(itr, i, true); // increments itr
15192 has_solo = true;
15194 else
15195 ++itr;
15200 // if the player's not online we don't know what binds it has
15201 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));
15202 // the following should not get executed when changing leaders
15203 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15206 bool Player::_LoadHomeBind(QueryResult *result)
15208 bool ok = false;
15209 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15210 if (result)
15212 Field *fields = result->Fetch();
15213 m_homebindMapId = fields[0].GetUInt32();
15214 m_homebindZoneId = fields[1].GetUInt16();
15215 m_homebindX = fields[2].GetFloat();
15216 m_homebindY = fields[3].GetFloat();
15217 m_homebindZ = fields[4].GetFloat();
15218 delete result;
15220 // accept saved data only for valid position (and non instanceable)
15221 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15222 !sMapStore.LookupEntry(m_homebindMapId)->Instanceable() )
15224 ok = true;
15226 else
15227 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15230 if(!ok)
15232 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15233 if(!info) return false;
15235 m_homebindMapId = info->mapId;
15236 m_homebindZoneId = info->zoneId;
15237 m_homebindX = info->positionX;
15238 m_homebindY = info->positionY;
15239 m_homebindZ = info->positionZ;
15241 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);
15244 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
15245 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15247 return true;
15250 /*********************************************************/
15251 /*** SAVE SYSTEM ***/
15252 /*********************************************************/
15254 void Player::SaveToDB()
15256 // delay auto save at any saves (manual, in code, or autosave)
15257 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15259 // first save/honor gain after midnight will also update the player's honor fields
15260 UpdateHonorFields();
15262 // players aren't saved on battleground maps
15263 uint32 mapid = IsBeingTeleported() ? GetTeleportDest().mapid : GetMapId();
15264 const MapEntry * me = sMapStore.LookupEntry(mapid);
15265 if(!me || me->IsBattleGroundOrArena())
15266 return;
15268 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15269 //save, far from tavern/city
15270 //save, but in tavern/city
15271 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15272 outDebugValues();
15274 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15275 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15276 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15277 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15278 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15279 uint32 tmp_displayid = GetDisplayId();
15281 // Set player sit state to standing on save, also stealth and shifted form
15282 SetByteValue(UNIT_FIELD_BYTES_1, 0, 0); // stand state
15283 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15284 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0); // stand flags?
15285 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15286 SetDisplayId(GetNativeDisplayId());
15288 bool inworld = IsInWorld();
15290 CharacterDatabase.BeginTransaction();
15292 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15294 std::string sql_name = m_name;
15295 CharacterDatabase.escape_string(sql_name);
15297 std::ostringstream ss;
15298 ss << "INSERT INTO characters (guid,account,name,race,class,"
15299 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15300 "taximask, online, cinematic, "
15301 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15302 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15303 "death_expire_time, taxi_path, arena_pending_points) VALUES ("
15304 << GetGUIDLow() << ", "
15305 << GetSession()->GetAccountId() << ", '"
15306 << sql_name << "', "
15307 << m_race << ", "
15308 << m_class << ", ";
15310 bool save_to_dest = false;
15311 if(IsBeingTeleported())
15313 // don't save to battlegrounds or arenas
15314 const MapEntry *entry = sMapStore.LookupEntry(GetTeleportDest().mapid);
15315 if(entry && entry->map_type != MAP_BATTLEGROUND && entry->map_type != MAP_ARENA)
15316 save_to_dest = true;
15319 if(!save_to_dest)
15321 ss << GetMapId() << ", "
15322 << (uint32)GetDifficulty() << ", "
15323 << finiteAlways(GetPositionX()) << ", "
15324 << finiteAlways(GetPositionY()) << ", "
15325 << finiteAlways(GetPositionZ()) << ", "
15326 << finiteAlways(GetOrientation()) << ", '";
15328 else
15330 ss << GetTeleportDest().mapid << ", "
15331 << (uint32)GetDifficulty() << ", "
15332 << finiteAlways(GetTeleportDest().x) << ", "
15333 << finiteAlways(GetTeleportDest().y) << ", "
15334 << finiteAlways(GetTeleportDest().z) << ", "
15335 << finiteAlways(GetTeleportDest().o) << ", '";
15338 uint16 i;
15339 for( i = 0; i < m_valuesCount; i++ )
15341 ss << GetUInt32Value(i) << " ";
15344 ss << "', '";
15346 for( i = 0; i < 8; i++ )
15347 ss << m_taxi.GetTaximask(i) << " ";
15349 ss << "', ";
15350 ss << (inworld ? 1 : 0);
15352 ss << ", ";
15353 ss << m_cinematic;
15355 ss << ", ";
15356 ss << m_Played_time[0];
15357 ss << ", ";
15358 ss << m_Played_time[1];
15360 ss << ", ";
15361 ss << finiteAlways(m_rest_bonus);
15362 ss << ", ";
15363 ss << (uint64)time(NULL);
15364 ss << ", ";
15365 ss << is_save_resting;
15366 ss << ", ";
15367 ss << m_resetTalentsCost;
15368 ss << ", ";
15369 ss << (uint64)m_resetTalentsTime;
15371 ss << ", ";
15372 ss << finiteAlways(m_movementInfo.t_x);
15373 ss << ", ";
15374 ss << finiteAlways(m_movementInfo.t_y);
15375 ss << ", ";
15376 ss << finiteAlways(m_movementInfo.t_z);
15377 ss << ", ";
15378 ss << finiteAlways(m_movementInfo.t_o);
15379 ss << ", ";
15380 if (m_transport)
15381 ss << m_transport->GetGUIDLow();
15382 else
15383 ss << "0";
15385 ss << ", ";
15386 ss << m_ExtraFlags;
15388 ss << ", ";
15389 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15391 ss << ", ";
15392 ss << uint32(m_atLoginFlags);
15394 ss << ", ";
15395 ss << GetZoneId();
15397 ss << ", ";
15398 ss << (uint64)m_deathExpireTime;
15400 ss << ", '";
15401 ss << m_taxi.SaveTaxiDestinationsToString();
15402 ss << "', '0' )";
15404 CharacterDatabase.Execute( ss.str().c_str() );
15406 if(m_mailsUpdated) //save mails only when needed
15407 _SaveMail();
15409 _SaveInventory();
15410 _SaveQuestStatus();
15411 _SaveDailyQuestStatus();
15412 _SaveTutorials();
15413 _SaveSpells();
15414 _SaveSpellCooldowns();
15415 _SaveActions();
15416 _SaveAuras();
15417 _SaveReputation();
15419 CharacterDatabase.CommitTransaction();
15421 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15422 SetDisplayId(tmp_displayid);
15423 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15424 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15425 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15426 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15428 // save pet (hunter pet level and experience and all type pets health/mana).
15429 if(Pet* pet = GetPet())
15430 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15431 m_achievementMgr.SaveToDB();
15434 // fast save function for item/money cheating preventing - save only inventory and money state
15435 void Player::SaveInventoryAndGoldToDB()
15437 _SaveInventory();
15438 //money is in data field
15439 SaveDataFieldToDB();
15442 void Player::_SaveActions()
15444 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15446 switch (itr->second.uState)
15448 case ACTIONBUTTON_NEW:
15449 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15450 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15451 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15452 ++itr;
15453 break;
15454 case ACTIONBUTTON_CHANGED:
15455 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15456 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15457 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15458 ++itr;
15459 break;
15460 case ACTIONBUTTON_DELETED:
15461 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15462 m_actionButtons.erase(itr++);
15463 break;
15464 default:
15465 ++itr;
15466 break;
15471 void Player::_SaveAuras()
15473 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15475 AuraMap const& auras = GetAuras();
15477 if (auras.empty())
15478 return;
15480 spellEffectPair lastEffectPair = auras.begin()->first;
15481 uint32 stackCounter = 1;
15483 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15485 if(itr == auras.end() || lastEffectPair != itr->first)
15487 AuraMap::const_iterator itr2 = itr;
15488 // save previous spellEffectPair to db
15489 itr2--;
15490 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15492 //skip all auras from spells that are passive or need a shapeshift
15493 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15495 //do not save single target auras (unless they were cast by the player)
15496 if (!(itr2->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo)))
15498 uint8 i;
15499 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15500 for (i = 0; i < 3; i++)
15501 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15502 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15503 break;
15505 if (i == 3)
15507 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15508 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15509 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->m_procCharges));
15514 if(itr == auras.end())
15515 break;
15518 if (lastEffectPair == itr->first)
15519 stackCounter++;
15520 else
15522 lastEffectPair = itr->first;
15523 stackCounter = 1;
15528 void Player::_SaveInventory()
15530 // force items in buyback slots to new state
15531 // and remove those that aren't already
15532 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; i++)
15534 Item *item = m_items[i];
15535 if (!item || item->GetState() == ITEM_NEW) continue;
15536 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15537 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15538 m_items[i]->FSetState(ITEM_NEW);
15541 // update enchantment durations
15542 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15544 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15547 // if no changes
15548 if (m_itemUpdateQueue.empty()) return;
15550 // do not save if the update queue is corrupt
15551 bool error = false;
15552 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15554 Item *item = m_itemUpdateQueue[i];
15555 if(!item || item->GetState() == ITEM_REMOVED) continue;
15556 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15558 if (test == NULL)
15560 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());
15561 error = true;
15563 else if (test != item)
15565 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());
15566 error = true;
15570 if (error)
15572 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15573 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15574 return;
15577 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15579 Item *item = m_itemUpdateQueue[i];
15580 if(!item) continue;
15582 Bag *container = item->GetContainer();
15583 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15585 switch(item->GetState())
15587 case ITEM_NEW:
15588 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());
15589 break;
15590 case ITEM_CHANGED:
15591 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());
15592 break;
15593 case ITEM_REMOVED:
15594 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15595 break;
15596 case ITEM_UNCHANGED:
15597 break;
15600 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15602 m_itemUpdateQueue.clear();
15605 void Player::_SaveMail()
15607 if (!m_mailsLoaded)
15608 return;
15610 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15612 Mail *m = (*itr);
15613 if (m->state == MAIL_STATE_CHANGED)
15615 CharacterDatabase.PExecute("UPDATE mail SET itemTextId = '%u',has_items = '%u',expire_time = '" I64FMTD "', deliver_time = '" I64FMTD "',money = '%u',cod = '%u',checked = '%u' WHERE id = '%u'",
15616 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15617 if(m->removedItems.size())
15619 for(std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15620 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15621 m->removedItems.clear();
15623 m->state = MAIL_STATE_UNCHANGED;
15625 else if (m->state == MAIL_STATE_DELETED)
15627 if (m->HasItems())
15628 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15629 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15630 if (m->itemTextId)
15631 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15632 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15633 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15637 //deallocate deleted mails...
15638 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15640 if ((*itr)->state == MAIL_STATE_DELETED)
15642 Mail* m = *itr;
15643 m_mail.erase(itr);
15644 delete m;
15645 itr = m_mail.begin();
15647 else
15648 ++itr;
15651 m_mailsUpdated = false;
15654 void Player::_SaveQuestStatus()
15656 // we don't need transactions here.
15657 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15659 switch (i->second.uState)
15661 case QUEST_NEW :
15662 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15663 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15664 GetGUIDLow(), i->first, i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / 1000 + 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]);
15665 break;
15666 case QUEST_CHANGED :
15667 CharacterDatabase.PExecute("UPDATE character_queststatus SET status = '%u',rewarded = '%u',explored = '%u',timer = '" I64FMTD "',mobcount1 = '%u',mobcount2 = '%u',mobcount3 = '%u',mobcount4 = '%u',itemcount1 = '%u',itemcount2 = '%u',itemcount3 = '%u',itemcount4 = '%u' WHERE guid = '%u' AND quest = '%u' ",
15668 i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / 1000 + 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 );
15669 break;
15670 case QUEST_UNCHANGED:
15671 break;
15673 i->second.uState = QUEST_UNCHANGED;
15677 void Player::_SaveDailyQuestStatus()
15679 if(!m_DailyQuestChanged)
15680 return;
15682 m_DailyQuestChanged = false;
15684 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15686 // we don't need transactions here.
15687 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15688 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15689 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15690 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
15691 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15694 void Player::_SaveReputation()
15696 for(FactionStateList::iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
15698 if (itr->second.Changed)
15700 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr->second.ID);
15701 CharacterDatabase.PExecute("INSERT INTO character_reputation (guid,faction,standing,flags) VALUES ('%u', '%u', '%i', '%u')", GetGUIDLow(), itr->second.ID, itr->second.Standing, itr->second.Flags);
15702 itr->second.Changed = false;
15707 void Player::_SaveSpells()
15709 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
15711 ++next;
15712 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15713 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15714 if (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED)
15715 CharacterDatabase.PExecute("INSERT INTO character_spell (guid,spell,slot,active,disabled) VALUES ('%u', '%u', '%u','%u','%u')", GetGUIDLow(), itr->first, itr->second->slotId,itr->second->active ? 1 : 0,itr->second->disabled ? 1 : 0);
15717 if (itr->second->state == PLAYERSPELL_REMOVED)
15718 _removeSpell(itr->first);
15719 else
15720 itr->second->state = PLAYERSPELL_UNCHANGED;
15724 void Player::_SaveTutorials()
15726 if(!m_TutorialsChanged)
15727 return;
15729 uint32 Rows=0;
15730 // it's better than rebuilding indexes multiple times
15731 QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID );
15732 if(result)
15734 Rows = result->Fetch()[0].GetUInt32();
15735 delete result;
15738 if (Rows)
15740 CharacterDatabase.PExecute("UPDATE character_tutorial SET tut0='%u', tut1='%u', tut2='%u', tut3='%u', tut4='%u', tut5='%u', tut6='%u', tut7='%u' WHERE account = '%u' AND realmid = '%u'",
15741 m_Tutorials[0], m_Tutorials[1], m_Tutorials[2], m_Tutorials[3], m_Tutorials[4], m_Tutorials[5], m_Tutorials[6], m_Tutorials[7], GetSession()->GetAccountId(), realmID );
15743 else
15745 CharacterDatabase.PExecute("INSERT INTO character_tutorial (account,realmid,tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7) VALUES ('%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')", GetSession()->GetAccountId(), realmID, m_Tutorials[0], m_Tutorials[1], m_Tutorials[2], m_Tutorials[3], m_Tutorials[4], m_Tutorials[5], m_Tutorials[6], m_Tutorials[7]);
15748 m_TutorialsChanged = false;
15751 void Player::outDebugValues() const
15753 if(!sLog.IsOutDebug()) // optimize disabled debug output
15754 return;
15756 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15757 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15758 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15759 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15760 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15761 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15762 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15763 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15764 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15765 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15766 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15767 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15770 /*********************************************************/
15771 /*** FLOOD FILTER SYSTEM ***/
15772 /*********************************************************/
15774 void Player::UpdateSpeakTime()
15776 // ignore chat spam protection for GMs in any mode
15777 if(GetSession()->GetSecurity() > SEC_PLAYER)
15778 return;
15780 time_t current = time (NULL);
15781 if(m_speakTime > current)
15783 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15784 if(!max_count)
15785 return;
15787 ++m_speakCount;
15788 if(m_speakCount >= max_count)
15790 // prevent overwrite mute time, if message send just before mutes set, for example.
15791 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15792 if(GetSession()->m_muteTime < new_mute)
15793 GetSession()->m_muteTime = new_mute;
15795 m_speakCount = 0;
15798 else
15799 m_speakCount = 0;
15801 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15804 bool Player::CanSpeak() const
15806 return GetSession()->m_muteTime <= time (NULL);
15809 /*********************************************************/
15810 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15811 /*********************************************************/
15813 void Player::SendAttackSwingNotInRange()
15815 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15816 GetSession()->SendPacket( &data );
15819 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15821 std::ostringstream ss;
15822 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15823 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15824 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15825 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15826 sLog.outDebug(ss.str().c_str());
15827 CharacterDatabase.Execute(ss.str().c_str());
15830 void Player::SaveDataFieldToDB()
15832 std::ostringstream ss;
15833 ss<<"UPDATE characters SET data='";
15835 for(uint16 i = 0; i < m_valuesCount; i++ )
15837 ss << GetUInt32Value(i) << " ";
15839 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
15841 CharacterDatabase.Execute(ss.str().c_str());
15844 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
15846 std::ostringstream ss2;
15847 ss2<<"UPDATE characters SET data='";
15848 int i=0;
15849 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
15851 ss2<<tokens[i]<<" ";
15853 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15855 return CharacterDatabase.Execute(ss2.str().c_str());
15858 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
15860 char buf[11];
15861 snprintf(buf,11,"%u",value);
15863 if(index >= tokens.size())
15864 return;
15866 tokens[index] = buf;
15869 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
15871 Tokens tokens;
15872 if(!LoadValuesArrayFromDB(tokens,guid))
15873 return;
15875 if(index >= tokens.size())
15876 return;
15878 char buf[11];
15879 snprintf(buf,11,"%u",value);
15880 tokens[index] = buf;
15882 SaveValuesArrayInDB(tokens,guid);
15885 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
15887 uint32 temp;
15888 memcpy(&temp, &value, sizeof(value));
15889 Player::SetUInt32ValueInDB(index, temp, guid);
15892 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
15894 Tokens tokens;
15895 if(!LoadValuesArrayFromDB(tokens, guid))
15896 return;
15898 uint32 unit_bytes0 = GetUInt32ValueFromArray(tokens, UNIT_FIELD_BYTES_0);
15899 uint8 race = unit_bytes0 & 0xFF;
15900 uint8 class_ = (unit_bytes0 >> 8) & 0xFF;
15902 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
15903 if(!info)
15904 return;
15906 unit_bytes0 &= ~(0xFF << 16);
15907 unit_bytes0 |= (gender << 16);
15908 SetUInt32ValueInArray(tokens, UNIT_FIELD_BYTES_0, unit_bytes0);
15910 SetUInt32ValueInArray(tokens, UNIT_FIELD_DISPLAYID, gender ? info->displayId_f : info->displayId_m);
15911 SetUInt32ValueInArray(tokens, UNIT_FIELD_NATIVEDISPLAYID, gender ? info->displayId_f : info->displayId_m);
15913 SetUInt32ValueInArray(tokens, PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
15915 uint32 player_bytes2 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_2);
15916 player_bytes2 &= ~0xFF;
15917 player_bytes2 |= facialHair;
15918 SetUInt32ValueInArray(tokens, PLAYER_BYTES_2, player_bytes2);
15920 uint32 player_bytes3 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_3);
15921 player_bytes3 &= ~0xFF;
15922 player_bytes3 |= gender;
15923 SetUInt32ValueInArray(tokens, PLAYER_BYTES_3, player_bytes3);
15925 SaveValuesArrayInDB(tokens, guid);
15928 void Player::SendAttackSwingNotStanding()
15930 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
15931 GetSession()->SendPacket( &data );
15934 void Player::SendAttackSwingDeadTarget()
15936 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
15937 GetSession()->SendPacket( &data );
15940 void Player::SendAttackSwingCantAttack()
15942 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
15943 GetSession()->SendPacket( &data );
15946 void Player::SendAttackSwingCancelAttack()
15948 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
15949 GetSession()->SendPacket( &data );
15952 void Player::SendAttackSwingBadFacingAttack()
15954 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
15955 GetSession()->SendPacket( &data );
15958 void Player::SendAutoRepeatCancel()
15960 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
15961 data.append(GetPackGUID()); // may be it's target guid
15962 GetSession()->SendPacket( &data );
15965 void Player::PlaySound(uint32 Sound, bool OnlySelf)
15967 WorldPacket data(SMSG_PLAY_SOUND, 4);
15968 data << Sound;
15969 if (OnlySelf)
15970 GetSession()->SendPacket( &data );
15971 else
15972 SendMessageToSet( &data, true );
15975 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
15977 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
15978 data << Area;
15979 data << Experience;
15980 GetSession()->SendPacket(&data);
15983 void Player::SendDungeonDifficulty(bool IsInGroup)
15985 uint8 val = 0x00000001;
15986 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
15987 data << (uint32)GetDifficulty();
15988 data << uint32(val);
15989 data << uint32(IsInGroup);
15990 GetSession()->SendPacket(&data);
15993 void Player::SendResetFailedNotify(uint32 mapid)
15995 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
15996 data << uint32(mapid);
15997 GetSession()->SendPacket(&data);
16000 /// Reset all solo instances and optionally send a message on success for each
16001 void Player::ResetInstances(uint8 method)
16003 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16005 // we assume that when the difficulty changes, all instances that can be reset will be
16006 uint8 dif = GetDifficulty();
16008 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
16010 InstanceSave *p = itr->second.save;
16011 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
16012 if(!entry || !p->CanReset())
16014 ++itr;
16015 continue;
16018 if(method == INSTANCE_RESET_ALL)
16020 // the "reset all instances" method can only reset normal maps
16021 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
16023 ++itr;
16024 continue;
16028 // if the map is loaded, reset it
16029 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
16030 if(map && map->IsDungeon())
16031 ((InstanceMap*)map)->Reset(method);
16033 // since this is a solo instance there should not be any players inside
16034 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16035 SendResetInstanceSuccess(p->GetMapId());
16037 p->DeleteFromDB();
16038 m_boundInstances[dif].erase(itr++);
16040 // the following should remove the instance save from the manager and delete it as well
16041 p->RemovePlayer(this);
16045 void Player::SendResetInstanceSuccess(uint32 MapId)
16047 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16048 data << MapId;
16049 GetSession()->SendPacket(&data);
16052 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16054 // TODO: find what other fail reasons there are besides players in the instance
16055 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16056 data << reason;
16057 data << MapId;
16058 GetSession()->SendPacket(&data);
16061 /*********************************************************/
16062 /*** Update timers ***/
16063 /*********************************************************/
16065 ///checks the 15 afk reports per 5 minutes limit
16066 void Player::UpdateAfkReport(time_t currTime)
16068 if(m_bgAfkReportedTimer <= currTime)
16070 m_bgAfkReportedCount = 0;
16071 m_bgAfkReportedTimer = currTime+5*MINUTE;
16075 void Player::UpdateContestedPvP(uint32 diff)
16077 if(!m_contestedPvPTimer||isInCombat())
16078 return;
16079 if(m_contestedPvPTimer <= diff)
16081 ResetContestedPvP();
16083 else
16084 m_contestedPvPTimer -= diff;
16087 void Player::UpdatePvPFlag(time_t currTime)
16089 if(!IsPvP())
16090 return;
16091 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16092 return;
16094 UpdatePvP(false);
16097 void Player::UpdateDuelFlag(time_t currTime)
16099 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16100 return;
16102 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16103 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16105 duel->startTimer = 0;
16106 duel->startTime = currTime;
16107 duel->opponent->duel->startTimer = 0;
16108 duel->opponent->duel->startTime = currTime;
16111 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16113 if(!pet)
16114 pet = GetPet();
16116 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16118 //returning of reagents only for players, so best done here
16119 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16120 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16122 if(spellInfo)
16124 for(uint32 i = 0; i < 7; ++i)
16126 if(spellInfo->Reagent[i] > 0)
16128 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16129 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16130 if( msg == EQUIP_ERR_OK )
16132 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16133 if(IsInWorld())
16134 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16139 m_temporaryUnsummonedPetNumber = 0;
16142 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16143 return;
16145 // only if current pet in slot
16146 switch(pet->getPetType())
16148 case MINI_PET:
16149 m_miniPet = 0;
16150 break;
16151 case GUARDIAN_PET:
16152 m_guardianPets.erase(pet->GetGUID());
16153 break;
16154 default:
16155 if(GetPetGUID() == pet->GetGUID())
16156 SetPet(NULL);
16157 break;
16160 pet->CombatStop();
16162 if(returnreagent)
16164 switch(pet->GetEntry())
16166 //warlock pets except imp are removed(?) when logging out
16167 case 1860:
16168 case 1863:
16169 case 417:
16170 case 17252:
16171 mode = PET_SAVE_NOT_IN_SLOT;
16172 break;
16176 pet->SavePetToDB(mode);
16178 pet->CleanupsBeforeDelete();
16179 pet->AddObjectToRemoveList();
16180 pet->m_removed = true;
16182 if(pet->isControlled())
16184 WorldPacket data(SMSG_PET_SPELLS, 8);
16185 data << uint64(0);
16186 data << uint32(0);
16187 GetSession()->SendPacket(&data);
16189 if(GetGroup())
16190 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16194 void Player::RemoveMiniPet()
16196 if(Pet* pet = GetMiniPet())
16198 pet->Remove(PET_SAVE_AS_DELETED);
16199 m_miniPet = 0;
16203 Pet* Player::GetMiniPet()
16205 if(!m_miniPet)
16206 return NULL;
16207 return ObjectAccessor::GetPet(m_miniPet);
16210 void Player::RemoveGuardians()
16212 while(!m_guardianPets.empty())
16214 uint64 guid = *m_guardianPets.begin();
16215 if(Pet* pet = ObjectAccessor::GetPet(guid))
16216 pet->Remove(PET_SAVE_AS_DELETED);
16218 m_guardianPets.erase(guid);
16222 bool Player::HasGuardianWithEntry(uint32 entry)
16224 // pet guid middle part is entry (and creature also)
16225 // and in guardian list must be guardians with same entry _always_
16226 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
16227 if(GUID_ENPART(*itr)==entry)
16228 return true;
16230 return false;
16233 void Player::Uncharm()
16235 Unit* charm = GetCharm();
16236 if(!charm)
16237 return;
16239 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16240 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16243 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16245 *data << (uint8)msgtype;
16246 *data << (uint32)language;
16247 *data << (uint64)GetGUID();
16248 *data << (uint32)language; //language 2.1.0 ?
16249 *data << (uint64)GetGUID();
16250 *data << (uint32)(text.length()+1);
16251 *data << text;
16252 *data << (uint8)chatTag();
16255 void Player::Say(const std::string& text, const uint32 language)
16257 WorldPacket data(SMSG_MESSAGECHAT, 200);
16258 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16259 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16262 void Player::Yell(const std::string& text, const uint32 language)
16264 WorldPacket data(SMSG_MESSAGECHAT, 200);
16265 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16266 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16269 void Player::TextEmote(const std::string& text)
16271 WorldPacket data(SMSG_MESSAGECHAT, 200);
16272 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16273 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16276 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16278 if (language != LANG_ADDON) // if not addon data
16279 language = LANG_UNIVERSAL; // whispers should always be readable
16281 Player *rPlayer = objmgr.GetPlayer(receiver);
16283 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16284 if(!rPlayer->isDND() || isGameMaster())
16286 WorldPacket data(SMSG_MESSAGECHAT, 200);
16287 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16288 rPlayer->GetSession()->SendPacket(&data);
16290 data.Initialize(SMSG_MESSAGECHAT, 200);
16291 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16292 GetSession()->SendPacket(&data);
16294 else
16296 // announce to player that player he is whispering to is dnd and cannot receive his message
16297 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16300 if(!isAcceptWhispers())
16302 SetAcceptWhispers(true);
16303 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16306 // announce to player that player he is whispering to is afk
16307 if(rPlayer->isAFK())
16308 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16310 // if player whisper someone, auto turn of dnd to be able to receive an answer
16311 if(isDND() && !rPlayer->isGameMaster())
16312 ToggleDND();
16315 void Player::PetSpellInitialize()
16317 Pet* pet = GetPet();
16319 if(!pet)
16320 return;
16322 sLog.outDebug("Pet Spells Groups");
16324 CharmInfo *charmInfo = pet->GetCharmInfo();
16326 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+10*4);
16327 data << uint64(pet->GetGUID());
16328 data << uint32(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16329 data << uint32(0);
16330 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16332 // action bar loop
16333 for(uint32 i = 0; i < 10; i++)
16335 data << uint32(charmInfo->GetActionBarEntry(i)->Raw);
16338 size_t spellsCountPos = data.wpos();
16340 // spells count
16341 uint8 addlist = 0;
16342 data << uint8(addlist); // placeholder
16344 if(pet->isControlled() && ((pet->getPetType() == HUNTER_PET) || ((pet->GetCreatureInfo()->type == CREATURE_TYPE_DEMON) && (getClass() == CLASS_WARLOCK))))
16346 // spells loop
16347 for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16349 if(itr->second->state == PETSPELL_REMOVED)
16350 continue;
16352 data << uint16(itr->first);
16353 data << uint16(itr->second->active); // pet spell active state isn't boolean
16354 ++addlist;
16358 data.put<uint8>(spellsCountPos, addlist);
16360 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16361 data << uint8(cooldownsCount);
16363 time_t curTime = time(NULL);
16365 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16367 time_t cooldown = 0;
16369 if(itr->second > curTime)
16370 cooldown = (itr->second - curTime) * 1000;
16372 data << uint16(itr->first); // spellid
16373 data << uint16(0); // spell category?
16374 data << uint32(itr->second); // cooldown
16375 data << uint32(0); // category cooldown
16378 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16380 time_t cooldown = 0;
16382 if(itr->second > curTime)
16383 cooldown = (itr->second - curTime) * 1000;
16385 data << uint16(itr->first); // spellid
16386 data << uint16(0); // spell category?
16387 data << uint32(0); // cooldown
16388 data << uint32(itr->second); // category cooldown
16391 GetSession()->SendPacket(&data);
16394 void Player::PossessSpellInitialize()
16396 Unit* charm = GetCharm();
16398 if(!charm)
16399 return;
16401 CharmInfo *charmInfo = charm->GetCharmInfo();
16403 if(!charmInfo)
16405 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16406 return;
16409 uint8 addlist = 0;
16410 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16412 //16
16413 data << uint64(charm->GetGUID());
16414 data << uint32(0x00000000);
16415 data << uint32(0);
16416 data << uint8(0) << uint8(0) << uint16(0);
16418 for(uint32 i = 0; i < 10; i++) //40
16420 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16423 data << uint8(addlist); //1
16425 uint8 count = 0;
16426 data << uint8(count); // cooldowns count
16428 GetSession()->SendPacket(&data);
16431 void Player::CharmSpellInitialize()
16433 Unit* charm = GetCharm();
16435 if(!charm)
16436 return;
16438 CharmInfo *charmInfo = charm->GetCharmInfo();
16439 if(!charmInfo)
16441 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16442 return;
16445 uint8 addlist = 0;
16447 if(charm->GetTypeId() != TYPEID_PLAYER)
16449 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16451 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16453 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16455 if(charmInfo->GetCharmSpell(i)->spellId)
16456 ++addlist;
16461 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16463 data << uint64(charm->GetGUID());
16464 data << uint32(0x00000000);
16465 data << uint32(0);
16466 if(charm->GetTypeId() != TYPEID_PLAYER)
16467 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
16468 else
16469 data << uint8(0) << uint8(0);
16470 data << uint16(0);
16472 for(uint32 i = 0; i < 10; i++) //40
16474 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16477 data << uint8(addlist); //1
16479 if(addlist)
16481 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16483 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16484 if(cspell->spellId)
16486 data << uint16(cspell->spellId);
16487 data << uint16(cspell->active);
16492 uint8 count = 0;
16493 data << uint8(count); // cooldowns count
16495 GetSession()->SendPacket(&data);
16498 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16500 if (!mod || !spellInfo)
16501 return false;
16503 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16505 // prevent apply to any spell except spell that trigger expire
16506 if(spell)
16508 if(mod->lastAffected != spell)
16509 return false;
16511 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16512 return false;
16515 return spellmgr.IsAffectedByMod(spellInfo, mod);
16518 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16520 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16522 for(int eff=0;eff<96;++eff)
16524 uint64 _mask = 0;
16525 uint64 _mask2= 0;
16526 if (eff<64) _mask = uint64(1) << (eff- 0);
16527 else _mask2= uint64(1) << (eff-64);
16528 if ( mod->mask & _mask || mod->mask2 & _mask2)
16530 int32 val = 0;
16531 for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16533 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16534 val += (*itr)->value;
16536 val += apply ? mod->value : -(mod->value);
16537 WorldPacket data(Opcode, (1+1+4));
16538 data << uint8(eff);
16539 data << uint8(mod->op);
16540 data << int32(val);
16541 SendDirectMessage(&data);
16545 if (apply)
16546 m_spellMods[mod->op].push_back(mod);
16547 else
16549 if (mod->charges == -1)
16550 --m_SpellModRemoveCount;
16551 m_spellMods[mod->op].remove(mod);
16552 delete mod;
16556 void Player::RemoveSpellMods(Spell const* spell)
16558 if(!spell || (m_SpellModRemoveCount == 0))
16559 return;
16561 for(int i=0;i<MAX_SPELLMOD;++i)
16563 for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16565 SpellModifier *mod = *itr;
16566 ++itr;
16568 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16570 RemoveAurasDueToSpell(mod->spellId);
16571 if (m_spellMods[i].empty())
16572 break;
16573 else
16574 itr = m_spellMods[i].begin();
16580 // send Proficiency
16581 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16583 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16584 data << pr1 << pr2;
16585 GetSession()->SendPacket (&data);
16588 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16590 QueryResult *result = NULL;
16591 if(type==10)
16592 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16593 else
16594 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16595 if(result)
16597 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.
16598 { // and SendPetitionQueryOpcode reads data from the DB
16599 Field *fields = result->Fetch();
16600 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16601 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16603 // send update if charter owner in game
16604 Player* owner = objmgr.GetPlayer(ownerguid);
16605 if(owner)
16606 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16608 } while ( result->NextRow() );
16610 delete result;
16612 if(type==10)
16613 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16614 else
16615 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16618 CharacterDatabase.BeginTransaction();
16619 if(type == 10)
16621 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16622 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16624 else
16626 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16627 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16629 CharacterDatabase.CommitTransaction();
16632 void Player::LeaveAllArenaTeams(uint64 guid)
16634 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));
16635 if(!result)
16636 return;
16640 Field *fields = result->Fetch();
16641 uint32 at_id = fields[0].GetUInt32();
16642 if(at_id != 0)
16644 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
16645 if(at)
16646 at->DelMember(guid);
16648 } while (result->NextRow());
16650 delete result;
16653 void Player::SetRestBonus (float rest_bonus_new)
16655 // Prevent resting on max level
16656 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16657 rest_bonus_new = 0;
16659 if(rest_bonus_new < 0)
16660 rest_bonus_new = 0;
16662 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16664 if(rest_bonus_new > rest_bonus_max)
16665 m_rest_bonus = rest_bonus_max;
16666 else
16667 m_rest_bonus = rest_bonus_new;
16669 // update data for client
16670 if(m_rest_bonus>10)
16671 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16672 else if(m_rest_bonus<=1)
16673 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16675 //RestTickUpdate
16676 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16679 void Player::HandleStealthedUnitsDetection()
16681 std::list<Unit*> stealthedUnits;
16683 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16684 Cell cell(p);
16685 cell.data.Part.reserved = ALL_DISTRICT;
16686 cell.SetNoCreate();
16688 MaNGOS::AnyStealthedCheck u_check;
16689 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(stealthedUnits, u_check);
16691 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16692 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16694 CellLock<GridReadGuard> cell_lock(cell, p);
16695 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
16696 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
16698 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16700 if((*i)==this)
16702 i = stealthedUnits.erase(i);
16703 continue;
16706 if ((*i)->isVisibleForOrDetect(this,true))
16709 (*i)->SendUpdateToPlayer(this);
16710 m_clientGUIDs.insert((*i)->GetGUID());
16712 #ifdef MANGOS_DEBUG
16713 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16714 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16715 #endif
16717 // target aura duration for caster show only if target exist at caster client
16718 // send data at target visibility change (adding to client)
16719 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16720 SendAurasForTarget(*i);
16722 i = stealthedUnits.erase(i);
16723 continue;
16726 ++i;
16730 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
16732 if(nodes.size() < 2)
16733 return false;
16735 // not let cheating with start flight mounted
16736 if(IsMounted())
16738 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16739 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16740 GetSession()->SendPacket(&data);
16741 return false;
16744 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16746 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16747 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16748 GetSession()->SendPacket(&data);
16749 return false;
16752 // not let cheating with start flight in time of logout process || if casting not finished || while in combat || if not use Spell's with EffectSendTaxi
16753 if(GetSession()->isLogingOut() ||
16754 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
16755 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
16756 IsNonMeleeSpellCasted(false) ||
16757 isInCombat())
16759 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16760 data << uint32(ERR_TAXIPLAYERBUSY);
16761 GetSession()->SendPacket(&data);
16762 return false;
16765 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16766 return false;
16768 uint32 sourcenode = nodes[0];
16770 // starting node too far away (cheat?)
16771 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16772 if( !node || node->map_id != GetMapId() ||
16773 (node->x - GetPositionX())*(node->x - GetPositionX())+
16774 (node->y - GetPositionY())*(node->y - GetPositionY())+
16775 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16776 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
16778 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16779 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16780 GetSession()->SendPacket(&data);
16781 return false;
16784 // Prepare to flight start now
16786 // stop combat at start taxi flight if any
16787 CombatStop();
16789 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16790 TradeCancel(true);
16792 // clean not finished taxi path if any
16793 m_taxi.ClearTaxiDestinations();
16795 // 0 element current node
16796 m_taxi.AddTaxiDestination(sourcenode);
16798 // fill destinations path tail
16799 uint32 sourcepath = 0;
16800 uint32 totalcost = 0;
16802 uint32 prevnode = sourcenode;
16803 uint32 lastnode = 0;
16805 for(uint32 i = 1; i < nodes.size(); ++i)
16807 uint32 path, cost;
16809 lastnode = nodes[i];
16810 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16812 if(!path)
16814 m_taxi.ClearTaxiDestinations();
16815 return false;
16818 totalcost += cost;
16820 if(prevnode == sourcenode)
16821 sourcepath = path;
16823 m_taxi.AddTaxiDestination(lastnode);
16825 prevnode = lastnode;
16828 if(!mount_id) // if not provide then attempt use default.
16829 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
16831 if (mount_id == 0 || sourcepath == 0)
16833 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16834 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16835 GetSession()->SendPacket(&data);
16836 m_taxi.ClearTaxiDestinations();
16837 return false;
16840 uint32 money = GetMoney();
16842 if(npc)
16844 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16847 if(money < totalcost)
16849 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16850 data << uint32(ERR_TAXINOTENOUGHMONEY);
16851 GetSession()->SendPacket(&data);
16852 m_taxi.ClearTaxiDestinations();
16853 return false;
16856 //Checks and preparations done, DO FLIGHT
16857 ModifyMoney(-(int32)totalcost);
16859 // prevent stealth flight
16860 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16862 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16863 data << uint32(ERR_TAXIOK);
16864 GetSession()->SendPacket(&data);
16866 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16868 GetSession()->SendDoFlight(mount_id, sourcepath);
16870 return true;
16873 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16875 // last check 2.0.10
16876 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16877 data << GetGUID();
16878 data << uint8(0x0); // flags (0x1, 0x2)
16879 time_t curTime = time(NULL);
16880 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
16882 if (itr->second->state == PLAYERSPELL_REMOVED)
16883 continue;
16884 uint32 unSpellId = itr->first;
16885 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
16886 if (!spellInfo)
16888 ASSERT(spellInfo);
16889 continue;
16892 // Not send cooldown for this spells
16893 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
16894 continue;
16896 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
16898 data << unSpellId;
16899 data << unTimeMs; // in m.secs
16900 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/1000);
16903 GetSession()->SendPacket(&data);
16906 void Player::InitDataForForm(bool reapplyMods)
16908 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
16909 if(ssEntry && ssEntry->attackSpeed)
16911 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
16912 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
16913 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
16915 else
16916 SetRegularAttackTime();
16918 switch(m_form)
16920 case FORM_CAT:
16922 if(getPowerType()!=POWER_ENERGY)
16923 setPowerType(POWER_ENERGY);
16924 break;
16926 case FORM_BEAR:
16927 case FORM_DIREBEAR:
16929 if(getPowerType()!=POWER_RAGE)
16930 setPowerType(POWER_RAGE);
16931 break;
16933 default: // 0, for example
16935 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
16936 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
16937 setPowerType(Powers(cEntry->powerType));
16938 break;
16942 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16943 if (!reapplyMods)
16944 UpdateEquipSpellsAtFormChange();
16946 UpdateAttackPowerAndDamage();
16947 UpdateAttackPowerAndDamage(true);
16950 // Return true is the bought item has a max count to force refresh of window by caller
16951 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
16953 // cheating attempt
16954 if(count < 1) count = 1;
16956 if(!isAlive())
16957 return false;
16959 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
16960 if( !pProto )
16962 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
16963 return false;
16966 Creature *pCreature = ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid,UNIT_NPC_FLAG_VENDOR);
16967 if (!pCreature)
16969 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
16970 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
16971 return false;
16974 VendorItemData const* vItems = pCreature->GetVendorItems();
16975 if(!vItems || vItems->Empty())
16977 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16978 return false;
16981 size_t vendor_slot = vItems->FindItemSlot(item);
16982 if(vendor_slot >= vItems->GetItemCount())
16984 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16985 return false;
16988 VendorItem const* crItem = vItems->m_items[vendor_slot];
16990 // check current item amount if it limited
16991 if( crItem->maxcount != 0 )
16993 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
16995 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
16996 return false;
17000 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
17002 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
17003 return false;
17006 if(crItem->ExtendedCost)
17008 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17009 if(!iece)
17011 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
17012 return false;
17015 // honor points price
17016 if(GetHonorPoints() < (iece->reqhonorpoints * count))
17018 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
17019 return false;
17022 // arena points price
17023 if(GetArenaPoints() < (iece->reqarenapoints * count))
17025 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
17026 return false;
17029 // item base price
17030 for (uint8 i = 0; i < 5; ++i)
17032 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17034 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17035 return false;
17039 // check for personal arena rating requirement
17040 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
17042 // probably not the proper equip err
17043 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17044 return false;
17048 uint32 price = pProto->BuyPrice * count;
17050 // reputation discount
17051 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17053 if( GetMoney() < price )
17055 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17056 return false;
17059 uint8 bag = 0; // init for case invalid bagGUID
17061 if (bagguid != NULL_BAG && slot != NULL_SLOT)
17063 Bag *pBag;
17064 if( bagguid == GetGUID() )
17066 bag = INVENTORY_SLOT_BAG_0;
17068 else
17070 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;i++)
17072 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
17073 if( pBag )
17075 if( bagguid == pBag->GetGUID() )
17077 bag = i;
17078 break;
17085 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
17087 ItemPosCountVec dest;
17088 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17089 if( msg != EQUIP_ERR_OK )
17091 SendEquipError( msg, NULL, NULL );
17092 return false;
17095 ModifyMoney( -(int32)price );
17096 if(crItem->ExtendedCost) // case for new honor system
17098 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17099 if(iece->reqhonorpoints)
17100 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17101 if(iece->reqarenapoints)
17102 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17103 for (uint8 i = 0; i < 5; ++i)
17105 if(iece->reqitem[i])
17106 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17110 if(Item *it = StoreNewItem( dest, item, true ))
17112 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17114 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17115 data << pCreature->GetGUID();
17116 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17117 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17118 data << (uint32)count;
17119 GetSession()->SendPacket(&data);
17121 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17124 else if( IsEquipmentPos( bag, slot ) )
17126 if(pProto->BuyCount * count != 1)
17128 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17129 return false;
17132 uint16 dest;
17133 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17134 if( msg != EQUIP_ERR_OK )
17136 SendEquipError( msg, NULL, NULL );
17137 return false;
17140 ModifyMoney( -(int32)price );
17141 if(crItem->ExtendedCost) // case for new honor system
17143 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17144 if(iece->reqhonorpoints)
17145 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17146 if(iece->reqarenapoints)
17147 ModifyArenaPoints( - int32(iece->reqarenapoints));
17148 for (uint8 i = 0; i < 5; ++i)
17150 if(iece->reqitem[i])
17151 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17155 if(Item *it = EquipNewItem( dest, item, true ))
17157 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17159 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17160 data << pCreature->GetGUID();
17161 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17162 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17163 data << (uint32)count;
17164 GetSession()->SendPacket(&data);
17166 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17168 AutoUnequipOffhandIfNeed();
17171 else
17173 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17174 return false;
17177 return crItem->maxcount!=0;
17180 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17182 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17183 // the personal rating of the arena team must match the required limit as well
17184 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17185 uint32 max_personal_rating = 0;
17186 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17188 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17190 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17191 uint32 t_rating = at->GetRating();
17192 p_rating = p_rating<t_rating? p_rating : t_rating;
17193 if(max_personal_rating < p_rating)
17194 max_personal_rating = p_rating;
17197 return max_personal_rating;
17200 void Player::UpdateHomebindTime(uint32 time)
17202 // GMs never get homebind timer online
17203 if (m_InstanceValid || isGameMaster())
17205 if(m_HomebindTimer) // instance valid, but timer not reset
17207 // hide reminder
17208 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17209 data << uint32(0);
17210 data << uint32(0);
17211 GetSession()->SendPacket(&data);
17213 // instance is valid, reset homebind timer
17214 m_HomebindTimer = 0;
17216 else if (m_HomebindTimer > 0)
17218 if (time >= m_HomebindTimer)
17220 // teleport to homebind location
17221 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
17223 else
17224 m_HomebindTimer -= time;
17226 else
17228 // instance is invalid, start homebind timer
17229 m_HomebindTimer = 60000;
17230 // send message to player
17231 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17232 data << m_HomebindTimer;
17233 data << uint32(1);
17234 GetSession()->SendPacket(&data);
17235 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17239 void Player::UpdatePvP(bool state, bool ovrride)
17241 if(!state || ovrride)
17243 SetPvP(state);
17244 if(Pet* pet = GetPet())
17245 pet->SetPvP(state);
17246 if(Unit* charmed = GetCharm())
17247 charmed->SetPvP(state);
17249 pvpInfo.endTimer = 0;
17251 else
17253 if(pvpInfo.endTimer != 0)
17254 pvpInfo.endTimer = time(NULL);
17255 else
17257 SetPvP(state);
17259 if(Pet* pet = GetPet())
17260 pet->SetPvP(state);
17261 if(Unit* charmed = GetCharm())
17262 charmed->SetPvP(state);
17267 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17269 SpellCooldown sc;
17270 sc.end = end_time;
17271 sc.itemid = itemid;
17272 m_spellCooldowns[spellid] = sc;
17275 void Player::SendCooldownEvent(SpellEntry const *spellInfo)
17277 if ( !(spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) )
17278 return;
17280 // Get spell cooldown
17281 int32 cooldown = GetSpellRecoveryTime(spellInfo);
17282 // Apply spellmods
17283 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, cooldown);
17284 if (cooldown < 0)
17285 cooldown = 0;
17286 // Add cooldown
17287 AddSpellCooldown(spellInfo->Id, 0, time(NULL) + cooldown / 1000);
17288 // Send activate
17289 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17290 data << spellInfo->Id;
17291 data << GetGUID();
17292 SendDirectMessage(&data);
17294 //slot to be excluded while counting
17295 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17297 if(!enchantmentcondition)
17298 return true;
17300 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17302 if(!Condition)
17303 return true;
17305 uint8 curcount[4] = {0, 0, 0, 0};
17307 //counting current equipped gem colors
17308 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17310 if(i == slot)
17311 continue;
17312 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17313 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17315 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17317 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17318 if(!enchant_id)
17319 continue;
17321 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17322 if(!enchantEntry)
17323 continue;
17325 uint32 gemid = enchantEntry->GemID;
17326 if(!gemid)
17327 continue;
17329 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17330 if(!gemProto)
17331 continue;
17333 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17334 if(!gemProperty)
17335 continue;
17337 uint8 GemColor = gemProperty->color;
17339 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17341 if(tmpcolormask & GemColor)
17342 ++curcount[b];
17348 bool activate = true;
17350 for(int i = 0; i < 5; i++)
17352 if(!Condition->Color[i])
17353 continue;
17355 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17357 // if have <CompareColor> use them as count, else use <value> from Condition
17358 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17360 switch(Condition->Comparator[i])
17362 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17363 activate &= (_cur_gem < _cmp_gem) ? true : false;
17364 break;
17365 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17366 activate &= (_cur_gem > _cmp_gem) ? true : false;
17367 break;
17368 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17369 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17370 break;
17374 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");
17376 return activate;
17379 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17381 //cycle all equipped items
17382 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17384 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17385 if(slot == exceptslot)
17386 continue;
17388 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17390 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17391 continue;
17393 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17395 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17396 if(!enchant_id)
17397 continue;
17399 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17400 if(!enchantEntry)
17401 continue;
17403 uint32 condition = enchantEntry->EnchantmentCondition;
17404 if(condition)
17406 //was enchant active with/without item?
17407 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17408 //should it now be?
17409 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17411 // ignore item gem conditions
17412 //if state changed, (dis)apply enchant
17413 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17420 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17421 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17423 //cycle all equipped items
17424 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17426 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17427 if(slot == exceptslot)
17428 continue;
17430 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17432 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17433 continue;
17435 //cycle all (gem)enchants
17436 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17438 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17439 if(!enchant_id) //if no enchant go to next enchant(slot)
17440 continue;
17442 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17443 if(!enchantEntry)
17444 continue;
17446 //only metagems to be (de)activated, so only enchants with condition
17447 uint32 condition = enchantEntry->EnchantmentCondition;
17448 if(condition)
17449 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17454 void Player::LeaveBattleground(bool teleportToEntryPoint)
17456 if(BattleGround *bg = GetBattleGround())
17458 bool need_debuf = bg->isBattleGround() && (bg->GetStatus() == STATUS_IN_PROGRESS) && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER);
17460 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17462 // call after remove to be sure that player resurrected for correct cast
17463 if(need_debuf)
17464 CastSpell(this, 26013, true); // Deserter
17468 bool Player::CanJoinToBattleground() const
17470 // check Deserter debuff
17471 if(GetDummyAura(26013))
17472 return false;
17474 return true;
17477 bool Player::CanReportAfkDueToLimit()
17479 // a player can complain about 15 people per 5 minutes
17480 if(m_bgAfkReportedCount >= 15)
17481 return false;
17482 ++m_bgAfkReportedCount;
17483 return true;
17486 ///This player has been blamed to be inactive in a battleground
17487 void Player::ReportedAfkBy(Player* reporter)
17489 BattleGround *bg = GetBattleGround();
17490 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17491 return;
17493 // check if player has 'Idle' or 'Inactive' debuff
17494 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17496 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17497 // 3 players have to complain to apply debuff
17498 if(m_bgAfkReporter.size() >= 3)
17500 // cast 'Idle' spell
17501 CastSpell(this, 43680, true);
17502 m_bgAfkReporter.clear();
17507 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17509 // gamemaster in GM mode see all, including ghosts
17510 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17511 return true;
17513 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17514 if (InBattleGround())
17516 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17517 return false;
17518 return true;
17521 // Live player see live player or dead player with not realized corpse
17522 if(pl->isAlive() || pl->m_deathTimer > 0)
17524 return isAlive() || m_deathTimer > 0;
17527 // Ghost see other friendly ghosts, that's for sure
17528 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17529 return true;
17531 // Dead player see live players near own corpse
17532 if(isAlive())
17534 Corpse *corpse = pl->GetCorpse();
17535 if(corpse)
17537 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17538 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17539 return true;
17543 // and not see any other
17544 return false;
17547 bool Player::IsVisibleGloballyFor( Player* u ) const
17549 if(!u)
17550 return false;
17552 // Always can see self
17553 if (u==this)
17554 return true;
17556 // Visible units, always are visible for all players
17557 if (GetVisibility() == VISIBILITY_ON)
17558 return true;
17560 // GMs are visible for higher gms (or players are visible for gms)
17561 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17562 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17564 // non faction visibility non-breakable for non-GMs
17565 if (GetVisibility() == VISIBILITY_OFF)
17566 return false;
17568 // non-gm stealth/invisibility not hide from global player lists
17569 return true;
17572 void Player::UpdateVisibilityOf(WorldObject* target)
17574 if(HaveAtClient(target))
17576 if(!target->isVisibleForInState(this,true))
17578 target->DestroyForPlayer(this);
17579 m_clientGUIDs.erase(target->GetGUID());
17581 #ifdef MANGOS_DEBUG
17582 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17583 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17584 #endif
17587 else
17589 if(target->isVisibleForInState(this,false))
17591 target->SendUpdateToPlayer(this);
17592 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17593 m_clientGUIDs.insert(target->GetGUID());
17595 #ifdef MANGOS_DEBUG
17596 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17597 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17598 #endif
17600 // target aura duration for caster show only if target exist at caster client
17601 // send data at target visibility change (adding to client)
17602 if(target!=this && target->isType(TYPEMASK_UNIT))
17603 SendAurasForTarget((Unit*)target);
17605 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17606 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17611 template<class T>
17612 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17614 s64.insert(target->GetGUID());
17617 template<>
17618 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17620 if(!target->IsTransport())
17621 s64.insert(target->GetGUID());
17624 template<class T>
17625 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17627 if(HaveAtClient(target))
17629 if(!target->isVisibleForInState(this,true))
17631 target->BuildOutOfRangeUpdateBlock(&data);
17632 m_clientGUIDs.erase(target->GetGUID());
17634 #ifdef MANGOS_DEBUG
17635 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17636 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));
17637 #endif
17640 else
17642 if(target->isVisibleForInState(this,false))
17644 visibleNow.insert(target);
17645 target->BuildUpdate(data_updates);
17646 target->BuildCreateUpdateBlockForPlayer(&data, this);
17647 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17649 #ifdef MANGOS_DEBUG
17650 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17651 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));
17652 #endif
17657 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17658 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17659 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17660 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17661 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17663 void Player::InitPrimaryProffesions()
17665 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17668 void Player::SendComboPoints()
17670 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17671 if (combotarget)
17673 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17674 data.append(combotarget->GetPackGUID());
17675 data << uint8(m_comboPoints);
17676 GetSession()->SendPacket(&data);
17680 void Player::AddComboPoints(Unit* target, int8 count)
17682 if(!count)
17683 return;
17685 // without combo points lost (duration checked in aura)
17686 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17688 if(target->GetGUID() == m_comboTarget)
17690 m_comboPoints += count;
17692 else
17694 if(m_comboTarget)
17695 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17696 target->RemoveComboPointHolder(GetGUIDLow());
17698 m_comboTarget = target->GetGUID();
17699 m_comboPoints = count;
17701 target->AddComboPointHolder(GetGUIDLow());
17704 if (m_comboPoints > 5) m_comboPoints = 5;
17705 if (m_comboPoints < 0) m_comboPoints = 0;
17707 SendComboPoints();
17710 void Player::ClearComboPoints()
17712 if(!m_comboTarget)
17713 return;
17715 // without combopoints lost (duration checked in aura)
17716 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17718 m_comboPoints = 0;
17720 SendComboPoints();
17722 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17723 target->RemoveComboPointHolder(GetGUIDLow());
17725 m_comboTarget = 0;
17728 void Player::SetGroup(Group *group, int8 subgroup)
17730 if(group == NULL) m_group.unlink();
17731 else
17733 // never use SetGroup without a subgroup unless you specify NULL for group
17734 assert(subgroup >= 0);
17735 m_group.link(group, this);
17736 m_group.setSubGroup((uint8)subgroup);
17740 void Player::SendInitialPacketsBeforeAddToMap()
17742 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
17743 data << uint32(0); // unknown, may be rest state time or experience
17744 GetSession()->SendPacket(&data);
17746 // Homebind
17747 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17748 data << m_homebindX << m_homebindY << m_homebindZ;
17749 data << (uint32) m_homebindMapId;
17750 data << (uint32) m_homebindZoneId;
17751 GetSession()->SendPacket(&data);
17753 // SMSG_SET_PROFICIENCY
17754 // SMSG_UPDATE_AURA_DURATION
17756 // tutorial stuff
17757 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
17758 for (int i = 0; i < 8; ++i)
17759 data << uint32( GetTutorialInt(i) );
17760 GetSession()->SendPacket(&data);
17762 SendInitialSpells();
17764 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17765 data << uint32(0); // count, for(count) uint32;
17766 GetSession()->SendPacket(&data);
17768 SendInitialActionButtons();
17769 SendInitialReputations();
17770 m_achievementMgr.SendAllAchievementData();
17771 UpdateZone(GetZoneId());
17772 SendInitWorldStates();
17774 // SMSG_SET_AURA_SINGLE
17776 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
17777 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
17778 data << (float)0.01666667f; // game speed
17779 GetSession()->SendPacket( &data );
17781 data.Initialize(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
17782 data << uint32(0x00000000); // on blizz it increments periodically
17783 GetSession()->SendPacket(&data);
17785 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17786 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
17787 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
17789 m_mover = this;
17792 void Player::SendInitialPacketsAfterAddToMap()
17794 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
17795 data << uint32(0x00000000); // on blizz it increments periodically
17796 GetSession()->SendPacket(&data);
17798 CastSpell(this, 836, true); // LOGINEFFECT
17800 // set some aura effects that send packet to player client after add player to map
17801 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17802 // same auras state lost at far teleport, send it one more time in this case also
17803 static const AuraType auratypes[] =
17805 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
17806 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
17807 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
17809 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
17811 Unit::AuraList const& auraList = GetAurasByType(*itr);
17812 if(!auraList.empty())
17813 auraList.front()->ApplyModifier(true,true);
17816 if(HasAuraType(SPELL_AURA_MOD_STUN))
17817 SetMovement(MOVE_ROOT);
17819 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17820 if(HasAuraType(SPELL_AURA_MOD_ROOT))
17822 WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
17823 data.append(GetPackGUID());
17824 data << (uint32)2;
17825 SendMessageToSet(&data,true);
17828 SendAurasForTarget(this);
17829 SendEnchantmentDurations(); // must be after add to map
17830 SendItemDurations(); // must be after add to map
17833 void Player::SendUpdateToOutOfRangeGroupMembers()
17835 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
17836 return;
17837 if(Group* group = GetGroup())
17838 group->UpdatePlayerOutOfRange(this);
17840 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
17841 m_auraUpdateMask = 0;
17842 if(Pet *pet = GetPet())
17843 pet->ResetAuraUpdateMask();
17846 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
17848 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
17849 data << uint32(mapid);
17850 data << uint8(reason); // transfer abort reason
17851 switch(reason)
17853 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
17854 case TRANSFER_ABORT_DIFFICULTY:
17855 case TRANSFER_ABORT_UNIQUE_MESSAGE:
17856 data << uint8(arg);
17857 break;
17859 GetSession()->SendPacket(&data);
17862 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
17864 // type of warning, based on the time remaining until reset
17865 uint32 type;
17866 if(time > 3600)
17867 type = RAID_INSTANCE_WELCOME;
17868 else if(time > 900 && time <= 3600)
17869 type = RAID_INSTANCE_WARNING_HOURS;
17870 else if(time > 300 && time <= 900)
17871 type = RAID_INSTANCE_WARNING_MIN;
17872 else
17873 type = RAID_INSTANCE_WARNING_MIN_SOON;
17874 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
17875 data << uint32(type);
17876 data << uint32(mapid);
17877 data << uint32(time);
17878 GetSession()->SendPacket(&data);
17881 void Player::ApplyEquipCooldown( Item * pItem )
17883 for(int i = 0; i <5; ++i)
17885 _Spell const& spellData = pItem->GetProto()->Spells[i];
17887 // no spell
17888 if( !spellData.SpellId )
17889 continue;
17891 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17892 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
17893 continue;
17895 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
17897 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
17898 data << pItem->GetGUID();
17899 data << uint32(spellData.SpellId);
17900 GetSession()->SendPacket(&data);
17904 void Player::resetSpells()
17906 // not need after this call
17907 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
17909 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
17910 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
17913 // make full copy of map (spells removed and marked as deleted at another spell remove
17914 // and we can't use original map for safe iterative with visit each spell at loop end
17915 PlayerSpellMap smap = GetSpellMap();
17917 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
17918 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
17920 learnDefaultSpells();
17921 learnQuestRewardedSpells();
17924 void Player::learnDefaultSpells(bool loading)
17926 // learn default race/class spells
17927 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
17928 std::list<CreateSpellPair>::const_iterator spell_itr;
17929 for (spell_itr = info->spell.begin(); spell_itr!=info->spell.end(); ++spell_itr)
17931 uint16 tspell = spell_itr->first;
17932 if (tspell)
17934 sLog.outDebug("PLAYER: Adding initial spell, id = %u",tspell);
17935 if(loading || !spell_itr->second) // not care about passive spells or loading case
17936 addSpell(tspell,spell_itr->second);
17937 else // but send in normal spell in game learn case
17938 learnSpell(tspell);
17943 void Player::learnQuestRewardedSpells(Quest const* quest)
17945 uint32 spell_id = quest->GetRewSpellCast();
17947 // skip quests without rewarded spell
17948 if( !spell_id )
17949 return;
17951 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
17952 if(!spellInfo)
17953 return;
17955 // check learned spells state
17956 bool found = false;
17957 for(int i=0; i < 3; ++i)
17959 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
17961 found = true;
17962 break;
17966 // skip quests with not teaching spell or already known spell
17967 if(!found)
17968 return;
17970 // prevent learn non first rank unknown profession and second specialization for same profession)
17971 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
17972 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
17974 // not have first rank learned (unlearned prof?)
17975 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
17976 if( !HasSpell(first_spell) )
17977 return;
17979 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
17980 if(!learnedInfo)
17981 return;
17983 // specialization
17984 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
17986 // search other specialization for same prof
17987 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17989 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
17990 continue;
17992 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
17993 if(!itrInfo)
17994 return;
17996 // compare only specializations
17997 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
17998 continue;
18000 // compare same chain spells
18001 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18002 continue;
18004 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18005 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18006 return;
18011 CastSpell( this, spell_id, true);
18014 void Player::learnQuestRewardedSpells()
18016 // learn spells received from quest completing
18017 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18019 // skip no rewarded quests
18020 if(!itr->second.m_rewarded)
18021 continue;
18023 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18024 if( !quest )
18025 continue;
18027 learnQuestRewardedSpells(quest);
18031 void Player::learnSkillRewardedSpells(uint32 skill_id )
18033 uint32 raceMask = getRaceMask();
18034 uint32 classMask = getClassMask();
18035 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18037 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18038 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18039 continue;
18040 // Check race if set
18041 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18042 continue;
18043 // Check class if set
18044 if (pAbility->classmask && !(pAbility->classmask & classMask))
18045 continue;
18047 if (sSpellStore.LookupEntry(pAbility->spellId))
18049 // Ok need learn spell
18050 learnSpell(pAbility->spellId);
18055 void Player::learnSkillRewardedSpells()
18057 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
18059 if(!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
18060 continue;
18062 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
18064 learnSkillRewardedSpells(pskill);
18068 void Player::SendAurasForTarget(Unit *target)
18070 if(target->GetVisibleAuras()->empty()) // speedup things
18071 return;
18073 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18074 data.append(target->GetPackGUID());
18076 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18077 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18079 for(uint32 j = 0; j < 3; ++j)
18081 if(Aura *aura = target->GetAura(itr->second, j))
18083 data << uint8(aura->GetAuraSlot());
18084 data << uint32(aura->GetId());
18086 if(aura->GetId())
18088 uint8 auraFlags = aura->GetAuraFlags();
18089 // flags
18090 data << uint8(auraFlags);
18091 // level
18092 data << uint8(aura->GetAuraLevel());
18093 // charges
18094 data << uint8(aura->m_procCharges >= 0 ? aura->m_procCharges : 0 );
18096 if(!(auraFlags & AFLAG_NOT_CASTER))
18098 data << uint8(0); // packed GUID of someone (caster?)
18101 if(auraFlags & AFLAG_DURATION) // include aura duration
18103 data << uint32(aura->GetAuraMaxDuration());
18104 data << uint32(aura->GetAuraDuration());
18107 break;
18112 GetSession()->SendPacket(&data);
18115 void Player::SetDailyQuestStatus( uint32 quest_id )
18117 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18119 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18121 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18122 m_lastDailyQuestTime = time(NULL); // last daily quest time
18123 m_DailyQuestChanged = true;
18124 break;
18129 void Player::ResetDailyQuestStatus()
18131 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18132 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18134 // DB data deleted in caller
18135 m_DailyQuestChanged = false;
18136 m_lastDailyQuestTime = 0;
18139 BattleGround* Player::GetBattleGround() const
18141 if(GetBattleGroundId()==0)
18142 return NULL;
18144 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
18147 bool Player::InArena() const
18149 BattleGround *bg = GetBattleGround();
18150 if(!bg || !bg->isArena())
18151 return false;
18153 return true;
18156 bool Player::GetBGAccessByLevel(uint32 bgTypeId) const
18158 // get a template bg instead of running one
18159 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18160 if(!bg)
18161 return false;
18163 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18164 return false;
18166 return true;
18169 uint32 Player::GetMinLevelForBattleGroundQueueId(uint32 queue_id)
18171 if(queue_id < 1)
18172 return 0;
18174 if(queue_id >=7)
18175 queue_id = 7;
18177 return 10*(queue_id+1);
18180 uint32 Player::GetMaxLevelForBattleGroundQueueId(uint32 queue_id)
18182 if(queue_id >=7)
18183 return 255; // hardcoded max level
18185 return 10*(queue_id+2)-1;
18188 uint32 Player::GetBattleGroundQueueIdFromLevel() const
18190 uint32 level = getLevel();
18191 if(level <= 19)
18192 return 0;
18193 else if (level > 79)
18194 return 7;
18195 else
18196 return level/10 - 1; // 20..29 -> 1, 30-39 -> 2, ...
18198 assert(bgTypeId < MAX_BATTLEGROUND_TYPES);
18199 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18200 assert(bg);
18201 return (getLevel() - bg->GetMinLevel()) / 10;*/
18204 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18206 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18207 if(!vendor_faction)
18208 return 1.0f;
18210 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18211 if(rank <= REP_NEUTRAL)
18212 return 1.0f;
18214 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18217 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18219 uint32 racemask = getRaceMask();
18220 uint32 classmask = getClassMask();
18222 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
18223 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
18225 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
18227 // skip wrong race skills
18228 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18229 return false;
18231 // skip wrong class skills
18232 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18233 return false;
18235 return true;
18238 bool Player::HasQuestForGO(int32 GOId)
18240 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
18242 QuestStatusData qs=i->second;
18243 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18245 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
18246 if(!qinfo)
18247 continue;
18249 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18250 continue;
18252 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
18254 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18255 continue;
18257 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18258 return true;
18262 return false;
18265 void Player::UpdateForQuestsGO()
18267 if(m_clientGUIDs.empty())
18268 return;
18270 UpdateData udata;
18271 WorldPacket packet;
18272 for(ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18274 if(IS_GAMEOBJECT_GUID(*itr))
18276 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18277 if(obj)
18278 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18281 udata.BuildPacket(&packet);
18282 GetSession()->SendPacket(&packet);
18285 void Player::SummonIfPossible(bool agree)
18287 if(!agree)
18289 m_summon_expire = 0;
18290 return;
18293 // expire and auto declined
18294 if(m_summon_expire < time(NULL))
18295 return;
18297 // stop taxi flight at summon
18298 if(isInFlight())
18300 GetMotionMaster()->MovementExpired();
18301 m_taxi.ClearTaxiDestinations();
18304 // drop flag at summon
18305 if(BattleGround *bg = GetBattleGround())
18306 bg->EventPlayerDroppedFlag(this);
18308 m_summon_expire = 0;
18310 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18313 void Player::RemoveItemDurations( Item *item )
18315 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18317 if(*itr==item)
18319 m_itemDuration.erase(itr);
18320 break;
18325 void Player::AddItemDurations( Item *item )
18327 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18329 m_itemDuration.push_back(item);
18330 item->SendTimeUpdate(this);
18334 void Player::AutoUnequipOffhandIfNeed()
18336 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18337 if(!offItem)
18338 return;
18340 // need unequip for 2h-weapon without TitanGrip
18341 if (!IsTwoHandUsed())
18342 return;
18344 ItemPosCountVec off_dest;
18345 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18346 if( off_msg == EQUIP_ERR_OK )
18348 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18349 StoreItem( off_dest, offItem, true );
18351 else
18353 sLog.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
18357 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18359 if(spellInfo->EquippedItemClass < 0)
18360 return true;
18362 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18363 // for optimize check 2 used cases only
18364 switch(spellInfo->EquippedItemClass)
18366 case ITEM_CLASS_WEAPON:
18368 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18369 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18370 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18371 return true;
18372 break;
18374 case ITEM_CLASS_ARMOR:
18376 // tabard not have dependent spells
18377 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18378 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18379 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18380 return true;
18382 // shields can be equipped to offhand slot
18383 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18384 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18385 return true;
18387 // ranged slot can have some armor subclasses
18388 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18389 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18390 return true;
18392 break;
18394 default:
18395 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18396 break;
18399 return false;
18402 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18404 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18405 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18406 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18407 return true;
18409 // Check no reagent use mask
18410 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18411 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18412 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18413 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18414 return true;
18416 return false;
18419 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18421 AuraMap& auras = GetAuras();
18422 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
18424 Aura* aura = itr->second;
18426 // skip passive (passive item dependent spells work in another way) and not self applied auras
18427 SpellEntry const* spellInfo = aura->GetSpellProto();
18428 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18430 ++itr;
18431 continue;
18434 // skip if not item dependent or have alternative item
18435 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18437 ++itr;
18438 continue;
18441 // no alt item, remove aura, restart check
18442 RemoveAurasDueToSpell(aura->GetId());
18443 itr = auras.begin();
18446 // currently casted spells can be dependent from item
18447 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
18449 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18450 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18451 InterruptSpell(i);
18455 uint32 Player::GetResurrectionSpellId()
18457 // search priceless resurrection possibilities
18458 uint32 prio = 0;
18459 uint32 spell_id = 0;
18460 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18461 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18463 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18464 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18466 switch((*itr)->GetId())
18468 case 20707: spell_id = 3026; break; // rank 1
18469 case 20762: spell_id = 20758; break; // rank 2
18470 case 20763: spell_id = 20759; break; // rank 3
18471 case 20764: spell_id = 20760; break; // rank 4
18472 case 20765: spell_id = 20761; break; // rank 5
18473 case 27239: spell_id = 27240; break; // rank 6
18474 default:
18475 sLog.outError("Unhandled spell %%u: S.Resurrection",(*itr)->GetId());
18476 continue;
18479 prio = 3;
18481 // Twisting Nether // prio: 2 (max)
18482 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18484 prio = 2;
18485 spell_id = 23700;
18489 // Reincarnation (passive spell) // prio: 1
18490 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18491 spell_id = 21169;
18493 return spell_id;
18496 // Used in triggers for check "Only to targets that grant experience or honor" req
18497 bool Player::isHonorOrXPTarget(Unit* pVictim)
18499 uint32 v_level = pVictim->getLevel();
18500 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
18502 // Victim level less gray level
18503 if(v_level<=k_grey)
18504 return false;
18506 if(pVictim->GetTypeId() == TYPEID_UNIT)
18508 if (((Creature*)pVictim)->isTotem() ||
18509 ((Creature*)pVictim)->isPet() ||
18510 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
18511 return false;
18513 return true;
18516 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18518 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18520 // prepare data for near group iteration (PvP and !PvP cases)
18521 uint32 xp = 0;
18522 bool honored_kill = false;
18524 if(Group *pGroup = GetGroup())
18526 uint32 count = 0;
18527 uint32 sum_level = 0;
18528 Player* member_with_max_level = NULL;
18529 Player* not_gray_member_with_max_level = NULL;
18531 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18533 if(member_with_max_level)
18535 /// not get Xp in PvP or no not gray players in group
18536 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18538 /// skip in check PvP case (for speed, not used)
18539 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18540 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18541 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18543 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18545 Player* pGroupGuy = itr->getSource();
18546 if(!pGroupGuy)
18547 continue;
18549 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18550 continue; // member (alive or dead) or his corpse at req. distance
18552 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18553 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18554 honored_kill = true;
18556 // xp and reputation only in !PvP case
18557 if(!PvP)
18559 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18561 // if is in dungeon then all receive full reputation at kill
18562 // rewarded any alive/dead/near_corpse group member
18563 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18565 // XP updated only for alive group member
18566 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18567 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18569 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18571 pGroupGuy->GiveXP(itr_xp, pVictim);
18572 if(Pet* pet = pGroupGuy->GetPet())
18573 pet->GivePetXP(itr_xp/2);
18576 // quest objectives updated only for alive group member or dead but with not released body
18577 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18579 // normal creature (not pet/etc) can be only in !PvP case
18580 if(pVictim->GetTypeId()==TYPEID_UNIT)
18581 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18587 else // if (!pGroup)
18589 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18591 // honor can be in PvP and !PvP (racial leader) cases
18592 if(RewardHonor(pVictim,1))
18593 honored_kill = true;
18595 // xp and reputation only in !PvP case
18596 if(!PvP)
18598 RewardReputation(pVictim,1);
18599 GiveXP(xp, pVictim);
18601 if(Pet* pet = GetPet())
18602 pet->GivePetXP(xp);
18604 // normal creature (not pet/etc) can be only in !PvP case
18605 if(pVictim->GetTypeId()==TYPEID_UNIT)
18606 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18609 return xp || honored_kill;
18612 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18614 if(pRewardSource->GetDistance(this) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
18615 return true;
18617 if(isAlive())
18618 return false;
18620 Corpse* corpse = GetCorpse();
18621 if(!corpse)
18622 return false;
18624 return pRewardSource->GetDistance(corpse) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE);
18627 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18629 Item* item = GetWeaponForAttack(attType,true);
18631 // unarmed only with base attack
18632 if(attType != BASE_ATTACK && !item)
18633 return 0;
18635 // weapon skill or (unarmed for base attack)
18636 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
18637 return GetBaseSkillValue(skill);
18640 void Player::ResurectUsingRequestData()
18642 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
18643 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18645 ResurrectPlayer(0.0f,false);
18647 if(GetMaxHealth() > m_resurrectHealth)
18648 SetHealth( m_resurrectHealth );
18649 else
18650 SetHealth( GetMaxHealth() );
18652 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18653 SetPower(POWER_MANA, m_resurrectMana );
18654 else
18655 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18657 SetPower(POWER_RAGE, 0 );
18659 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18661 SpawnCorpseBones();
18664 void Player::SetClientControl(Unit* target, uint8 allowMove)
18666 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18667 data.append(target->GetPackGUID());
18668 data << uint8(allowMove);
18669 GetSession()->SendPacket(&data);
18672 void Player::UpdateZoneDependentAuras( uint32 newZone )
18674 // remove new continent flight forms
18675 uint32 v_map = GetVirtualMapForMapAndZone(GetMapId(), newZone);
18676 if( !isGameMaster() && v_map != 530 && v_map != 571)
18678 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18679 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18682 // Some spells applied at enter into zone (with subzones)
18683 // Human Illusion
18684 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
18685 if ( newZone == 2367 ) // Old Hillsbrad Foothills
18687 uint32 spellid = 0;
18688 // all horde races
18689 if( GetTeam() == HORDE )
18690 spellid = getGender() == GENDER_FEMALE ? 35481 : 35480;
18691 // and some alliance races
18692 else if( getRace() == RACE_NIGHTELF || getRace() == RACE_DRAENEI )
18693 spellid = getGender() == GENDER_FEMALE ? 35483 : 35482;
18695 if(spellid && !HasAura(spellid,0) )
18696 CastSpell(this,spellid,true);
18700 void Player::UpdateAreaDependentAuras( uint32 newArea )
18702 // remove auras from spells with area limitations
18703 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
18705 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18706 if(GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea)!=0)
18707 RemoveAura(iter);
18708 else
18709 ++iter;
18712 // some auras applied at subzone enter
18713 switch(newArea)
18715 // Dragonmaw Illusion
18716 case 3759: // Netherwing Ledge
18717 case 3939: // Dragonmaw Fortress
18718 case 3966: // Dragonmaw Base Camp
18719 if( GetDummyAura(40214) )
18721 if( !HasAura(40216,0) )
18722 CastSpell(this,40216,true);
18723 if( !HasAura(42016,0) )
18724 CastSpell(this,42016,true);
18726 break;
18727 // Dominion Over Acherus
18728 case 4281: // Acherus: The Ebon Hold
18729 case 4342: // Acherus: The Ebon Hold
18730 if( HasSpell(51721) )
18731 if( !HasAura(51721,0) )
18732 CastSpell(this,51721,true);
18733 break;
18737 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18739 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18740 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18742 return copseReclaimDelay[0];
18745 time_t now = time(NULL);
18746 // 0..2 full period
18747 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18748 return copseReclaimDelay[count];
18751 void Player::UpdateCorpseReclaimDelay()
18753 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18755 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18756 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18757 return;
18759 time_t now = time(NULL);
18760 if(now < m_deathExpireTime)
18762 // full and partly periods 1..3
18763 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18764 if(count < MAX_DEATH_COUNT)
18765 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
18766 else
18767 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
18769 else
18770 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
18773 void Player::SendCorpseReclaimDelay(bool load)
18775 Corpse* corpse = GetCorpse();
18776 if(!corpse)
18777 return;
18779 uint32 delay;
18780 if(load)
18782 if(corpse->GetGhostTime() > m_deathExpireTime)
18783 return;
18785 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
18787 uint32 count;
18788 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18789 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18791 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
18792 if(count>=MAX_DEATH_COUNT)
18793 count = MAX_DEATH_COUNT-1;
18795 else
18796 count=0;
18798 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
18800 time_t now = time(NULL);
18801 if(now >= expected_time)
18802 return;
18804 delay = expected_time-now;
18806 else
18807 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
18809 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18810 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
18811 data << uint32(delay*1000);
18812 GetSession()->SendPacket( &data );
18815 Player* Player::GetNextRandomRaidMember(float radius)
18817 Group *pGroup = GetGroup();
18818 if(!pGroup)
18819 return NULL;
18821 std::vector<Player*> nearMembers;
18822 nearMembers.reserve(pGroup->GetMembersCount());
18824 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18826 Player* Target = itr->getSource();
18828 // IsHostileTo check duel and controlled by enemy
18829 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
18830 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
18831 nearMembers.push_back(Target);
18834 if (nearMembers.empty())
18835 return NULL;
18837 uint32 randTarget = urand(0,nearMembers.size()-1);
18838 return nearMembers[randTarget];
18841 PartyResult Player::CanUninviteFromGroup() const
18843 const Group* grp = GetGroup();
18844 if(!grp)
18845 return PARTY_RESULT_YOU_NOT_IN_GROUP;
18847 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
18848 return PARTY_RESULT_YOU_NOT_LEADER;
18850 if(InBattleGround())
18851 return PARTY_RESULT_INVITE_RESTRICTED;
18853 return PARTY_RESULT_OK;
18856 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
18858 float water_z = m->GetWaterLevel(x,y);
18859 float height_z = m->GetHeight(x,y,z, false); // use .map base surface height
18860 uint8 flag1 = m->GetTerrainType(x,y);
18862 //!Underwater check, not in water if underground or above water level
18863 if (height_z <= INVALID_HEIGHT || z < (height_z-2) || z > (water_z - 2) )
18864 m_isunderwater &= 0x7A;
18865 else if ((z < (water_z - 2)) && (flag1 & 0x01))
18866 m_isunderwater |= 0x01;
18868 //!in lava check, anywhere under lava level
18869 if ((height_z <= INVALID_HEIGHT || z < (height_z - 0)) && (flag1 == 0x00) && IsInWater())
18870 m_isunderwater |= 0x80;
18873 void Player::SetCanParry( bool value )
18875 if(m_canParry==value)
18876 return;
18878 m_canParry = value;
18879 UpdateParryPercentage();
18882 void Player::SetCanBlock( bool value )
18884 if(m_canBlock==value)
18885 return;
18887 m_canBlock = value;
18888 UpdateBlockPercentage();
18891 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
18893 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
18894 if(itr->pos == pos)
18895 return true;
18897 return false;
18900 bool Player::isAllowUseBattleGroundObject()
18902 return ( //InBattleGround() && // in battleground - not need, check in other cases
18903 !IsMounted() && // not mounted
18904 !HasStealthAura() && // not stealthed
18905 !HasInvisibilityAura() && // not invisible
18906 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
18907 isAlive() // live player
18911 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
18913 uint32 level = getLevel();
18915 if(level > GT_MAX_LEVEL)
18916 level = GT_MAX_LEVEL; // max level in this dbc
18918 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
18919 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
18920 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
18922 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
18923 return 0;
18925 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
18927 if(!bsc) // shouldn't happen
18928 return 0xFFFFFFFF;
18930 float cost = 0;
18932 if(hairstyle != newhairstyle)
18933 cost += bsc->cost; // full price
18935 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
18936 cost += bsc->cost * 0.5f; // +1/2 of price
18938 if(facialhair != newfacialhair)
18939 cost += bsc->cost * 0.75f; // +3/4 of price
18941 return uint32(cost);
18944 void Player::InitGlyphsForLevel()
18946 uint32 level = getLevel();
18947 uint32 value = 0;
18949 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
18950 if(level >= 15)
18951 value |= (0x01 | 0x02);
18952 if(level >= 30)
18953 value |= 0x04;
18954 if(level >= 50)
18955 value |= 0x08;
18956 if(level >= 70)
18957 value |= 0x10;
18958 if(level >= 80)
18959 value |= 0x20;
18961 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
18964 void Player::EnterVehicle(Vehicle *vehicle)
18966 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
18967 if(!ve)
18968 return;
18970 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
18971 if(!veSeat)
18972 return;
18974 vehicle->SetCharmerGUID(GetGUID());
18975 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
18976 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNKNOWN5);
18977 vehicle->setFaction(getFaction());
18979 SetCharm(vehicle); // charm
18980 SetFarSight(vehicle->GetGUID()); // set view
18982 SetClientControl(vehicle, 1); // redirect controls to vehicle
18984 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
18985 GetSession()->SendPacket(&data);
18987 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
18988 data.append(GetPackGUID());
18989 data << uint32(0); // counter?
18990 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
18991 data << uint16(0); // special flags
18992 data << uint32(getMSTime()); // time
18993 data << vehicle->GetPositionX(); // x
18994 data << vehicle->GetPositionY(); // y
18995 data << vehicle->GetPositionZ(); // z
18996 data << vehicle->GetOrientation(); // o
18997 // transport part, TODO: load/calculate seat offsets
18998 data << uint64(vehicle->GetGUID()); // transport guid
18999 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19000 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19001 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19002 data << float(0); // transport orientation
19003 data << uint32(getMSTime()); // transport time
19004 data << uint8(0); // seat
19005 // end of transport part
19006 data << uint32(0); // fall time
19007 GetSession()->SendPacket(&data);
19009 data.Initialize(SMSG_PET_SPELLS, 8+4+4+4+4*10+1+1);
19010 data << uint64(vehicle->GetGUID());
19011 data << uint32(0x00000000);
19012 data << uint32(0x00000000);
19013 data << uint32(0x00000101);
19015 for(uint32 i = 0; i < 10; ++i)
19016 data << uint16(0) << uint8(0) << uint8(i+8);
19018 data << uint8(0);
19019 data << uint8(0);
19020 GetSession()->SendPacket(&data);
19023 void Player::ExitVehicle(Vehicle *vehicle)
19025 vehicle->SetCharmerGUID(0);
19026 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19027 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNKNOWN5);
19028 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19030 SetCharm(NULL);
19031 SetFarSight(NULL);
19033 SetClientControl(vehicle, 0);
19035 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19036 data.append(GetPackGUID());
19037 data << uint32(0); // counter?
19038 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19039 data << uint16(0x40); // special flags
19040 data << uint32(getMSTime()); // time
19041 data << vehicle->GetPositionX(); // x
19042 data << vehicle->GetPositionY(); // y
19043 data << vehicle->GetPositionZ(); // z
19044 data << vehicle->GetOrientation(); // o
19045 data << uint32(0); // fall time
19046 GetSession()->SendPacket(&data);
19048 data.Initialize(SMSG_PET_SPELLS, 8+4);
19049 data << uint64(0);
19050 data << uint32(0);
19051 GetSession()->SendPacket(&data);
19053 // only for flyable vehicles?
19054 CastSpell(this, 45472, true); // Parachute
19057 bool Player::HasTitle(uint32 bitIndex)
19059 if (bitIndex > 128)
19060 return false;
19062 uint32 fieldIndexOffset = bitIndex/32;
19063 uint32 flag = 1 << (bitIndex%32);
19064 return HasFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19067 void Player::SetTitle(CharTitlesEntry const* title)
19069 uint32 fieldIndexOffset = title->bit_index/32;
19070 uint32 flag = 1 << (title->bit_index%32);
19071 SetFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19074 void Player::ConvertRune(uint8 index, uint8 newType)
19076 SetCurrentRune(index, newType);
19078 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19079 data << uint8(index);
19080 data << uint8(newType);
19081 GetSession()->SendPacket(&data);
19084 void Player::ResyncRunes(uint8 count)
19086 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19087 for(uint32 i = 0; i < count; ++i)
19089 data << uint8(GetCurrentRune(i)); // rune type
19090 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
19092 GetSession()->SendPacket(&data);
19095 void Player::AddRunePower(uint8 index)
19097 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19098 data << uint32(1 << index); // mask (0x00-0x3F probably)
19099 GetSession()->SendPacket(&data);
19102 void Player::InitRunes()
19104 if(getClass() != CLASS_DEATH_KNIGHT)
19105 return;
19107 m_runes = new Runes;
19109 m_runes->runeState = 0;
19111 for(uint32 i = 0; i < MAX_RUNES; ++i)
19113 SetBaseRune(i, i / 2); // init base types
19114 SetCurrentRune(i, i / 2); // init current types
19115 SetRuneCooldown(i, 0); // reset cooldowns
19116 m_runes->SetRuneState(i);
19119 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19120 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);