[7029] Some work vs aura charges
[getmangos.git] / src / game / Player.cpp
blobb6ca879ae45a2edaf84cfc0f5192f08d9cc1cebf
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 // set starting level
598 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
599 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
600 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
602 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
604 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
605 if(gm_level > start_level)
606 start_level = gm_level;
609 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
611 InitRunes();
613 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
614 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
615 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
617 // Played time
618 m_Last_tick = time(NULL);
619 m_Played_time[0] = 0;
620 m_Played_time[1] = 0;
622 // base stats and related field values
623 InitStatsForLevel();
624 InitTaxiNodesForLevel();
625 InitGlyphsForLevel();
626 InitTalentForLevel();
627 InitPrimaryProffesions(); // to max set before any spell added
629 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
630 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
631 SetHealth(GetMaxHealth());
632 if (getPowerType()==POWER_MANA)
634 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
635 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
638 if(getPowerType() == POWER_RUNIC_POWER)
640 SetPower(POWER_RUNE, 8);
641 SetMaxPower(POWER_RUNE, 8);
642 SetPower(POWER_RUNIC_POWER, 0);
643 SetMaxPower(POWER_RUNIC_POWER, 1000);
646 // original spells
647 learnDefaultSpells(true);
649 // original action bar
650 std::list<uint16>::const_iterator action_itr[4];
651 for(int i=0; i<4; i++)
652 action_itr[i] = info->action[i].begin();
654 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
656 uint16 taction[4];
657 for(int i=0; i<4 ;i++)
658 taction[i] = (*action_itr[i]);
660 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
662 for(int i=0; i<4 ;i++)
663 ++action_itr[i];
666 // original items
667 CharStartOutfitEntry const* oEntry = NULL;
668 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
670 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
672 if(entry->RaceClassGender == RaceClassGender)
674 oEntry = entry;
675 break;
680 if(oEntry)
682 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
684 if(oEntry->ItemId[j] <= 0)
685 continue;
687 uint32 item_id = oEntry->ItemId[j];
690 // Hack for not existed item id in dbc 3.0.3
691 if(item_id==40582)
692 continue;
694 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
695 if(!iProto)
697 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
698 continue;
701 // max stack by default (mostly 1), 1 for infinity stackable
702 uint32 count = iProto->Stackable > 0 ? uint32(iProto->Stackable) : 1;
704 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
706 switch(iProto->Spells[0].SpellCategory)
708 case 11: // food
709 if(iProto->Stackable > 4)
710 count = 4;
711 break;
712 case 59: // drink
713 if(iProto->Stackable > 2)
714 count = 2;
715 break;
719 StoreNewItemInBestSlots(item_id, count);
723 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
724 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
726 // bags and main-hand weapon must equipped at this moment
727 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
728 // or ammo not equipped in special bag
729 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
731 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
733 uint16 eDest;
734 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
735 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
736 if( msg == EQUIP_ERR_OK )
738 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
739 EquipItem( eDest, pItem, true);
741 // move other items to more appropriate slots (ammo not equipped in special bag)
742 else
744 ItemPosCountVec sDest;
745 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
746 if( msg == EQUIP_ERR_OK )
748 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
749 pItem = StoreItem( sDest, pItem, true);
752 // if this is ammo then use it
753 uint8 msg = CanUseAmmo( pItem->GetProto()->ItemId );
754 if( msg == EQUIP_ERR_OK )
755 SetAmmo( pItem->GetProto()->ItemId );
759 // all item positions resolved
761 return true;
764 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
766 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
768 // attempt equip by one
769 while(titem_amount > 0)
771 uint16 eDest;
772 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
773 if( msg != EQUIP_ERR_OK )
774 break;
776 EquipNewItem( eDest, titem_id, true);
777 AutoUnequipOffhandIfNeed();
778 --titem_amount;
781 if(titem_amount == 0)
782 return true; // equipped
784 // attempt store
785 ItemPosCountVec sDest;
786 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
787 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
788 if( msg == EQUIP_ERR_OK )
790 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
791 return true; // stored
794 // item can't be added
795 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
796 return false;
799 void Player::StartMirrorTimer(MirrorTimerType Type, uint32 MaxValue)
801 uint32 BreathRegen = (uint32)-1;
803 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
804 data << (uint32)Type;
805 data << MaxValue;
806 data << MaxValue;
807 data << BreathRegen;
808 data << (uint8)0;
809 data << (uint32)0; // spell id
810 GetSession()->SendPacket(&data);
813 void Player::ModifyMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, uint32 Regen)
815 if(Type==BREATH_TIMER)
816 m_breathTimer = ((MaxValue + 1000) - CurrentValue) / Regen;
818 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
819 data << (uint32)Type;
820 data << CurrentValue;
821 data << MaxValue;
822 data << Regen;
823 data << (uint8)0;
824 data << (uint32)0; // spell id
825 GetSession()->SendPacket( &data );
828 void Player::StopMirrorTimer(MirrorTimerType Type)
830 if(Type==BREATH_TIMER)
831 m_breathTimer = 0;
833 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
834 data << (uint32)Type;
835 GetSession()->SendPacket( &data );
838 void Player::EnvironmentalDamage(uint64 guid, EnviromentalDamage type, uint32 damage)
840 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
841 data << (uint64)guid;
842 data << (uint8)(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
843 data << (uint32)damage;
844 data << (uint32)0;
845 data << (uint32)0;
846 SendMessageToSet(&data, true);
848 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
850 if(type==DAMAGE_FALL && !isAlive()) // DealDamage not apply item durability loss at self damage
852 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
853 DurabilityLossAll(0.10f,false);
854 // durability lost message
855 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
856 GetSession()->SendPacket(&data);
860 void Player::HandleDrowning()
862 if(!m_isunderwater)
863 return;
865 //if player is GM, have waterbreath, is dead or if breathing is disabled then return
866 if(waterbreath || isGameMaster() || !isAlive() || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
868 StopMirrorTimer(BREATH_TIMER);
869 m_isunderwater = 0;
870 return;
873 uint32 UnderWaterTime = 1*MINUTE*1000; // default length 1 min
875 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
876 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
877 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
879 if ((m_isunderwater & 0x01) && !(m_isunderwater & 0x80) && isAlive())
881 //single trigger timer
882 if (!(m_isunderwater & 0x02))
884 m_isunderwater|= 0x02;
885 m_breathTimer = UnderWaterTime + 1000;
887 //single trigger "Breathbar"
888 if ( m_breathTimer <= UnderWaterTime && !(m_isunderwater & 0x04))
890 m_isunderwater|= 0x04;
891 StartMirrorTimer(BREATH_TIMER, UnderWaterTime);
893 //continuous trigger drowning "Damage"
894 if ((m_breathTimer == 0) && (m_isunderwater & 0x01))
896 //TODO: Check this formula
897 uint64 guid = GetGUID();
898 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
900 EnvironmentalDamage(guid, DAMAGE_DROWNING,damage);
901 m_breathTimer = 2000;
904 //single trigger retract bar
905 else if (!(m_isunderwater & 0x01) && !(m_isunderwater & 0x08) && (m_isunderwater & 0x02) && (m_breathTimer > 0) && isAlive())
907 m_isunderwater = 0x08;
909 uint32 BreathRegen = 10;
910 ModifyMirrorTimer(BREATH_TIMER, UnderWaterTime, m_breathTimer,BreathRegen);
911 m_isunderwater = 0x10;
913 //remove bar
914 else if ((m_breathTimer < 50) && !(m_isunderwater & 0x01) && (m_isunderwater == 0x10))
916 StopMirrorTimer(BREATH_TIMER);
917 m_isunderwater = 0;
921 void Player::HandleLava()
923 if ((m_isunderwater & 0x80) && isAlive())
925 // Single trigger Set BreathTimer
926 if (!(m_isunderwater & 0x80))
928 m_isunderwater|= 0x04;
929 m_breathTimer = 1000;
932 // Reset BreathTimer and still in the lava
933 if (!m_breathTimer)
935 uint64 guid = GetGUID();
936 uint32 damage = urand(600, 700); // TODO: Get more detailed information about lava damage
938 // if not gamemaster then deal damage
939 if ( !isGameMaster() )
940 EnvironmentalDamage(guid, DAMAGE_LAVA, damage);
942 m_breathTimer = 1000;
945 else if (m_deathState == DEAD) // Disable breath timer and reset underwater flags
947 m_breathTimer = 0;
948 m_isunderwater = 0;
952 ///The player sobers by 256 every 10 seconds
953 void Player::HandleSobering()
955 m_drunkTimer = 0;
957 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
958 SetDrunkValue(drunk);
961 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
963 if(value >= 23000)
964 return DRUNKEN_SMASHED;
965 if(value >= 12800)
966 return DRUNKEN_DRUNK;
967 if(value & 0xFFFE)
968 return DRUNKEN_TIPSY;
969 return DRUNKEN_SOBER;
972 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
974 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
976 m_drunk = newDrunkenValue;
977 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
979 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
981 // special drunk invisibility detection
982 if(newDrunkenState >= DRUNKEN_DRUNK)
983 m_detectInvisibilityMask |= (1<<6);
984 else
985 m_detectInvisibilityMask &= ~(1<<6);
987 if(newDrunkenState == oldDrunkenState)
988 return;
990 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
991 data << uint64(GetGUID());
992 data << uint32(newDrunkenState);
993 data << uint32(itemId);
995 SendMessageToSet(&data, true);
998 void Player::Update( uint32 p_time )
1000 if(!IsInWorld())
1001 return;
1003 // undelivered mail
1004 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1006 SendNewMail();
1007 ++unReadMails;
1009 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1010 m_nextMailDelivereTime = 0;
1013 Unit::Update( p_time );
1015 // update player only attacks
1016 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1018 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1021 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1023 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1026 time_t now = time (NULL);
1028 UpdatePvPFlag(now);
1030 UpdateContestedPvP(p_time);
1032 UpdateDuelFlag(now);
1034 CheckDuelDistance(now);
1036 UpdateAfkReport(now);
1038 CheckExploreSystem();
1040 // Update items that have just a limited lifetime
1041 if (now>m_Last_tick)
1042 UpdateItemDuration(uint32(now- m_Last_tick));
1044 if (!m_timedquests.empty())
1046 std::set<uint32>::iterator iter = m_timedquests.begin();
1047 while (iter != m_timedquests.end())
1049 QuestStatusData& q_status = mQuestStatus[*iter];
1050 if( q_status.m_timer <= p_time )
1052 uint32 quest_id = *iter;
1053 ++iter; // current iter will be removed in FailTimedQuest
1054 FailTimedQuest( quest_id );
1056 else
1058 q_status.m_timer -= p_time;
1059 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1060 ++iter;
1065 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1067 Unit *pVictim = getVictim();
1068 if( !IsNonMeleeSpellCasted(false) && pVictim)
1070 // default combat reach 10
1071 // TODO add weapon,skill check
1073 float pldistance = ATTACK_DISTANCE;
1075 if (isAttackReady(BASE_ATTACK))
1077 if(!IsWithinDistInMap(pVictim, pldistance))
1079 setAttackTimer(BASE_ATTACK,100);
1080 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1082 SendAttackSwingNotInRange();
1083 m_swingErrorMsg = 1;
1086 //120 degrees of radiant range
1087 else if( !HasInArc( 2*M_PI/3, pVictim ))
1089 setAttackTimer(BASE_ATTACK,100);
1090 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1092 SendAttackSwingBadFacingAttack();
1093 m_swingErrorMsg = 2;
1096 else
1098 m_swingErrorMsg = 0; // reset swing error state
1100 // prevent base and off attack in same time, delay attack at 0.2 sec
1101 if(haveOffhandWeapon())
1103 uint32 off_att = getAttackTimer(OFF_ATTACK);
1104 if(off_att < ATTACK_DISPLAY_DELAY)
1105 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1107 AttackerStateUpdate(pVictim, BASE_ATTACK);
1108 resetAttackTimer(BASE_ATTACK);
1112 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1114 if(!IsWithinDistInMap(pVictim, pldistance))
1116 setAttackTimer(OFF_ATTACK,100);
1118 else if( !HasInArc( 2*M_PI/3, pVictim ))
1120 setAttackTimer(OFF_ATTACK,100);
1122 else
1124 // prevent base and off attack in same time, delay attack at 0.2 sec
1125 uint32 base_att = getAttackTimer(BASE_ATTACK);
1126 if(base_att < ATTACK_DISPLAY_DELAY)
1127 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1128 // do attack
1129 AttackerStateUpdate(pVictim, OFF_ATTACK);
1130 resetAttackTimer(OFF_ATTACK);
1134 Unit *owner = pVictim->GetOwner();
1135 Unit *u = owner ? owner : pVictim;
1136 if(u->IsPvP() && (!duel || duel->opponent != u))
1138 UpdatePvP(true);
1139 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1144 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1146 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1148 int time_inn = time(NULL)-GetTimeInnEnter();
1149 if (time_inn >= 10) //freeze update
1151 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1152 //speed collect rest bonus (section/in hour)
1153 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1154 UpdateInnerTime(time(NULL));
1159 if(m_regenTimer > 0)
1161 if(p_time >= m_regenTimer)
1162 m_regenTimer = 0;
1163 else
1164 m_regenTimer -= p_time;
1167 if (m_weaponChangeTimer > 0)
1169 if(p_time >= m_weaponChangeTimer)
1170 m_weaponChangeTimer = 0;
1171 else
1172 m_weaponChangeTimer -= p_time;
1175 if (m_zoneUpdateTimer > 0)
1177 if(p_time >= m_zoneUpdateTimer)
1179 uint32 newzone = GetZoneId();
1180 if( m_zoneUpdateId != newzone )
1181 UpdateZone(newzone); // also update area
1182 else
1184 // use area updates as well
1185 // needed for free far all arenas for example
1186 uint32 newarea = GetAreaId();
1187 if( m_areaUpdateId != newarea )
1188 UpdateArea(newarea);
1190 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1193 else
1194 m_zoneUpdateTimer -= p_time;
1197 if (isAlive())
1199 RegenerateAll();
1202 if (m_deathState == JUST_DIED)
1204 KillPlayer();
1207 if(m_nextSave > 0)
1209 if(p_time >= m_nextSave)
1211 // m_nextSave reseted in SaveToDB call
1212 SaveToDB();
1213 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1215 else
1217 m_nextSave -= p_time;
1221 //Breathtimer
1222 if(m_breathTimer > 0)
1224 if(p_time >= m_breathTimer)
1225 m_breathTimer = 0;
1226 else
1227 m_breathTimer -= p_time;
1231 //Handle Water/drowning
1232 HandleDrowning();
1234 //Handle lava
1235 HandleLava();
1237 //Handle detect stealth players
1238 if (m_DetectInvTimer > 0)
1240 if (p_time >= m_DetectInvTimer)
1242 m_DetectInvTimer = 3000;
1243 HandleStealthedUnitsDetection();
1245 else
1246 m_DetectInvTimer -= p_time;
1249 // Played time
1250 if (now > m_Last_tick)
1252 uint32 elapsed = uint32(now - m_Last_tick);
1253 m_Played_time[0] += elapsed; // Total played time
1254 m_Played_time[1] += elapsed; // Level played time
1255 m_Last_tick = now;
1258 if (m_drunk)
1260 m_drunkTimer += p_time;
1262 if (m_drunkTimer > 10000)
1263 HandleSobering();
1266 // not auto-free ghost from body in instances
1267 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1269 if(p_time >= m_deathTimer)
1271 m_deathTimer = 0;
1272 BuildPlayerRepop();
1273 RepopAtGraveyard();
1275 else
1276 m_deathTimer -= p_time;
1279 UpdateEnchantTime(p_time);
1280 UpdateHomebindTime(p_time);
1282 // group update
1283 SendUpdateToOutOfRangeGroupMembers();
1285 Pet* pet = GetPet();
1286 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1288 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1289 return;
1293 void Player::setDeathState(DeathState s)
1295 uint32 ressSpellId = 0;
1297 bool cur = isAlive();
1299 if(s == JUST_DIED && cur)
1301 // drunken state is cleared on death
1302 SetDrunkValue(0);
1303 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1304 ClearComboPoints();
1306 clearResurrectRequestData();
1308 // remove form before other mods to prevent incorrect stats calculation
1309 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1311 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1312 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1314 // remove uncontrolled pets
1315 RemoveMiniPet();
1316 RemoveGuardians();
1318 // save value before aura remove in Unit::setDeathState
1319 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1321 // passive spell
1322 if(!ressSpellId)
1323 ressSpellId = GetResurrectionSpellId();
1324 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1326 Unit::setDeathState(s);
1328 // restore resurrection spell id for player after aura remove
1329 if(s == JUST_DIED && cur && ressSpellId)
1330 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1332 if(isAlive() && !cur)
1334 //clear aura case after resurrection by another way (spells will be applied before next death)
1335 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1337 // restore default warrior stance
1338 if(getClass()== CLASS_WARRIOR)
1339 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1343 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1345 Field *fields = result->Fetch();
1347 *p_data << uint64(GetGUID());
1348 *p_data << m_name;
1350 *p_data << uint8(getRace());
1351 uint8 pClass = getClass();
1352 *p_data << uint8(pClass);
1353 *p_data << uint8(getGender());
1355 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1356 *p_data << uint8(bytes);
1357 *p_data << uint8(bytes >> 8);
1358 *p_data << uint8(bytes >> 16);
1359 *p_data << uint8(bytes >> 24);
1361 bytes = GetUInt32Value(PLAYER_BYTES_2);
1362 *p_data << uint8(bytes);
1364 *p_data << uint8(getLevel()); // player level
1365 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1366 uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY(),GetPositionZ());
1367 sLog.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId);
1368 *p_data << uint32(zoneId);
1369 *p_data << uint32(GetMapId());
1371 *p_data << GetPositionX();
1372 *p_data << GetPositionY();
1373 *p_data << GetPositionZ();
1375 // guild id
1376 *p_data << (result ? fields[13].GetUInt32() : 0);
1378 uint32 char_flags = 0;
1379 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1380 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1381 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1382 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1383 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1384 char_flags |= CHARACTER_FLAG_GHOST;
1385 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1386 char_flags |= CHARACTER_FLAG_RENAME;
1387 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) && (fields[14].GetCppString() != ""))
1388 char_flags |= CHARACTER_FLAG_DECLINED;
1390 *p_data << uint32(char_flags); // character flags
1391 // character customize (flags?)
1392 *p_data << uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE) ? 1 : 0);
1393 *p_data << uint8(1); // unknown
1395 // Pets info
1397 uint32 petDisplayId = 0;
1398 uint32 petLevel = 0;
1399 uint32 petFamily = 0;
1401 // show pet at selection character in character list only for non-ghost character
1402 if(result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER))
1404 uint32 entry = fields[10].GetUInt32();
1405 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1406 if(cInfo)
1408 petDisplayId = fields[11].GetUInt32();
1409 petLevel = fields[12].GetUInt32();
1410 petFamily = cInfo->family;
1414 *p_data << uint32(petDisplayId);
1415 *p_data << uint32(petLevel);
1416 *p_data << uint32(petFamily);
1419 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1421 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
1422 uint32 item_id = GetUInt32Value(visualbase);
1423 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1424 SpellItemEnchantmentEntry const *enchant = NULL;
1426 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot<=TEMP_ENCHANTMENT_SLOT; enchantSlot++)
1428 uint32 enchantId = GetUInt32Value(visualbase+1+enchantSlot);
1429 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1430 break;
1433 if (proto != NULL)
1435 *p_data << uint32(proto->DisplayInfoID);
1436 *p_data << uint8(proto->InventoryType);
1437 *p_data << uint32(enchant ? enchant->aura_id : 0);
1439 else
1441 *p_data << uint32(0);
1442 *p_data << uint8(0);
1443 *p_data << uint32(0); // enchant?
1446 *p_data << uint32(0); // first bag display id
1447 *p_data << uint8(0); // first bag inventory type
1448 *p_data << uint32(0); // enchant?
1451 bool Player::ToggleAFK()
1453 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1455 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1457 // afk player not allowed in battleground
1458 if(state && InBattleGround())
1459 LeaveBattleground();
1461 return state;
1464 bool Player::ToggleDND()
1466 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1468 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1471 uint8 Player::chatTag() const
1473 // it's bitmask
1474 // 0x8 - ??
1475 // 0x4 - gm
1476 // 0x2 - dnd
1477 // 0x1 - afk
1478 if(isGMChat())
1479 return 4;
1480 else if(isDND())
1481 return 3;
1482 if(isAFK())
1483 return 1;
1484 else
1485 return 0;
1488 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1490 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1492 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1493 return false;
1496 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1497 Pet* pet = GetPet();
1499 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1501 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1502 // don't let gm level > 1 either
1503 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1504 return false;
1506 // client without expansion support
1507 if(GetSession()->Expansion() < mEntry->Expansion())
1509 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1511 if(GetTransport())
1512 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1514 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1516 return false; // normal client can't teleport to this map...
1518 else
1520 sLog.outDebug("Player %s will teleported to map %u", GetName(), mapid);
1523 // if we were on a transport, leave
1524 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1526 m_transport->RemovePassenger(this);
1527 m_transport = NULL;
1528 m_movementInfo.t_x = 0.0f;
1529 m_movementInfo.t_y = 0.0f;
1530 m_movementInfo.t_z = 0.0f;
1531 m_movementInfo.t_o = 0.0f;
1532 m_movementInfo.t_time = 0;
1535 SetSemaphoreTeleport(true);
1537 // The player was ported to another map and looses the duel immediately.
1538 // We have to perform this check before the teleport, otherwise the
1539 // ObjectAccessor won't find the flag.
1540 if (duel && GetMapId()!=mapid)
1542 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
1543 if (obj)
1544 DuelComplete(DUEL_FLED);
1547 // reset movement flags at teleport, because player will continue move with these flags after teleport
1548 SetUnitMovementFlags(0);
1550 if ((GetMapId() == mapid) && (!m_transport))
1552 // prepare zone change detect
1553 uint32 old_zone = GetZoneId();
1555 // near teleport
1556 if(!GetSession()->PlayerLogout())
1558 WorldPacket data;
1559 BuildTeleportAckMsg(&data, x, y, z, orientation);
1560 GetSession()->SendPacket(&data);
1561 SetPosition( x, y, z, orientation, true);
1563 else
1564 // this will be used instead of the current location in SaveToDB
1565 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1566 SetFallInformation(0, z);
1568 //BuildHeartBeatMsg(&data);
1569 //SendMessageToSet(&data, true);
1570 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1572 //same map, only remove pet if out of range
1573 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1575 if(pet->isControlled() && !pet->isTemporarySummoned() )
1576 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1577 else
1578 m_temporaryUnsummonedPetNumber = 0;
1580 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1584 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1585 CombatStop();
1587 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1589 // resummon pet
1590 if(pet && m_temporaryUnsummonedPetNumber)
1592 Pet* NewPet = new Pet;
1593 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
1594 delete NewPet;
1596 m_temporaryUnsummonedPetNumber = 0;
1600 if(!GetSession()->PlayerLogout())
1602 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1603 SetSemaphoreTeleport(false);
1605 UpdateZone(GetZoneId());
1608 // new zone
1609 if(old_zone != GetZoneId())
1611 // honorless target
1612 if(pvpInfo.inHostileArea)
1613 CastSpell(this, 2479, true);
1616 else
1618 // far teleport to another map
1619 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1620 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1622 // Check enter rights before map getting to avoid creating instance copy for player
1623 // this check not dependent from map instance copy and same for all instance copies of selected map
1624 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1626 SetSemaphoreTeleport(false);
1627 return false;
1630 // If the map is not created, assume it is possible to enter it.
1631 // It will be created in the WorldPortAck.
1632 Map *map = MapManager::Instance().FindMap(mapid);
1633 if (!map || map->CanEnter(this))
1635 SetSelection(0);
1637 CombatStop();
1639 ResetContestedPvP();
1641 // remove player from battleground on far teleport (when changing maps)
1642 if(BattleGround const* bg = GetBattleGround())
1644 // Note: at battleground join battleground id set before teleport
1645 // and we already will found "current" battleground
1646 // just need check that this is targeted map or leave
1647 if(bg->GetMapId() != mapid)
1648 LeaveBattleground(false); // don't teleport to entry point
1651 // remove pet on map change
1652 if (pet)
1654 //leaving map -> delete pet right away (doing this later will cause problems)
1655 if(pet->isControlled() && !pet->isTemporarySummoned())
1656 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1657 else
1658 m_temporaryUnsummonedPetNumber = 0;
1660 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1663 // remove all dyn objects
1664 RemoveAllDynObjects();
1666 // stop spellcasting
1667 // not attempt interrupt teleportation spell at caster teleport
1668 if(!(options & TELE_TO_SPELL))
1669 if(IsNonMeleeSpellCasted(true))
1670 InterruptNonMeleeSpells(true);
1672 if(!GetSession()->PlayerLogout())
1674 // send transfer packets
1675 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1676 data << uint32(mapid);
1677 if (m_transport)
1679 data << m_transport->GetEntry() << GetMapId();
1681 GetSession()->SendPacket(&data);
1683 data.Initialize(SMSG_NEW_WORLD, (20));
1684 if (m_transport)
1686 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1688 else
1690 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1692 GetSession()->SendPacket( &data );
1693 SendSavedInstances();
1695 // remove from old map now
1696 if(oldmap) oldmap->Remove(this, false);
1699 // new final coordinates
1700 float final_x = x;
1701 float final_y = y;
1702 float final_z = z;
1703 float final_o = orientation;
1705 if(m_transport)
1707 final_x += m_movementInfo.t_x;
1708 final_y += m_movementInfo.t_y;
1709 final_z += m_movementInfo.t_z;
1710 final_o += m_movementInfo.t_o;
1713 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1714 SetFallInformation(0, final_z);
1715 // if the player is saved before worldportack (at logout for example)
1716 // this will be used instead of the current location in SaveToDB
1718 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
1720 // move packet sent by client always after far teleport
1721 // SetPosition(final_x, final_y, final_z, final_o, true);
1722 SetDontMove(true);
1724 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1726 else
1727 return false;
1729 return true;
1732 void Player::AddToWorld()
1734 ///- Do not add/remove the player from the object storage
1735 ///- It will crash when updating the ObjectAccessor
1736 ///- The player should only be added when logging in
1737 Unit::AddToWorld();
1739 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1741 if(m_items[i])
1742 m_items[i]->AddToWorld();
1746 void Player::RemoveFromWorld()
1748 // cleanup
1749 if(IsInWorld())
1751 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1752 Uncharm();
1753 UnsummonAllTotems();
1754 RemoveMiniPet();
1755 RemoveGuardians();
1758 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1760 if(m_items[i])
1761 m_items[i]->RemoveFromWorld();
1764 ///- Do not add/remove the player from the object storage
1765 ///- It will crash when updating the ObjectAccessor
1766 ///- The player should only be removed when logging out
1767 Unit::RemoveFromWorld();
1770 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1772 float addRage;
1774 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1776 if(attacker)
1778 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1780 // talent who gave more rage on attack
1781 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1783 else
1785 addRage = damage/rageconversion*2.5;
1787 // Berserker Rage effect
1788 if(HasAura(18499,0))
1789 addRage *= 1.3;
1792 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1794 ModifyPower(POWER_RAGE, uint32(addRage*10));
1797 void Player::RegenerateAll()
1799 if (m_regenTimer != 0)
1800 return;
1801 uint32 regenDelay = 2000;
1803 // Not in combat or they have regeneration
1804 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1805 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1807 RegenerateHealth();
1808 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1810 Regenerate(POWER_RAGE);
1811 if(getClass() == CLASS_DEATH_KNIGHT)
1812 Regenerate(POWER_RUNIC_POWER);
1816 Regenerate( POWER_ENERGY );
1818 Regenerate( POWER_MANA );
1820 if(getClass() == CLASS_DEATH_KNIGHT)
1821 Regenerate( POWER_RUNE );
1823 m_regenTimer = regenDelay;
1826 void Player::Regenerate(Powers power)
1828 uint32 curValue = GetPower(power);
1829 uint32 maxValue = GetMaxPower(power);
1831 float addvalue = 0.0f;
1833 switch (power)
1835 case POWER_MANA:
1837 bool recentCast = IsUnderLastManaUseEffect();
1838 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1839 if (recentCast)
1841 // Mangos Updates Mana in intervals of 2s, which is correct
1842 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1844 else
1846 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1848 } break;
1849 case POWER_RAGE: // Regenerate rage
1851 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1852 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1853 } break;
1854 case POWER_ENERGY: // Regenerate energy (rogue)
1855 addvalue = 20;
1856 break;
1857 case POWER_RUNIC_POWER:
1859 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1860 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1861 } break;
1862 case POWER_RUNE:
1864 for(uint32 i = 0; i < MAX_RUNES; ++i)
1865 if(uint8 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1866 SetRuneCooldown(i, cd - 1); // ... by 2 sec (because update is every 2 sec)
1867 } break;
1868 case POWER_FOCUS:
1869 case POWER_HAPPINESS:
1870 break;
1873 // Mana regen calculated in Player::UpdateManaRegen()
1874 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1875 if(power != POWER_MANA)
1877 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1878 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1879 if ((*i)->GetModifier()->m_miscvalue == power)
1880 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1883 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
1885 curValue += uint32(addvalue);
1886 if (curValue > maxValue)
1887 curValue = maxValue;
1889 else
1891 if(curValue <= uint32(addvalue))
1892 curValue = 0;
1893 else
1894 curValue -= uint32(addvalue);
1896 SetPower(power, curValue);
1899 void Player::RegenerateHealth()
1901 uint32 curValue = GetHealth();
1902 uint32 maxValue = GetMaxHealth();
1904 if (curValue >= maxValue) return;
1906 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1908 float addvalue = 0.0f;
1910 // polymorphed case
1911 if ( IsPolymorphed() )
1912 addvalue = GetMaxHealth()/3;
1913 // normal regen case (maybe partly in combat case)
1914 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1916 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1917 if (!isInCombat())
1919 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1920 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1921 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1923 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1924 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1926 if(!IsStandState())
1927 addvalue *= 1.5;
1930 // always regeneration bonus (including combat)
1931 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1933 if(addvalue < 0)
1934 addvalue = 0;
1936 ModifyHealth(int32(addvalue));
1939 bool Player::CanInteractWithNPCs(bool alive) const
1941 if(alive && !isAlive())
1942 return false;
1943 if(isInFlight())
1944 return false;
1946 return true;
1949 bool Player::IsUnderWater() const
1951 return IsInWater() &&
1952 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1955 void Player::SetInWater(bool apply)
1957 if(m_isInWater==apply)
1958 return;
1960 //define player in water by opcodes
1961 //move player's guid into HateOfflineList of those mobs
1962 //which can't swim and move guid back into ThreatList when
1963 //on surface.
1964 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1965 m_isInWater = apply;
1967 // remove auras that need water/land
1968 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
1970 getHostilRefManager().updateThreatTables();
1973 void Player::SetGameMaster(bool on)
1975 if(on)
1977 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
1978 setFaction(35);
1979 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1981 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
1982 ResetContestedPvP();
1984 getHostilRefManager().setOnlineOfflineState(false);
1985 CombatStop();
1987 else
1989 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
1990 setFactionForRace(getRace());
1991 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1993 // restore FFA PvP Server state
1994 if(sWorld.IsFFAPvPRealm())
1995 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
1997 // restore FFA PvP area state, remove not allowed for GM mounts
1998 UpdateArea(m_areaUpdateId);
2000 getHostilRefManager().setOnlineOfflineState(true);
2003 ObjectAccessor::UpdateVisibilityForPlayer(this);
2006 void Player::SetGMVisible(bool on)
2008 if(on)
2010 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2012 // Reapply stealth/invisibility if active or show if not any
2013 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2014 SetVisibility(VISIBILITY_GROUP_STEALTH);
2015 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2016 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2017 else
2018 SetVisibility(VISIBILITY_ON);
2020 else
2022 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2024 SetAcceptWhispers(false);
2025 SetGameMaster(true);
2027 SetVisibility(VISIBILITY_OFF);
2031 bool Player::IsGroupVisibleFor(Player* p) const
2033 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2035 default: return IsInSameGroupWith(p);
2036 case 1: return IsInSameRaidWith(p);
2037 case 2: return GetTeam()==p->GetTeam();
2041 bool Player::IsInSameGroupWith(Player const* p) const
2043 return p==this || GetGroup() != NULL &&
2044 GetGroup() == p->GetGroup() &&
2045 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2048 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2049 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2050 void Player::UninviteFromGroup()
2052 Group* group = GetGroupInvite();
2053 if(!group)
2054 return;
2056 group->RemoveInvite(this);
2058 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2060 if(group->IsCreated())
2062 group->Disband(true);
2063 objmgr.RemoveGroup(group);
2065 else
2066 group->RemoveAllInvites();
2068 delete group;
2072 void Player::RemoveFromGroup(Group* group, uint64 guid)
2074 if(group)
2076 if (group->RemoveMember(guid, 0) <= 1)
2078 // group->Disband(); already disbanded in RemoveMember
2079 objmgr.RemoveGroup(group);
2080 delete group;
2081 // removemember sets the player's group pointer to NULL
2086 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2088 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2089 data << uint64(victim ? victim->GetGUID() : 0); // guid
2090 data << uint32(GivenXP+RestXP); // given experience
2091 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2092 if(victim)
2094 data << uint32(GivenXP); // experience without rested bonus
2095 data << float(1); // 1 - none 0 - 100% group bonus output
2097 data << uint8(0); // new 2.4.0
2098 GetSession()->SendPacket(&data);
2101 void Player::GiveXP(uint32 xp, Unit* victim)
2103 if ( xp < 1 )
2104 return;
2106 if(!isAlive())
2107 return;
2109 uint32 level = getLevel();
2111 // XP to money conversion processed in Player::RewardQuest
2112 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2113 return;
2115 // handle SPELL_AURA_MOD_XP_PCT auras
2116 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2117 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2118 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2120 // XP resting bonus for kill
2121 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2123 SendLogXPGain(xp,victim,rested_bonus_xp);
2125 uint32 curXP = GetUInt32Value(PLAYER_XP);
2126 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2127 uint32 newXP = curXP + xp + rested_bonus_xp;
2129 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2131 newXP -= nextLvlXP;
2133 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2134 GiveLevel(level + 1);
2136 level = getLevel();
2137 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2140 SetUInt32Value(PLAYER_XP, newXP);
2143 // Update player to next level
2144 // Current player experience not update (must be update by caller)
2145 void Player::GiveLevel(uint32 level)
2147 if ( level == getLevel() )
2148 return;
2150 PlayerLevelInfo info;
2151 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2153 PlayerClassLevelInfo classInfo;
2154 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2156 // send levelup info to client
2157 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2158 data << uint32(level);
2159 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2160 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2161 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2162 data << uint32(0);
2163 data << uint32(0);
2164 data << uint32(0);
2165 data << uint32(0);
2166 data << uint32(0);
2167 data << uint32(0);
2168 // end for
2169 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2170 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2172 GetSession()->SendPacket(&data);
2174 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(level));
2176 //update level, max level of skills
2177 if(getLevel()!= level)
2178 m_Played_time[1] = 0; // Level Played Time reset
2179 SetLevel(level);
2180 UpdateSkillsForLevel ();
2182 // save base values (bonuses already included in stored stats
2183 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2184 SetCreateStat(Stats(i), info.stats[i]);
2186 SetCreateHealth(classInfo.basehealth);
2187 SetCreateMana(classInfo.basemana);
2189 InitTalentForLevel();
2190 InitTaxiNodesForLevel();
2191 InitGlyphsForLevel();
2193 UpdateAllStats();
2195 // set current level health and mana/energy to maximum after applying all mods.
2196 SetHealth(GetMaxHealth());
2197 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2198 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2199 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2200 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2201 SetPower(POWER_FOCUS, 0);
2202 SetPower(POWER_HAPPINESS, 0);
2204 // give level to summoned pet
2205 Pet* pet = GetPet();
2206 if(pet && pet->getPetType()==SUMMON_PET)
2207 pet->GivePetLevel(level);
2208 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2211 void Player::InitTalentForLevel()
2213 uint32 level = getLevel();
2214 // talents base at level diff ( talents = level - 9 but some can be used already)
2215 if(level < 10)
2217 // Remove all talent points
2218 if(m_usedTalentCount > 0) // Free any used talents
2220 resetTalents(true);
2221 SetFreeTalentPoints(0);
2224 else
2226 uint32 talentPointsForLevel = uint32((level-9)*sWorld.getRate(RATE_TALENT));
2227 // if used more that have then reset
2228 if(m_usedTalentCount > talentPointsForLevel)
2230 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2231 resetTalents(true);
2232 else
2233 SetFreeTalentPoints(0);
2235 // else update amount of free points
2236 else
2237 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2241 void Player::InitStatsForLevel(bool reapplyMods)
2243 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2244 _RemoveAllStatBonuses();
2246 PlayerClassLevelInfo classInfo;
2247 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2249 PlayerLevelInfo info;
2250 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2252 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2253 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(getLevel()));
2255 UpdateSkillsForLevel ();
2257 // set default cast time multiplier
2258 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2260 // reset size before reapply auras
2261 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2263 // save base values (bonuses already included in stored stats
2264 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2265 SetCreateStat(Stats(i), info.stats[i]);
2267 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2268 SetStat(Stats(i), info.stats[i]);
2270 SetCreateHealth(classInfo.basehealth);
2272 //set create powers
2273 SetCreateMana(classInfo.basemana);
2275 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2277 InitStatBuffMods();
2279 //reset rating fields values
2280 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2281 SetUInt32Value(index, 0);
2283 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2284 for (int i = 0; i < 7; i++)
2286 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2287 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2288 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2291 //reset attack power, damage and attack speed fields
2292 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2293 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2294 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2296 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2297 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2298 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2299 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2300 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2301 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2303 SetUInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2304 SetUInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2305 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2306 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2307 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2308 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2310 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2311 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2312 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2313 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2315 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2316 for (uint8 i = 0; i < 7; ++i)
2317 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2319 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2320 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2321 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2323 // Dodge percentage
2324 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2326 // set armor (resistance 0) to original value (create_agility*2)
2327 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2328 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2329 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2330 // set other resistance to original value (0)
2331 for (int i = 1; i < MAX_SPELL_SCHOOL; i++)
2333 SetResistance(SpellSchools(i), 0);
2334 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2335 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2338 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2339 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2340 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2342 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER+i,0.0f);
2343 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2345 // Reset no reagent cost field
2346 for(int i = 0; i < 3; i++)
2347 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2348 // Init data for form but skip reapply item mods for form
2349 InitDataForForm(reapplyMods);
2351 // save new stats
2352 for (int i = POWER_MANA; i < MAX_POWERS; i++)
2353 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2355 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2357 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2358 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2360 // cleanup unit flags (will be re-applied if need at aura load).
2361 RemoveFlag( UNIT_FIELD_FLAGS,
2362 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2363 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2364 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2365 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2366 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2367 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2369 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2370 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2372 SetByteValue(UNIT_FIELD_BYTES_1, 2, 0x00); // one form stealth modified bytes
2373 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2375 // restore if need some important flags
2376 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2378 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2379 _ApplyAllStatBonuses();
2381 // set current level health and mana/energy to maximum after applying all mods.
2382 SetHealth(GetMaxHealth());
2383 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2384 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2385 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2386 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2387 SetPower(POWER_FOCUS, 0);
2388 SetPower(POWER_HAPPINESS, 0);
2389 SetPower(POWER_RUNIC_POWER, 0);
2392 void Player::SendInitialSpells()
2394 uint16 spellCount = 0;
2396 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2397 data << uint8(0);
2399 size_t countPos = data.wpos();
2400 data << uint16(spellCount); // spell count placeholder
2402 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2404 if(itr->second->state == PLAYERSPELL_REMOVED)
2405 continue;
2407 if(!itr->second->active || itr->second->disabled)
2408 continue;
2410 data << uint16(itr->first);
2411 data << uint16(0); // it's not slot id
2413 spellCount +=1;
2416 data.put<uint16>(countPos,spellCount); // write real count value
2418 uint16 spellCooldowns = m_spellCooldowns.size();
2419 data << uint16(spellCooldowns);
2420 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2422 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2423 if(!sEntry)
2424 continue;
2426 data << uint16(itr->first);
2428 time_t cooldown = 0;
2429 time_t curTime = time(NULL);
2430 if(itr->second.end > curTime)
2431 cooldown = (itr->second.end-curTime)*1000;
2433 data << uint16(itr->second.itemid); // cast item id
2434 data << uint16(sEntry->Category); // spell category
2435 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2437 data << uint32(0); // cooldown
2438 data << uint32(cooldown); // category cooldown
2440 else
2442 data << uint32(cooldown); // cooldown
2443 data << uint32(0); // category cooldown
2447 GetSession()->SendPacket(&data);
2449 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2452 void Player::RemoveMail(uint32 id)
2454 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2456 if ((*itr)->messageID == id)
2458 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2459 m_mail.erase(itr);
2460 return;
2465 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2467 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2468 data << (uint32) mailId;
2469 data << (uint32) mailAction;
2470 data << (uint32) mailError;
2471 if ( mailError == MAIL_ERR_BAG_FULL )
2472 data << (uint32) equipError;
2473 else if( mailAction == MAIL_ITEM_TAKEN )
2475 data << (uint32) item_guid; // item guid low?
2476 data << (uint32) item_count; // item count?
2478 GetSession()->SendPacket(&data);
2481 void Player::SendNewMail()
2483 // deliver undelivered mail
2484 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2485 data << (uint32) 0;
2486 GetSession()->SendPacket(&data);
2489 void Player::UpdateNextMailTimeAndUnreads()
2491 // calculate next delivery time (min. from non-delivered mails
2492 // and recalculate unReadMail
2493 time_t cTime = time(NULL);
2494 m_nextMailDelivereTime = 0;
2495 unReadMails = 0;
2496 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2498 if((*itr)->deliver_time > cTime)
2500 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2501 m_nextMailDelivereTime = (*itr)->deliver_time;
2503 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2504 ++unReadMails;
2508 void Player::AddNewMailDeliverTime(time_t deliver_time)
2510 if(deliver_time <= time(NULL)) // ready now
2512 ++unReadMails;
2513 SendNewMail();
2515 else // not ready and no have ready mails
2517 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2518 m_nextMailDelivereTime = deliver_time;
2522 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool loading, uint16 slot_id, bool disabled)
2524 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2525 if (!spellInfo)
2527 // do character spell book cleanup (all characters)
2528 if(loading && !learning) // spell load case
2530 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2531 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2533 else
2534 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2536 return false;
2539 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2541 // do character spell book cleanup (all characters)
2542 if(loading && !learning) // spell load case
2544 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2545 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2547 else
2548 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2550 return false;
2553 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2555 bool disabled_case = false;
2556 bool superceded_old = false;
2558 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2559 if (itr != m_spells.end())
2561 // update active state for known spell
2562 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2564 itr->second->active = active;
2566 // loading && !learning == explicitly load from DB and then exist in it already and set correctly
2567 if(loading && !learning)
2568 itr->second->state = PLAYERSPELL_UNCHANGED;
2569 else if(itr->second->state != PLAYERSPELL_NEW)
2570 itr->second->state = PLAYERSPELL_CHANGED;
2572 if(!active)
2574 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2575 data << uint16(spell_id);
2576 GetSession()->SendPacket(&data);
2578 return active; // learn (show in spell book if active now)
2581 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2583 if(itr->second->state != PLAYERSPELL_NEW)
2584 itr->second->state = PLAYERSPELL_CHANGED;
2585 itr->second->disabled = disabled;
2587 if(disabled)
2588 return false;
2590 disabled_case = true;
2592 else switch(itr->second->state)
2594 case PLAYERSPELL_UNCHANGED: // known saved spell
2595 return false;
2596 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2598 delete itr->second;
2599 m_spells.erase(itr);
2600 state = PLAYERSPELL_CHANGED;
2601 break; // need re-add
2603 default: // known not saved yet spell (new or modified)
2605 // can be in case spell loading but learned at some previous spell loading
2606 if(loading && !learning)
2607 itr->second->state = PLAYERSPELL_UNCHANGED;
2609 return false;
2614 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2616 // talent: unlearn all other talent ranks (high and low)
2617 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2619 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2621 for(int i=0; i <5; ++i)
2623 // skip learning spell and no rank spell case
2624 uint32 rankSpellId = talentInfo->RankID[i];
2625 if(!rankSpellId || rankSpellId==spell_id)
2626 continue;
2628 // skip unknown ranks
2629 if(!HasSpell(rankSpellId))
2630 continue;
2632 removeSpell(rankSpellId);
2636 // non talent spell: learn low ranks (recursive call)
2637 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2639 if(loading) // at spells loading, no output, but allow save
2640 addSpell(prev_spell,active,true,loading,SPELL_WITHOUT_SLOT_ID,disabled);
2641 else // at normal learning
2642 learnSpell(prev_spell);
2645 PlayerSpell *newspell = new PlayerSpell;
2646 newspell->active = active;
2647 newspell->state = state;
2648 newspell->disabled = disabled;
2650 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2651 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2653 for( PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr )
2655 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
2656 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr->first);
2657 if(!i_spellInfo) continue;
2659 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr->first) )
2661 if(itr->second->active)
2663 if(spellmgr.IsHighRankOfSpell(spell_id,itr->first))
2665 if(!loading) // not send spell (re-/over-)learn packets at loading
2667 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2668 data << uint16(itr->first);
2669 data << uint16(spell_id);
2670 GetSession()->SendPacket( &data );
2673 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2674 itr->second->active = false;
2675 itr->second->state = PLAYERSPELL_CHANGED;
2676 superceded_old = true; // new spell replace old in action bars and spell book.
2678 else if(spellmgr.IsHighRankOfSpell(itr->first,spell_id))
2680 if(!loading) // not send spell (re-/over-)learn packets at loading
2682 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2683 data << uint16(spell_id);
2684 data << uint16(itr->first);
2685 GetSession()->SendPacket( &data );
2688 // mark new spell as disable (not learned yet for client and will not learned)
2689 newspell->active = false;
2690 if(newspell->state != PLAYERSPELL_NEW)
2691 newspell->state = PLAYERSPELL_CHANGED;
2698 uint16 tmpslot=slot_id;
2700 if (tmpslot == SPELL_WITHOUT_SLOT_ID)
2702 uint16 maxid = 0;
2703 PlayerSpellMap::iterator itr;
2704 for (itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2706 if(itr->second->state == PLAYERSPELL_REMOVED)
2707 continue;
2708 if (itr->second->slotId > maxid)
2709 maxid = itr->second->slotId;
2711 tmpslot = maxid + 1;
2714 newspell->slotId = tmpslot;
2715 m_spells[spell_id] = newspell;
2717 // return false if spell disabled
2718 if (newspell->disabled)
2719 return false;
2722 uint32 talentCost = GetTalentSpellCost(spell_id);
2724 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2725 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2726 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2728 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2729 CastSpell(this, spell_id, true);
2731 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2732 else if (IsPassiveSpell(spell_id))
2734 // if spell doesn't require a stance or the player is in the required stance
2735 if( ( !spellInfo->Stances &&
2736 spell_id != 5420 && spell_id != 5419 && spell_id != 7376 &&
2737 spell_id != 7381 && spell_id != 21156 && spell_id != 21009 &&
2738 spell_id != 21178 && spell_id != 33948 && spell_id != 40121 ) ||
2739 m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))) ||
2740 (spell_id == 5420 && m_form == FORM_TREE) ||
2741 (spell_id == 5419 && m_form == FORM_TRAVEL) ||
2742 (spell_id == 7376 && m_form == FORM_DEFENSIVESTANCE) ||
2743 (spell_id == 7381 && m_form == FORM_BERSERKERSTANCE) ||
2744 (spell_id == 21156 && m_form == FORM_BATTLESTANCE)||
2745 (spell_id == 21178 && (m_form == FORM_BEAR || m_form == FORM_DIREBEAR) ) ||
2746 (spell_id == 33948 && m_form == FORM_FLIGHT) ||
2747 (spell_id == 40121 && m_form == FORM_FLIGHT_EPIC) )
2748 //Check CasterAuraStates
2749 if (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)))
2750 CastSpell(this, spell_id, true);
2752 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2754 CastSpell(this, spell_id, true);
2755 return false;
2758 // update used talent points count
2759 m_usedTalentCount += talentCost;
2761 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2762 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2764 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2765 SetFreePrimaryProffesions(freeProfs-1);
2768 // add dependent skills
2769 uint16 maxskill = GetMaxSkillValueForLevel();
2771 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2773 if(spellLearnSkill)
2775 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2776 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2778 if(skill_value < spellLearnSkill->value)
2779 skill_value = spellLearnSkill->value;
2781 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2783 if(skill_max_value < new_skill_max_value)
2784 skill_max_value = new_skill_max_value;
2786 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2788 else
2790 // not ranked skills
2791 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2792 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2794 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2796 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2797 if(!pSkill)
2798 continue;
2800 if(HasSkill(pSkill->id))
2801 continue;
2803 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2804 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2805 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2807 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2809 case SKILL_RANGE_LANGUAGE:
2810 SetSkill(pSkill->id, 300, 300 );
2811 break;
2812 case SKILL_RANGE_LEVEL:
2813 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2814 break;
2815 case SKILL_RANGE_MONO:
2816 SetSkill(pSkill->id, 1, 1 );
2817 break;
2818 default:
2819 break;
2825 // learn dependent spells
2826 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2827 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2829 for(SpellLearnSpellMap::const_iterator itr = spell_begin; itr != spell_end; ++itr)
2831 if(!itr->second.autoLearned)
2833 if(loading) // at spells loading, no output, but allow save
2834 addSpell(itr->second.spell,true,true,loading);
2835 else // at normal learning
2836 learnSpell(itr->second.spell);
2840 if(!loading)
2842 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL);
2843 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS);
2846 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2847 return active && !disabled && !superceded_old;
2850 void Player::learnSpell(uint32 spell_id)
2852 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2854 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
2855 bool active = disabled ? itr->second->active : true;
2857 bool learning = addSpell(spell_id,active);
2859 // learn all disabled higher ranks (recursive)
2860 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2861 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
2863 PlayerSpellMap::iterator iter = m_spells.find(i->second);
2864 if (disabled && iter != m_spells.end() && iter->second->disabled)
2865 learnSpell(i->second);
2868 // prevent duplicated entires in spell book
2869 if(!learning)
2870 return;
2872 WorldPacket data(SMSG_LEARNED_SPELL, 4);
2873 data << uint32(spell_id);
2874 GetSession()->SendPacket(&data);
2877 void Player::removeSpell(uint32 spell_id, bool disabled)
2879 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2880 if (itr == m_spells.end())
2881 return;
2883 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
2884 return;
2886 // unlearn non talent higher ranks (recursive)
2887 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2888 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
2889 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
2890 removeSpell(itr2->second,disabled);
2892 // removing
2893 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2894 data << uint16(spell_id);
2895 GetSession()->SendPacket(&data);
2897 if (disabled)
2899 itr->second->disabled = disabled;
2900 if(itr->second->state != PLAYERSPELL_NEW)
2901 itr->second->state = PLAYERSPELL_CHANGED;
2903 else
2905 if(itr->second->state == PLAYERSPELL_NEW)
2907 delete itr->second;
2908 m_spells.erase(itr);
2910 else
2911 itr->second->state = PLAYERSPELL_REMOVED;
2914 RemoveAurasDueToSpell(spell_id);
2916 // remove pet auras
2917 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
2918 RemovePetAura(petSpell);
2920 // free talent points
2921 uint32 talentCosts = GetTalentSpellCost(spell_id);
2922 if(talentCosts > 0)
2924 if(talentCosts < m_usedTalentCount)
2925 m_usedTalentCount -= talentCosts;
2926 else
2927 m_usedTalentCount = 0;
2930 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2931 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2933 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
2934 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
2935 SetFreePrimaryProffesions(freeProfs);
2938 // remove dependent skill
2939 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2940 if(spellLearnSkill)
2942 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
2943 if(!prev_spell) // first rank, remove skill
2944 SetSkill(spellLearnSkill->skill,0,0);
2945 else
2947 // search prev. skill setting by spell ranks chain
2948 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
2949 while(!prevSkill && prev_spell)
2951 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
2952 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
2955 if(!prevSkill) // not found prev skill setting, remove skill
2956 SetSkill(spellLearnSkill->skill,0,0);
2957 else // set to prev. skill setting values
2959 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
2960 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
2962 if(skill_value > prevSkill->value)
2963 skill_value = prevSkill->value;
2965 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
2967 if(skill_max_value > new_skill_max_value)
2968 skill_max_value = new_skill_max_value;
2970 SetSkill(prevSkill->skill,skill_value,skill_max_value);
2975 else
2977 // not ranked skills
2978 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2979 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2981 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2983 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2984 if(!pSkill)
2985 continue;
2987 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2988 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2989 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2991 // not reset skills for professions and racial abilities
2992 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
2993 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
2994 continue;
2996 SetSkill(pSkill->id, 0, 0 );
3001 // remove dependent spells
3002 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
3003 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
3005 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
3006 removeSpell(itr2->second.spell, disabled);
3008 // TODO: recast if need lesser ranks spell for passive with IsPassiveSpellStackableWithRanks
3011 void Player::RemoveArenaSpellCooldowns()
3013 // remove cooldowns on spells that has < 15 min CD
3014 SpellCooldowns::iterator itr, next;
3015 // iterate spell cooldowns
3016 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3018 next = itr;
3019 ++next;
3020 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3021 // check if spellentry is present and if the cooldown is less than 15 mins
3022 if( entry &&
3023 entry->RecoveryTime <= 15 * MINUTE * 1000 &&
3024 entry->CategoryRecoveryTime <= 15 * MINUTE * 1000 )
3026 // notify player
3027 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3028 data << uint32(itr->first);
3029 data << GetGUID();
3030 GetSession()->SendPacket(&data);
3031 // remove cooldown
3032 m_spellCooldowns.erase(itr);
3037 void Player::RemoveAllSpellCooldown()
3039 if(!m_spellCooldowns.empty())
3041 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3043 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3044 data << uint32(itr->first);
3045 data << uint64(GetGUID());
3046 GetSession()->SendPacket(&data);
3048 m_spellCooldowns.clear();
3052 void Player::_LoadSpellCooldowns(QueryResult *result)
3054 m_spellCooldowns.clear();
3056 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3058 if(result)
3060 time_t curTime = time(NULL);
3064 Field *fields = result->Fetch();
3066 uint32 spell_id = fields[0].GetUInt32();
3067 uint32 item_id = fields[1].GetUInt32();
3068 time_t db_time = (time_t)fields[2].GetUInt64();
3070 if(!sSpellStore.LookupEntry(spell_id))
3072 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3073 continue;
3076 // skip outdated cooldown
3077 if(db_time <= curTime)
3078 continue;
3080 AddSpellCooldown(spell_id, item_id, db_time);
3082 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3084 while( result->NextRow() );
3086 delete result;
3090 void Player::_SaveSpellCooldowns()
3092 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3094 time_t curTime = time(NULL);
3096 // remove outdated and save active
3097 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3099 if(itr->second.end <= curTime)
3100 m_spellCooldowns.erase(itr++);
3101 else
3103 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));
3104 ++itr;
3109 uint32 Player::resetTalentsCost() const
3111 // The first time reset costs 1 gold
3112 if(m_resetTalentsCost < 1*GOLD)
3113 return 1*GOLD;
3114 // then 5 gold
3115 else if(m_resetTalentsCost < 5*GOLD)
3116 return 5*GOLD;
3117 // After that it increases in increments of 5 gold
3118 else if(m_resetTalentsCost < 10*GOLD)
3119 return 10*GOLD;
3120 else
3122 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3123 if(months > 0)
3125 // This cost will be reduced by a rate of 5 gold per month
3126 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3127 // to a minimum of 10 gold.
3128 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3130 else
3132 // After that it increases in increments of 5 gold
3133 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3134 // until it hits a cap of 50 gold.
3135 if(new_cost > 50*GOLD)
3136 new_cost = 50*GOLD;
3137 return new_cost;
3142 bool Player::resetTalents(bool no_cost)
3144 // not need after this call
3145 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3147 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3148 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3151 uint32 level = getLevel();
3152 uint32 talentPointsForLevel = level < 10 ? 0 : uint32((level-9)*sWorld.getRate(RATE_TALENT));
3154 if (m_usedTalentCount == 0)
3156 SetFreeTalentPoints(talentPointsForLevel);
3157 return false;
3160 uint32 cost = 0;
3162 if(!no_cost)
3164 cost = resetTalentsCost();
3166 if (GetMoney() < cost)
3168 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3169 return false;
3173 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); i++)
3175 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3177 if (!talentInfo) continue;
3179 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3181 if(!talentTabInfo)
3182 continue;
3184 // unlearn only talents for character class
3185 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3186 // to prevent unexpected lost normal learned spell skip another class talents
3187 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3188 continue;
3190 for (int j = 0; j < 5; j++)
3192 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3194 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3196 ++itr;
3197 continue;
3200 // remove learned spells (all ranks)
3201 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3203 // unlearn if first rank is talent or learned by talent
3204 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3206 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3207 itr = GetSpellMap().begin();
3208 continue;
3210 else
3211 ++itr;
3216 SetFreeTalentPoints(talentPointsForLevel);
3218 if(!no_cost)
3220 ModifyMoney(-(int32)cost);
3222 m_resetTalentsCost = cost;
3223 m_resetTalentsTime = time(NULL);
3226 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3227 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3229 return true;
3232 bool Player::_removeSpell(uint16 spell_id)
3234 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3235 if (itr != m_spells.end())
3237 delete itr->second;
3238 m_spells.erase(itr);
3239 return true;
3241 return false;
3244 Mail* Player::GetMail(uint32 id)
3246 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3248 if ((*itr)->messageID == id)
3250 return (*itr);
3253 return NULL;
3256 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3258 if(target == this)
3260 Object::_SetCreateBits(updateMask, target);
3262 else
3264 for(uint16 index = 0; index < m_valuesCount; index++)
3266 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3267 updateMask->SetBit(index);
3272 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3274 if(target == this)
3276 Object::_SetUpdateBits(updateMask, target);
3278 else
3280 Object::_SetUpdateBits(updateMask, target);
3281 *updateMask &= updateVisualBits;
3285 void Player::InitVisibleBits()
3287 updateVisualBits.SetCount(PLAYER_END);
3289 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3290 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3291 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3292 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3293 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3294 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3295 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3296 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3297 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3298 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3299 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3300 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3301 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3302 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3303 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3304 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3305 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3306 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3307 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3308 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3309 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3310 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3311 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3312 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3313 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3314 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3315 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3316 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3317 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3318 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3319 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3320 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3321 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3322 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3323 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3324 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3325 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3326 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3327 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3328 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3329 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3330 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3331 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3332 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3333 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3334 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3335 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3336 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3337 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3338 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3339 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3340 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3341 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3342 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3343 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3345 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3346 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3347 updateVisualBits.SetBit(PLAYER_FLAGS);
3348 updateVisualBits.SetBit(PLAYER_GUILDID);
3349 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3350 updateVisualBits.SetBit(PLAYER_BYTES);
3351 updateVisualBits.SetBit(PLAYER_BYTES_2);
3352 updateVisualBits.SetBit(PLAYER_BYTES_3);
3353 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3354 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3356 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3357 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3358 updateVisualBits.SetBit(i);
3360 // Players visible items are not inventory stuff
3361 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3363 uint32 offset = i * MAX_VISIBLE_ITEM_OFFSET;
3365 // item creator
3366 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 0 + offset);
3367 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 1 + offset);
3369 // item entry
3370 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 0 + offset);
3372 // item enchantments
3373 for(uint8 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
3374 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 1 + j + offset);
3376 // random properties
3377 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + offset);
3378 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_SEED + offset);
3379 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PAD + offset);
3382 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3385 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3387 for(int i = 0; i < EQUIPMENT_SLOT_END; i++)
3389 if(m_items[i] == NULL)
3390 continue;
3392 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3395 if(target == this)
3397 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3399 if(m_items[i] == NULL)
3400 continue;
3402 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3404 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3406 if(m_items[i] == NULL)
3407 continue;
3409 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3413 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3416 void Player::DestroyForPlayer( Player *target ) const
3418 Unit::DestroyForPlayer( target );
3420 for(int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
3422 if(m_items[i] == NULL)
3423 continue;
3425 m_items[i]->DestroyForPlayer( target );
3428 if(target == this)
3430 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3432 if(m_items[i] == NULL)
3433 continue;
3435 m_items[i]->DestroyForPlayer( target );
3437 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3439 if(m_items[i] == NULL)
3440 continue;
3442 m_items[i]->DestroyForPlayer( target );
3447 bool Player::HasSpell(uint32 spell) const
3449 PlayerSpellMap::const_iterator itr = m_spells.find((uint16)spell);
3450 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled);
3453 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3455 if (!trainer_spell)
3456 return TRAINER_SPELL_RED;
3458 if (!trainer_spell->spell)
3459 return TRAINER_SPELL_RED;
3461 // known spell
3462 if(HasSpell(trainer_spell->spell))
3463 return TRAINER_SPELL_GRAY;
3465 // check race/class requirement
3466 if(!IsSpellFitByClassAndRace(trainer_spell->spell))
3467 return TRAINER_SPELL_RED;
3469 // check level requirement
3470 if(getLevel() < trainer_spell->reqlevel)
3471 return TRAINER_SPELL_RED;
3473 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->spell))
3475 // check prev.rank requirement
3476 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3477 return TRAINER_SPELL_RED;
3479 // check additional spell requirement
3480 if(spell_chain->req && !HasSpell(spell_chain->req))
3481 return TRAINER_SPELL_RED;
3484 // check skill requirement
3485 if(trainer_spell->reqskill && GetBaseSkillValue(trainer_spell->reqskill) < trainer_spell->reqskillvalue)
3486 return TRAINER_SPELL_RED;
3488 // exist, already checked at loading
3489 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->spell);
3491 // secondary prof. or not prof. spell
3492 uint32 skill = spell->EffectMiscValue[1];
3494 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3495 return TRAINER_SPELL_GREEN;
3497 // check primary prof. limit
3498 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3499 return TRAINER_SPELL_RED;
3501 return TRAINER_SPELL_GREEN;
3504 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3506 uint32 guid = GUID_LOPART(playerguid);
3508 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3509 // bones will be deleted by corpse/bones deleting thread shortly
3510 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3512 // remove from guild
3513 uint32 guildId = GetGuildIdFromDB(playerguid);
3514 if(guildId != 0)
3516 Guild* guild = objmgr.GetGuildById(guildId);
3517 if(guild)
3518 guild->DelMember(guid);
3521 // remove from arena teams
3522 LeaveAllArenaTeams(playerguid);
3524 // the player was uninvited already on logout so just remove from group
3525 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3526 if(resultGroup)
3528 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3529 delete resultGroup;
3530 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3531 if(group)
3533 RemoveFromGroup(group, playerguid);
3537 // remove signs from petitions (also remove petitions if owner);
3538 RemovePetitionsAndSigns(playerguid, 10);
3540 // return back all mails with COD and Item 0 1 2 3 4 5 6
3541 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);
3542 if(resultMail)
3546 Field *fields = resultMail->Fetch();
3548 uint32 mail_id = fields[0].GetUInt32();
3549 uint16 mailTemplateId= fields[1].GetUInt16();
3550 uint32 sender = fields[2].GetUInt32();
3551 std::string subject = fields[3].GetCppString();
3552 uint32 itemTextId = fields[4].GetUInt32();
3553 uint32 money = fields[5].GetUInt32();
3554 bool has_items = fields[6].GetBool();
3556 //we can return mail now
3557 //so firstly delete the old one
3558 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3560 MailItemsInfo mi;
3561 if(has_items)
3563 // data needs to be at first place for Item::LoadFromDB
3564 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);
3565 if(resultItems)
3569 Field *fields2 = resultItems->Fetch();
3571 uint32 item_guidlow = fields2[1].GetUInt32();
3572 uint32 item_template = fields2[2].GetUInt32();
3574 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3575 if(!itemProto)
3577 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3578 continue;
3581 Item *pItem = NewItemOrBag(itemProto);
3582 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3584 pItem->FSetState(ITEM_REMOVED);
3585 pItem->SaveToDB(); // it also deletes item object !
3586 continue;
3589 mi.AddItem(item_guidlow, item_template, pItem);
3591 while (resultItems->NextRow());
3593 delete resultItems;
3597 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3599 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3601 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3603 while (resultMail->NextRow());
3605 delete resultMail;
3608 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3609 // Get guids of character's pets, will deleted in transaction
3610 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3612 // NOW we can finally clear other DB data related to character
3613 CharacterDatabase.BeginTransaction();
3614 if (resultPets)
3618 Field *fields3 = resultPets->Fetch();
3619 uint32 petguidlow = fields3[0].GetUInt32();
3620 Pet::DeleteFromDB(petguidlow);
3621 } while (resultPets->NextRow());
3622 delete resultPets;
3625 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3626 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3627 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3628 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3629 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3630 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3631 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3632 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3633 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3634 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3635 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3636 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3637 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3638 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3639 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3640 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3641 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3642 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3643 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3644 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3645 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3646 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3647 CharacterDatabase.CommitTransaction();
3649 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3650 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3653 void Player::SetMovement(PlayerMovementType pType)
3655 WorldPacket data;
3656 switch(pType)
3658 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3659 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3660 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3661 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3662 default:
3663 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3664 return;
3666 data.append(GetPackGUID());
3667 data << uint32(0);
3668 GetSession()->SendPacket( &data );
3671 /* Preconditions:
3672 - a resurrectable corpse must not be loaded for the player (only bones)
3673 - the player must be in world
3675 void Player::BuildPlayerRepop()
3677 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3678 data.append(GetPackGUID());
3679 GetSession()->SendPacket(&data);
3681 if(getRace() == RACE_NIGHTELF)
3682 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)
3683 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3685 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3686 // there must be SMSG.STOP_MIRROR_TIMER
3687 // there we must send 888 opcode
3689 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3690 if(GetCorpse())
3692 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3693 assert(false);
3696 // create a corpse and place it at the player's location
3697 CreateCorpse();
3698 Corpse *corpse = GetCorpse();
3699 if(!corpse)
3701 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3702 return;
3704 GetMap()->Add(corpse);
3706 // convert player body to ghost
3707 SetHealth( 1 );
3709 SetMovement(MOVE_WATER_WALK);
3710 if(!GetSession()->isLogingOut())
3711 SetMovement(MOVE_UNROOT);
3713 // BG - remove insignia related
3714 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3716 SendCorpseReclaimDelay();
3718 // to prevent cheating
3719 corpse->ResetGhostTime();
3721 StopMirrorTimers(); //disable timers(bars)
3723 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3725 SetByteValue(UNIT_FIELD_BYTES_1, 3, PLAYER_STATE_FLAG_ALWAYS_STAND);
3728 void Player::SendDelayResponse(const uint32 ml_seconds)
3730 //FIXME: is this delay time arg really need? 50msec by default in code
3731 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3732 data << (uint32)time(NULL);
3733 data << (uint32)0;
3734 GetSession()->SendPacket( &data );
3737 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
3739 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3740 data << uint32(-1);
3741 data << float(0);
3742 data << float(0);
3743 data << float(0);
3744 GetSession()->SendPacket(&data);
3746 // speed change, land walk
3748 // remove death flag + set aura
3749 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3750 if(getRace() == RACE_NIGHTELF)
3751 RemoveAurasDueToSpell(20584); // speed bonuses
3752 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3754 setDeathState(ALIVE);
3756 SetMovement(MOVE_LAND_WALK);
3757 SetMovement(MOVE_UNROOT);
3759 m_deathTimer = 0;
3761 // set health/powers (0- will be set in caller)
3762 if(restore_percent>0.0f)
3764 SetHealth(uint32(GetMaxHealth()*restore_percent));
3765 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3766 SetPower(POWER_RAGE, 0);
3767 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3770 // update visibility
3771 ObjectAccessor::UpdateVisibilityForPlayer(this);
3773 // some items limited to specific map
3774 DestroyZoneLimitedItem( true, GetZoneId());
3776 if(!applySickness)
3777 return;
3779 //Characters from level 1-10 are not affected by resurrection sickness.
3780 //Characters from level 11-19 will suffer from one minute of sickness
3781 //for each level they are above 10.
3782 //Characters level 20 and up suffer from ten minutes of sickness.
3783 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3785 if(int32(getLevel()) >= startLevel)
3787 // set resurrection sickness
3788 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
3790 // not full duration
3791 if(int32(getLevel()) < startLevel+9)
3793 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
3795 for(int i =0; i < 3; ++i)
3797 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
3799 Aur->SetAuraDuration(delta*1000);
3800 Aur->SendAuraUpdate(false);
3807 void Player::KillPlayer()
3809 SetMovement(MOVE_ROOT);
3811 StopMirrorTimers(); //disable timers(bars)
3813 setDeathState(CORPSE);
3814 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3816 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
3817 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
3819 // 6 minutes until repop at graveyard
3820 m_deathTimer = 6*MINUTE*1000;
3822 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3824 // don't create corpse at this moment, player might be falling
3826 // update visibility
3827 ObjectAccessor::UpdateObjectVisibility(this);
3830 void Player::CreateCorpse()
3832 // prevent existence 2 corpse for player
3833 SpawnCorpseBones();
3835 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
3837 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
3838 SetPvPDeath(false);
3840 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this, GetMapId(), GetPositionX(),
3841 GetPositionY(), GetPositionZ(), GetOrientation()))
3843 delete corpse;
3844 return;
3847 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
3848 _pb = GetUInt32Value(PLAYER_BYTES);
3849 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
3851 uint8 race = (uint8)(_uf);
3852 uint8 skin = (uint8)(_pb);
3853 uint8 face = (uint8)(_pb >> 8);
3854 uint8 hairstyle = (uint8)(_pb >> 16);
3855 uint8 haircolor = (uint8)(_pb >> 24);
3856 uint8 facialhair = (uint8)(_pb2);
3858 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
3859 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
3861 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
3862 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
3864 uint32 flags = CORPSE_FLAG_UNK2;
3865 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
3866 flags |= CORPSE_FLAG_HIDE_HELM;
3867 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
3868 flags |= CORPSE_FLAG_HIDE_CLOAK;
3869 if(InBattleGround())
3870 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
3871 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
3873 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
3875 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
3877 uint32 iDisplayID;
3878 uint16 iIventoryType;
3879 uint32 _cfi;
3880 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
3882 if(m_items[i])
3884 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
3885 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
3887 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
3888 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
3892 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
3893 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
3894 assert(entry);
3895 if(entry->map_type != MAP_BATTLEGROUND)
3896 corpse->SaveToDB();
3898 // register for player, but not show
3899 ObjectAccessor::Instance().AddCorpse(corpse);
3902 void Player::SpawnCorpseBones()
3904 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
3905 SaveToDB(); // prevent loading as ghost without corpse
3908 Corpse* Player::GetCorpse() const
3910 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
3913 void Player::DurabilityLossAll(double percent, bool inventory)
3915 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3916 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3917 DurabilityLoss(pItem,percent);
3919 if(inventory)
3921 // bags not have durability
3922 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3924 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3925 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3926 DurabilityLoss(pItem,percent);
3928 // keys not have durability
3929 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3931 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3932 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3933 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
3934 if(Item* pItem = GetItemByPos( i, j ))
3935 DurabilityLoss(pItem,percent);
3939 void Player::DurabilityLoss(Item* item, double percent)
3941 if(!item )
3942 return;
3944 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3946 if(!pMaxDurability)
3947 return;
3949 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
3951 if(pDurabilityLoss < 1 )
3952 pDurabilityLoss = 1;
3954 DurabilityPointsLoss(item,pDurabilityLoss);
3957 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
3959 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3960 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3961 DurabilityPointsLoss(pItem,points);
3963 if(inventory)
3965 // bags not have durability
3966 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3968 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3969 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3970 DurabilityPointsLoss(pItem,points);
3972 // keys not have durability
3973 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3975 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3976 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3977 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
3978 if(Item* pItem = GetItemByPos( i, j ))
3979 DurabilityPointsLoss(pItem,points);
3983 void Player::DurabilityPointsLoss(Item* item, int32 points)
3985 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3986 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
3987 int32 pNewDurability = pOldDurability - points;
3989 if (pNewDurability < 0)
3990 pNewDurability = 0;
3991 else if (pNewDurability > pMaxDurability)
3992 pNewDurability = pMaxDurability;
3994 if (pOldDurability != pNewDurability)
3996 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
3997 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
3998 _ApplyItemMods(item,item->GetSlot(), false);
4000 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4002 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4003 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4004 _ApplyItemMods(item,item->GetSlot(), true);
4006 item->SetState(ITEM_CHANGED, this);
4010 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4012 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4013 DurabilityPointsLoss(pItem,1);
4016 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4018 uint32 TotalCost = 0;
4019 // equipped, backpack, bags itself
4020 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
4021 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4023 // bank, buyback and keys not repaired
4025 // items in inventory bags
4026 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
4027 for(int i = 0; i < MAX_BAG_SIZE; i++)
4028 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4029 return TotalCost;
4032 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4034 Item* item = GetItemByPos(pos);
4036 uint32 TotalCost = 0;
4037 if(!item)
4038 return TotalCost;
4040 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4041 if(!maxDurability)
4042 return TotalCost;
4044 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4046 if(cost)
4048 uint32 LostDurability = maxDurability - curDurability;
4049 if(LostDurability>0)
4051 ItemPrototype const *ditemProto = item->GetProto();
4053 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4054 if(!dcost)
4056 sLog.outError("ERROR: RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4057 return TotalCost;
4060 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4061 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4062 if(!dQualitymodEntry)
4064 sLog.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4065 return TotalCost;
4068 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4069 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4071 costs = uint32(costs * discountMod);
4073 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4074 costs = 1;
4076 if (guildBank)
4078 if (GetGuildId()==0)
4080 DEBUG_LOG("You are not member of a guild");
4081 return TotalCost;
4084 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4085 if (!pGuild)
4086 return TotalCost;
4088 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4090 DEBUG_LOG("You do not have rights to withdraw for repairs");
4091 return TotalCost;
4094 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4096 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4097 return TotalCost;
4100 if (pGuild->GetGuildBankMoney() < costs)
4102 DEBUG_LOG("There is not enough money in bank");
4103 return TotalCost;
4106 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4107 TotalCost = costs;
4109 else if (GetMoney() < costs)
4111 DEBUG_LOG("You do not have enough money");
4112 return TotalCost;
4114 else
4115 ModifyMoney( -int32(costs) );
4119 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4120 item->SetState(ITEM_CHANGED, this);
4122 // reapply mods for total broken and repaired item if equipped
4123 if(IsEquipmentPos(pos) && !curDurability)
4124 _ApplyItemMods(item,pos & 255, true);
4125 return TotalCost;
4128 void Player::RepopAtGraveyard()
4130 // note: this can be called also when the player is alive
4131 // for example from WorldSession::HandleMovementOpcodes
4133 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4135 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4136 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4138 ResurrectPlayer(0.5f);
4139 SpawnCorpseBones();
4142 WorldSafeLocsEntry const *ClosestGrave = NULL;
4144 // Special handle for battleground maps
4145 BattleGround *bg = sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
4147 if(bg && (bg->GetTypeID() == BATTLEGROUND_AB || bg->GetTypeID() == BATTLEGROUND_EY))
4148 ClosestGrave = bg->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4149 else
4150 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4152 // stop countdown until repop
4153 m_deathTimer = 0;
4155 // if no grave found, stay at the current location
4156 // and don't show spirit healer location
4157 if(ClosestGrave)
4159 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4160 if(isDead()) // not send if alive, because it used in TeleportTo()
4162 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4163 data << ClosestGrave->map_id;
4164 data << ClosestGrave->x;
4165 data << ClosestGrave->y;
4166 data << ClosestGrave->z;
4167 GetSession()->SendPacket(&data);
4172 void Player::JoinedChannel(Channel *c)
4174 m_channels.push_back(c);
4177 void Player::LeftChannel(Channel *c)
4179 m_channels.remove(c);
4182 void Player::CleanupChannels()
4184 while(!m_channels.empty())
4186 Channel* ch = *m_channels.begin();
4187 m_channels.erase(m_channels.begin()); // remove from player's channel list
4188 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4189 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4190 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4193 sLog.outDebug("Player: channels cleaned up!");
4196 void Player::UpdateLocalChannels(uint32 newZone )
4198 if(m_channels.empty())
4199 return;
4201 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4202 if(!current_zone)
4203 return;
4205 ChannelMgr* cMgr = channelMgr(GetTeam());
4206 if(!cMgr)
4207 return;
4209 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4211 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4213 next = i; ++next;
4215 // skip non built-in channels
4216 if(!(*i)->IsConstant())
4217 continue;
4219 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4220 if(!ch)
4221 continue;
4223 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4224 continue;
4226 // new channel
4227 char new_channel_name_buf[100];
4228 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4229 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4231 if((*i)!=new_channel)
4233 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4235 // leave old channel
4236 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4237 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4238 LeftChannel(*i); // remove from player's channel list
4239 cMgr->LeftChannel(name); // delete if empty
4242 sLog.outDebug("Player: channels cleaned up!");
4245 void Player::LeaveLFGChannel()
4247 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4249 if((*i)->IsLFG())
4251 (*i)->Leave(GetGUID());
4252 break;
4257 void Player::UpdateDefense()
4259 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4261 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4263 // update dependent from defense skill part
4264 UpdateDefenseBonusesMod();
4268 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4270 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4272 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4273 return;
4276 float val = 1.0f;
4278 switch(modType)
4280 case FLAT_MOD:
4281 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4282 break;
4283 case PCT_MOD:
4284 if(amount <= -100.0f)
4285 amount = -200.0f;
4287 val = (100.0f + amount) / 100.0f;
4288 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4289 break;
4292 if(!CanModifyStats())
4293 return;
4295 switch(modGroup)
4297 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4298 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4299 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4300 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4301 default: break;
4305 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4307 if(modGroup >= BASEMOD_END || modType > MOD_END)
4309 sLog.outError("ERROR: trial to access non existed BaseModGroup or wrong BaseModType!");
4310 return 0.0f;
4313 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4314 return 0.0f;
4316 return m_auraBaseMod[modGroup][modType];
4319 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4321 if(modGroup >= BASEMOD_END)
4323 sLog.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4324 return 0.0f;
4327 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4328 return 0.0f;
4330 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4333 uint32 Player::GetShieldBlockValue() const
4335 BaseModGroup modGroup = SHIELD_BLOCK_VALUE;
4337 float value = GetTotalBaseModValue(modGroup) + GetStat(STAT_STRENGTH) * 0.5f - 10;
4339 value = (value < 0) ? 0 : value;
4341 return uint32(value);
4344 float Player::GetMeleeCritFromAgility()
4346 uint32 level = getLevel();
4347 uint32 pclass = getClass();
4349 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4351 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4352 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4353 if (critBase==NULL || critRatio==NULL)
4354 return 0.0f;
4356 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4357 return crit*100.0f;
4360 float Player::GetDodgeFromAgility()
4362 // Table for base dodge values
4363 float dodge_base[MAX_CLASSES] = {
4364 0.0075f, // Warrior
4365 0.00652f, // Paladin
4366 -0.0545f, // Hunter
4367 -0.0059f, // Rogue
4368 0.03183f, // Priest
4369 0.0114f, // DK
4370 0.0167f, // Shaman
4371 0.034575f, // Mage
4372 0.02011f, // Warlock
4373 0.0f, // ??
4374 -0.0187f // Druid
4376 // Crit/agility to dodge/agility coefficient multipliers
4377 float crit_to_dodge[MAX_CLASSES] = {
4378 1.1f, // Warrior
4379 1.0f, // Paladin
4380 1.6f, // Hunter
4381 2.0f, // Rogue
4382 1.0f, // Priest
4383 1.0f, // DK?
4384 1.0f, // Shaman
4385 1.0f, // Mage
4386 1.0f, // Warlock
4387 0.0f, // ??
4388 1.7f // Druid
4391 uint32 level = getLevel();
4392 uint32 pclass = getClass();
4394 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4396 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4397 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4398 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4399 return 0.0f;
4401 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4402 return dodge*100.0f;
4405 float Player::GetSpellCritFromIntellect()
4407 uint32 level = getLevel();
4408 uint32 pclass = getClass();
4410 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4412 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4413 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4414 if (critBase==NULL || critRatio==NULL)
4415 return 0.0f;
4417 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4418 return crit*100.0f;
4421 float Player::GetRatingCoefficient(CombatRating cr) const
4423 uint32 level = getLevel();
4425 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4427 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4428 if (Rating == NULL)
4429 return 1.0f; // By default use minimum coefficient (not must be called)
4431 return Rating->ratio;
4434 float Player::GetRatingBonusValue(CombatRating cr) const
4436 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4439 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4441 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.0f;
4442 if (melee>25.0f) melee = 25.0f;
4443 return uint32 (melee * damage /100.0f);
4446 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4448 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.0f;
4449 if (ranged>25.0f) ranged=25.0f;
4450 return uint32 (ranged * damage /100.0f);
4453 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4455 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.0f;
4456 // In wow script resilience limited to 25%
4457 if (spell>25.0f)
4458 spell = 25.0f;
4459 return uint32 (spell * damage / 100.0f);
4462 uint32 Player::GetDotDamageReduction(uint32 damage) const
4464 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4465 // Dot resilience not limited (limit it by 100%)
4466 if (spellDot > 100.0f)
4467 spellDot = 100.0f;
4468 return uint32 (spellDot * damage / 100.0f);
4471 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4473 switch (attType)
4475 case BASE_ATTACK:
4476 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4477 case OFF_ATTACK:
4478 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4479 default:
4480 break;
4482 return 0.0f;
4485 float Player::OCTRegenHPPerSpirit()
4487 uint32 level = getLevel();
4488 uint32 pclass = getClass();
4490 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4492 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4493 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4494 if (baseRatio==NULL || moreRatio==NULL)
4495 return 0.0f;
4497 // Formula from PaperDollFrame script
4498 float spirit = GetStat(STAT_SPIRIT);
4499 float baseSpirit = spirit;
4500 if (baseSpirit>50) baseSpirit = 50;
4501 float moreSpirit = spirit - baseSpirit;
4502 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4503 return regen;
4506 float Player::OCTRegenMPPerSpirit()
4508 uint32 level = getLevel();
4509 uint32 pclass = getClass();
4511 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4513 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4514 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4515 if (moreRatio==NULL)
4516 return 0.0f;
4518 // Formula get from PaperDollFrame script
4519 float spirit = GetStat(STAT_SPIRIT);
4520 float regen = spirit * moreRatio->ratio;
4521 return regen;
4524 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4526 m_baseRatingValue[cr]+=(apply ? value : -value);
4528 int32 amount = uint32(m_baseRatingValue[cr]);
4529 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4530 // stat used stored in miscValueB for this aura
4531 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4532 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4533 if ((*i)->GetMiscValue() & (1<<cr))
4534 amount += GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f;
4535 if (amount < 0)
4536 amount = 0;
4537 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4539 float RatingCoeffecient = GetRatingCoefficient(cr);
4540 float RatingChange = 0.0f;
4542 bool affectStats = CanModifyStats();
4544 switch (cr)
4546 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4547 case CR_DEFENSE_SKILL:
4548 UpdateDefenseBonusesMod();
4549 break;
4550 case CR_DODGE:
4551 UpdateDodgePercentage();
4552 break;
4553 case CR_PARRY:
4554 UpdateParryPercentage();
4555 break;
4556 case CR_BLOCK:
4557 UpdateBlockPercentage();
4558 break;
4559 case CR_HIT_MELEE:
4560 UpdateMeleeHitChances();
4561 break;
4562 case CR_HIT_RANGED:
4563 UpdateRangedHitChances();
4564 break;
4565 case CR_HIT_SPELL:
4566 UpdateSpellHitChances();
4567 break;
4568 case CR_CRIT_MELEE:
4569 if(affectStats)
4571 UpdateCritPercentage(BASE_ATTACK);
4572 UpdateCritPercentage(OFF_ATTACK);
4574 break;
4575 case CR_CRIT_RANGED:
4576 if(affectStats)
4577 UpdateCritPercentage(RANGED_ATTACK);
4578 break;
4579 case CR_CRIT_SPELL:
4580 if(affectStats)
4581 UpdateAllSpellCritChances();
4582 break;
4583 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4584 case CR_HIT_TAKEN_RANGED:
4585 break;
4586 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4587 break;
4588 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4589 case CR_CRIT_TAKEN_RANGED:
4590 break;
4591 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4592 break;
4593 case CR_HASTE_MELEE:
4594 RatingChange = value / RatingCoeffecient;
4595 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4596 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4597 break;
4598 case CR_HASTE_RANGED:
4599 RatingChange = value / RatingCoeffecient;
4600 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4601 break;
4602 case CR_HASTE_SPELL:
4603 RatingChange = value / RatingCoeffecient;
4604 ApplyCastTimePercentMod(RatingChange,apply);
4605 break;
4606 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4607 case CR_WEAPON_SKILL_OFFHAND:
4608 case CR_WEAPON_SKILL_RANGED:
4609 break;
4610 case CR_EXPERTISE:
4611 if(affectStats)
4613 UpdateExpertise(BASE_ATTACK);
4614 UpdateExpertise(OFF_ATTACK);
4616 break;
4620 void Player::SetRegularAttackTime()
4622 for(int i = 0; i < MAX_ATTACK; ++i)
4624 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4625 if(tmpitem && !tmpitem->IsBroken())
4627 ItemPrototype const *proto = tmpitem->GetProto();
4628 if(proto->Delay)
4629 SetAttackTime(WeaponAttackType(i), proto->Delay);
4630 else
4631 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4636 //skill+step, checking for max value
4637 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4639 if(!skill_id)
4640 return false;
4642 uint16 i=0;
4643 for (; i < PLAYER_MAX_SKILLS; i++)
4644 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4645 break;
4647 if(i>=PLAYER_MAX_SKILLS)
4648 return false;
4650 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4651 uint32 value = SKILL_VALUE(data);
4652 uint32 max = SKILL_MAX(data);
4654 if ((!max) || (!value) || (value >= max))
4655 return false;
4657 if (value*512 < max*urand(0,512))
4659 uint32 new_value = value+step;
4660 if(new_value > max)
4661 new_value = max;
4663 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4664 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4665 return true;
4668 return false;
4671 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4673 if ( SkillValue >= GrayLevel )
4674 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4675 if ( SkillValue >= GreenLevel )
4676 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4677 if ( SkillValue >= YellowLevel )
4678 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4679 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4682 bool Player::UpdateCraftSkill(uint32 spellid)
4684 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4686 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4687 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4689 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4691 if(_spell_idx->second->skillId)
4693 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4695 // Alchemy Discoveries here
4696 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4697 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4699 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4700 learnSpell(discoveredSpell);
4703 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4705 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4706 _spell_idx->second->max_value,
4707 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4708 _spell_idx->second->min_value),
4709 craft_skill_gain);
4712 return false;
4715 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4717 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4719 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4721 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4722 switch (SkillId)
4724 case SKILL_HERBALISM:
4725 case SKILL_LOCKPICKING:
4726 case SKILL_JEWELCRAFTING:
4727 case SKILL_INSCRIPTION:
4728 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4729 case SKILL_SKINNING:
4730 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4731 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4732 else
4733 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4734 case SKILL_MINING:
4735 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4736 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4737 else
4738 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4740 return false;
4743 bool Player::UpdateFishingSkill()
4745 sLog.outDebug("UpdateFishingSkill");
4747 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4749 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4751 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4753 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4756 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4758 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4759 if ( !SkillId )
4760 return false;
4762 if(Chance <= 0) // speedup in 0 chance case
4764 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4765 return false;
4768 uint16 i=0;
4769 for (; i < PLAYER_MAX_SKILLS; i++)
4770 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4771 if ( i >= PLAYER_MAX_SKILLS )
4772 return false;
4774 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4775 uint16 SkillValue = SKILL_VALUE(data);
4776 uint16 MaxValue = SKILL_MAX(data);
4778 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4779 return false;
4781 int32 Roll = irand(1,1000);
4783 if ( Roll <= Chance )
4785 uint32 new_value = SkillValue+step;
4786 if(new_value > MaxValue)
4787 new_value = MaxValue;
4789 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
4790 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4791 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
4792 return true;
4795 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4796 return false;
4799 void Player::UpdateWeaponSkill (WeaponAttackType attType)
4801 // no skill gain in pvp
4802 Unit *pVictim = getVictim();
4803 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
4804 return;
4806 if(IsInFeralForm())
4807 return; // always maximized SKILL_FERAL_COMBAT in fact
4809 if(m_form == FORM_TREE)
4810 return; // use weapon but not skill up
4812 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
4814 switch(attType)
4816 case BASE_ATTACK:
4818 Item *tmpitem = GetWeaponForAttack(attType,true);
4820 if (!tmpitem)
4821 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
4822 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
4823 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4824 break;
4826 case OFF_ATTACK:
4827 case RANGED_ATTACK:
4829 Item *tmpitem = GetWeaponForAttack(attType,true);
4830 if (tmpitem)
4831 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4832 break;
4835 UpdateAllCritPercentages();
4838 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, MeleeHitOutcome outcome, bool defence)
4840 /* Not need, this checked on call this func from trigger system
4841 switch(outcome)
4843 case MELEE_HIT_CRIT:
4844 case MELEE_HIT_DODGE:
4845 case MELEE_HIT_PARRY:
4846 case MELEE_HIT_BLOCK:
4847 case MELEE_HIT_BLOCK_CRIT:
4848 return;
4850 default:
4851 break;
4854 uint32 plevel = getLevel(); // if defense than pVictim == attacker
4855 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
4856 uint32 moblevel = pVictim->getLevelForTarget(this);
4857 if(moblevel < greylevel)
4858 return;
4860 if (moblevel > plevel + 5)
4861 moblevel = plevel + 5;
4863 uint32 lvldif = moblevel - greylevel;
4864 if(lvldif < 3)
4865 lvldif = 3;
4867 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
4868 if(skilldif <= 0)
4869 return;
4871 float chance = float(3 * lvldif * skilldif) / plevel;
4872 if(!defence)
4874 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
4875 chance *= 0.1f * GetStat(STAT_INTELLECT);
4878 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
4880 if(roll_chance_f(chance))
4882 if(defence)
4883 UpdateDefense();
4884 else
4885 UpdateWeaponSkill(attType);
4887 else
4888 return;
4891 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
4893 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4894 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
4896 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4897 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
4898 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
4900 if(talent) // permanent bonus stored in high part
4901 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
4902 else // temporary/item bonus stored in low part
4903 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
4904 return;
4908 void Player::UpdateSkillsForLevel()
4910 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
4911 uint32 maxSkill = GetMaxSkillValueForLevel();
4913 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
4915 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4916 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4918 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4920 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
4921 if(!pSkill)
4922 continue;
4924 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
4925 continue;
4927 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4928 uint32 max = SKILL_MAX(data);
4929 uint32 val = SKILL_VALUE(data);
4931 /// update only level dependent max skill values
4932 if(max!=1)
4934 /// miximize skill always
4935 if(alwaysMaxSkill)
4936 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
4937 /// update max skill value if current max skill not maximized
4938 else if(max != maxconfskill)
4939 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
4944 void Player::UpdateSkillsToMaxSkillsForLevel()
4946 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4947 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4949 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4950 if( IsProfessionSkill(pskill) || pskill == SKILL_RIDING )
4951 continue;
4952 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4954 uint32 max = SKILL_MAX(data);
4956 if(max > 1)
4957 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
4959 if(pskill == SKILL_DEFENSE)
4960 UpdateDefenseBonusesMod();
4964 // This functions sets a skill line value (and adds if doesn't exist yet)
4965 // To "remove" a skill line, set it's values to zero
4966 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
4968 if(!id)
4969 return;
4971 uint16 i=0;
4972 for (; i < PLAYER_MAX_SKILLS; i++)
4973 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
4975 if(i<PLAYER_MAX_SKILLS) //has skill
4977 if(currVal)
4979 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
4980 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4982 else //remove
4984 // clear skill fields
4985 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
4986 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
4987 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
4989 // remove spells that depend on this skill when removing the skill
4990 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
4992 ++next;
4993 if(itr->second->state == PLAYERSPELL_REMOVED)
4994 continue;
4996 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(itr->first);
4997 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(itr->first);
4999 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
5001 if (_spell_idx->second->skillId == id)
5003 // this may remove more than one spell (dependents)
5004 removeSpell(itr->first);
5005 next = m_spells.begin();
5006 break;
5012 else if(currVal) //add
5014 for (i=0; i < PLAYER_MAX_SKILLS; i++)
5015 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5017 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5018 if(!pSkill)
5020 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5021 return;
5023 // enable unlearn button for primary professions only
5024 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5025 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5026 else
5027 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5028 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5029 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
5031 // apply skill bonuses
5032 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5034 // temporary bonuses
5035 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5036 for(AuraList::const_iterator i = mModSkill.begin(); i != mModSkill.end(); ++i)
5037 if ((*i)->GetModifier()->m_miscvalue == int32(id))
5038 (*i)->ApplyModifier(true);
5040 // permanent bonuses
5041 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5042 for(AuraList::const_iterator i = mModSkillTalent.begin(); i != mModSkillTalent.end(); ++i)
5043 if ((*i)->GetModifier()->m_miscvalue == int32(id))
5044 (*i)->ApplyModifier(true);
5046 // Learn all spells for skill
5047 learnSkillRewardedSpells(id);
5048 return;
5053 bool Player::HasSkill(uint32 skill) const
5055 if(!skill)return false;
5056 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5058 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5060 return true;
5063 return false;
5066 uint16 Player::GetSkillValue(uint32 skill) const
5068 if(!skill)
5069 return 0;
5071 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5073 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5075 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5077 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5078 result += SKILL_TEMP_BONUS(bonus);
5079 result += SKILL_PERM_BONUS(bonus);
5080 return result < 0 ? 0 : result;
5083 return 0;
5086 uint16 Player::GetMaxSkillValue(uint32 skill) const
5088 if(!skill)return 0;
5089 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5091 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5093 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5095 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5096 result += SKILL_TEMP_BONUS(bonus);
5097 result += SKILL_PERM_BONUS(bonus);
5098 return result < 0 ? 0 : result;
5101 return 0;
5104 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5106 if(!skill)return 0;
5107 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5109 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5111 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5114 return 0;
5117 uint16 Player::GetBaseSkillValue(uint32 skill) const
5119 if(!skill)return 0;
5120 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5122 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5124 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5125 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5126 return result < 0 ? 0 : result;
5129 return 0;
5132 uint16 Player::GetPureSkillValue(uint32 skill) const
5134 if(!skill)return 0;
5135 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5137 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5139 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5142 return 0;
5145 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5147 if(!skill)
5148 return 0;
5150 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5152 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5154 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5158 return 0;
5161 void Player::SendInitialActionButtons()
5163 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5165 WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
5166 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5168 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5169 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5171 data << uint16(itr->second.action);
5172 data << uint8(itr->second.misc);
5173 data << uint8(itr->second.type);
5175 else
5177 data << uint32(0);
5181 GetSession()->SendPacket( &data );
5182 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5185 void Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5187 if(button >= MAX_ACTION_BUTTONS)
5189 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5190 return;
5193 // check cheating with adding non-known spells to action bar
5194 if(type==ACTION_BUTTON_SPELL)
5196 if(!sSpellStore.LookupEntry(action))
5198 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5199 return;
5202 if(!HasSpell(action))
5204 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5205 return;
5209 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5211 if (buttonItr==m_actionButtons.end())
5212 { // just add new button
5213 m_actionButtons[button] = ActionButton(action,type,misc);
5215 else
5216 { // change state of current button
5217 ActionButtonUpdateState uState = buttonItr->second.uState;
5218 buttonItr->second = ActionButton(action,type,misc);
5219 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5222 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5225 void Player::removeActionButton(uint8 button)
5227 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5228 if (buttonItr==m_actionButtons.end())
5229 return;
5231 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5232 m_actionButtons.erase(buttonItr); // new and not saved
5233 else
5234 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5236 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5239 void Player::SetDontMove(bool dontMove)
5241 m_dontMove = dontMove;
5244 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5246 // prevent crash when a bad coord is sent by the client
5247 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5249 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5250 return false;
5253 Map *m = GetMap();
5255 const float old_x = GetPositionX();
5256 const float old_y = GetPositionY();
5257 const float old_z = GetPositionZ();
5258 const float old_r = GetOrientation();
5260 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5262 if (teleport || old_x != x || old_y != y || old_z != z)
5263 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5264 else
5265 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5267 // move and update visible state if need
5268 m->PlayerRelocation(this, x, y, z, orientation);
5270 // reread after Map::Relocation
5271 m = GetMap();
5272 x = GetPositionX();
5273 y = GetPositionY();
5274 z = GetPositionZ();
5276 // group update
5277 if(GetGroup() && (old_x != x || old_y != y))
5278 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5281 // code block for underwater state update
5282 UpdateUnderwaterState(m, x, y, z);
5284 CheckExploreSystem();
5286 return true;
5289 void Player::SaveRecallPosition()
5291 m_recallMap = GetMapId();
5292 m_recallX = GetPositionX();
5293 m_recallY = GetPositionY();
5294 m_recallZ = GetPositionZ();
5295 m_recallO = GetOrientation();
5298 void Player::SendMessageToSet(WorldPacket *data, bool self)
5300 GetMap()->MessageBroadcast(this, data, self);
5303 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5305 GetMap()->MessageDistBroadcast(this, data, dist, self);
5308 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5310 GetMap()->MessageDistBroadcast(this, data, dist, self,own_team_only);
5313 void Player::SendDirectMessage(WorldPacket *data)
5315 GetSession()->SendPacket(data);
5318 void Player::CheckExploreSystem()
5320 if (!isAlive())
5321 return;
5323 if (isInFlight())
5324 return;
5326 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5327 if(areaFlag==0xffff)
5328 return;
5329 int offset = areaFlag / 32;
5331 if(offset >= 128)
5333 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);
5334 return;
5337 uint32 val = (uint32)(1 << (areaFlag % 32));
5338 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5340 if( !(currFields & val) )
5342 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5344 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5346 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5347 if(!p)
5349 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5351 else if(p->area_level > 0)
5353 uint32 area = p->ID;
5354 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5356 SendExplorationExperience(area,0);
5358 else
5360 int32 diff = int32(getLevel()) - p->area_level;
5361 uint32 XP = 0;
5362 if (diff < -5)
5364 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5366 else if (diff > 5)
5368 int32 exploration_percent = (100-((diff-5)*5));
5369 if (exploration_percent > 100)
5370 exploration_percent = 100;
5371 else if (exploration_percent < 0)
5372 exploration_percent = 0;
5374 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5376 else
5378 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5381 GiveXP( XP, NULL );
5382 SendExplorationExperience(area,XP);
5384 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5389 uint32 Player::TeamForRace(uint8 race)
5391 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5392 if(!rEntry)
5394 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5395 return ALLIANCE;
5398 switch(rEntry->TeamID)
5400 case 7: return ALLIANCE;
5401 case 1: return HORDE;
5404 sLog.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5405 return ALLIANCE;
5408 uint32 Player::getFactionForRace(uint8 race)
5410 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5411 if(!rEntry)
5413 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5414 return 0;
5417 return rEntry->FactionID;
5420 void Player::setFactionForRace(uint8 race)
5422 m_team = TeamForRace(race);
5423 setFaction( getFactionForRace(race) );
5426 void Player::UpdateReputation() const
5428 sLog.outDetail( "WORLD: Player::UpdateReputation" );
5430 for(FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5432 SendFactionState(&(itr->second));
5436 void Player::SendFactionState(FactionState const* faction) const
5438 if(faction->Flags & FACTION_FLAG_VISIBLE) //If faction is visible then update it
5440 WorldPacket data(SMSG_SET_FACTION_STANDING, (16)); // last check 2.4.0
5441 data << (float) 0; // unk 2.4.0
5442 data << (uint8) 0; // wotlk 8634
5443 data << (uint32) 1; // count
5444 // for
5445 data << (uint32) faction->ReputationListID;
5446 data << (uint32) faction->Standing;
5447 // end for
5448 GetSession()->SendPacket(&data);
5452 void Player::SendInitialReputations()
5454 WorldPacket data(SMSG_INITIALIZE_FACTIONS, (4+128*5));
5455 data << uint32 (0x00000080);
5457 RepListID a = 0;
5459 for (FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5461 // fill in absent fields
5462 for (; a != itr->first; a++)
5464 data << uint8 (0x00);
5465 data << uint32 (0x00000000);
5468 // fill in encountered data
5469 data << uint8 (itr->second.Flags);
5470 data << uint32 (itr->second.Standing);
5472 ++a;
5475 // fill in absent fields
5476 for (; a != 128; a++)
5478 data << uint8 (0x00);
5479 data << uint32 (0x00000000);
5482 GetSession()->SendPacket(&data);
5485 FactionState const* Player::GetFactionState( FactionEntry const* factionEntry) const
5487 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5488 if (itr != m_factions.end())
5489 return &itr->second;
5491 return NULL;
5494 void Player::SetFactionAtWar(FactionState* faction, bool atWar)
5496 // not allow declare war to own faction
5497 if(atWar && (faction->Flags & FACTION_FLAG_PEACE_FORCED) )
5498 return;
5500 // already set
5501 if(((faction->Flags & FACTION_FLAG_AT_WAR) != 0) == atWar)
5502 return;
5504 if( atWar )
5505 faction->Flags |= FACTION_FLAG_AT_WAR;
5506 else
5507 faction->Flags &= ~FACTION_FLAG_AT_WAR;
5509 faction->Changed = true;
5512 void Player::SetFactionInactive(FactionState* faction, bool inactive)
5514 // always invisible or hidden faction can't be inactive
5515 if(inactive && ((faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN)) || !(faction->Flags & FACTION_FLAG_VISIBLE) ) )
5516 return;
5518 // already set
5519 if(((faction->Flags & FACTION_FLAG_INACTIVE) != 0) == inactive)
5520 return;
5522 if(inactive)
5523 faction->Flags |= FACTION_FLAG_INACTIVE;
5524 else
5525 faction->Flags &= ~FACTION_FLAG_INACTIVE;
5527 faction->Changed = true;
5530 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId)
5532 FactionTemplateEntry const*factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5534 if(!factionTemplateEntry)
5535 return;
5537 SetFactionVisibleForFactionId(factionTemplateEntry->faction);
5540 void Player::SetFactionVisibleForFactionId(uint32 FactionId)
5542 FactionEntry const *factionEntry = sFactionStore.LookupEntry(FactionId);
5543 if(!factionEntry)
5544 return;
5546 if(factionEntry->reputationListID < 0)
5547 return;
5549 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5550 if (itr == m_factions.end())
5551 return;
5553 SetFactionVisible(&itr->second);
5556 void Player::SetFactionVisible(FactionState* faction)
5558 // always invisible or hidden faction can't be make visible
5559 if(faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN))
5560 return;
5562 // already set
5563 if(faction->Flags & FACTION_FLAG_VISIBLE)
5564 return;
5566 faction->Flags |= FACTION_FLAG_VISIBLE;
5567 faction->Changed = true;
5569 if(!m_session->PlayerLoading())
5571 // make faction visible in reputation list at client
5572 WorldPacket data(SMSG_SET_FACTION_VISIBLE, 4);
5573 data << faction->ReputationListID;
5574 GetSession()->SendPacket(&data);
5578 void Player::SetInitialFactions()
5580 for(unsigned int i = 1; i < sFactionStore.GetNumRows(); i++)
5582 FactionEntry const *factionEntry = sFactionStore.LookupEntry(i);
5584 if( factionEntry && (factionEntry->reputationListID >= 0))
5586 FactionState newFaction;
5587 newFaction.ID = factionEntry->ID;
5588 newFaction.ReputationListID = factionEntry->reputationListID;
5589 newFaction.Standing = 0;
5590 newFaction.Flags = GetDefaultReputationFlags(factionEntry);
5591 newFaction.Changed = true;
5593 m_factions[newFaction.ReputationListID] = newFaction;
5598 uint32 Player::GetDefaultReputationFlags(const FactionEntry *factionEntry) const
5600 if (!factionEntry)
5601 return 0;
5603 uint32 raceMask = getRaceMask();
5604 uint32 classMask = getClassMask();
5605 for (int i=0; i < 4; i++)
5607 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5608 (factionEntry->BaseRepClassMask[i]==0 ||
5609 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5610 return factionEntry->ReputationFlags[i];
5612 return 0;
5615 int32 Player::GetBaseReputation(const FactionEntry *factionEntry) const
5617 if (!factionEntry)
5618 return 0;
5620 uint32 raceMask = getRaceMask();
5621 uint32 classMask = getClassMask();
5622 for (int i=0; i < 4; i++)
5624 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5625 (factionEntry->BaseRepClassMask[i]==0 ||
5626 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5627 return factionEntry->BaseRepValue[i];
5630 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5631 return 0;
5634 int32 Player::GetReputation(uint32 faction_id) const
5636 FactionEntry const *factionEntry = sFactionStore.LookupEntry(faction_id);
5638 if (!factionEntry)
5640 sLog.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id);
5641 return 0;
5644 return GetReputation(factionEntry);
5647 int32 Player::GetReputation(const FactionEntry *factionEntry) const
5649 // Faction without recorded reputation. Just ignore.
5650 if(!factionEntry)
5651 return 0;
5653 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5654 if (itr != m_factions.end())
5655 return GetBaseReputation(factionEntry) + itr->second.Standing;
5657 return 0;
5660 ReputationRank Player::GetReputationRank(uint32 faction) const
5662 FactionEntry const*factionEntry = sFactionStore.LookupEntry(faction);
5663 if(!factionEntry)
5664 return MIN_REPUTATION_RANK;
5666 return GetReputationRank(factionEntry);
5669 ReputationRank Player::ReputationToRank(int32 standing) const
5671 int32 Limit = Reputation_Cap + 1;
5672 for (int i = MAX_REPUTATION_RANK-1; i >= MIN_REPUTATION_RANK; --i)
5674 Limit -= ReputationRank_Length[i];
5675 if (standing >= Limit )
5676 return ReputationRank(i);
5678 return MIN_REPUTATION_RANK;
5681 ReputationRank Player::GetReputationRank(const FactionEntry *factionEntry) const
5683 int32 Reputation = GetReputation(factionEntry);
5684 return ReputationToRank(Reputation);
5687 ReputationRank Player::GetBaseReputationRank(const FactionEntry *factionEntry) const
5689 int32 Reputation = GetBaseReputation(factionEntry);
5690 return ReputationToRank(Reputation);
5693 bool Player::ModifyFactionReputation(uint32 FactionTemplateId, int32 DeltaReputation)
5695 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5697 if(!factionTemplateEntry)
5699 sLog.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5700 return false;
5703 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5705 // Faction without recorded reputation. Just ignore.
5706 if(!factionEntry)
5707 return false;
5709 return ModifyFactionReputation(factionEntry, DeltaReputation);
5712 bool Player::ModifyFactionReputation(FactionEntry const* factionEntry, int32 standing)
5714 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5715 if (flist)
5717 bool res = false;
5718 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5720 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5721 if(factionEntryCalc)
5722 res = ModifyOneFactionReputation(factionEntryCalc, standing);
5724 return res;
5726 else
5727 return ModifyOneFactionReputation(factionEntry, standing);
5730 bool Player::ModifyOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5732 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5733 if (itr != m_factions.end())
5735 int32 BaseRep = GetBaseReputation(factionEntry);
5736 int32 new_rep = BaseRep + itr->second.Standing + standing;
5738 if (new_rep > Reputation_Cap)
5739 new_rep = Reputation_Cap;
5740 else
5741 if (new_rep < Reputation_Bottom)
5742 new_rep = Reputation_Bottom;
5744 if(ReputationToRank(new_rep) <= REP_HOSTILE)
5745 SetFactionAtWar(&itr->second,true);
5747 itr->second.Standing = new_rep - BaseRep;
5748 itr->second.Changed = true;
5750 SetFactionVisible(&itr->second);
5752 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
5754 if(uint32 questid = GetQuestSlotQuestId(i))
5756 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
5757 if( qInfo && qInfo->GetRepObjectiveFaction() == factionEntry->ID )
5759 QuestStatusData& q_status = mQuestStatus[questid];
5760 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
5762 if(GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
5763 if ( CanCompleteQuest( questid ) )
5764 CompleteQuest( questid );
5766 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
5768 if(GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
5769 IncompleteQuest( questid );
5774 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION);
5775 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION);
5776 SendFactionState(&(itr->second));
5778 return true;
5780 return false;
5783 bool Player::SetFactionReputation(uint32 FactionTemplateId, int32 standing)
5785 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5787 if(!factionTemplateEntry)
5789 sLog.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5790 return false;
5793 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5795 // Faction without recorded reputation. Just ignore.
5796 if(!factionEntry)
5797 return false;
5799 return SetFactionReputation(factionEntry, standing);
5802 bool Player::SetFactionReputation(FactionEntry const* factionEntry, int32 standing)
5804 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5805 if (flist)
5807 bool res = false;
5808 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5810 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5811 if(factionEntryCalc)
5812 res = SetOneFactionReputation(factionEntryCalc, standing);
5814 return res;
5816 else
5817 return SetOneFactionReputation(factionEntry, standing);
5820 bool Player::SetOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5822 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5823 if (itr != m_factions.end())
5825 if (standing > Reputation_Cap)
5826 standing = Reputation_Cap;
5827 else
5828 if (standing < Reputation_Bottom)
5829 standing = Reputation_Bottom;
5831 int32 BaseRep = GetBaseReputation(factionEntry);
5832 itr->second.Standing = standing - BaseRep;
5833 itr->second.Changed = true;
5835 SetFactionVisible(&itr->second);
5837 if(ReputationToRank(standing) <= REP_HOSTILE)
5838 SetFactionAtWar(&itr->second,true);
5840 SendFactionState(&(itr->second));
5841 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION);
5842 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION);
5843 return true;
5845 return false;
5848 //Calculate total reputation percent player gain with quest/creature level
5849 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5851 // for grey creature kill received 20%, in other case 100.
5852 int32 percent = (!for_quest && (creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5854 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5856 percent += rep > 0 ? repMod : -repMod;
5858 if(percent <=0)
5859 return 0;
5861 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5864 //Calculates how many reputation points player gains in victim's enemy factions
5865 void Player::RewardReputation(Unit *pVictim, float rate)
5867 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5868 return;
5870 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5872 if(!Rep)
5873 return;
5875 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5877 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
5878 donerep1 = int32(donerep1*rate);
5879 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5880 uint32 current_reputation_rank1 = GetReputationRank(factionEntry1);
5881 if(factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5882 ModifyFactionReputation(factionEntry1, donerep1);
5884 // Wiki: Team factions value divided by 2
5885 if(Rep->is_teamaward1)
5887 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5888 if(team1_factionEntry)
5889 ModifyFactionReputation(team1_factionEntry, donerep1 / 2);
5893 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5895 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
5896 donerep2 = int32(donerep2*rate);
5897 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5898 uint32 current_reputation_rank2 = GetReputationRank(factionEntry2);
5899 if(factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5900 ModifyFactionReputation(factionEntry2, donerep2);
5902 // Wiki: Team factions value divided by 2
5903 if(Rep->is_teamaward2)
5905 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5906 if(team2_factionEntry)
5907 ModifyFactionReputation(team2_factionEntry, donerep2 / 2);
5912 //Calculate how many reputation points player gain with the quest
5913 void Player::RewardReputation(Quest const *pQuest)
5915 // quest reputation reward/loss
5916 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5918 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5920 int32 rep = CalculateReputationGain(pQuest->GetQuestLevel(),pQuest->RewRepValue[i],true);
5921 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5922 if(factionEntry)
5923 ModifyFactionReputation(factionEntry, rep);
5927 // TODO: implement reputation spillover
5930 void Player::UpdateArenaFields(void)
5932 /* arena calcs go here */
5935 void Player::UpdateHonorFields()
5937 /// called when rewarding honor and at each save
5938 uint64 now = time(NULL);
5939 uint64 today = uint64(time(NULL) / DAY) * DAY;
5941 if(m_lastHonorUpdateTime < today)
5943 uint64 yesterday = today - DAY;
5945 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5947 // update yesterday's contribution
5948 if(m_lastHonorUpdateTime >= yesterday )
5950 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5952 // this is the first update today, reset today's contribution
5953 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5954 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5956 else
5958 // no honor/kills yesterday or today, reset
5959 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5960 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5964 m_lastHonorUpdateTime = now;
5967 ///Calculate the amount of honor gained based on the victim
5968 ///and the size of the group for which the honor is divided
5969 ///An exact honor value can also be given (overriding the calcs)
5970 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5972 // do not reward honor in arenas, but enable onkill spellproc
5973 if(InArena())
5975 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
5976 return false;
5978 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
5979 return false;
5981 return true;
5984 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5985 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5986 return false;
5988 uint64 victim_guid = 0;
5989 uint32 victim_rank = 0;
5991 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5992 UpdateHonorFields();
5994 if(honor <= 0)
5996 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5997 return false;
5999 victim_guid = uVictim->GetGUID();
6001 if( uVictim->GetTypeId() == TYPEID_PLAYER )
6003 Player *pVictim = (Player *)uVictim;
6005 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
6006 return false;
6008 float f = 1; //need for total kills (?? need more info)
6009 uint32 k_grey = 0;
6010 uint32 k_level = getLevel();
6011 uint32 v_level = pVictim->getLevel();
6014 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6015 // [0] Just name
6016 // [1..14] Alliance honor titles and player name
6017 // [15..28] Horde honor titles and player name
6018 // [29..38] Other title and player name
6019 // [39+] Nothing
6020 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
6021 // Get Killer titles, CharTitlesEntry::bit_index
6022 // Ranks:
6023 // title[1..14] -> rank[5..18]
6024 // title[15..28] -> rank[5..18]
6025 // title[other] -> 0
6026 if (victim_title == 0)
6027 victim_guid = 0; // Don't show HK: <rank> message, only log.
6028 else if (victim_title < 15)
6029 victim_rank = victim_title + 4;
6030 else if (victim_title < 29)
6031 victim_rank = victim_title - 14 + 4;
6032 else
6033 victim_guid = 0; // Don't show HK: <rank> message, only log.
6036 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
6038 if(v_level<=k_grey)
6039 return false;
6041 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
6043 int32 v_rank =1; //need more info
6045 honor = ((f * diff_level * (190 + v_rank*10))/6);
6046 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
6048 // count the number of playerkills in one day
6049 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
6050 // and those in a lifetime
6051 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
6053 else
6055 Creature *cVictim = (Creature *)uVictim;
6057 if (!cVictim->isRacialLeader())
6058 return false;
6060 honor = 100; // ??? need more info
6061 victim_rank = 19; // HK: Leader
6065 if (uVictim != NULL)
6067 honor *= sWorld.getRate(RATE_HONOR);
6069 if(groupsize > 1)
6070 honor /= groupsize;
6072 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6075 // honor - for show honor points in log
6076 // victim_guid - for show victim name in log
6077 // victim_rank [1..4] HK: <dishonored rank>
6078 // victim_rank [5..19] HK: <alliance\horde rank>
6079 // victim_rank [0,20+] HK: <>
6080 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
6081 data << (uint32) honor;
6082 data << (uint64) victim_guid;
6083 data << (uint32) victim_rank;
6085 GetSession()->SendPacket(&data);
6087 // add honor points
6088 ModifyHonorPoints(int32(honor));
6090 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
6091 return true;
6094 void Player::ModifyHonorPoints( int32 value )
6096 if(value < 0)
6098 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
6099 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
6100 else
6101 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6103 else
6104 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6107 void Player::ModifyArenaPoints( int32 value )
6109 if(value < 0)
6111 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6112 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6113 else
6114 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6116 else
6117 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6120 uint32 Player::GetGuildIdFromDB(uint64 guid)
6122 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
6123 if(!result)
6124 return 0;
6126 uint32 id = result->Fetch()[0].GetUInt32();
6127 delete result;
6128 return id;
6131 uint32 Player::GetRankFromDB(uint64 guid)
6133 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6134 if( result )
6136 uint32 v = result->Fetch()[0].GetUInt32();
6137 delete result;
6138 return v;
6140 else
6141 return 0;
6144 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6146 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);
6147 if(!result)
6148 return 0;
6150 uint32 id = (*result)[0].GetUInt32();
6151 delete result;
6152 return id;
6155 uint32 Player::GetZoneIdFromDB(uint64 guid)
6157 uint32 guidLow = GUID_LOPART(guid);
6158 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6159 if (!result)
6160 return 0;
6161 Field* fields = result->Fetch();
6162 uint32 zone = fields[0].GetUInt32();
6163 delete result;
6165 if (!zone)
6167 // stored zone is zero, use generic and slow zone detection
6168 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6169 if( !result )
6170 return 0;
6171 fields = result->Fetch();
6172 uint32 map = fields[0].GetUInt32();
6173 float posx = fields[1].GetFloat();
6174 float posy = fields[2].GetFloat();
6175 float posz = fields[3].GetFloat();
6176 delete result;
6178 zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
6180 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6183 return zone;
6186 void Player::UpdateArea(uint32 newArea)
6188 // FFA_PVP flags are area and not zone id dependent
6189 // so apply them accordingly
6190 m_areaUpdateId = newArea;
6192 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6194 if(area && (area->flags & AREA_FLAG_ARENA))
6196 if(!isGameMaster())
6197 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6199 else
6201 // remove ffa flag only if not ffapvp realm
6202 // removal in sanctuaries and capitals is handled in zone update
6203 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6204 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6207 UpdateAreaDependentAuras(newArea);
6210 void Player::UpdateZone(uint32 newZone)
6212 m_zoneUpdateId = newZone;
6213 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6215 // zone changed, so area changed as well, update it
6216 UpdateArea(GetAreaId());
6218 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6219 if(!zone)
6220 return;
6222 if (sWorld.getConfig(CONFIG_WEATHER))
6224 Weather *wth = sWorld.FindWeather(zone->ID);
6225 if(wth)
6227 wth->SendWeatherUpdateToPlayer(this);
6229 else
6231 if(!sWorld.AddWeather(zone->ID))
6233 // send fine weather packet to remove old zone's weather
6234 Weather::SendFineWeatherUpdateToPlayer(this);
6239 pvpInfo.inHostileArea =
6240 GetTeam() == ALLIANCE && zone->team == AREATEAM_HORDE ||
6241 GetTeam() == HORDE && zone->team == AREATEAM_ALLY ||
6242 sWorld.IsPvPRealm() && zone->team == AREATEAM_NONE ||
6243 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6245 if(pvpInfo.inHostileArea) // in hostile area
6247 if(!IsPvP() || pvpInfo.endTimer != 0)
6248 UpdatePvP(true, true);
6250 else // in friendly area
6252 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6253 pvpInfo.endTimer = time(0); // start toggle-off
6256 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6258 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6259 if(sWorld.IsFFAPvPRealm())
6260 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6262 else
6264 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6267 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6269 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6270 SetRestType(REST_TYPE_IN_CITY);
6271 InnEnter(time(0),GetMapId(),0,0,0);
6273 if(sWorld.IsFFAPvPRealm())
6274 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6276 else // anywhere else
6278 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6280 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6282 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6284 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6285 SetRestType(REST_TYPE_NO);
6287 if(sWorld.IsFFAPvPRealm())
6288 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6291 else // not in tavern (leave city then)
6293 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6294 SetRestType(REST_TYPE_NO);
6296 // Set player to FFA PVP when not in rested environment.
6297 if(sWorld.IsFFAPvPRealm())
6298 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6303 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6304 // if player resurrected at teleport this will be applied in resurrect code
6305 if(isAlive())
6306 DestroyZoneLimitedItem( true, newZone );
6308 // recent client version not send leave/join channel packets for built-in local channels
6309 UpdateLocalChannels( newZone );
6311 // group update
6312 if(GetGroup())
6313 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6315 UpdateZoneDependentAuras(newZone);
6318 //If players are too far way of duel flag... then player loose the duel
6319 void Player::CheckDuelDistance(time_t currTime)
6321 if(!duel)
6322 return;
6324 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6325 GameObject* obj = ObjectAccessor::GetGameObject(*this, duelFlagGUID);
6326 if(!obj)
6327 return;
6329 if(duel->outOfBound == 0)
6331 if(!IsWithinDistInMap(obj, 50))
6333 duel->outOfBound = currTime;
6335 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6336 GetSession()->SendPacket(&data);
6339 else
6341 if(IsWithinDistInMap(obj, 40))
6343 duel->outOfBound = 0;
6345 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6346 GetSession()->SendPacket(&data);
6348 else if(currTime >= (duel->outOfBound+10))
6350 DuelComplete(DUEL_FLED);
6355 void Player::DuelComplete(DuelCompleteType type)
6357 // duel not requested
6358 if(!duel)
6359 return;
6361 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6362 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6363 GetSession()->SendPacket(&data);
6364 duel->opponent->GetSession()->SendPacket(&data);
6366 if(type != DUEL_INTERUPTED)
6368 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6369 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6370 data << duel->opponent->GetName();
6371 data << GetName();
6372 SendMessageToSet(&data,true);
6375 // cool-down duel spell
6376 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6378 data<<GetGUID();
6379 data<<uint8(0x0);
6381 data<<(uint32)7266;
6382 data<<uint32(0x0);
6383 GetSession()->SendPacket(&data);
6384 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6385 data<<duel->opponent->GetGUID();
6386 data<<uint8(0x0);
6387 data<<(uint32)7266;
6388 data<<uint32(0x0);
6389 duel->opponent->GetSession()->SendPacket(&data);*/
6391 //Remove Duel Flag object
6392 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
6393 if(obj)
6394 duel->initiator->RemoveGameObject(obj,true);
6396 /* remove auras */
6397 std::vector<uint32> auras2remove;
6398 AuraMap const& vAuras = duel->opponent->GetAuras();
6399 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6401 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6402 auras2remove.push_back(i->second->GetId());
6405 for(size_t i=0; i<auras2remove.size(); i++)
6406 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6408 auras2remove.clear();
6409 AuraMap const& auras = GetAuras();
6410 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6412 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6413 auras2remove.push_back(i->second->GetId());
6415 for(size_t i=0; i<auras2remove.size(); i++)
6416 RemoveAurasDueToSpell(auras2remove[i]);
6418 // cleanup combo points
6419 if(GetComboTarget()==duel->opponent->GetGUID())
6420 ClearComboPoints();
6421 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6422 ClearComboPoints();
6424 if(duel->opponent->GetComboTarget()==GetGUID())
6425 duel->opponent->ClearComboPoints();
6426 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6427 duel->opponent->ClearComboPoints();
6429 //cleanups
6430 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6431 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6432 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6433 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6435 delete duel->opponent->duel;
6436 duel->opponent->duel = NULL;
6437 delete duel;
6438 duel = NULL;
6441 //---------------------------------------------------------//
6443 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6445 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6446 return;
6448 // not apply/remove mods for broken item
6449 if(item->IsBroken())
6450 return;
6452 ItemPrototype const *proto = item->GetProto();
6454 if(!proto)
6455 return;
6457 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6459 uint32 attacktype = Player::GetAttackBySlot(slot);
6460 if(attacktype < MAX_ATTACK)
6461 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6463 _ApplyItemBonuses(proto,slot,apply);
6465 if( slot==EQUIPMENT_SLOT_RANGED )
6466 _ApplyAmmoBonuses();
6468 ApplyItemEquipSpell(item,apply);
6469 ApplyEnchantment(item, apply);
6471 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6472 CorrectMetaGemEnchants(slot, apply);
6474 sLog.outDebug("_ApplyItemMods complete.");
6477 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6479 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6480 return;
6482 for (int i = 0; i < 10; i++)
6484 uint32 statType = 0;
6485 int32 val = 0;
6487 if(proto->ScalingStatDistribution)
6489 if(ScalingStatDistributionEntry const *ssd = sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution))
6491 statType = ssd->StatMod[i];
6493 if(uint32 modifier = ssd->Modifier[i])
6495 uint32 level = ((getLevel() > ssd->MaxLevel) ? ssd->MaxLevel : getLevel());
6496 if(ScalingStatValuesEntry const *ssv = sScalingStatValuesStore.LookupEntry(level))
6498 int multiplier = ssv->Multiplier[proto->GetScalingStatValuesColumn()];
6499 val = (multiplier * modifier) / 10000;
6504 else
6506 statType = proto->ItemStat[i].ItemStatType;
6507 val = float(proto->ItemStat[i].ItemStatValue);
6510 if(val == 0)
6511 continue;
6513 switch (statType)
6515 case ITEM_MOD_MANA:
6516 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6517 break;
6518 case ITEM_MOD_HEALTH: // modify HP
6519 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6520 break;
6521 case ITEM_MOD_AGILITY: // modify agility
6522 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6523 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6524 break;
6525 case ITEM_MOD_STRENGTH: //modify strength
6526 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6527 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6528 break;
6529 case ITEM_MOD_INTELLECT: //modify intellect
6530 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6531 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6532 break;
6533 case ITEM_MOD_SPIRIT: //modify spirit
6534 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6535 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6536 break;
6537 case ITEM_MOD_STAMINA: //modify stamina
6538 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6539 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6540 break;
6541 case ITEM_MOD_DEFENSE_SKILL_RATING:
6542 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6543 break;
6544 case ITEM_MOD_DODGE_RATING:
6545 ApplyRatingMod(CR_DODGE, int32(val), apply);
6546 break;
6547 case ITEM_MOD_PARRY_RATING:
6548 ApplyRatingMod(CR_PARRY, int32(val), apply);
6549 break;
6550 case ITEM_MOD_BLOCK_RATING:
6551 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6552 break;
6553 case ITEM_MOD_HIT_MELEE_RATING:
6554 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6555 break;
6556 case ITEM_MOD_HIT_RANGED_RATING:
6557 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6558 break;
6559 case ITEM_MOD_HIT_SPELL_RATING:
6560 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6561 break;
6562 case ITEM_MOD_CRIT_MELEE_RATING:
6563 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6564 break;
6565 case ITEM_MOD_CRIT_RANGED_RATING:
6566 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6567 break;
6568 case ITEM_MOD_CRIT_SPELL_RATING:
6569 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6570 break;
6571 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6572 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6573 break;
6574 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6575 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6576 break;
6577 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6578 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6579 break;
6580 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6581 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6582 break;
6583 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6584 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6585 break;
6586 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6587 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6588 break;
6589 case ITEM_MOD_HASTE_MELEE_RATING:
6590 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6591 break;
6592 case ITEM_MOD_HASTE_RANGED_RATING:
6593 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6594 break;
6595 case ITEM_MOD_HASTE_SPELL_RATING:
6596 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6597 break;
6598 case ITEM_MOD_HIT_RATING:
6599 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6600 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6601 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6602 break;
6603 case ITEM_MOD_CRIT_RATING:
6604 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6605 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6606 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6607 break;
6608 case ITEM_MOD_HIT_TAKEN_RATING:
6609 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6610 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6611 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6612 break;
6613 case ITEM_MOD_CRIT_TAKEN_RATING:
6614 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6615 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6616 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6617 break;
6618 case ITEM_MOD_RESILIENCE_RATING:
6619 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6620 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6621 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6622 break;
6623 case ITEM_MOD_HASTE_RATING:
6624 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6625 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6626 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6627 break;
6628 case ITEM_MOD_EXPERTISE_RATING:
6629 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6630 break;
6631 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6632 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6633 break;
6637 if (proto->Armor)
6638 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6640 if (proto->Block)
6641 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6643 if (proto->HolyRes)
6644 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6646 if (proto->FireRes)
6647 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6649 if (proto->NatureRes)
6650 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6652 if (proto->FrostRes)
6653 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6655 if (proto->ShadowRes)
6656 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6658 if (proto->ArcaneRes)
6659 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6661 WeaponAttackType attType = BASE_ATTACK;
6662 float damage = 0.0f;
6664 if( slot == EQUIPMENT_SLOT_RANGED && (
6665 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6666 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6668 attType = RANGED_ATTACK;
6670 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6672 attType = OFF_ATTACK;
6675 if (proto->Damage[0].DamageMin > 0 )
6677 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6678 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6679 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6682 if (proto->Damage[0].DamageMax > 0 )
6684 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6685 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6688 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6689 return;
6691 if (proto->Delay)
6693 if(slot == EQUIPMENT_SLOT_RANGED)
6694 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6695 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6696 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6697 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6698 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6701 if(CanModifyStats() && (damage || proto->Delay))
6702 UpdateDamagePhysical(attType);
6705 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6707 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6708 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6709 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6711 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6712 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6713 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6715 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6716 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6717 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6720 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6722 // generic not weapon specific case processes in aura code
6723 if(aura->GetSpellProto()->EquippedItemClass == -1)
6724 return;
6726 BaseModGroup mod = BASEMOD_END;
6727 switch(attackType)
6729 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6730 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6731 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6732 default: return;
6735 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6737 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6741 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6743 // ignore spell mods for not wands
6744 Modifier const* modifier = aura->GetModifier();
6745 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6746 return;
6748 // generic not weapon specific case processes in aura code
6749 if(aura->GetSpellProto()->EquippedItemClass == -1)
6750 return;
6752 UnitMods unitMod = UNIT_MOD_END;
6753 switch(attackType)
6755 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6756 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6757 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6758 default: return;
6761 UnitModifierType unitModType = TOTAL_VALUE;
6762 switch(modifier->m_auraname)
6764 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6765 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6766 default: return;
6769 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6771 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6775 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6777 if(!item)
6778 return;
6780 ItemPrototype const *proto = item->GetProto();
6781 if(!proto)
6782 return;
6784 for (int i = 0; i < 5; i++)
6786 _Spell const& spellData = proto->Spells[i];
6788 // no spell
6789 if(!spellData.SpellId )
6790 continue;
6792 // wrong triggering type
6793 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6794 continue;
6796 // check if it is valid spell
6797 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6798 if(!spellproto)
6799 continue;
6801 ApplyEquipSpell(spellproto,item,apply,form_change);
6805 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6807 if(apply)
6809 // Cannot be used in this stance/form
6810 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)!=0)
6811 return;
6813 if(form_change) // check aura active state from other form
6815 bool found = false;
6816 for (int k=0; k < 3; ++k)
6818 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6819 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6821 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6823 found = true;
6824 break;
6827 if(found)
6828 break;
6831 if(found) // and skip re-cast already active aura at form change
6832 return;
6835 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6837 CastSpell(this,spellInfo,true,item);
6839 else
6841 if(form_change) // check aura compatibility
6843 // Cannot be used in this stance/form
6844 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==0)
6845 return; // and remove only not compatible at form change
6848 if(item)
6849 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6850 else
6851 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6855 void Player::UpdateEquipSpellsAtFormChange()
6857 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6859 if(m_items[i] && !m_items[i]->IsBroken())
6861 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6862 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6866 // item set bonuses not dependent from item broken state
6867 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6869 ItemSetEffect* eff = ItemSetEff[setindex];
6870 if(!eff)
6871 continue;
6873 for(uint32 y=0;y<8; ++y)
6875 SpellEntry const* spellInfo = eff->spells[y];
6876 if(!spellInfo)
6877 continue;
6879 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6880 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6885 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
6887 if(!item || item->IsBroken())
6888 return;
6890 ItemPrototype const *proto = item->GetProto();
6891 if(!proto)
6892 return;
6894 if (!Target || Target == this )
6895 return;
6897 for (int i = 0; i < 5; i++)
6899 _Spell const& spellData = proto->Spells[i];
6901 // no spell
6902 if(!spellData.SpellId )
6903 continue;
6905 // wrong triggering type
6906 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6907 continue;
6909 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6910 if(!spellInfo)
6912 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6913 continue;
6916 // not allow proc extra attack spell at extra attack
6917 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6918 return;
6920 float chance = spellInfo->procChance;
6922 if(spellData.SpellPPMRate)
6924 uint32 WeaponSpeed = GetAttackTime(attType);
6925 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6927 else if(chance > 100.0f)
6929 chance = GetWeaponProcChance();
6932 if (roll_chance_f(chance))
6933 CastSpell(Target, spellInfo->Id, true, item);
6936 // item combat enchantments
6937 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6939 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6940 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6941 if(!pEnchant) continue;
6942 for (int s=0;s<3;s++)
6944 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6945 continue;
6947 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6948 if (!spellInfo)
6950 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6951 continue;
6954 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6955 if (roll_chance_f(chance))
6957 if(IsPositiveSpell(pEnchant->spellid[s]))
6958 CastSpell(this, pEnchant->spellid[s], true, item);
6959 else
6960 CastSpell(Target, pEnchant->spellid[s], true, item);
6966 void Player::_RemoveAllItemMods()
6968 sLog.outDebug("_RemoveAllItemMods start.");
6970 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6972 if(m_items[i])
6974 ItemPrototype const *proto = m_items[i]->GetProto();
6975 if(!proto)
6976 continue;
6978 // item set bonuses not dependent from item broken state
6979 if(proto->ItemSet)
6980 RemoveItemsSetItem(this,proto);
6982 if(m_items[i]->IsBroken())
6983 continue;
6985 ApplyItemEquipSpell(m_items[i],false);
6986 ApplyEnchantment(m_items[i], false);
6990 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6992 if(m_items[i])
6994 if(m_items[i]->IsBroken())
6995 continue;
6996 ItemPrototype const *proto = m_items[i]->GetProto();
6997 if(!proto)
6998 continue;
7000 uint32 attacktype = Player::GetAttackBySlot(i);
7001 if(attacktype < MAX_ATTACK)
7002 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7004 _ApplyItemBonuses(proto,i, false);
7006 if( i == EQUIPMENT_SLOT_RANGED )
7007 _ApplyAmmoBonuses();
7011 sLog.outDebug("_RemoveAllItemMods complete.");
7014 void Player::_ApplyAllItemMods()
7016 sLog.outDebug("_ApplyAllItemMods start.");
7018 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7020 if(m_items[i])
7022 if(m_items[i]->IsBroken())
7023 continue;
7025 ItemPrototype const *proto = m_items[i]->GetProto();
7026 if(!proto)
7027 continue;
7029 uint32 attacktype = Player::GetAttackBySlot(i);
7030 if(attacktype < MAX_ATTACK)
7031 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7033 _ApplyItemBonuses(proto,i, true);
7035 if( i == EQUIPMENT_SLOT_RANGED )
7036 _ApplyAmmoBonuses();
7040 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7042 if(m_items[i])
7044 ItemPrototype const *proto = m_items[i]->GetProto();
7045 if(!proto)
7046 continue;
7048 // item set bonuses not dependent from item broken state
7049 if(proto->ItemSet)
7050 AddItemsSetItem(this,m_items[i]);
7052 if(m_items[i]->IsBroken())
7053 continue;
7055 ApplyItemEquipSpell(m_items[i],true);
7056 ApplyEnchantment(m_items[i], true);
7060 sLog.outDebug("_ApplyAllItemMods complete.");
7063 void Player::_ApplyAmmoBonuses()
7065 // check ammo
7066 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7067 if(!ammo_id)
7068 return;
7070 float currentAmmoDPS;
7072 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
7073 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7074 currentAmmoDPS = 0.0f;
7075 else
7076 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7078 if(currentAmmoDPS == GetAmmoDPS())
7079 return;
7081 m_ammoDPS = currentAmmoDPS;
7083 if(CanModifyStats())
7084 UpdateDamagePhysical(RANGED_ATTACK);
7087 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7089 if(!ammo_proto)
7090 return false;
7092 // check ranged weapon
7093 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7094 if(!weapon || weapon->IsBroken() )
7095 return false;
7097 ItemPrototype const* weapon_proto = weapon->GetProto();
7098 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7099 return false;
7101 // check ammo ws. weapon compatibility
7102 switch(weapon_proto->SubClass)
7104 case ITEM_SUBCLASS_WEAPON_BOW:
7105 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7106 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7107 return false;
7108 break;
7109 case ITEM_SUBCLASS_WEAPON_GUN:
7110 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7111 return false;
7112 break;
7113 default:
7114 return false;
7117 return true;
7120 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7121 Called by remove insignia spell effect */
7122 void Player::RemovedInsignia(Player* looterPlr)
7124 if (!GetBattleGroundId())
7125 return;
7127 // If not released spirit, do it !
7128 if(m_deathTimer > 0)
7130 m_deathTimer = 0;
7131 BuildPlayerRepop();
7132 RepopAtGraveyard();
7135 Corpse *corpse = GetCorpse();
7136 if (!corpse)
7137 return;
7139 // We have to convert player corpse to bones, not to be able to resurrect there
7140 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7141 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
7142 if (!bones)
7143 return;
7145 // Now we must make bones lootable, and send player loot
7146 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7148 // We store the level of our player in the gold field
7149 // We retrieve this information at Player::SendLoot()
7150 bones->loot.gold = getLevel();
7151 bones->lootRecipient = looterPlr;
7152 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7155 /*Loot type MUST be
7156 1-corpse, go
7157 2-skinning
7158 3-Fishing
7161 void Player::SendLootRelease( uint64 guid )
7163 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7164 data << uint64(guid) << uint8(1);
7165 SendDirectMessage( &data );
7168 void Player::SendLoot(uint64 guid, LootType loot_type)
7170 Loot *loot = 0;
7171 PermissionTypes permission = ALL_PERMISSION;
7173 sLog.outDebug("Player::SendLoot");
7174 if (IS_GAMEOBJECT_GUID(guid))
7176 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7177 GameObject *go =
7178 ObjectAccessor::GetGameObject(*this, guid);
7180 // not check distance for GO in case owned GO (fishing bobber case, for example)
7181 // And permit out of range GO with no owner in case fishing hole
7182 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7184 SendLootRelease(guid);
7185 return;
7188 loot = &go->loot;
7190 if(go->getLootState() == GO_READY)
7192 uint32 lootid = go->GetLootId();
7194 if(lootid)
7196 sLog.outDebug(" if(lootid)");
7197 loot->clear();
7198 loot->FillLoot(lootid, LootTemplates_Gameobject, this);
7201 if(loot_type == LOOT_FISHING)
7202 go->getFishLoot(loot);
7204 go->SetLootState(GO_ACTIVATED);
7207 else if (IS_ITEM_GUID(guid))
7209 Item *item = GetItemByGuid( guid );
7211 if (!item)
7213 SendLootRelease(guid);
7214 return;
7217 if(loot_type == LOOT_DISENCHANTING)
7219 loot = &item->loot;
7221 if(!item->m_lootGenerated)
7223 item->m_lootGenerated = true;
7224 loot->clear();
7225 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this);
7228 else if(loot_type == LOOT_PROSPECTING)
7230 loot = &item->loot;
7232 if(!item->m_lootGenerated)
7234 item->m_lootGenerated = true;
7235 loot->clear();
7236 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this);
7239 else if(loot_type == LOOT_MILLING)
7241 loot = &item->loot;
7243 if(!item->m_lootGenerated)
7245 item->m_lootGenerated = true;
7246 loot->clear();
7247 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this);
7250 else
7252 loot = &item->loot;
7254 if(!item->m_lootGenerated)
7256 item->m_lootGenerated = true;
7257 loot->clear();
7258 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this);
7260 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7264 else if (IS_CORPSE_GUID(guid)) // remove insignia
7266 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7268 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7270 SendLootRelease(guid);
7271 return;
7274 loot = &bones->loot;
7276 if (!bones->lootForBody)
7278 bones->lootForBody = true;
7279 uint32 pLevel = bones->loot.gold;
7280 bones->loot.clear();
7281 // It may need a better formula
7282 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7283 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7286 if (bones->lootRecipient != this)
7287 permission = NONE_PERMISSION;
7289 else
7291 Creature *creature = ObjectAccessor::GetCreature(*this, guid);
7293 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7294 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7296 SendLootRelease(guid);
7297 return;
7300 if(loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7302 SendLootRelease(guid);
7303 return;
7306 loot = &creature->loot;
7308 if(loot_type == LOOT_PICKPOCKETING)
7310 if ( !creature->lootForPickPocketed )
7312 creature->lootForPickPocketed = true;
7313 loot->clear();
7315 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7316 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this);
7318 // Generate extra money for pick pocket loot
7319 const uint32 a = urand(0, creature->getLevel()/2);
7320 const uint32 b = urand(0, getLevel()/2);
7321 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7324 else
7326 // the player whose group may loot the corpse
7327 Player *recipient = creature->GetLootRecipient();
7328 if (!recipient)
7330 creature->SetLootRecipient(this);
7331 recipient = this;
7334 if (creature->lootForPickPocketed)
7336 creature->lootForPickPocketed = false;
7337 loot->clear();
7340 if(!creature->lootForBody)
7342 creature->lootForBody = true;
7343 loot->clear();
7345 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7346 loot->FillLoot(lootid, LootTemplates_Creature, recipient);
7348 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7350 if(Group* group = recipient->GetGroup())
7352 group->UpdateLooterGuid(creature,true);
7354 switch (group->GetLootMethod())
7356 case GROUP_LOOT:
7357 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7358 group->GroupLoot(recipient->GetGUID(), loot, creature);
7359 break;
7360 case NEED_BEFORE_GREED:
7361 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7362 break;
7363 case MASTER_LOOT:
7364 group->MasterLoot(recipient->GetGUID(), loot, creature);
7365 break;
7366 default:
7367 break;
7372 // possible only if creature->lootForBody && loot->empty() at spell cast check
7373 if (loot_type == LOOT_SKINNING)
7375 loot->clear();
7376 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this);
7378 // set group rights only for loot_type != LOOT_SKINNING
7379 else
7381 if(Group* group = GetGroup())
7383 if( group == recipient->GetGroup() )
7385 if(group->GetLootMethod() == FREE_FOR_ALL)
7386 permission = ALL_PERMISSION;
7387 else if(group->GetLooterGuid() == GetGUID())
7389 if(group->GetLootMethod() == MASTER_LOOT)
7390 permission = MASTER_PERMISSION;
7391 else
7392 permission = ALL_PERMISSION;
7394 else
7395 permission = GROUP_PERMISSION;
7397 else
7398 permission = NONE_PERMISSION;
7400 else if(recipient == this)
7401 permission = ALL_PERMISSION;
7402 else
7403 permission = NONE_PERMISSION;
7408 SetLootGUID(guid);
7410 QuestItemList *q_list = 0;
7411 if (permission != NONE_PERMISSION)
7413 QuestItemMap const& lootPlayerQuestItems = loot->GetPlayerQuestItems();
7414 QuestItemMap::const_iterator itr = lootPlayerQuestItems.find(GetGUIDLow());
7415 if (itr == lootPlayerQuestItems.end())
7416 q_list = loot->FillQuestLoot(this);
7417 else
7418 q_list = itr->second;
7421 QuestItemList *ffa_list = 0;
7422 if (permission != NONE_PERMISSION)
7424 QuestItemMap const& lootPlayerFFAItems = loot->GetPlayerFFAItems();
7425 QuestItemMap::const_iterator itr = lootPlayerFFAItems.find(GetGUIDLow());
7426 if (itr == lootPlayerFFAItems.end())
7427 ffa_list = loot->FillFFALoot(this);
7428 else
7429 ffa_list = itr->second;
7432 QuestItemList *conditional_list = 0;
7433 if (permission != NONE_PERMISSION)
7435 QuestItemMap const& lootPlayerNonQuestNonFFAConditionalItems = loot->GetPlayerNonQuestNonFFAConditionalItems();
7436 QuestItemMap::const_iterator itr = lootPlayerNonQuestNonFFAConditionalItems.find(GetGUIDLow());
7437 if (itr == lootPlayerNonQuestNonFFAConditionalItems.end())
7438 conditional_list = loot->FillNonQuestNonFFAConditionalLoot(this);
7439 else
7440 conditional_list = itr->second;
7443 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING, LOOT_INSIGNIA and LOOT_MILLING unsupported by client, sending LOOT_SKINNING instead
7444 if(loot_type == LOOT_PICKPOCKETING || loot_type == LOOT_DISENCHANTING || loot_type == LOOT_PROSPECTING || loot_type == LOOT_INSIGNIA || loot_type == LOOT_MILLING)
7445 loot_type = LOOT_SKINNING;
7447 if(loot_type == LOOT_FISHINGHOLE)
7448 loot_type = LOOT_FISHING;
7450 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7452 data << uint64(guid);
7453 data << uint8(loot_type);
7454 data << LootView(*loot, q_list, ffa_list, conditional_list, this, permission);
7456 SendDirectMessage(&data);
7458 // add 'this' player as one of the players that are looting 'loot'
7459 if (permission != NONE_PERMISSION)
7460 loot->AddLooter(GetGUID());
7462 if ( loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid) )
7463 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7466 void Player::SendNotifyLootMoneyRemoved()
7468 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7469 GetSession()->SendPacket( &data );
7472 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7474 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7475 data << uint8(lootSlot);
7476 GetSession()->SendPacket( &data );
7479 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7481 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7482 data << Field;
7483 data << Value;
7484 GetSession()->SendPacket(&data);
7487 void Player::SendInitWorldStates()
7489 // data depends on zoneid/mapid...
7490 BattleGround* bg = GetBattleGround();
7491 uint16 NumberOfFields = 0;
7492 uint32 mapid = GetMapId();
7493 uint32 zoneid = GetZoneId();
7494 uint32 areaid = GetAreaId();
7495 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7496 // may be exist better way to do this...
7497 switch(zoneid)
7499 case 0:
7500 case 1:
7501 case 4:
7502 case 8:
7503 case 10:
7504 case 11:
7505 case 12:
7506 case 36:
7507 case 38:
7508 case 40:
7509 case 41:
7510 case 51:
7511 case 267:
7512 case 1519:
7513 case 1537:
7514 case 2257:
7515 case 2918:
7516 NumberOfFields = 8;
7517 break;
7518 case 139:
7519 NumberOfFields = 41;
7520 break;
7521 case 1377:
7522 NumberOfFields = 15;
7523 break;
7524 case 2597:
7525 NumberOfFields = 83;
7526 break;
7527 case 3277:
7528 NumberOfFields = 16;
7529 break;
7530 case 3358:
7531 case 3820:
7532 NumberOfFields = 40;
7533 break;
7534 case 3483:
7535 NumberOfFields = 27;
7536 break;
7537 case 3518:
7538 NumberOfFields = 39;
7539 break;
7540 case 3519:
7541 NumberOfFields = 38;
7542 break;
7543 case 3521:
7544 NumberOfFields = 37;
7545 break;
7546 case 3698:
7547 case 3702:
7548 case 3968:
7549 NumberOfFields = 11;
7550 break;
7551 case 3703:
7552 NumberOfFields = 11;
7553 break;
7554 default:
7555 NumberOfFields = 12;
7556 break;
7559 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7560 data << uint32(mapid); // mapid
7561 data << uint32(zoneid); // zone id
7562 data << uint32(areaid); // area id, new 2.1.0
7563 data << uint16(NumberOfFields); // count of uint64 blocks
7564 data << uint32(0x8d8) << uint32(0x0); // 1
7565 data << uint32(0x8d7) << uint32(0x0); // 2
7566 data << uint32(0x8d6) << uint32(0x0); // 3
7567 data << uint32(0x8d5) << uint32(0x0); // 4
7568 data << uint32(0x8d4) << uint32(0x0); // 5
7569 data << uint32(0x8d3) << uint32(0x0); // 6
7570 // 7 1 - Arena season in progress, 0 - end of season
7571 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7572 // 8 Arena season id
7573 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7574 if(mapid == 530) // Outland
7576 data << uint32(0x9bf) << uint32(0x0); // 7
7577 data << uint32(0x9bd) << uint32(0xF); // 8
7578 data << uint32(0x9bb) << uint32(0xF); // 9
7580 switch(zoneid)
7582 case 1:
7583 case 11:
7584 case 12:
7585 case 38:
7586 case 40:
7587 case 51:
7588 case 1519:
7589 case 1537:
7590 case 2257:
7591 break;
7592 case 2597: // AV
7593 data << uint32(0x7ae) << uint32(0x1); // 7
7594 data << uint32(0x532) << uint32(0x1); // 8
7595 data << uint32(0x531) << uint32(0x0); // 9
7596 data << uint32(0x52e) << uint32(0x0); // 10
7597 data << uint32(0x571) << uint32(0x0); // 11
7598 data << uint32(0x570) << uint32(0x0); // 12
7599 data << uint32(0x567) << uint32(0x1); // 13
7600 data << uint32(0x566) << uint32(0x1); // 14
7601 data << uint32(0x550) << uint32(0x1); // 15
7602 data << uint32(0x544) << uint32(0x0); // 16
7603 data << uint32(0x536) << uint32(0x0); // 17
7604 data << uint32(0x535) << uint32(0x1); // 18
7605 data << uint32(0x518) << uint32(0x0); // 19
7606 data << uint32(0x517) << uint32(0x0); // 20
7607 data << uint32(0x574) << uint32(0x0); // 21
7608 data << uint32(0x573) << uint32(0x0); // 22
7609 data << uint32(0x572) << uint32(0x0); // 23
7610 data << uint32(0x56f) << uint32(0x0); // 24
7611 data << uint32(0x56e) << uint32(0x0); // 25
7612 data << uint32(0x56d) << uint32(0x0); // 26
7613 data << uint32(0x56c) << uint32(0x0); // 27
7614 data << uint32(0x56b) << uint32(0x0); // 28
7615 data << uint32(0x56a) << uint32(0x1); // 29
7616 data << uint32(0x569) << uint32(0x1); // 30
7617 data << uint32(0x568) << uint32(0x1); // 13
7618 data << uint32(0x565) << uint32(0x0); // 32
7619 data << uint32(0x564) << uint32(0x0); // 33
7620 data << uint32(0x563) << uint32(0x0); // 34
7621 data << uint32(0x562) << uint32(0x0); // 35
7622 data << uint32(0x561) << uint32(0x0); // 36
7623 data << uint32(0x560) << uint32(0x0); // 37
7624 data << uint32(0x55f) << uint32(0x0); // 38
7625 data << uint32(0x55e) << uint32(0x0); // 39
7626 data << uint32(0x55d) << uint32(0x0); // 40
7627 data << uint32(0x3c6) << uint32(0x4); // 41
7628 data << uint32(0x3c4) << uint32(0x6); // 42
7629 data << uint32(0x3c2) << uint32(0x4); // 43
7630 data << uint32(0x516) << uint32(0x1); // 44
7631 data << uint32(0x515) << uint32(0x0); // 45
7632 data << uint32(0x3b6) << uint32(0x6); // 46
7633 data << uint32(0x55c) << uint32(0x0); // 47
7634 data << uint32(0x55b) << uint32(0x0); // 48
7635 data << uint32(0x55a) << uint32(0x0); // 49
7636 data << uint32(0x559) << uint32(0x0); // 50
7637 data << uint32(0x558) << uint32(0x0); // 51
7638 data << uint32(0x557) << uint32(0x0); // 52
7639 data << uint32(0x556) << uint32(0x0); // 53
7640 data << uint32(0x555) << uint32(0x0); // 54
7641 data << uint32(0x554) << uint32(0x1); // 55
7642 data << uint32(0x553) << uint32(0x1); // 56
7643 data << uint32(0x552) << uint32(0x1); // 57
7644 data << uint32(0x551) << uint32(0x1); // 58
7645 data << uint32(0x54f) << uint32(0x0); // 59
7646 data << uint32(0x54e) << uint32(0x0); // 60
7647 data << uint32(0x54d) << uint32(0x1); // 61
7648 data << uint32(0x54c) << uint32(0x0); // 62
7649 data << uint32(0x54b) << uint32(0x0); // 63
7650 data << uint32(0x545) << uint32(0x0); // 64
7651 data << uint32(0x543) << uint32(0x1); // 65
7652 data << uint32(0x542) << uint32(0x0); // 66
7653 data << uint32(0x540) << uint32(0x0); // 67
7654 data << uint32(0x53f) << uint32(0x0); // 68
7655 data << uint32(0x53e) << uint32(0x0); // 69
7656 data << uint32(0x53d) << uint32(0x0); // 70
7657 data << uint32(0x53c) << uint32(0x0); // 71
7658 data << uint32(0x53b) << uint32(0x0); // 72
7659 data << uint32(0x53a) << uint32(0x1); // 73
7660 data << uint32(0x539) << uint32(0x0); // 74
7661 data << uint32(0x538) << uint32(0x0); // 75
7662 data << uint32(0x537) << uint32(0x0); // 76
7663 data << uint32(0x534) << uint32(0x0); // 77
7664 data << uint32(0x533) << uint32(0x0); // 78
7665 data << uint32(0x530) << uint32(0x0); // 79
7666 data << uint32(0x52f) << uint32(0x0); // 80
7667 data << uint32(0x52d) << uint32(0x1); // 81
7668 break;
7669 case 3277: // WS
7670 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7671 bg->FillInitialWorldStates(data);
7672 else
7674 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7675 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7676 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7677 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7678 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7679 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7680 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7681 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7683 break;
7684 case 3358: // AB
7685 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7686 bg->FillInitialWorldStates(data);
7687 else
7689 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7690 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7691 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7692 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7693 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7694 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7695 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7696 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7697 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7698 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7699 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7700 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7701 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7702 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7703 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7704 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7705 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7706 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7707 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7708 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7709 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7710 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7711 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7712 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7713 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7714 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7715 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7716 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7717 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7718 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7719 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7720 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7722 break;
7723 case 3820: // EY
7724 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7725 bg->FillInitialWorldStates(data);
7726 else
7728 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7729 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7730 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7731 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7732 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7733 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7734 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7735 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7736 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7737 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7738 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7739 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7740 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7741 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7742 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7743 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7744 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7745 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7746 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7747 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7748 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7749 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7750 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7751 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7752 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7753 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7754 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7755 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7756 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7757 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7758 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7759 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7760 // and some more ... unknown
7762 break;
7763 case 3483: // Hellfire Peninsula
7764 data << uint32(0x9ba) << uint32(0x1); // 10
7765 data << uint32(0x9b9) << uint32(0x1); // 11
7766 data << uint32(0x9b5) << uint32(0x0); // 12
7767 data << uint32(0x9b4) << uint32(0x1); // 13
7768 data << uint32(0x9b3) << uint32(0x0); // 14
7769 data << uint32(0x9b2) << uint32(0x0); // 15
7770 data << uint32(0x9b1) << uint32(0x1); // 16
7771 data << uint32(0x9b0) << uint32(0x0); // 17
7772 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7773 data << uint32(0x9ac) << uint32(0x0); // 19
7774 data << uint32(0x9a8) << uint32(0x0); // 20
7775 data << uint32(0x9a7) << uint32(0x0); // 21
7776 data << uint32(0x9a6) << uint32(0x1); // 22
7777 break;
7778 case 3519: // Terokkar Forest
7779 data << uint32(0xa41) << uint32(0x0); // 10
7780 data << uint32(0xa40) << uint32(0x14); // 11
7781 data << uint32(0xa3f) << uint32(0x0); // 12
7782 data << uint32(0xa3e) << uint32(0x0); // 13
7783 data << uint32(0xa3d) << uint32(0x5); // 14
7784 data << uint32(0xa3c) << uint32(0x0); // 15
7785 data << uint32(0xa87) << uint32(0x0); // 16
7786 data << uint32(0xa86) << uint32(0x0); // 17
7787 data << uint32(0xa85) << uint32(0x0); // 18
7788 data << uint32(0xa84) << uint32(0x0); // 19
7789 data << uint32(0xa83) << uint32(0x0); // 20
7790 data << uint32(0xa82) << uint32(0x0); // 21
7791 data << uint32(0xa81) << uint32(0x0); // 22
7792 data << uint32(0xa80) << uint32(0x0); // 23
7793 data << uint32(0xa7e) << uint32(0x0); // 24
7794 data << uint32(0xa7d) << uint32(0x0); // 25
7795 data << uint32(0xa7c) << uint32(0x0); // 26
7796 data << uint32(0xa7b) << uint32(0x0); // 27
7797 data << uint32(0xa7a) << uint32(0x0); // 28
7798 data << uint32(0xa79) << uint32(0x0); // 29
7799 data << uint32(0x9d0) << uint32(0x5); // 30
7800 data << uint32(0x9ce) << uint32(0x0); // 31
7801 data << uint32(0x9cd) << uint32(0x0); // 32
7802 data << uint32(0x9cc) << uint32(0x0); // 33
7803 data << uint32(0xa88) << uint32(0x0); // 34
7804 data << uint32(0xad0) << uint32(0x0); // 35
7805 data << uint32(0xacf) << uint32(0x1); // 36
7806 break;
7807 case 3521: // Zangarmarsh
7808 data << uint32(0x9e1) << uint32(0x0); // 10
7809 data << uint32(0x9e0) << uint32(0x0); // 11
7810 data << uint32(0x9df) << uint32(0x0); // 12
7811 data << uint32(0xa5d) << uint32(0x1); // 13
7812 data << uint32(0xa5c) << uint32(0x0); // 14
7813 data << uint32(0xa5b) << uint32(0x1); // 15
7814 data << uint32(0xa5a) << uint32(0x0); // 16
7815 data << uint32(0xa59) << uint32(0x1); // 17
7816 data << uint32(0xa58) << uint32(0x0); // 18
7817 data << uint32(0xa57) << uint32(0x0); // 19
7818 data << uint32(0xa56) << uint32(0x0); // 20
7819 data << uint32(0xa55) << uint32(0x1); // 21
7820 data << uint32(0xa54) << uint32(0x0); // 22
7821 data << uint32(0x9e7) << uint32(0x0); // 23
7822 data << uint32(0x9e6) << uint32(0x0); // 24
7823 data << uint32(0x9e5) << uint32(0x0); // 25
7824 data << uint32(0xa00) << uint32(0x0); // 26
7825 data << uint32(0x9ff) << uint32(0x1); // 27
7826 data << uint32(0x9fe) << uint32(0x0); // 28
7827 data << uint32(0x9fd) << uint32(0x0); // 29
7828 data << uint32(0x9fc) << uint32(0x1); // 30
7829 data << uint32(0x9fb) << uint32(0x0); // 31
7830 data << uint32(0xa62) << uint32(0x0); // 32
7831 data << uint32(0xa61) << uint32(0x1); // 33
7832 data << uint32(0xa60) << uint32(0x1); // 34
7833 data << uint32(0xa5f) << uint32(0x0); // 35
7834 break;
7835 case 3698: // Nagrand Arena
7836 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
7837 bg->FillInitialWorldStates(data);
7838 else
7840 data << uint32(0xa0f) << uint32(0x0); // 7
7841 data << uint32(0xa10) << uint32(0x0); // 8
7842 data << uint32(0xa11) << uint32(0x0); // 9 show
7844 break;
7845 case 3702: // Blade's Edge Arena
7846 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
7847 bg->FillInitialWorldStates(data);
7848 else
7850 data << uint32(0x9f0) << uint32(0x0); // 7 gold
7851 data << uint32(0x9f1) << uint32(0x0); // 8 green
7852 data << uint32(0x9f3) << uint32(0x0); // 9 show
7854 break;
7855 case 3968: // Ruins of Lordaeron
7856 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
7857 bg->FillInitialWorldStates(data);
7858 else
7860 data << uint32(0xbb8) << uint32(0x0); // 7 gold
7861 data << uint32(0xbb9) << uint32(0x0); // 8 green
7862 data << uint32(0xbba) << uint32(0x0); // 9 show
7864 break;
7865 case 3703: // Shattrath City
7866 break;
7867 default:
7868 data << uint32(0x914) << uint32(0x0); // 7
7869 data << uint32(0x913) << uint32(0x0); // 8
7870 data << uint32(0x912) << uint32(0x0); // 9
7871 data << uint32(0x915) << uint32(0x0); // 10
7872 break;
7874 GetSession()->SendPacket(&data);
7877 uint32 Player::GetXPRestBonus(uint32 xp)
7879 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7881 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7882 rested_bonus = xp;
7884 SetRestBonus( GetRestBonus() - rested_bonus);
7886 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7887 return rested_bonus;
7890 void Player::SetBindPoint(uint64 guid)
7892 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7893 data << uint64(guid);
7894 GetSession()->SendPacket( &data );
7897 void Player::SendTalentWipeConfirm(uint64 guid)
7899 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7900 data << uint64(guid);
7901 data << uint32(resetTalentsCost());
7902 GetSession()->SendPacket( &data );
7905 void Player::SendPetSkillWipeConfirm()
7907 Pet* pet = GetPet();
7908 if(!pet)
7909 return;
7910 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7911 data << pet->GetGUID();
7912 data << uint32(pet->resetTalentsCost());
7913 GetSession()->SendPacket( &data );
7916 /*********************************************************/
7917 /*** STORAGE SYSTEM ***/
7918 /*********************************************************/
7920 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7922 assert(i < 3);
7923 if(i < 2 && item)
7925 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7926 return;
7927 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7928 if(charges == 0)
7929 return;
7930 if(charges > 1)
7931 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7932 else if(charges <= 1)
7934 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7935 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7940 void Player::SetSheath( uint32 sheathed )
7942 switch (sheathed)
7944 case SHEATH_STATE_UNARMED: // no prepared weapon
7945 SetVirtualItemSlot(0,NULL);
7946 SetVirtualItemSlot(1,NULL);
7947 SetVirtualItemSlot(2,NULL);
7948 break;
7949 case SHEATH_STATE_MELEE: // prepared melee weapon
7951 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7952 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7953 SetVirtualItemSlot(2,NULL);
7954 }; break;
7955 case SHEATH_STATE_RANGED: // prepared ranged weapon
7956 SetVirtualItemSlot(0,NULL);
7957 SetVirtualItemSlot(1,NULL);
7958 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7959 break;
7960 default:
7961 SetVirtualItemSlot(0,NULL);
7962 SetVirtualItemSlot(1,NULL);
7963 SetVirtualItemSlot(2,NULL);
7964 break;
7966 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
7969 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7971 uint8 pClass = getClass();
7973 uint8 slots[4];
7974 slots[0] = NULL_SLOT;
7975 slots[1] = NULL_SLOT;
7976 slots[2] = NULL_SLOT;
7977 slots[3] = NULL_SLOT;
7978 switch( proto->InventoryType )
7980 case INVTYPE_HEAD:
7981 slots[0] = EQUIPMENT_SLOT_HEAD;
7982 break;
7983 case INVTYPE_NECK:
7984 slots[0] = EQUIPMENT_SLOT_NECK;
7985 break;
7986 case INVTYPE_SHOULDERS:
7987 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7988 break;
7989 case INVTYPE_BODY:
7990 slots[0] = EQUIPMENT_SLOT_BODY;
7991 break;
7992 case INVTYPE_CHEST:
7993 slots[0] = EQUIPMENT_SLOT_CHEST;
7994 break;
7995 case INVTYPE_ROBE:
7996 slots[0] = EQUIPMENT_SLOT_CHEST;
7997 break;
7998 case INVTYPE_WAIST:
7999 slots[0] = EQUIPMENT_SLOT_WAIST;
8000 break;
8001 case INVTYPE_LEGS:
8002 slots[0] = EQUIPMENT_SLOT_LEGS;
8003 break;
8004 case INVTYPE_FEET:
8005 slots[0] = EQUIPMENT_SLOT_FEET;
8006 break;
8007 case INVTYPE_WRISTS:
8008 slots[0] = EQUIPMENT_SLOT_WRISTS;
8009 break;
8010 case INVTYPE_HANDS:
8011 slots[0] = EQUIPMENT_SLOT_HANDS;
8012 break;
8013 case INVTYPE_FINGER:
8014 slots[0] = EQUIPMENT_SLOT_FINGER1;
8015 slots[1] = EQUIPMENT_SLOT_FINGER2;
8016 break;
8017 case INVTYPE_TRINKET:
8018 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8019 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8020 break;
8021 case INVTYPE_CLOAK:
8022 slots[0] = EQUIPMENT_SLOT_BACK;
8023 break;
8024 case INVTYPE_WEAPON:
8026 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8028 // suggest offhand slot only if know dual wielding
8029 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8030 if(CanDualWield())
8031 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8032 break;
8034 case INVTYPE_SHIELD:
8035 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8036 break;
8037 case INVTYPE_RANGED:
8038 slots[0] = EQUIPMENT_SLOT_RANGED;
8039 break;
8040 case INVTYPE_2HWEAPON:
8041 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8042 if (CanDualWield() && CanTitanGrip())
8043 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8044 break;
8045 case INVTYPE_TABARD:
8046 slots[0] = EQUIPMENT_SLOT_TABARD;
8047 break;
8048 case INVTYPE_WEAPONMAINHAND:
8049 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8050 break;
8051 case INVTYPE_WEAPONOFFHAND:
8052 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8053 break;
8054 case INVTYPE_HOLDABLE:
8055 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8056 break;
8057 case INVTYPE_THROWN:
8058 slots[0] = EQUIPMENT_SLOT_RANGED;
8059 break;
8060 case INVTYPE_RANGEDRIGHT:
8061 slots[0] = EQUIPMENT_SLOT_RANGED;
8062 break;
8063 case INVTYPE_BAG:
8064 slots[0] = INVENTORY_SLOT_BAG_1;
8065 slots[1] = INVENTORY_SLOT_BAG_2;
8066 slots[2] = INVENTORY_SLOT_BAG_3;
8067 slots[3] = INVENTORY_SLOT_BAG_4;
8068 break;
8069 case INVTYPE_RELIC:
8071 switch(proto->SubClass)
8073 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8074 if (pClass == CLASS_PALADIN)
8075 slots[0] = EQUIPMENT_SLOT_RANGED;
8076 break;
8077 case ITEM_SUBCLASS_ARMOR_IDOL:
8078 if (pClass == CLASS_DRUID)
8079 slots[0] = EQUIPMENT_SLOT_RANGED;
8080 break;
8081 case ITEM_SUBCLASS_ARMOR_TOTEM:
8082 if (pClass == CLASS_SHAMAN)
8083 slots[0] = EQUIPMENT_SLOT_RANGED;
8084 break;
8085 case ITEM_SUBCLASS_ARMOR_MISC:
8086 if (pClass == CLASS_WARLOCK)
8087 slots[0] = EQUIPMENT_SLOT_RANGED;
8088 break;
8089 case ITEM_SUBCLASS_ARMOR_SIGIL:
8090 if (pClass == CLASS_DEATH_KNIGHT)
8091 slots[0] = EQUIPMENT_SLOT_RANGED;
8092 break;
8094 break;
8096 default :
8097 return NULL_SLOT;
8100 if( slot != NULL_SLOT )
8102 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8104 for (int i = 0; i < 4; i++)
8106 if ( slots[i] == slot )
8107 return slot;
8111 else
8113 // search free slot at first
8114 for (int i = 0; i < 4; i++)
8116 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8118 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8119 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8120 return slots[i];
8124 // if not found free and can swap return first appropriate from used
8125 for (int i = 0; i < 4; i++)
8127 if ( slots[i] != NULL_SLOT && swap )
8128 return slots[i];
8132 // no free position
8133 return NULL_SLOT;
8136 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8138 Item *pItem;
8139 uint32 tempcount = 0;
8141 uint8 res = EQUIP_ERR_OK;
8143 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
8145 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8146 if( pItem && pItem->GetEntry() == item )
8148 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8149 if(ires==EQUIP_ERR_OK)
8151 tempcount += pItem->GetCount();
8152 if( tempcount >= count )
8153 return EQUIP_ERR_OK;
8155 else
8156 res = ires;
8159 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
8161 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8162 if( pItem && pItem->GetEntry() == item )
8164 tempcount += pItem->GetCount();
8165 if( tempcount >= count )
8166 return EQUIP_ERR_OK;
8169 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8171 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8172 if( pItem && pItem->GetEntry() == item )
8174 tempcount += pItem->GetCount();
8175 if( tempcount >= count )
8176 return EQUIP_ERR_OK;
8179 Bag *pBag;
8180 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8182 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8183 if( pBag )
8185 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8187 pItem = GetItemByPos( i, j );
8188 if( pItem && pItem->GetEntry() == item )
8190 tempcount += pItem->GetCount();
8191 if( tempcount >= count )
8192 return EQUIP_ERR_OK;
8198 // not found req. item count and have unequippable items
8199 return res;
8202 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8204 uint32 count = 0;
8205 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_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 = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8213 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8214 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8215 count += pItem->GetCount();
8217 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8219 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8220 if( pBag )
8221 count += pBag->GetItemCount(item,skipItem);
8224 if(skipItem && skipItem->GetProto()->GemProperties)
8226 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8228 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8229 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8230 count += pItem->GetGemCountWithID(item);
8234 if(inBankAlso)
8236 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8238 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8239 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8240 count += pItem->GetCount();
8242 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8244 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8245 if( pBag )
8246 count += pBag->GetItemCount(item,skipItem);
8249 if(skipItem && skipItem->GetProto()->GemProperties)
8251 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8253 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8254 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8255 count += pItem->GetGemCountWithID(item);
8260 return count;
8263 Item* Player::GetItemByGuid( uint64 guid ) const
8265 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8267 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8268 if( pItem && pItem->GetGUID() == guid )
8269 return pItem;
8271 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8273 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8274 if( pItem && pItem->GetGUID() == guid )
8275 return pItem;
8278 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8280 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8281 if( pBag )
8283 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8285 Item* pItem = pBag->GetItemByPos( j );
8286 if( pItem && pItem->GetGUID() == guid )
8287 return pItem;
8291 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8293 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8294 if( pBag )
8296 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8298 Item* pItem = pBag->GetItemByPos( j );
8299 if( pItem && pItem->GetGUID() == guid )
8300 return pItem;
8305 return NULL;
8308 Item* Player::GetItemByPos( uint16 pos ) const
8310 uint8 bag = pos >> 8;
8311 uint8 slot = pos & 255;
8312 return GetItemByPos( bag, slot );
8315 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8317 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8318 return m_items[slot];
8319 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8320 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8322 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8323 if ( pBag )
8324 return pBag->GetItemByPos(slot);
8326 return NULL;
8329 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8331 uint16 slot;
8332 switch (attackType)
8334 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8335 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8336 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8337 default: return NULL;
8340 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8341 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8342 return NULL;
8344 if(!useable)
8345 return item;
8347 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8348 return NULL;
8350 return item;
8353 Item* Player::GetShield(bool useable) const
8355 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8356 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8357 return NULL;
8359 if(!useable)
8360 return item;
8362 if( item->IsBroken())
8363 return NULL;
8365 return item;
8368 uint32 Player::GetAttackBySlot( uint8 slot )
8370 switch(slot)
8372 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8373 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8374 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8375 default: return MAX_ATTACK;
8379 bool Player::HasBankBagSlot( uint8 slot ) const
8381 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8382 if( slot < maxslot )
8383 return true;
8384 return false;
8387 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8389 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8390 return true;
8391 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8392 return true;
8393 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8394 return true;
8395 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8396 return true;
8397 return false;
8400 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8402 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8403 return true;
8404 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8405 return true;
8406 return false;
8409 bool Player::IsBankPos( uint8 bag, uint8 slot )
8411 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8412 return true;
8413 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8414 return true;
8415 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8416 return true;
8417 return false;
8420 bool Player::IsBagPos( uint16 pos )
8422 uint8 bag = pos >> 8;
8423 uint8 slot = pos & 255;
8424 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8425 return true;
8426 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8427 return true;
8428 return false;
8431 bool Player::IsValidPos( uint8 bag, uint8 slot )
8433 // post selected
8434 if(bag == NULL_BAG)
8435 return true;
8437 if (bag == INVENTORY_SLOT_BAG_0)
8439 // any post selected
8440 if (slot == NULL_SLOT)
8441 return true;
8443 // equipment
8444 if (slot < EQUIPMENT_SLOT_END)
8445 return true;
8447 // bag equip slots
8448 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8449 return true;
8451 // backpack slots
8452 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8453 return true;
8455 // keyring slots
8456 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8457 return true;
8459 // bank main slots
8460 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8461 return true;
8463 // bank bag slots
8464 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8465 return true;
8467 return false;
8470 // bag content slots
8471 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8473 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8474 if(!pBag)
8475 return false;
8477 // any post selected
8478 if (slot == NULL_SLOT)
8479 return true;
8481 return slot < pBag->GetBagSize();
8484 // bank bag content slots
8485 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8487 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8488 if(!pBag)
8489 return false;
8491 // any post selected
8492 if (slot == NULL_SLOT)
8493 return true;
8495 return slot < pBag->GetBagSize();
8498 // where this?
8499 return false;
8503 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8505 uint32 tempcount = 0;
8506 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8508 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8509 if( pItem && pItem->GetEntry() == item )
8511 tempcount += pItem->GetCount();
8512 if( tempcount >= count )
8513 return true;
8516 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8518 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8519 if( pItem && pItem->GetEntry() == item )
8521 tempcount += pItem->GetCount();
8522 if( tempcount >= count )
8523 return true;
8526 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8528 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8530 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8532 Item* pItem = GetItemByPos( i, j );
8533 if( pItem && pItem->GetEntry() == item )
8535 tempcount += pItem->GetCount();
8536 if( tempcount >= count )
8537 return true;
8543 if(inBankAlso)
8545 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8547 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8548 if( pItem && pItem->GetEntry() == item )
8550 tempcount += pItem->GetCount();
8551 if( tempcount >= count )
8552 return true;
8555 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8557 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8559 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8561 Item* pItem = GetItemByPos( i, j );
8562 if( pItem && pItem->GetEntry() == item )
8564 tempcount += pItem->GetCount();
8565 if( tempcount >= count )
8566 return true;
8573 return false;
8576 Item* Player::GetItemOrItemWithGemEquipped( uint32 item ) const
8578 Item *pItem;
8579 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8581 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8582 if( pItem && pItem->GetEntry() == item )
8583 return pItem;
8586 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8587 if (pProto && pProto->GemProperties)
8589 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8591 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8592 if( pItem && pItem->GetProto()->Socket[0].Color )
8594 if (pItem->GetGemCountWithID(item) > 0 )
8595 return pItem;
8600 return NULL;
8603 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8605 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8606 if( !pProto )
8608 if(no_space_count)
8609 *no_space_count = count;
8610 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8613 // no maximum
8614 if(pProto->MaxCount <= 0)
8615 return EQUIP_ERR_OK;
8617 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8619 if (curcount + count > uint32(pProto->MaxCount))
8621 if(no_space_count)
8622 *no_space_count = count +curcount - pProto->MaxCount;
8623 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8626 return EQUIP_ERR_OK;
8629 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8631 Item *pItem;
8632 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_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 = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8640 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8641 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8642 return true;
8644 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8646 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8648 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8650 pItem = GetItemByPos( i, j );
8651 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8652 return true;
8656 return false;
8659 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8661 Item* pItem2 = GetItemByPos( bag, slot );
8663 // ignore move item (this slot will be empty at move)
8664 if(pItem2==pSrcItem)
8665 pItem2 = NULL;
8667 uint32 need_space;
8669 // empty specific slot - check item fit to slot
8670 if( !pItem2 || swap )
8672 if( bag == INVENTORY_SLOT_BAG_0 )
8674 // keyring case
8675 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8676 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8678 // vanitypet case (disabled until proper implement)
8679 if(slot >= VANITYPET_SLOT_START && slot < VANITYPET_SLOT_END && !(false /*pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS*/))
8680 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8682 // currencytoken case (disabled until proper implement)
8683 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(false /*pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS*/))
8684 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8686 // guestbag case (disabled until proper implement)
8687 if(slot >= QUESTBAG_SLOT_START && slot < QUESTBAG_SLOT_END && !(false /*pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS*/))
8688 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8690 // prevent cheating
8691 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8692 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8694 else
8696 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8697 if( !pBag )
8698 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8700 ItemPrototype const* pBagProto = pBag->GetProto();
8701 if( !pBagProto )
8702 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8704 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8705 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8708 // non empty stack with space
8709 need_space = pProto->GetMaxStackSize();
8711 // non empty slot, check item type
8712 else
8714 // check item type
8715 if(pItem2->GetEntry() != pProto->ItemId)
8716 return EQUIP_ERR_ITEM_CANT_STACK;
8718 // check free space
8719 if(pItem2->GetCount() >= pProto->GetMaxStackSize())
8720 return EQUIP_ERR_ITEM_CANT_STACK;
8722 // free stack space or infinity
8723 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8726 if(need_space > count)
8727 need_space = count;
8729 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8730 if(!newPosition.isContainedIn(dest))
8732 dest.push_back(newPosition);
8733 count -= need_space;
8735 return EQUIP_ERR_OK;
8738 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
8740 // skip specific bag already processed in first called _CanStoreItem_InBag
8741 if(bag==skip_bag)
8742 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8744 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8745 if( !pBag )
8746 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8748 ItemPrototype const* pBagProto = pBag->GetProto();
8749 if( !pBagProto )
8750 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8752 // specialized bag mode or non-specilized
8753 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8754 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8756 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8757 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8759 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8761 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8762 if(j==skip_slot)
8763 continue;
8765 Item* pItem2 = GetItemByPos( bag, j );
8767 // ignore move item (this slot will be empty at move)
8768 if(pItem2==pSrcItem)
8769 pItem2 = NULL;
8771 // if merge skip empty, if !merge skip non-empty
8772 if((pItem2!=NULL)!=merge)
8773 continue;
8775 if( pItem2 )
8777 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8779 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8780 if(need_space > count)
8781 need_space = count;
8783 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8784 if(!newPosition.isContainedIn(dest))
8786 dest.push_back(newPosition);
8787 count -= need_space;
8789 if(count==0)
8790 return EQUIP_ERR_OK;
8794 else
8796 uint32 need_space = pProto->GetMaxStackSize();
8797 if(need_space > count)
8798 need_space = count;
8800 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8801 if(!newPosition.isContainedIn(dest))
8803 dest.push_back(newPosition);
8804 count -= need_space;
8806 if(count==0)
8807 return EQUIP_ERR_OK;
8811 return EQUIP_ERR_OK;
8814 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
8816 for(uint32 j = slot_begin; j < slot_end; j++)
8818 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8819 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8820 continue;
8822 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8824 // ignore move item (this slot will be empty at move)
8825 if(pItem2==pSrcItem)
8826 pItem2 = NULL;
8828 // if merge skip empty, if !merge skip non-empty
8829 if((pItem2!=NULL)!=merge)
8830 continue;
8832 if( pItem2 )
8834 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8836 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8837 if(need_space > count)
8838 need_space = count;
8839 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8840 if(!newPosition.isContainedIn(dest))
8842 dest.push_back(newPosition);
8843 count -= need_space;
8845 if(count==0)
8846 return EQUIP_ERR_OK;
8850 else
8852 uint32 need_space = pProto->GetMaxStackSize();
8853 if(need_space > count)
8854 need_space = count;
8856 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8857 if(!newPosition.isContainedIn(dest))
8859 dest.push_back(newPosition);
8860 count -= need_space;
8862 if(count==0)
8863 return EQUIP_ERR_OK;
8867 return EQUIP_ERR_OK;
8870 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8872 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8874 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8875 if( !pProto )
8877 if(no_space_count)
8878 *no_space_count = count;
8879 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8882 if(pItem && pItem->IsBindedNotWith(GetGUID()))
8884 if(no_space_count)
8885 *no_space_count = count;
8886 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8889 // check count of items (skip for auto move for same player from bank)
8890 uint32 no_similar_count = 0; // can't store this amount similar items
8891 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8892 if(res!=EQUIP_ERR_OK)
8894 if(count==no_similar_count)
8896 if(no_space_count)
8897 *no_space_count = no_similar_count;
8898 return res;
8900 count -= no_similar_count;
8903 // in specific slot
8904 if( bag != NULL_BAG && slot != NULL_SLOT )
8906 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8907 if(res!=EQUIP_ERR_OK)
8909 if(no_space_count)
8910 *no_space_count = count + no_similar_count;
8911 return res;
8914 if(count==0)
8916 if(no_similar_count==0)
8917 return EQUIP_ERR_OK;
8919 if(no_space_count)
8920 *no_space_count = count + no_similar_count;
8921 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8925 // not specific slot or have space for partly store only in specific slot
8927 // in specific bag
8928 if( bag != NULL_BAG )
8930 // search stack in bag for merge to
8931 if( pProto->Stackable != 1 )
8933 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8935 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8936 if(res!=EQUIP_ERR_OK)
8938 if(no_space_count)
8939 *no_space_count = count + no_similar_count;
8940 return res;
8943 if(count==0)
8945 if(no_similar_count==0)
8946 return EQUIP_ERR_OK;
8948 if(no_space_count)
8949 *no_space_count = count + no_similar_count;
8950 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8953 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8954 if(res!=EQUIP_ERR_OK)
8956 if(no_space_count)
8957 *no_space_count = count + no_similar_count;
8958 return res;
8961 if(count==0)
8963 if(no_similar_count==0)
8964 return EQUIP_ERR_OK;
8966 if(no_space_count)
8967 *no_space_count = count + no_similar_count;
8968 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8971 else // equipped bag
8973 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8974 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
8975 if(res!=EQUIP_ERR_OK)
8976 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
8978 if(res!=EQUIP_ERR_OK)
8980 if(no_space_count)
8981 *no_space_count = count + no_similar_count;
8982 return res;
8985 if(count==0)
8987 if(no_similar_count==0)
8988 return EQUIP_ERR_OK;
8990 if(no_space_count)
8991 *no_space_count = count + no_similar_count;
8992 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8997 // search free slot in bag for place to
8998 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
9000 // search free slot - keyring case
9001 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9003 uint32 keyringSize = GetMaxKeyringSize();
9004 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9005 if(res!=EQUIP_ERR_OK)
9007 if(no_space_count)
9008 *no_space_count = count + no_similar_count;
9009 return res;
9012 if(count==0)
9014 if(no_similar_count==0)
9015 return EQUIP_ERR_OK;
9017 if(no_space_count)
9018 *no_space_count = count + no_similar_count;
9019 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9022 /* until proper implementation
9023 else if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9025 res = _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START,VANITYPET_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9026 if(res!=EQUIP_ERR_OK)
9028 if(no_space_count)
9029 *no_space_count = count + no_similar_count;
9030 return res;
9033 if(count==0)
9035 if(no_similar_count==0)
9036 return EQUIP_ERR_OK;
9038 if(no_space_count)
9039 *no_space_count = count + no_similar_count;
9040 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9044 /* until proper implementation
9045 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9047 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9048 if(res!=EQUIP_ERR_OK)
9050 if(no_space_count)
9051 *no_space_count = count + no_similar_count;
9052 return res;
9055 if(count==0)
9057 if(no_similar_count==0)
9058 return EQUIP_ERR_OK;
9060 if(no_space_count)
9061 *no_space_count = count + no_similar_count;
9062 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9066 /* until proper implementation
9067 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9069 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9070 if(res!=EQUIP_ERR_OK)
9072 if(no_space_count)
9073 *no_space_count = count + no_similar_count;
9074 return res;
9077 if(count==0)
9079 if(no_similar_count==0)
9080 return EQUIP_ERR_OK;
9082 if(no_space_count)
9083 *no_space_count = count + no_similar_count;
9084 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9089 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9090 if(res!=EQUIP_ERR_OK)
9092 if(no_space_count)
9093 *no_space_count = count + no_similar_count;
9094 return res;
9097 if(count==0)
9099 if(no_similar_count==0)
9100 return EQUIP_ERR_OK;
9102 if(no_space_count)
9103 *no_space_count = count + no_similar_count;
9104 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9107 else // equipped bag
9109 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9110 if(res!=EQUIP_ERR_OK)
9111 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9113 if(res!=EQUIP_ERR_OK)
9115 if(no_space_count)
9116 *no_space_count = count + no_similar_count;
9117 return res;
9120 if(count==0)
9122 if(no_similar_count==0)
9123 return EQUIP_ERR_OK;
9125 if(no_space_count)
9126 *no_space_count = count + no_similar_count;
9127 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9132 // not specific bag or have space for partly store only in specific bag
9134 // search stack for merge to
9135 if( pProto->Stackable != 1 )
9137 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9138 if(res!=EQUIP_ERR_OK)
9140 if(no_space_count)
9141 *no_space_count = count + no_similar_count;
9142 return res;
9145 if(count==0)
9147 if(no_similar_count==0)
9148 return EQUIP_ERR_OK;
9150 if(no_space_count)
9151 *no_space_count = count + no_similar_count;
9152 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9155 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9156 if(res!=EQUIP_ERR_OK)
9158 if(no_space_count)
9159 *no_space_count = count + no_similar_count;
9160 return res;
9163 if(count==0)
9165 if(no_similar_count==0)
9166 return EQUIP_ERR_OK;
9168 if(no_space_count)
9169 *no_space_count = count + no_similar_count;
9170 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9173 if( pProto->BagFamily )
9175 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9177 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9178 if(res!=EQUIP_ERR_OK)
9179 continue;
9181 if(count==0)
9183 if(no_similar_count==0)
9184 return EQUIP_ERR_OK;
9186 if(no_space_count)
9187 *no_space_count = count + no_similar_count;
9188 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9193 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9195 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9196 if(res!=EQUIP_ERR_OK)
9197 continue;
9199 if(count==0)
9201 if(no_similar_count==0)
9202 return EQUIP_ERR_OK;
9204 if(no_space_count)
9205 *no_space_count = count + no_similar_count;
9206 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9211 // search free slot - special bag case
9212 if( pProto->BagFamily )
9214 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9216 uint32 keyringSize = GetMaxKeyringSize();
9217 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9218 if(res!=EQUIP_ERR_OK)
9220 if(no_space_count)
9221 *no_space_count = count + no_similar_count;
9222 return res;
9225 if(count==0)
9227 if(no_similar_count==0)
9228 return EQUIP_ERR_OK;
9230 if(no_space_count)
9231 *no_space_count = count + no_similar_count;
9232 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9235 /* until proper implementation
9236 else if(false pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9238 res = _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START,VANITYPET_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9239 if(res!=EQUIP_ERR_OK)
9241 if(no_space_count)
9242 *no_space_count = count + no_similar_count;
9243 return res;
9246 if(count==0)
9248 if(no_similar_count==0)
9249 return EQUIP_ERR_OK;
9251 if(no_space_count)
9252 *no_space_count = count + no_similar_count;
9253 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9257 /* until proper implementation
9258 else if(false pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9260 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9261 if(res!=EQUIP_ERR_OK)
9263 if(no_space_count)
9264 *no_space_count = count + no_similar_count;
9265 return res;
9268 if(count==0)
9270 if(no_similar_count==0)
9271 return EQUIP_ERR_OK;
9273 if(no_space_count)
9274 *no_space_count = count + no_similar_count;
9275 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9279 /* until proper implementation
9280 else if(false pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9282 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9283 if(res!=EQUIP_ERR_OK)
9285 if(no_space_count)
9286 *no_space_count = count + no_similar_count;
9287 return res;
9290 if(count==0)
9292 if(no_similar_count==0)
9293 return EQUIP_ERR_OK;
9295 if(no_space_count)
9296 *no_space_count = count + no_similar_count;
9297 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9302 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9304 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9305 if(res!=EQUIP_ERR_OK)
9306 continue;
9308 if(count==0)
9310 if(no_similar_count==0)
9311 return EQUIP_ERR_OK;
9313 if(no_space_count)
9314 *no_space_count = count + no_similar_count;
9315 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9320 // search free slot
9321 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9322 if(res!=EQUIP_ERR_OK)
9324 if(no_space_count)
9325 *no_space_count = count + no_similar_count;
9326 return res;
9329 if(count==0)
9331 if(no_similar_count==0)
9332 return EQUIP_ERR_OK;
9334 if(no_space_count)
9335 *no_space_count = count + no_similar_count;
9336 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9339 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9341 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9342 if(res!=EQUIP_ERR_OK)
9343 continue;
9345 if(count==0)
9347 if(no_similar_count==0)
9348 return EQUIP_ERR_OK;
9350 if(no_space_count)
9351 *no_space_count = count + no_similar_count;
9352 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9356 if(no_space_count)
9357 *no_space_count = count + no_similar_count;
9359 return EQUIP_ERR_INVENTORY_FULL;
9362 //////////////////////////////////////////////////////////////////////////
9363 uint8 Player::CanStoreItems( Item **pItems,int count) const
9365 Item *pItem2;
9367 // fill space table
9368 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9369 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9370 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9371 int inv_pets[VANITYPET_SLOT_END-VANITYPET_SLOT_START];
9372 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9373 int inv_quests[QUESTBAG_SLOT_END-QUESTBAG_SLOT_START];
9375 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9376 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9377 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9378 memset(inv_pets,0,sizeof(int)*(VANITYPET_SLOT_END-VANITYPET_SLOT_START));
9379 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9380 memset(inv_quests,0,sizeof(int)*(QUESTBAG_SLOT_END-QUESTBAG_SLOT_START));
9382 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
9384 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9386 if (pItem2 && !pItem2->IsInTrade())
9388 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9392 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
9394 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9396 if (pItem2 && !pItem2->IsInTrade())
9398 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9402 for(int i = VANITYPET_SLOT_START; i < VANITYPET_SLOT_END; i++)
9404 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9406 if (pItem2 && !pItem2->IsInTrade())
9408 inv_pets[i-VANITYPET_SLOT_START] = pItem2->GetCount();
9412 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; i++)
9414 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9416 if (pItem2 && !pItem2->IsInTrade())
9418 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9422 for(int i = QUESTBAG_SLOT_START; i < QUESTBAG_SLOT_END; i++)
9424 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9426 if (pItem2 && !pItem2->IsInTrade())
9428 inv_quests[i-QUESTBAG_SLOT_START] = pItem2->GetCount();
9432 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9434 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9436 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9438 pItem2 = GetItemByPos( i, j );
9439 if (pItem2 && !pItem2->IsInTrade())
9441 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9447 // check free space for all items
9448 for (int k=0;k<count;k++)
9450 Item *pItem = pItems[k];
9452 // no item
9453 if (!pItem) continue;
9455 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9456 ItemPrototype const *pProto = pItem->GetProto();
9458 // strange item
9459 if( !pProto )
9460 return EQUIP_ERR_ITEM_NOT_FOUND;
9462 // item it 'bind'
9463 if(pItem->IsBindedNotWith(GetGUID()))
9464 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9466 Bag *pBag;
9467 ItemPrototype const *pBagProto;
9469 // item is 'one item only'
9470 uint8 res = CanTakeMoreSimilarItems(pItem);
9471 if(res != EQUIP_ERR_OK)
9472 return res;
9474 // search stack for merge to
9475 if( pProto->Stackable != 1 )
9477 bool b_found = false;
9479 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
9481 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9482 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9484 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9485 b_found = true;
9486 break;
9489 if (b_found) continue;
9491 for(int t = VANITYPET_SLOT_START; t < VANITYPET_SLOT_END; t++)
9493 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9494 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_pets[t-VANITYPET_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9496 inv_pets[t-VANITYPET_SLOT_START] += pItem->GetCount();
9497 b_found = true;
9498 break;
9501 if (b_found) continue;
9503 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; t++)
9505 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9506 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9508 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9509 b_found = true;
9510 break;
9513 if (b_found) continue;
9515 for(int t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; t++)
9517 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9518 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_quests[t-QUESTBAG_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9520 inv_quests[t-QUESTBAG_SLOT_START] += pItem->GetCount();
9521 b_found = true;
9522 break;
9525 if (b_found) continue;
9527 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9529 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9530 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9532 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9533 b_found = true;
9534 break;
9537 if (b_found) continue;
9539 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9541 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9542 if( pBag )
9544 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9546 pItem2 = GetItemByPos( t, j );
9547 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9549 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9550 b_found = true;
9551 break;
9556 if (b_found) continue;
9559 // special bag case
9560 if( pProto->BagFamily )
9562 bool b_found = false;
9563 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9565 uint32 keyringSize = GetMaxKeyringSize();
9566 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9568 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9570 inv_keys[t-KEYRING_SLOT_START] = 1;
9571 b_found = true;
9572 break;
9577 if (b_found) continue;
9579 /* until proper implementation
9580 if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9582 for(uint32 t = VANITYPET_SLOT_START; t < VANITYPET_SLOT_END; ++t)
9584 if( inv_pets[t-VANITYPET_SLOT_START] == 0 )
9586 inv_pets[t-VANITYPET_SLOT_START] = 1;
9587 b_found = true;
9588 break;
9593 if (b_found) continue;
9595 /* until proper implementation
9596 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9598 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9600 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9602 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9603 b_found = true;
9604 break;
9609 if (b_found) continue;
9611 /* until proper implementation
9612 if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9614 for(uint32 t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; ++t)
9616 if( inv_quests[t-QUESTBAG_SLOT_START] == 0 )
9618 inv_quests[t-QUESTBAG_SLOT_START] = 1;
9619 b_found = true;
9620 break;
9625 if (b_found) continue;
9628 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9630 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9631 if( pBag )
9633 pBagProto = pBag->GetProto();
9635 // not plain container check
9636 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9637 ItemCanGoIntoBag(pProto,pBagProto) )
9639 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9641 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9643 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9644 b_found = true;
9645 break;
9651 if (b_found) continue;
9654 // search free slot
9655 bool b_found = false;
9656 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9658 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9660 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9661 b_found = true;
9662 break;
9665 if (b_found) continue;
9667 // search free slot in bags
9668 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9670 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9671 if( pBag )
9673 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9675 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9677 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9678 b_found = true;
9679 break;
9685 // no free slot found?
9686 if (!b_found)
9687 return EQUIP_ERR_INVENTORY_FULL;
9690 return EQUIP_ERR_OK;
9693 //////////////////////////////////////////////////////////////////////////
9694 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9696 dest = 0;
9697 Item *pItem = Item::CreateItem( item, 1, this );
9698 if( pItem )
9700 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9701 delete pItem;
9702 return result;
9705 return EQUIP_ERR_ITEM_NOT_FOUND;
9708 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9710 dest = 0;
9711 if( pItem )
9713 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9714 ItemPrototype const *pProto = pItem->GetProto();
9715 if( pProto )
9717 // May be here should be more stronger checks; STUNNED checked
9718 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9719 if (not_loading && hasUnitState(UNIT_STAT_STUNNED))
9720 return EQUIP_ERR_YOU_ARE_STUNNED;
9722 if(pItem->IsBindedNotWith(GetGUID()))
9723 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9725 // check count of items (skip for auto move for same player from bank)
9726 uint8 res = CanTakeMoreSimilarItems(pItem);
9727 if(res != EQUIP_ERR_OK)
9728 return res;
9730 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9731 // - combat
9732 // - in-progress arenas
9733 if( !pProto->CanChangeEquipStateInCombat() )
9735 if( isInCombat() )
9736 return EQUIP_ERR_NOT_IN_COMBAT;
9738 if(BattleGround* bg = GetBattleGround())
9739 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9740 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9743 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9744 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9746 if(IsNonMeleeSpellCasted(false))
9747 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9749 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9750 if( eslot == NULL_SLOT )
9751 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9753 uint8 msg = CanUseItem( pItem , not_loading );
9754 if( msg != EQUIP_ERR_OK )
9755 return msg;
9756 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9757 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9759 // check unique-equipped on item
9760 if (pProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
9762 // there is an equip limit on this item
9763 Item* tItem = GetItemOrItemWithGemEquipped(pProto->ItemId);
9764 if (tItem && (!swap || tItem->GetSlot() != eslot ) )
9765 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9768 // check unique-equipped on gems
9769 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
9771 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
9772 if(!enchant_id)
9773 continue;
9774 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
9775 if(!enchantEntry)
9776 continue;
9778 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
9779 if(pGem && (pGem->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED))
9781 Item* tItem = GetItemOrItemWithGemEquipped(enchantEntry->GemID);
9782 if(tItem && (!swap || tItem->GetSlot() != eslot ))
9783 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9787 // check unique-equipped special item classes
9788 if (pProto->Class == ITEM_CLASS_QUIVER)
9790 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9792 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9794 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9796 if( pBagProto->Class==pProto->Class && pBagProto->SubClass==pProto->SubClass &&
9797 (!swap || pBag->GetSlot() != eslot ) )
9799 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9800 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9801 else
9802 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9809 uint32 type = pProto->InventoryType;
9811 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9813 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9815 if(!CanDualWield())
9816 return EQUIP_ERR_CANT_DUAL_WIELD;
9818 else if (type == INVTYPE_2HWEAPON)
9820 if(!CanDualWield() || !CanTitanGrip())
9821 return EQUIP_ERR_CANT_DUAL_WIELD;
9824 if(IsTwoHandUsed())
9825 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9828 // equip two-hand weapon case (with possible unequip 2 items)
9829 if( type == INVTYPE_2HWEAPON )
9831 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9833 if (!CanTitanGrip())
9834 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9836 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9837 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9839 if (!CanTitanGrip())
9841 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9842 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9843 ItemPosCountVec off_dest;
9844 if( offItem && (!not_loading ||
9845 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9846 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
9847 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9850 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9851 return EQUIP_ERR_OK;
9854 if( !swap )
9855 return EQUIP_ERR_ITEM_NOT_FOUND;
9856 else
9857 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9860 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9862 // Applied only to equipped items and bank bags
9863 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9864 return EQUIP_ERR_OK;
9866 Item* pItem = GetItemByPos(pos);
9868 // Applied only to existed equipped item
9869 if( !pItem )
9870 return EQUIP_ERR_OK;
9872 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9874 ItemPrototype const *pProto = pItem->GetProto();
9875 if( !pProto )
9876 return EQUIP_ERR_ITEM_NOT_FOUND;
9878 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9879 // - combat
9880 // - in-progress arenas
9881 if( !pProto->CanChangeEquipStateInCombat() )
9883 if( isInCombat() )
9884 return EQUIP_ERR_NOT_IN_COMBAT;
9886 if(BattleGround* bg = GetBattleGround())
9887 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9888 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9891 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9892 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9894 return EQUIP_ERR_OK;
9897 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9899 if( !pItem )
9900 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9902 uint32 count = pItem->GetCount();
9904 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9905 ItemPrototype const *pProto = pItem->GetProto();
9906 if( !pProto )
9907 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9909 if( pItem->IsBindedNotWith(GetGUID()) )
9910 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9912 // check count of items (skip for auto move for same player from bank)
9913 uint8 res = CanTakeMoreSimilarItems(pItem);
9914 if(res != EQUIP_ERR_OK)
9915 return res;
9917 // in specific slot
9918 if( bag != NULL_BAG && slot != NULL_SLOT )
9920 if( pProto->InventoryType == INVTYPE_BAG )
9922 Bag *pBag = (Bag*)pItem;
9923 if( pBag )
9925 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9927 if( !HasBankBagSlot( slot ) )
9928 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9929 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
9930 return cantuse;
9932 else
9934 if( !pBag->IsEmpty() )
9935 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9939 else
9941 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9942 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9945 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9946 if(res!=EQUIP_ERR_OK)
9947 return res;
9949 if(count==0)
9950 return EQUIP_ERR_OK;
9953 // not specific slot or have space for partly store only in specific slot
9955 // in specific bag
9956 if( bag != NULL_BAG )
9958 if( pProto->InventoryType == INVTYPE_BAG )
9960 Bag *pBag = (Bag*)pItem;
9961 if( pBag && !pBag->IsEmpty() )
9962 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9965 // search stack in bag for merge to
9966 if( pProto->Stackable != 1 )
9968 if( bag == INVENTORY_SLOT_BAG_0 )
9970 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9971 if(res!=EQUIP_ERR_OK)
9972 return res;
9974 if(count==0)
9975 return EQUIP_ERR_OK;
9977 else
9979 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9980 if(res!=EQUIP_ERR_OK)
9981 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9983 if(res!=EQUIP_ERR_OK)
9984 return res;
9986 if(count==0)
9987 return EQUIP_ERR_OK;
9991 // search free slot in bag
9992 if( bag == INVENTORY_SLOT_BAG_0 )
9994 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9995 if(res!=EQUIP_ERR_OK)
9996 return res;
9998 if(count==0)
9999 return EQUIP_ERR_OK;
10001 else
10003 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
10004 if(res!=EQUIP_ERR_OK)
10005 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
10007 if(res!=EQUIP_ERR_OK)
10008 return res;
10010 if(count==0)
10011 return EQUIP_ERR_OK;
10015 // not specific bag or have space for partly store only in specific bag
10017 // search stack for merge to
10018 if( pProto->Stackable != 1 )
10020 // in slots
10021 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10022 if(res!=EQUIP_ERR_OK)
10023 return res;
10025 if(count==0)
10026 return EQUIP_ERR_OK;
10028 // in special bags
10029 if( pProto->BagFamily )
10031 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10033 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
10034 if(res!=EQUIP_ERR_OK)
10035 continue;
10037 if(count==0)
10038 return EQUIP_ERR_OK;
10042 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10044 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
10045 if(res!=EQUIP_ERR_OK)
10046 continue;
10048 if(count==0)
10049 return EQUIP_ERR_OK;
10053 // search free place in special bag
10054 if( pProto->BagFamily )
10056 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10058 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
10059 if(res!=EQUIP_ERR_OK)
10060 continue;
10062 if(count==0)
10063 return EQUIP_ERR_OK;
10067 // search free space
10068 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10069 if(res!=EQUIP_ERR_OK)
10070 return res;
10072 if(count==0)
10073 return EQUIP_ERR_OK;
10075 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10077 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
10078 if(res!=EQUIP_ERR_OK)
10079 continue;
10081 if(count==0)
10082 return EQUIP_ERR_OK;
10084 return EQUIP_ERR_BANK_FULL;
10087 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
10089 if( pItem )
10091 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
10092 if( !isAlive() && not_loading )
10093 return EQUIP_ERR_YOU_ARE_DEAD;
10094 //if( isStunned() )
10095 // return EQUIP_ERR_YOU_ARE_STUNNED;
10096 ItemPrototype const *pProto = pItem->GetProto();
10097 if( pProto )
10099 if( pItem->IsBindedNotWith(GetGUID()) )
10100 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10101 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10102 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10103 if( pItem->GetSkill() != 0 )
10105 if( GetSkillValue( pItem->GetSkill() ) == 0 )
10106 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10108 if( pProto->RequiredSkill != 0 )
10110 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10111 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10112 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10113 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10115 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10116 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10117 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
10118 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10119 if( getLevel() < pProto->RequiredLevel )
10120 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10121 return EQUIP_ERR_OK;
10124 return EQUIP_ERR_ITEM_NOT_FOUND;
10127 bool Player::CanUseItem( ItemPrototype const *pProto )
10129 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10131 if( pProto )
10133 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10134 return false;
10135 if( pProto->RequiredSkill != 0 )
10137 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10138 return false;
10139 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10140 return false;
10142 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10143 return false;
10144 if( getLevel() < pProto->RequiredLevel )
10145 return false;
10146 return true;
10148 return false;
10151 uint8 Player::CanUseAmmo( uint32 item ) const
10153 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10154 if( !isAlive() )
10155 return EQUIP_ERR_YOU_ARE_DEAD;
10156 //if( isStunned() )
10157 // return EQUIP_ERR_YOU_ARE_STUNNED;
10158 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
10159 if( pProto )
10161 if( pProto->InventoryType!= INVTYPE_AMMO )
10162 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10163 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10164 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10165 if( pProto->RequiredSkill != 0 )
10167 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10168 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10169 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10170 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10172 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10173 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10174 /*if( GetReputation() < pProto->RequiredReputation )
10175 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10177 if( getLevel() < pProto->RequiredLevel )
10178 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10180 // Requires No Ammo
10181 if(GetDummyAura(46699))
10182 return EQUIP_ERR_BAG_FULL6;
10184 return EQUIP_ERR_OK;
10186 return EQUIP_ERR_ITEM_NOT_FOUND;
10189 void Player::SetAmmo( uint32 item )
10191 if(!item)
10192 return;
10194 // already set
10195 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10196 return;
10198 // check ammo
10199 if(item)
10201 uint8 msg = CanUseAmmo( item );
10202 if( msg != EQUIP_ERR_OK )
10204 SendEquipError( msg, NULL, NULL );
10205 return;
10209 SetUInt32Value(PLAYER_AMMO_ID, item);
10211 _ApplyAmmoBonuses();
10214 void Player::RemoveAmmo()
10216 SetUInt32Value(PLAYER_AMMO_ID, 0);
10218 m_ammoDPS = 0.0f;
10220 if(CanModifyStats())
10221 UpdateDamagePhysical(RANGED_ATTACK);
10224 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10225 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10227 uint32 count = 0;
10228 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10229 count += itr->count;
10231 Item *pItem = Item::CreateItem( item, count, this );
10232 if( pItem )
10234 ItemAddedQuestCheck( item, count );
10235 if(randomPropertyId)
10236 pItem->SetItemRandomProperties(randomPropertyId);
10237 pItem = StoreItem( dest, pItem, update );
10239 return pItem;
10242 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10244 if( !pItem )
10245 return NULL;
10247 Item* lastItem = pItem;
10249 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10251 uint16 pos = itr->pos;
10252 uint32 count = itr->count;
10254 ++itr;
10256 if(itr == dest.end())
10258 lastItem = _StoreItem(pos,pItem,count,false,update);
10259 break;
10262 lastItem = _StoreItem(pos,pItem,count,true,update);
10265 return lastItem;
10268 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10269 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10271 if( !pItem )
10272 return NULL;
10274 uint8 bag = pos >> 8;
10275 uint8 slot = pos & 255;
10277 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10279 Item *pItem2 = GetItemByPos( bag, slot );
10281 if( !pItem2 )
10283 if(clone)
10284 pItem = pItem->CloneItem(count,this);
10285 else
10286 pItem->SetCount(count);
10288 if(!pItem)
10289 return NULL;
10291 if( pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10292 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10293 pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10294 pItem->SetBinding( true );
10296 if( bag == INVENTORY_SLOT_BAG_0 )
10298 m_items[slot] = pItem;
10299 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10300 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10301 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10303 pItem->SetSlot( slot );
10304 pItem->SetContainer( NULL );
10306 if( IsInWorld() && update )
10308 pItem->AddToWorld();
10309 pItem->SendUpdateToPlayer( this );
10312 pItem->SetState(ITEM_CHANGED, this);
10314 else
10316 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10317 if( pBag )
10319 pBag->StoreItem( slot, pItem, update );
10320 if( IsInWorld() && update )
10322 pItem->AddToWorld();
10323 pItem->SendUpdateToPlayer( this );
10325 pItem->SetState(ITEM_CHANGED, this);
10326 pBag->SetState(ITEM_CHANGED, this);
10330 AddEnchantmentDurations(pItem);
10331 AddItemDurations(pItem);
10333 return pItem;
10335 else
10337 if( pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10338 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10339 pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10340 pItem2->SetBinding( true );
10342 pItem2->SetCount( pItem2->GetCount() + count );
10343 if( IsInWorld() && update )
10344 pItem2->SendUpdateToPlayer( this );
10346 if(!clone)
10348 // delete item (it not in any slot currently)
10349 if( IsInWorld() && update )
10351 pItem->RemoveFromWorld();
10352 pItem->DestroyForPlayer( this );
10355 RemoveEnchantmentDurations(pItem);
10356 RemoveItemDurations(pItem);
10358 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10359 pItem->SetState(ITEM_REMOVED, this);
10361 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10362 AddEnchantmentDurations(pItem2);
10364 pItem2->SetState(ITEM_CHANGED, this);
10366 return pItem2;
10370 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10372 Item *pItem = Item::CreateItem( item, 1, this );
10373 if( pItem )
10375 ItemAddedQuestCheck( item, 1 );
10376 Item * retItem = EquipItem( pos, pItem, update );
10378 return retItem;
10380 return NULL;
10383 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10385 if( pItem )
10387 AddEnchantmentDurations(pItem);
10388 AddItemDurations(pItem);
10390 uint8 bag = pos >> 8;
10391 uint8 slot = pos & 255;
10393 Item *pItem2 = GetItemByPos( bag, slot );
10395 if( !pItem2 )
10397 VisualizeItem( slot, pItem);
10399 if(isAlive())
10401 ItemPrototype const *pProto = pItem->GetProto();
10403 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10404 if(pProto && pProto->ItemSet)
10405 AddItemsSetItem(this,pItem);
10407 _ApplyItemMods(pItem, slot, true);
10409 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10411 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10413 if (getClass() == CLASS_ROGUE)
10414 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10416 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10418 if (!spellProto)
10419 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10420 else
10422 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10424 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10425 data << uint64(GetGUID());
10426 data << uint8(1);
10427 data << uint32(cooldownSpell);
10428 data << uint32(0);
10429 GetSession()->SendPacket(&data);
10434 if( IsInWorld() && update )
10436 pItem->AddToWorld();
10437 pItem->SendUpdateToPlayer( this );
10440 ApplyEquipCooldown(pItem);
10442 if( slot == EQUIPMENT_SLOT_MAINHAND )
10443 UpdateExpertise(BASE_ATTACK);
10444 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10445 UpdateExpertise(OFF_ATTACK);
10447 else
10449 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10450 if( IsInWorld() && update )
10451 pItem2->SendUpdateToPlayer( this );
10453 // delete item (it not in any slot currently)
10454 //pItem->DeleteFromDB();
10455 if( IsInWorld() && update )
10457 pItem->RemoveFromWorld();
10458 pItem->DestroyForPlayer( this );
10461 RemoveEnchantmentDurations(pItem);
10462 RemoveItemDurations(pItem);
10464 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10465 pItem->SetState(ITEM_REMOVED, this);
10466 pItem2->SetState(ITEM_CHANGED, this);
10468 ApplyEquipCooldown(pItem2);
10470 return pItem2;
10474 return pItem;
10477 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10479 if( pItem )
10481 AddEnchantmentDurations(pItem);
10482 AddItemDurations(pItem);
10484 uint8 slot = pos & 255;
10485 VisualizeItem( slot, pItem);
10487 if( IsInWorld() )
10489 pItem->AddToWorld();
10490 pItem->SendUpdateToPlayer( this );
10495 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10497 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10498 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10499 // entry // Size: 1
10500 // inspected enchantments // Size: 6
10501 // ? // Size: 5
10502 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10503 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10504 // // = 16
10506 if(pItem)
10508 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10510 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10511 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10513 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10514 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10516 // Use SetInt16Value to prevent set high part to FFFF for negative value
10517 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10518 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10520 else
10522 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10524 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10525 SetUInt32Value(VisibleBase + 0, 0);
10527 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10528 SetUInt32Value(VisibleBase + 1 + i, 0);
10530 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10531 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10535 void Player::VisualizeItem( uint8 slot, Item *pItem)
10537 if(!pItem)
10538 return;
10540 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10541 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10542 pItem->SetBinding( true );
10544 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10546 m_items[slot] = pItem;
10547 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10548 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10549 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10550 pItem->SetSlot( slot );
10551 pItem->SetContainer( NULL );
10553 if( slot < EQUIPMENT_SLOT_END )
10554 SetVisibleItemSlot(slot,pItem);
10556 pItem->SetState(ITEM_CHANGED, this);
10559 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10561 // note: removeitem does not actually change the item
10562 // it only takes the item out of storage temporarily
10563 // note2: if removeitem is to be used for delinking
10564 // the item must be removed from the player's updatequeue
10566 Item *pItem = GetItemByPos( bag, slot );
10567 if( pItem )
10569 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10571 RemoveEnchantmentDurations(pItem);
10572 RemoveItemDurations(pItem);
10574 if( bag == INVENTORY_SLOT_BAG_0 )
10576 if ( slot < INVENTORY_SLOT_BAG_END )
10578 ItemPrototype const *pProto = pItem->GetProto();
10579 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10581 if(pProto && pProto->ItemSet)
10582 RemoveItemsSetItem(this,pProto);
10584 _ApplyItemMods(pItem, slot, false);
10586 // remove item dependent auras and casts (only weapon and armor slots)
10587 if(slot < EQUIPMENT_SLOT_END)
10588 RemoveItemDependentAurasAndCasts(pItem);
10590 // remove held enchantments
10591 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10593 if (pItem->GetItemSuffixFactor())
10595 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10596 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10598 else
10600 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10601 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10606 m_items[slot] = NULL;
10607 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10609 if ( slot < EQUIPMENT_SLOT_END )
10610 SetVisibleItemSlot(slot,NULL);
10612 else
10614 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10615 if( pBag )
10616 pBag->RemoveItem(slot, update);
10618 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10619 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10620 pItem->SetSlot( NULL_SLOT );
10621 if( IsInWorld() && update )
10622 pItem->SendUpdateToPlayer( this );
10624 if( slot == EQUIPMENT_SLOT_MAINHAND )
10625 UpdateExpertise(BASE_ATTACK);
10626 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10627 UpdateExpertise(OFF_ATTACK);
10631 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10632 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10634 if(Item* it = GetItemByPos(bag,slot))
10636 ItemRemovedQuestCheck(it->GetEntry(),it->GetCount());
10637 RemoveItem( bag,slot,update);
10638 it->RemoveFromUpdateQueueOf(this);
10639 if(it->IsInWorld())
10641 it->RemoveFromWorld();
10642 it->DestroyForPlayer( this );
10647 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10648 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10650 // update quest counters
10651 ItemAddedQuestCheck(pItem->GetEntry(),pItem->GetCount());
10653 // store item
10654 Item* pLastItem = StoreItem( dest, pItem, update);
10656 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10657 if(pLastItem==pItem)
10659 // update owner for last item (this can be original item with wrong owner
10660 if(pLastItem->GetOwnerGUID() != GetGUID())
10661 pLastItem->SetOwnerGUID(GetGUID());
10663 // if this original item then it need create record in inventory
10664 // in case trade we already have item in other player inventory
10665 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10669 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10671 Item *pItem = GetItemByPos( bag, slot );
10672 if( pItem )
10674 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10676 // start from destroy contained items (only equipped bag can have its)
10677 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10679 for (int i = 0; i < MAX_BAG_SIZE; i++)
10680 DestroyItem(slot,i,update);
10683 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10684 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10686 RemoveEnchantmentDurations(pItem);
10687 RemoveItemDurations(pItem);
10689 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10691 if( bag == INVENTORY_SLOT_BAG_0 )
10693 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10695 // equipment and equipped bags can have applied bonuses
10696 if ( slot < INVENTORY_SLOT_BAG_END )
10698 ItemPrototype const *pProto = pItem->GetProto();
10700 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10701 if(pProto && pProto->ItemSet)
10702 RemoveItemsSetItem(this,pProto);
10704 _ApplyItemMods(pItem, slot, false);
10707 if ( slot < EQUIPMENT_SLOT_END )
10709 // remove item dependent auras and casts (only weapon and armor slots)
10710 RemoveItemDependentAurasAndCasts(pItem);
10712 // equipment visual show
10713 SetVisibleItemSlot(slot,NULL);
10716 m_items[slot] = NULL;
10718 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10719 pBag->RemoveItem(slot, update);
10721 if( IsInWorld() && update )
10723 pItem->RemoveFromWorld();
10724 pItem->DestroyForPlayer(this);
10727 //pItem->SetOwnerGUID(0);
10728 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10729 pItem->SetSlot( NULL_SLOT );
10730 pItem->SetState(ITEM_REMOVED, this);
10734 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10736 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10737 Item *pItem;
10738 ItemPrototype const *pProto;
10739 uint32 remcount = 0;
10741 // in inventory
10742 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10744 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10745 if( pItem && pItem->GetEntry() == item )
10747 if( pItem->GetCount() + remcount <= count )
10749 // all items in inventory can unequipped
10750 remcount += pItem->GetCount();
10751 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10753 if(remcount >=count)
10754 return;
10756 else
10758 pProto = pItem->GetProto();
10759 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10760 pItem->SetCount( pItem->GetCount() - count + remcount );
10761 if( IsInWorld() & update )
10762 pItem->SendUpdateToPlayer( this );
10763 pItem->SetState(ITEM_CHANGED, this);
10764 return;
10768 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10770 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10771 if( pItem && pItem->GetEntry() == item )
10773 if( pItem->GetCount() + remcount <= count )
10775 // all keys can be unequipped
10776 remcount += pItem->GetCount();
10777 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10779 if(remcount >=count)
10780 return;
10782 else
10784 pProto = pItem->GetProto();
10785 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10786 pItem->SetCount( pItem->GetCount() - count + remcount );
10787 if( IsInWorld() & update )
10788 pItem->SendUpdateToPlayer( this );
10789 pItem->SetState(ITEM_CHANGED, this);
10790 return;
10795 // in inventory bags
10796 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10798 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10800 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10802 pItem = pBag->GetItemByPos(j);
10803 if( pItem && pItem->GetEntry() == item )
10805 // all items in bags can be unequipped
10806 if( pItem->GetCount() + remcount <= count )
10808 remcount += pItem->GetCount();
10809 DestroyItem( i, j, update );
10811 if(remcount >=count)
10812 return;
10814 else
10816 pProto = pItem->GetProto();
10817 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10818 pItem->SetCount( pItem->GetCount() - count + remcount );
10819 if( IsInWorld() && update )
10820 pItem->SendUpdateToPlayer( this );
10821 pItem->SetState(ITEM_CHANGED, this);
10822 return;
10829 // in equipment and bag list
10830 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10832 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10833 if( pItem && pItem->GetEntry() == item )
10835 if( pItem->GetCount() + remcount <= count )
10837 if(!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
10839 remcount += pItem->GetCount();
10840 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10842 if(remcount >=count)
10843 return;
10846 else
10848 pProto = pItem->GetProto();
10849 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10850 pItem->SetCount( pItem->GetCount() - count + remcount );
10851 if( IsInWorld() & update )
10852 pItem->SendUpdateToPlayer( this );
10853 pItem->SetState(ITEM_CHANGED, this);
10854 return;
10860 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10862 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10864 // in inventory
10865 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_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);
10871 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10873 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10874 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10875 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10878 // in inventory bags
10879 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10881 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10882 if( pBag )
10884 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10886 Item* pItem = pBag->GetItemByPos(j);
10887 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10888 DestroyItem( i, j, update);
10893 // in equipment and bag list
10894 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10896 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10897 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10898 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10902 void Player::DestroyConjuredItems( bool update )
10904 // used when entering arena
10905 // destroys all conjured items
10906 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10908 // in inventory
10909 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10911 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10912 if( pItem && pItem->GetProto() &&
10913 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10914 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10915 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10918 // in inventory bags
10919 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10921 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10922 if( pBag )
10924 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10926 Item* pItem = pBag->GetItemByPos(j);
10927 if( pItem && pItem->GetProto() &&
10928 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10929 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10930 DestroyItem( i, j, update);
10935 // in equipment and bag list
10936 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10938 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10939 if( pItem && pItem->GetProto() &&
10940 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10941 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10942 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10946 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10948 if(!pItem)
10949 return;
10951 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10953 if( pItem->GetCount() <= count )
10955 count-= pItem->GetCount();
10957 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10959 else
10961 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10962 pItem->SetCount( pItem->GetCount() - count );
10963 count = 0;
10964 if( IsInWorld() & update )
10965 pItem->SendUpdateToPlayer( this );
10966 pItem->SetState(ITEM_CHANGED, this);
10970 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10972 uint8 srcbag = src >> 8;
10973 uint8 srcslot = src & 255;
10975 uint8 dstbag = dst >> 8;
10976 uint8 dstslot = dst & 255;
10978 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10979 if( !pSrcItem )
10981 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10982 return;
10985 // not let split all items (can be only at cheating)
10986 if(pSrcItem->GetCount() == count)
10988 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10989 return;
10992 // not let split more existed items (can be only at cheating)
10993 if(pSrcItem->GetCount() < count)
10995 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10996 return;
10999 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
11001 //best error message found for attempting to split while looting
11002 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11003 return;
11006 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
11007 Item *pNewItem = pSrcItem->CloneItem( count, this );
11008 if( !pNewItem )
11010 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11011 return;
11014 if( IsInventoryPos( dst ) )
11016 // change item amount before check (for unique max count check)
11017 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11019 ItemPosCountVec dest;
11020 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
11021 if( msg != EQUIP_ERR_OK )
11023 delete pNewItem;
11024 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11025 SendEquipError( msg, pSrcItem, NULL );
11026 return;
11029 if( IsInWorld() )
11030 pSrcItem->SendUpdateToPlayer( this );
11031 pSrcItem->SetState(ITEM_CHANGED, this);
11032 StoreItem( dest, pNewItem, true);
11034 else if( IsBankPos ( dst ) )
11036 // change item amount before check (for unique max count check)
11037 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11039 ItemPosCountVec dest;
11040 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
11041 if( msg != EQUIP_ERR_OK )
11043 delete pNewItem;
11044 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11045 SendEquipError( msg, pSrcItem, NULL );
11046 return;
11049 if( IsInWorld() )
11050 pSrcItem->SendUpdateToPlayer( this );
11051 pSrcItem->SetState(ITEM_CHANGED, this);
11052 BankItem( dest, pNewItem, true);
11054 else if( IsEquipmentPos ( dst ) )
11056 // change item amount before check (for unique max count check), provide space for splitted items
11057 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11059 uint16 dest;
11060 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
11061 if( msg != EQUIP_ERR_OK )
11063 delete pNewItem;
11064 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11065 SendEquipError( msg, pSrcItem, NULL );
11066 return;
11069 if( IsInWorld() )
11070 pSrcItem->SendUpdateToPlayer( this );
11071 pSrcItem->SetState(ITEM_CHANGED, this);
11072 EquipItem( dest, pNewItem, true);
11073 AutoUnequipOffhandIfNeed();
11077 void Player::SwapItem( uint16 src, uint16 dst )
11079 uint8 srcbag = src >> 8;
11080 uint8 srcslot = src & 255;
11082 uint8 dstbag = dst >> 8;
11083 uint8 dstslot = dst & 255;
11085 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11086 Item *pDstItem = GetItemByPos( dstbag, dstslot );
11088 if( !pSrcItem )
11089 return;
11091 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
11093 if(!isAlive() )
11095 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
11096 return;
11099 if(pSrcItem->m_lootGenerated) // prevent swap looting item
11101 //best error message found for attempting to swap while looting
11102 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
11103 return;
11106 // check unequip potability for equipped items and bank bags
11107 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
11109 // bags can be swapped with empty bag slots
11110 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ));
11111 if(msg != EQUIP_ERR_OK)
11113 SendEquipError( msg, pSrcItem, pDstItem );
11114 return;
11118 // prevent put equipped/bank bag in self
11119 if( IsBagPos ( src ) && srcslot == dstbag)
11121 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11122 return;
11125 if( !pDstItem )
11127 if( IsInventoryPos( dst ) )
11129 ItemPosCountVec dest;
11130 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
11131 if( msg != EQUIP_ERR_OK )
11133 SendEquipError( msg, pSrcItem, NULL );
11134 return;
11137 RemoveItem(srcbag, srcslot, true);
11138 StoreItem( dest, pSrcItem, true);
11140 else if( IsBankPos ( dst ) )
11142 ItemPosCountVec dest;
11143 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11144 if( msg != EQUIP_ERR_OK )
11146 SendEquipError( msg, pSrcItem, NULL );
11147 return;
11150 RemoveItem(srcbag, srcslot, true);
11151 BankItem( dest, pSrcItem, true);
11153 else if( IsEquipmentPos ( dst ) )
11155 uint16 dest;
11156 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11157 if( msg != EQUIP_ERR_OK )
11159 SendEquipError( msg, pSrcItem, NULL );
11160 return;
11163 RemoveItem(srcbag, srcslot, true);
11164 EquipItem( dest, pSrcItem, true);
11165 AutoUnequipOffhandIfNeed();
11168 else // if (!pDstItem)
11170 if(pDstItem->m_lootGenerated) // prevent swap looting item
11172 //best error message found for attempting to swap while looting
11173 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
11174 return;
11177 // check unequip potability for equipped items and bank bags
11178 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11180 // bags can be swapped with empty bag slots
11181 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) );
11182 if(msg != EQUIP_ERR_OK)
11184 SendEquipError( msg, pSrcItem, pDstItem );
11185 return;
11189 // attempt merge to / fill target item
11191 uint8 msg;
11192 ItemPosCountVec sDest;
11193 uint16 eDest;
11194 if( IsInventoryPos( dst ) )
11195 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11196 else if( IsBankPos ( dst ) )
11197 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11198 else if( IsEquipmentPos ( dst ) )
11199 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11200 else
11201 return;
11203 // can be merge/fill
11204 if(msg == EQUIP_ERR_OK)
11206 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11208 RemoveItem(srcbag, srcslot, true);
11210 if( IsInventoryPos( dst ) )
11211 StoreItem( sDest, pSrcItem, true);
11212 else if( IsBankPos ( dst ) )
11213 BankItem( sDest, pSrcItem, true);
11214 else if( IsEquipmentPos ( dst ) )
11216 EquipItem( eDest, pSrcItem, true);
11217 AutoUnequipOffhandIfNeed();
11220 else
11222 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11223 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11224 pSrcItem->SetState(ITEM_CHANGED, this);
11225 pDstItem->SetState(ITEM_CHANGED, this);
11226 if( IsInWorld() )
11228 pSrcItem->SendUpdateToPlayer( this );
11229 pDstItem->SendUpdateToPlayer( this );
11232 return;
11236 // impossible merge/fill, do real swap
11237 uint8 msg;
11239 // check src->dest move possibility
11240 ItemPosCountVec sDest;
11241 uint16 eDest;
11242 if( IsInventoryPos( dst ) )
11243 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11244 else if( IsBankPos( dst ) )
11245 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11246 else if( IsEquipmentPos( dst ) )
11248 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11249 if( msg == EQUIP_ERR_OK )
11250 msg = CanUnequipItem( eDest, true );
11253 if( msg != EQUIP_ERR_OK )
11255 SendEquipError( msg, pSrcItem, pDstItem );
11256 return;
11259 // check dest->src move possibility
11260 ItemPosCountVec sDest2;
11261 uint16 eDest2;
11262 if( IsInventoryPos( src ) )
11263 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11264 else if( IsBankPos( src ) )
11265 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11266 else if( IsEquipmentPos( src ) )
11268 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11269 if( msg == EQUIP_ERR_OK )
11270 msg = CanUnequipItem( eDest2, true);
11273 if( msg != EQUIP_ERR_OK )
11275 SendEquipError( msg, pDstItem, pSrcItem );
11276 return;
11279 // now do moves, remove...
11280 RemoveItem(dstbag, dstslot, false);
11281 RemoveItem(srcbag, srcslot, false);
11283 // add to dest
11284 if( IsInventoryPos( dst ) )
11285 StoreItem(sDest, pSrcItem, true);
11286 else if( IsBankPos( dst ) )
11287 BankItem(sDest, pSrcItem, true);
11288 else if( IsEquipmentPos( dst ) )
11289 EquipItem(eDest, pSrcItem, true);
11291 // add to src
11292 if( IsInventoryPos( src ) )
11293 StoreItem(sDest2, pDstItem, true);
11294 else if( IsBankPos( src ) )
11295 BankItem(sDest2, pDstItem, true);
11296 else if( IsEquipmentPos( src ) )
11297 EquipItem(eDest2, pDstItem, true);
11299 AutoUnequipOffhandIfNeed();
11303 void Player::AddItemToBuyBackSlot( Item *pItem )
11305 if( pItem )
11307 uint32 slot = m_currentBuybackSlot;
11308 // if current back slot non-empty search oldest or free
11309 if(m_items[slot])
11311 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11312 uint32 oldest_slot = BUYBACK_SLOT_START;
11314 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11316 // found empty
11317 if(!m_items[i])
11319 slot = i;
11320 break;
11323 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11325 if(oldest_time > i_time)
11327 oldest_time = i_time;
11328 oldest_slot = i;
11332 // find oldest
11333 slot = oldest_slot;
11336 RemoveItemFromBuyBackSlot( slot, true );
11337 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11339 m_items[slot] = pItem;
11340 time_t base = time(NULL);
11341 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11342 uint32 eslot = slot - BUYBACK_SLOT_START;
11344 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
11345 ItemPrototype const *pProto = pItem->GetProto();
11346 if( pProto )
11347 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11348 else
11349 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11350 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11352 // move to next (for non filled list is move most optimized choice)
11353 if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
11354 ++m_currentBuybackSlot;
11358 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11360 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11361 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11362 return m_items[slot];
11363 return NULL;
11366 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11368 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11369 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11371 Item *pItem = m_items[slot];
11372 if( pItem )
11374 pItem->RemoveFromWorld();
11375 if(del) pItem->SetState(ITEM_REMOVED, this);
11378 m_items[slot] = NULL;
11380 uint32 eslot = slot - BUYBACK_SLOT_START;
11381 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
11382 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11383 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11385 // if current backslot is filled set to now free slot
11386 if(m_items[m_currentBuybackSlot])
11387 m_currentBuybackSlot = slot;
11391 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11393 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg);
11394 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11395 data << uint8(msg);
11397 if(msg)
11399 data << uint64(pItem ? pItem->GetGUID() : 0);
11400 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11401 data << uint8(0); // not 0 there...
11403 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11405 uint32 level = 0;
11407 if(pItem)
11408 if(ItemPrototype const* proto = pItem->GetProto())
11409 level = proto->RequiredLevel;
11411 data << uint32(level); // new 2.4.0
11414 GetSession()->SendPacket(&data);
11417 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11419 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11420 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11421 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11422 data << uint32(item);
11423 if( param > 0 )
11424 data << uint32(param);
11425 data << uint8(msg);
11426 GetSession()->SendPacket(&data);
11429 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11431 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11432 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11433 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11434 data << uint64(guid);
11435 if( param > 0 )
11436 data << uint32(param);
11437 data << uint8(msg);
11438 GetSession()->SendPacket(&data);
11441 void Player::ClearTrade()
11443 tradeGold = 0;
11444 acceptTrade = false;
11445 for(int i = 0; i < TRADE_SLOT_COUNT; i++)
11446 tradeItems[i] = NULL_SLOT;
11449 void Player::TradeCancel(bool sendback)
11451 if(pTrader)
11453 // send yellow "Trade canceled" message to both traders
11454 WorldSession* ws;
11455 ws = GetSession();
11456 if(sendback)
11457 ws->SendCancelTrade();
11458 ws = pTrader->GetSession();
11459 if(!ws->PlayerLogout())
11460 ws->SendCancelTrade();
11462 // cleanup
11463 ClearTrade();
11464 pTrader->ClearTrade();
11465 // prevent loss of reference
11466 pTrader->pTrader = NULL;
11467 pTrader = NULL;
11471 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11473 if(m_itemDuration.empty())
11474 return;
11476 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);
11478 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
11480 Item* item = *itr;
11481 ++itr; // current element can be erased in UpdateDuration
11483 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11484 item->UpdateDuration(this,time);
11488 void Player::UpdateEnchantTime(uint32 time)
11490 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11492 assert(itr->item);
11493 next=itr;
11494 if(!itr->item->GetEnchantmentId(itr->slot))
11496 next = m_enchantDuration.erase(itr);
11498 else if(itr->leftduration <= time)
11500 ApplyEnchantment(itr->item,itr->slot,false,false);
11501 itr->item->ClearEnchantment(itr->slot);
11502 next = m_enchantDuration.erase(itr);
11504 else if(itr->leftduration > time)
11506 itr->leftduration -= time;
11507 ++next;
11512 void Player::AddEnchantmentDurations(Item *item)
11514 for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
11516 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11517 continue;
11519 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11520 if( duration > 0 )
11521 AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
11525 void Player::RemoveEnchantmentDurations(Item *item)
11527 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
11529 if(itr->item == item)
11531 // save duration in item
11532 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
11533 itr = m_enchantDuration.erase(itr);
11535 else
11536 ++itr;
11540 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11542 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11543 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11545 next = itr;
11546 if(itr->slot==slot)
11548 if(itr->item && itr->item->GetEnchantmentId(slot))
11550 // remove from stats
11551 ApplyEnchantment(itr->item,slot,false,false);
11552 // remove visual
11553 itr->item->ClearEnchantment(slot);
11555 // remove from update list
11556 next = m_enchantDuration.erase(itr);
11558 else
11559 ++next;
11562 // remove enchants from inventory items
11563 // NOTE: no need to remove these from stats, since these aren't equipped
11564 // in inventory
11565 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11567 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11568 if( pItem && pItem->GetEnchantmentId(slot) )
11569 pItem->ClearEnchantment(slot);
11572 // in inventory bags
11573 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11575 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11576 if( pBag )
11578 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11580 Item* pItem = pBag->GetItemByPos(j);
11581 if( pItem && pItem->GetEnchantmentId(slot) )
11582 pItem->ClearEnchantment(slot);
11588 // duration == 0 will remove item enchant
11589 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11591 if(!item)
11592 return;
11594 if(slot >= MAX_ENCHANTMENT_SLOT)
11595 return;
11597 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11599 if(itr->item == item && itr->slot == slot)
11601 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
11602 m_enchantDuration.erase(itr);
11603 break;
11606 if(item && duration > 0 )
11608 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
11609 m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
11613 void Player::ApplyEnchantment(Item *item,bool apply)
11615 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11616 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11619 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
11621 if(!item)
11622 return;
11624 if(!item->IsEquipped())
11625 return;
11627 if(slot >= MAX_ENCHANTMENT_SLOT)
11628 return;
11630 uint32 enchant_id = item->GetEnchantmentId(slot);
11631 if(!enchant_id)
11632 return;
11634 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11635 if(!pEnchant)
11636 return;
11638 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11639 return;
11641 for (int s=0; s<3; s++)
11643 uint32 enchant_display_type = pEnchant->type[s];
11644 uint32 enchant_amount = pEnchant->amount[s];
11645 uint32 enchant_spell_id = pEnchant->spellid[s];
11647 switch(enchant_display_type)
11649 case ITEM_ENCHANTMENT_TYPE_NONE:
11650 break;
11651 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11652 // processed in Player::CastItemCombatSpell
11653 break;
11654 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11655 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11656 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11657 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11658 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11659 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11660 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11661 break;
11662 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11663 if(enchant_spell_id)
11665 if(apply)
11667 int32 basepoints = 0;
11668 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11669 if (item->GetItemRandomPropertyId())
11671 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11672 if (item_rand)
11674 // Search enchant_amount
11675 for (int k=0; k<3; k++)
11677 if(item_rand->enchant_id[k] == enchant_id)
11679 basepoints = int32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11680 break;
11685 // Cast custom spell vs all equal basepoints getted from enchant_amount
11686 if (basepoints)
11687 CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
11688 else
11689 CastSpell(this,enchant_spell_id,true,item);
11691 else
11692 RemoveAurasDueToItemSpell(item,enchant_spell_id);
11694 break;
11695 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11696 if (!enchant_amount)
11698 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11699 if(item_rand)
11701 for (int k=0; k<3; k++)
11703 if(item_rand->enchant_id[k] == enchant_id)
11705 enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11706 break;
11712 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11713 break;
11714 case ITEM_ENCHANTMENT_TYPE_STAT:
11716 if (!enchant_amount)
11718 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11719 if(item_rand_suffix)
11721 for (int k=0; k<3; k++)
11723 if(item_rand_suffix->enchant_id[k] == enchant_id)
11725 enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11726 break;
11732 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11733 switch (enchant_spell_id)
11735 case ITEM_MOD_AGILITY:
11736 sLog.outDebug("+ %u AGILITY",enchant_amount);
11737 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11738 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11739 break;
11740 case ITEM_MOD_STRENGTH:
11741 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11742 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11743 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11744 break;
11745 case ITEM_MOD_INTELLECT:
11746 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11747 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11748 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11749 break;
11750 case ITEM_MOD_SPIRIT:
11751 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11752 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11753 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11754 break;
11755 case ITEM_MOD_STAMINA:
11756 sLog.outDebug("+ %u STAMINA",enchant_amount);
11757 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11758 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11759 break;
11760 case ITEM_MOD_DEFENSE_SKILL_RATING:
11761 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11762 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11763 break;
11764 case ITEM_MOD_DODGE_RATING:
11765 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11766 sLog.outDebug("+ %u DODGE", enchant_amount);
11767 break;
11768 case ITEM_MOD_PARRY_RATING:
11769 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11770 sLog.outDebug("+ %u PARRY", enchant_amount);
11771 break;
11772 case ITEM_MOD_BLOCK_RATING:
11773 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11774 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11775 break;
11776 case ITEM_MOD_HIT_MELEE_RATING:
11777 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11778 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11779 break;
11780 case ITEM_MOD_HIT_RANGED_RATING:
11781 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11782 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11783 break;
11784 case ITEM_MOD_HIT_SPELL_RATING:
11785 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11786 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11787 break;
11788 case ITEM_MOD_CRIT_MELEE_RATING:
11789 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11790 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11791 break;
11792 case ITEM_MOD_CRIT_RANGED_RATING:
11793 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11794 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11795 break;
11796 case ITEM_MOD_CRIT_SPELL_RATING:
11797 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11798 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11799 break;
11800 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11801 // in Enchantments
11802 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11803 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11804 // break;
11805 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11806 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11807 // break;
11808 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11809 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11810 // break;
11811 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11812 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11813 // break;
11814 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11815 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11816 // break;
11817 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11818 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11819 // break;
11820 // case ITEM_MOD_HASTE_MELEE_RATING:
11821 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11822 // break;
11823 // case ITEM_MOD_HASTE_RANGED_RATING:
11824 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11825 // break;
11826 case ITEM_MOD_HASTE_SPELL_RATING:
11827 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11828 break;
11829 case ITEM_MOD_HIT_RATING:
11830 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11831 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11832 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11833 sLog.outDebug("+ %u HIT", enchant_amount);
11834 break;
11835 case ITEM_MOD_CRIT_RATING:
11836 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11837 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11838 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11839 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11840 break;
11841 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11842 // case ITEM_MOD_HIT_TAKEN_RATING:
11843 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11844 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11845 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11846 // break;
11847 // case ITEM_MOD_CRIT_TAKEN_RATING:
11848 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11849 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11850 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11851 // break;
11852 case ITEM_MOD_RESILIENCE_RATING:
11853 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11854 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11855 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11856 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11857 break;
11858 case ITEM_MOD_HASTE_RATING:
11859 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11860 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11861 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11862 sLog.outDebug("+ %u HASTE", enchant_amount);
11863 break;
11864 case ITEM_MOD_EXPERTISE_RATING:
11865 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11866 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11867 break;
11868 case ITEM_MOD_ARMOR_PENETRATION_RATING:
11869 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
11870 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
11871 break;
11872 default:
11873 break;
11875 break;
11877 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11879 if(getClass() == CLASS_SHAMAN)
11881 float addValue = 0.0f;
11882 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11884 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11885 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11887 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11889 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11890 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11893 break;
11895 default:
11896 sLog.outError("Unknown item enchantment display type: %d",enchant_display_type);
11897 break;
11898 } /*switch(enchant_display_type)*/
11899 } /*for*/
11901 // visualize enchantment at player and equipped items
11902 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
11904 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
11905 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
11908 if(apply_dur)
11910 if(apply)
11912 // set duration
11913 uint32 duration = item->GetEnchantmentDuration(slot);
11914 if(duration > 0)
11915 AddEnchantmentDuration(item,slot,duration);
11917 else
11919 // duration == 0 will remove EnchantDuration
11920 AddEnchantmentDuration(item,slot,0);
11925 void Player::SendEnchantmentDurations()
11927 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11929 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
11933 void Player::SendItemDurations()
11935 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
11937 (*itr)->SendTimeUpdate(this);
11941 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11943 if(!item) // prevent crash
11944 return;
11946 // last check 2.0.10
11947 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11948 data << GetGUID(); // player GUID
11949 data << uint32(received); // 0=looted, 1=from npc
11950 data << uint32(created); // 0=received, 1=created
11951 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11952 data << (uint8)item->GetBagSlot(); // bagslot
11953 // item slot, but when added to stack: 0xFFFFFFFF
11954 data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
11955 data << uint32(item->GetEntry()); // item id
11956 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11957 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11958 data << uint32(count); // count of items
11959 data << GetItemCount(item->GetEntry()); // count of items in inventory
11961 if (broadcast && GetGroup())
11962 GetGroup()->BroadcastPacket(&data);
11963 else
11964 GetSession()->SendPacket(&data);
11967 /*********************************************************/
11968 /*** QUEST SYSTEM ***/
11969 /*********************************************************/
11971 void Player::PrepareQuestMenu( uint64 guid )
11973 Object *pObject;
11974 QuestRelations* pObjectQR;
11975 QuestRelations* pObjectQIR;
11976 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11977 if( pCreature )
11979 pObject = (Object*)pCreature;
11980 pObjectQR = &objmgr.mCreatureQuestRelations;
11981 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11983 else
11985 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
11986 if( pGameObject )
11988 pObject = (Object*)pGameObject;
11989 pObjectQR = &objmgr.mGOQuestRelations;
11990 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11992 else
11993 return;
11996 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11997 qm.ClearMenu();
11999 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
12001 uint32 quest_id = i->second;
12002 QuestStatus status = GetQuestStatus( quest_id );
12003 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
12004 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
12005 else if ( status == QUEST_STATUS_INCOMPLETE )
12006 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
12007 else if (status == QUEST_STATUS_AVAILABLE )
12008 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12011 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
12013 uint32 quest_id = i->second;
12014 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12015 if(!pQuest) continue;
12017 QuestStatus status = GetQuestStatus( quest_id );
12019 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
12020 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
12021 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
12022 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
12026 void Player::SendPreparedQuest( uint64 guid )
12028 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
12029 if( questMenu.Empty() )
12030 return;
12032 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
12034 uint32 status = qmi0.m_qIcon;
12036 // single element case
12037 if ( questMenu.MenuItemCount() == 1 )
12039 // Auto open -- maybe also should verify there is no greeting
12040 uint32 quest_id = qmi0.m_qId;
12041 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12042 if ( pQuest )
12044 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
12045 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
12046 else if( status == DIALOG_STATUS_INCOMPLETE )
12047 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
12048 // Send completable on repeatable quest if player don't have quest
12049 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
12050 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
12051 else
12052 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
12055 // multiply entries
12056 else
12058 QEmote qe;
12059 qe._Delay = 0;
12060 qe._Emote = 0;
12061 std::string title = "";
12062 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12063 if( pCreature )
12065 uint32 textid = pCreature->GetNpcTextId();
12066 GossipText * gossiptext = objmgr.GetGossipText(textid);
12067 if( !gossiptext )
12069 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12070 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12071 title = "";
12073 else
12075 qe = gossiptext->Options[0].Emotes[0];
12077 if(!gossiptext->Options[0].Text_0.empty())
12079 title = gossiptext->Options[0].Text_0;
12081 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12082 if (loc_idx >= 0)
12084 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12085 if (nl)
12087 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12088 title = nl->Text_0[0][loc_idx];
12092 else
12094 title = gossiptext->Options[0].Text_1;
12096 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12097 if (loc_idx >= 0)
12099 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12100 if (nl)
12102 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12103 title = nl->Text_1[0][loc_idx];
12109 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
12113 bool Player::IsActiveQuest( uint32 quest_id ) const
12115 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12117 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12120 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12122 Object *pObject;
12123 QuestRelations* pObjectQR;
12124 QuestRelations* pObjectQIR;
12126 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12127 if( pCreature )
12129 pObject = (Object*)pCreature;
12130 pObjectQR = &objmgr.mCreatureQuestRelations;
12131 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12133 else
12135 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
12136 if( pGameObject )
12138 pObject = (Object*)pGameObject;
12139 pObjectQR = &objmgr.mGOQuestRelations;
12140 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12142 else
12143 return NULL;
12146 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12147 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12149 if (itr->second == nextQuestID)
12150 return objmgr.GetQuestTemplate(nextQuestID);
12153 return NULL;
12156 bool Player::CanSeeStartQuest( Quest const *pQuest )
12158 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12159 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12160 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12161 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12163 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12166 return false;
12169 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12171 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12172 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12173 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12174 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12175 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12176 && SatisfyQuestDay( pQuest, msg );
12179 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12181 if( !SatisfyQuestLog( msg ) )
12182 return false;
12184 uint32 srcitem = pQuest->GetSrcItemId();
12185 if( srcitem > 0 )
12187 uint32 count = pQuest->GetSrcItemCount();
12188 ItemPosCountVec dest;
12189 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12191 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12192 if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12193 return true;
12194 else if( msg != EQUIP_ERR_OK )
12196 SendEquipError( msg, NULL, NULL );
12197 return false;
12200 return true;
12203 bool Player::CanCompleteQuest( uint32 quest_id )
12205 if( quest_id )
12207 QuestStatusData& q_status = mQuestStatus[quest_id];
12208 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12209 return false; // not allow re-complete quest
12211 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12213 if(!qInfo)
12214 return false;
12216 // auto complete quest
12217 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12218 return true;
12220 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12223 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12225 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12227 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12228 return false;
12232 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12234 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12236 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12237 continue;
12239 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12240 return false;
12244 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12245 return false;
12247 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12248 return false;
12250 if ( qInfo->GetRewOrReqMoney() < 0 )
12252 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12253 return false;
12256 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12257 if ( repFacId && GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12258 return false;
12260 return true;
12263 return false;
12266 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12268 // Solve problem that player don't have the quest and try complete it.
12269 // if repeatable she must be able to complete event if player don't have it.
12270 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12271 if( !CanTakeQuest(pQuest, false) )
12272 return false;
12274 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12275 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12276 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12277 return false;
12279 if( !CanRewardQuest(pQuest, false) )
12280 return false;
12282 return true;
12285 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12287 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12288 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12289 return false;
12291 // daily quest can't be rewarded (25 daily quest already completed)
12292 if(!SatisfyQuestDay(pQuest,true))
12293 return false;
12295 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12296 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12297 return false;
12299 // prevent receive reward with quest items in bank
12300 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12302 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12304 if( pQuest->ReqItemCount[i]!= 0 &&
12305 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12307 if(msg)
12308 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12309 return false;
12314 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12315 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12316 return false;
12318 return true;
12321 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12323 // prevent receive reward with quest items in bank or for not completed quest
12324 if(!CanRewardQuest(pQuest,msg))
12325 return false;
12327 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12329 if( pQuest->RewChoiceItemId[reward] )
12331 ItemPosCountVec dest;
12332 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12333 if( res != EQUIP_ERR_OK )
12335 SendEquipError( res, NULL, NULL );
12336 return false;
12341 if ( pQuest->GetRewItemsCount() > 0 )
12343 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12345 if( pQuest->RewItemId[i] )
12347 ItemPosCountVec dest;
12348 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12349 if( res != EQUIP_ERR_OK )
12351 SendEquipError( res, NULL, NULL );
12352 return false;
12358 return true;
12361 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12363 uint16 log_slot = FindQuestSlot( 0 );
12364 assert(log_slot < MAX_QUEST_LOG_SIZE);
12366 uint32 quest_id = pQuest->GetQuestId();
12368 // if not exist then created with set uState==NEW and rewarded=false
12369 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12370 if (questStatusData.uState != QUEST_NEW)
12371 questStatusData.uState = QUEST_CHANGED;
12373 // check for repeatable quests status reset
12374 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12375 questStatusData.m_explored = false;
12377 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12379 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12380 questStatusData.m_itemcount[i] = 0;
12383 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12385 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12386 questStatusData.m_creatureOrGOcount[i] = 0;
12389 GiveQuestSourceItem( pQuest );
12390 AdjustQuestReqItemCount( pQuest );
12392 if( pQuest->GetRepObjectiveFaction() )
12393 SetFactionVisibleForFactionId(pQuest->GetRepObjectiveFaction());
12395 uint32 qtime = 0;
12396 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12398 uint32 limittime = pQuest->GetLimitTime();
12400 // shared timed quest
12401 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12402 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / 1000;
12404 AddTimedQuest( quest_id );
12405 questStatusData.m_timer = limittime * 1000;
12406 qtime = static_cast<uint32>(time(NULL)) + limittime;
12408 else
12409 questStatusData.m_timer = 0;
12411 SetQuestSlot(log_slot, quest_id, qtime);
12413 //starting initial quest script
12414 if(questGiver && pQuest->GetQuestStartScript()!=0)
12415 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12417 UpdateForQuestsGO();
12420 void Player::CompleteQuest( uint32 quest_id )
12422 if( quest_id )
12424 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12426 uint16 log_slot = FindQuestSlot( quest_id );
12427 if( log_slot < MAX_QUEST_LOG_SIZE)
12428 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12430 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12432 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12433 RewardQuest(qInfo,0,this,false);
12434 else
12435 SendQuestComplete( quest_id );
12440 void Player::IncompleteQuest( uint32 quest_id )
12442 if( quest_id )
12444 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12446 uint16 log_slot = FindQuestSlot( quest_id );
12447 if( log_slot < MAX_QUEST_LOG_SIZE)
12448 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12452 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12454 uint32 quest_id = pQuest->GetQuestId();
12456 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; i++ )
12458 if ( pQuest->ReqItemId[i] )
12459 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12462 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12463 // SetTimedQuest( 0 );
12464 m_timedquests.erase(pQuest->GetQuestId());
12466 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12468 if( pQuest->RewChoiceItemId[reward] )
12470 ItemPosCountVec dest;
12471 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12473 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12474 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12479 if ( pQuest->GetRewItemsCount() > 0 )
12481 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12483 if( pQuest->RewItemId[i] )
12485 ItemPosCountVec dest;
12486 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12488 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12489 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12495 RewardReputation( pQuest );
12497 if( pQuest->GetRewSpellCast() > 0 )
12498 CastSpell( this, pQuest->GetRewSpellCast(), true);
12499 else if( pQuest->GetRewSpell() > 0)
12500 CastSpell( this, pQuest->GetRewSpell(), true);
12502 uint16 log_slot = FindQuestSlot( quest_id );
12503 if( log_slot < MAX_QUEST_LOG_SIZE)
12504 SetQuestSlot(log_slot,0);
12506 QuestStatusData& q_status = mQuestStatus[quest_id];
12508 // Not give XP in case already completed once repeatable quest
12509 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12511 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12512 GiveXP( XP , NULL );
12513 else
12514 ModifyMoney( int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)) );
12516 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12517 ModifyMoney( pQuest->GetRewOrReqMoney() );
12519 // honor reward
12520 if(pQuest->GetRewHonorableKills())
12521 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12523 // title reward
12524 if(pQuest->GetCharTitleId())
12526 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12527 SetTitle(titleEntry);
12530 // Send reward mail
12531 if(pQuest->GetRewMailTemplateId())
12533 MailMessageType mailType;
12534 uint32 senderGuidOrEntry;
12535 switch(questGiver->GetTypeId())
12537 case TYPEID_UNIT:
12538 mailType = MAIL_CREATURE;
12539 senderGuidOrEntry = questGiver->GetEntry();
12540 break;
12541 case TYPEID_GAMEOBJECT:
12542 mailType = MAIL_GAMEOBJECT;
12543 senderGuidOrEntry = questGiver->GetEntry();
12544 break;
12545 case TYPEID_ITEM:
12546 mailType = MAIL_ITEM;
12547 senderGuidOrEntry = questGiver->GetEntry();
12548 break;
12549 case TYPEID_PLAYER:
12550 mailType = MAIL_NORMAL;
12551 senderGuidOrEntry = questGiver->GetGUIDLow();
12552 break;
12553 default:
12554 mailType = MAIL_NORMAL;
12555 senderGuidOrEntry = GetGUIDLow();
12556 break;
12559 Loot questMailLoot;
12561 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this);
12563 // fill mail
12564 MailItemsInfo mi; // item list preparing
12566 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.items.size(); ++i)
12568 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12570 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12572 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12573 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12578 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.quest_items.size(); ++i)
12580 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i+questMailLoot.items.size(),this))
12582 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12584 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12585 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12590 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12593 if(pQuest->IsDaily())
12595 SetDailyQuestStatus(quest_id);
12596 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12599 if ( !pQuest->IsRepeatable() )
12600 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12601 else
12602 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12604 q_status.m_rewarded = true;
12606 if(announce)
12607 SendQuestReward( pQuest, XP, questGiver );
12609 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12610 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12611 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST);
12614 void Player::FailQuest( uint32 quest_id )
12616 if( quest_id )
12618 IncompleteQuest( quest_id );
12620 uint16 log_slot = FindQuestSlot( quest_id );
12621 if( log_slot < MAX_QUEST_LOG_SIZE)
12623 SetQuestSlotTimer(log_slot, 1 );
12624 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12626 SendQuestFailed( quest_id );
12630 void Player::FailTimedQuest( uint32 quest_id )
12632 if( quest_id )
12634 QuestStatusData& q_status = mQuestStatus[quest_id];
12636 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12637 q_status.m_timer = 0;
12639 IncompleteQuest( quest_id );
12641 uint16 log_slot = FindQuestSlot( quest_id );
12642 if( log_slot < MAX_QUEST_LOG_SIZE)
12644 SetQuestSlotTimer(log_slot, 1 );
12645 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12647 SendQuestTimerFailed( quest_id );
12651 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12653 int32 zoneOrSort = qInfo->GetZoneOrSort();
12654 int32 skillOrClass = qInfo->GetSkillOrClass();
12656 // skip zone zoneOrSort and 0 case skillOrClass
12657 if( zoneOrSort >= 0 && skillOrClass == 0 )
12658 return true;
12660 int32 questSort = -zoneOrSort;
12661 uint8 reqSortClass = ClassByQuestSort(questSort);
12663 // check class sort cases in zoneOrSort
12664 if( reqSortClass != 0 && getClass() != reqSortClass)
12666 if( msg )
12667 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12668 return false;
12671 // check class
12672 if( skillOrClass < 0 )
12674 uint8 reqClass = -int32(skillOrClass);
12675 if(getClass() != reqClass)
12677 if( msg )
12678 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12679 return false;
12682 // check skill
12683 else if( skillOrClass > 0 )
12685 uint32 reqSkill = skillOrClass;
12686 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12688 if( msg )
12689 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12690 return false;
12694 return true;
12697 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12699 if( getLevel() < qInfo->GetMinLevel() )
12701 if( msg )
12702 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12703 return false;
12705 return true;
12708 bool Player::SatisfyQuestLog( bool msg )
12710 // exist free slot
12711 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12712 return true;
12714 if( msg )
12716 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12717 GetSession()->SendPacket( &data );
12718 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12720 return false;
12723 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12725 // No previous quest (might be first quest in a series)
12726 if( qInfo->prevQuests.empty())
12727 return true;
12729 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12731 uint32 prevId = abs(*iter);
12733 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12734 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12736 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12738 // If any of the positive previous quests completed, return true
12739 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12741 // skip one-from-all exclusive group
12742 if(qPrevInfo->GetExclusiveGroup() >= 0)
12743 return true;
12745 // each-from-all exclusive group ( < 0)
12746 // can be start if only all quests in prev quest exclusive group completed and rewarded
12747 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12748 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12750 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12752 for(; iter != end; ++iter)
12754 uint32 exclude_Id = iter->second;
12756 // skip checked quest id, only state of other quests in group is interesting
12757 if(exclude_Id == prevId)
12758 continue;
12760 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12762 // alternative quest from group also must be completed and rewarded(reported)
12763 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12765 if( msg )
12766 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12767 return false;
12770 return true;
12772 // If any of the negative previous quests active, return true
12773 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12774 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12776 // skip one-from-all exclusive group
12777 if(qPrevInfo->GetExclusiveGroup() >= 0)
12778 return true;
12780 // each-from-all exclusive group ( < 0)
12781 // can be start if only all quests in prev quest exclusive group active
12782 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12783 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12785 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12787 for(; iter != end; ++iter)
12789 uint32 exclude_Id = iter->second;
12791 // skip checked quest id, only state of other quests in group is interesting
12792 if(exclude_Id == prevId)
12793 continue;
12795 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12797 // alternative quest from group also must be active
12798 if( i_exstatus == mQuestStatus.end() ||
12799 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12800 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12802 if( msg )
12803 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12804 return false;
12807 return true;
12812 // Has only positive prev. quests in non-rewarded state
12813 // and negative prev. quests in non-active state
12814 if( msg )
12815 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12817 return false;
12820 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12822 uint32 reqraces = qInfo->GetRequiredRaces();
12823 if ( reqraces == 0 )
12824 return true;
12825 if( (reqraces & getRaceMask()) == 0 )
12827 if( msg )
12828 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12829 return false;
12831 return true;
12834 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12836 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12837 if(fIdMin && GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12839 if( msg )
12840 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12841 return false;
12844 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12845 if(fIdMax && GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12847 if( msg )
12848 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12849 return false;
12852 return true;
12855 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12857 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12858 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12860 if( msg )
12861 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12862 return false;
12864 return true;
12867 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12869 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12871 if( msg )
12872 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12873 return false;
12875 return true;
12878 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12880 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12881 if(qInfo->GetExclusiveGroup() <= 0)
12882 return true;
12884 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12885 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12887 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12889 for(; iter != end; ++iter)
12891 uint32 exclude_Id = iter->second;
12893 // skip checked quest id, only state of other quests in group is interesting
12894 if(exclude_Id == qInfo->GetQuestId())
12895 continue;
12897 // not allow have daily quest if daily quest from exclusive group already recently completed
12898 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
12899 if( !SatisfyQuestDay(Nquest, false) )
12901 if( msg )
12902 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12903 return false;
12906 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12908 // alternative quest already started or completed
12909 if( i_exstatus != mQuestStatus.end()
12910 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12912 if( msg )
12913 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12914 return false;
12917 return true;
12920 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12922 if(!qInfo->GetNextQuestInChain())
12923 return true;
12925 // next quest in chain already started or completed
12926 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12927 if( itr != mQuestStatus.end()
12928 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12930 if( msg )
12931 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12932 return false;
12935 // check for all quests further up the chain
12936 // only necessary if there are quest chains with more than one quest that can be skipped
12937 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12938 return true;
12941 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12943 // No previous quest in chain
12944 if( qInfo->prevChainQuests.empty())
12945 return true;
12947 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12949 uint32 prevId = *iter;
12951 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12953 if( i_prevstatus != mQuestStatus.end() )
12955 // If any of the previous quests in chain active, return false
12956 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12957 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12959 if( msg )
12960 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12961 return false;
12965 // check for all quests further down the chain
12966 // only necessary if there are quest chains with more than one quest that can be skipped
12967 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12968 // return false;
12971 // No previous quest in chain active
12972 return true;
12975 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12977 if(!qInfo->IsDaily())
12978 return true;
12980 bool have_slot = false;
12981 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12983 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12984 if(qInfo->GetQuestId()==id)
12985 return false;
12987 if(!id)
12988 have_slot = true;
12991 if(!have_slot)
12993 if( msg )
12994 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
12995 return false;
12998 return true;
13001 bool Player::GiveQuestSourceItem( Quest const *pQuest )
13003 uint32 srcitem = pQuest->GetSrcItemId();
13004 if( srcitem > 0 )
13006 uint32 count = pQuest->GetSrcItemCount();
13007 if( count <= 0 )
13008 count = 1;
13010 ItemPosCountVec dest;
13011 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13012 if( msg == EQUIP_ERR_OK )
13014 Item * item = StoreNewItem(dest, srcitem, true);
13015 SendNewItem(item, count, true, false);
13016 return true;
13018 // player already have max amount required item, just report success
13019 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13020 return true;
13021 else
13022 SendEquipError( msg, NULL, NULL );
13023 return false;
13026 return true;
13029 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13031 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13032 if( qInfo )
13034 uint32 srcitem = qInfo->GetSrcItemId();
13035 if( srcitem > 0 )
13037 uint32 count = qInfo->GetSrcItemCount();
13038 if( count <= 0 )
13039 count = 1;
13041 // exist one case when destroy source quest item not possible:
13042 // non un-equippable item (equipped non-empty bag, for example)
13043 uint8 res = CanUnequipItems(srcitem,count);
13044 if(res != EQUIP_ERR_OK)
13046 if(msg)
13047 SendEquipError( res, NULL, NULL );
13048 return false;
13051 DestroyItemCount(srcitem, count, true, true);
13054 return true;
13057 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13059 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13060 if( qInfo )
13062 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13063 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13064 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13065 && !qInfo->IsRepeatable() )
13066 return itr->second.m_rewarded;
13068 return false;
13070 return false;
13073 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13075 if( quest_id )
13077 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13078 if( itr != mQuestStatus.end() )
13079 return itr->second.m_status;
13081 return QUEST_STATUS_NONE;
13084 bool Player::CanShareQuest(uint32 quest_id) const
13086 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13087 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13089 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13090 if( itr != mQuestStatus.end() )
13091 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13093 return false;
13096 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
13098 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13099 if( qInfo )
13101 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
13103 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13104 m_timedquests.erase(qInfo->GetQuestId());
13107 QuestStatusData& q_status = mQuestStatus[quest_id];
13109 q_status.m_status = status;
13110 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13113 UpdateForQuestsGO();
13116 // not used in MaNGOS, but used in scripting code
13117 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13119 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13120 if( !qInfo )
13121 return 0;
13123 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13124 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13125 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13127 return 0;
13130 void Player::AdjustQuestReqItemCount( Quest const* pQuest )
13132 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13134 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
13136 uint32 reqitemcount = pQuest->ReqItemCount[i];
13137 if( reqitemcount != 0 )
13139 uint32 quest_id = pQuest->GetQuestId();
13140 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13142 QuestStatusData& q_status = mQuestStatus[quest_id];
13143 q_status.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13144 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13150 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13152 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13153 if ( GetQuestSlotQuestId(i) == quest_id )
13154 return i;
13156 return MAX_QUEST_LOG_SIZE;
13159 void Player::AreaExploredOrEventHappens( uint32 questId )
13161 if( questId )
13163 uint16 log_slot = FindQuestSlot( questId );
13164 if( log_slot < MAX_QUEST_LOG_SIZE)
13166 QuestStatusData& q_status = mQuestStatus[questId];
13168 if(!q_status.m_explored)
13170 q_status.m_explored = true;
13171 if (q_status.uState != QUEST_NEW)
13172 q_status.uState = QUEST_CHANGED;
13175 if( CanCompleteQuest( questId ) )
13176 CompleteQuest( questId );
13180 //not used in mangosd, function for external script library
13181 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13183 if( Group *pGroup = GetGroup() )
13185 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13187 Player *pGroupGuy = itr->getSource();
13189 // for any leave or dead (with not released body) group member at appropriate distance
13190 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13191 pGroupGuy->AreaExploredOrEventHappens(questId);
13194 else
13195 AreaExploredOrEventHappens(questId);
13198 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13200 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13202 uint32 questid = GetQuestSlotQuestId(i);
13203 if ( questid == 0 )
13204 continue;
13206 QuestStatusData& q_status = mQuestStatus[questid];
13208 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13209 continue;
13211 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13212 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13213 continue;
13215 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13217 uint32 reqitem = qInfo->ReqItemId[j];
13218 if ( reqitem == entry )
13220 uint32 reqitemcount = qInfo->ReqItemCount[j];
13221 uint32 curitemcount = q_status.m_itemcount[j];
13222 if ( curitemcount < reqitemcount )
13224 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13225 q_status.m_itemcount[j] += additemcount;
13226 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13228 SendQuestUpdateAddItem( qInfo, j, additemcount );
13230 if ( CanCompleteQuest( questid ) )
13231 CompleteQuest( questid );
13232 return;
13236 UpdateForQuestsGO();
13237 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
13240 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13242 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13244 uint32 questid = GetQuestSlotQuestId(i);
13245 if(!questid)
13246 continue;
13247 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13248 if ( !qInfo )
13249 continue;
13250 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13251 continue;
13253 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13255 uint32 reqitem = qInfo->ReqItemId[j];
13256 if ( reqitem == entry )
13258 QuestStatusData& q_status = mQuestStatus[questid];
13260 uint32 reqitemcount = qInfo->ReqItemCount[j];
13261 uint32 curitemcount;
13262 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13263 curitemcount = q_status.m_itemcount[j];
13264 else
13265 curitemcount = GetItemCount(entry,true);
13266 if ( curitemcount < reqitemcount + count )
13268 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13269 q_status.m_itemcount[j] = curitemcount - remitemcount;
13270 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13272 IncompleteQuest( questid );
13274 return;
13278 UpdateForQuestsGO();
13281 void Player::KilledMonster( uint32 entry, uint64 guid )
13283 uint32 addkillcount = 1;
13284 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13285 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13287 uint32 questid = GetQuestSlotQuestId(i);
13288 if(!questid)
13289 continue;
13291 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13292 if( !qInfo )
13293 continue;
13294 // just if !ingroup || !noraidgroup || raidgroup
13295 QuestStatusData& q_status = mQuestStatus[questid];
13296 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13298 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13300 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13302 // skip GO activate objective or none
13303 if(qInfo->ReqCreatureOrGOId[j] <=0)
13304 continue;
13306 // skip Cast at creature objective
13307 if(qInfo->ReqSpell[j] !=0 )
13308 continue;
13310 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13312 if ( reqkill == entry )
13314 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13315 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13316 if ( curkillcount < reqkillcount )
13318 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13319 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13321 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13323 if ( CanCompleteQuest( questid ) )
13324 CompleteQuest( questid );
13326 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13327 continue;
13335 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13337 bool isCreature = IS_CREATURE_GUID(guid);
13339 uint32 addCastCount = 1;
13340 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13342 uint32 questid = GetQuestSlotQuestId(i);
13343 if(!questid)
13344 continue;
13346 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13347 if ( !qInfo )
13348 continue;
13350 QuestStatusData& q_status = mQuestStatus[questid];
13352 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13354 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13356 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13358 // skip kill creature objective (0) or wrong spell casts
13359 if(qInfo->ReqSpell[j] != spell_id )
13360 continue;
13362 uint32 reqTarget = 0;
13364 if(isCreature)
13366 // creature activate objectives
13367 if(qInfo->ReqCreatureOrGOId[j] > 0)
13368 // checked at quest_template loading
13369 reqTarget = qInfo->ReqCreatureOrGOId[j];
13371 else
13373 // GO activate objective
13374 if(qInfo->ReqCreatureOrGOId[j] < 0)
13375 // checked at quest_template loading
13376 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13379 // other not this creature/GO related objectives
13380 if( reqTarget != entry )
13381 continue;
13383 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13384 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13385 if ( curCastCount < reqCastCount )
13387 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13388 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13390 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13393 if ( CanCompleteQuest( questid ) )
13394 CompleteQuest( questid );
13396 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13397 break;
13404 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13406 uint32 addTalkCount = 1;
13407 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13409 uint32 questid = GetQuestSlotQuestId(i);
13410 if(!questid)
13411 continue;
13413 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13414 if ( !qInfo )
13415 continue;
13417 QuestStatusData& q_status = mQuestStatus[questid];
13419 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13421 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13423 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13425 // skip spell casts and Gameobject objectives
13426 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13427 continue;
13429 uint32 reqTarget = 0;
13431 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13432 // checked at quest_template loading
13433 reqTarget = qInfo->ReqCreatureOrGOId[j];
13434 else
13435 continue;
13437 if ( reqTarget == entry )
13439 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13440 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13441 if ( curTalkCount < reqTalkCount )
13443 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13444 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13446 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13448 if ( CanCompleteQuest( questid ) )
13449 CompleteQuest( questid );
13451 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13452 continue;
13460 void Player::MoneyChanged( uint32 count )
13462 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13464 uint32 questid = GetQuestSlotQuestId(i);
13465 if (!questid)
13466 continue;
13468 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13469 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13471 QuestStatusData& q_status = mQuestStatus[questid];
13473 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13475 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13477 if ( CanCompleteQuest( questid ) )
13478 CompleteQuest( questid );
13481 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13483 if(int32(count) < -qInfo->GetRewOrReqMoney())
13484 IncompleteQuest( questid );
13490 bool Player::HasQuestForItem( uint32 itemid ) const
13492 for( QuestStatusMap::const_iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
13494 QuestStatusData const& q_status = i->second;
13496 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13498 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
13499 if(!qinfo)
13500 continue;
13502 // hide quest if player is in raid-group and quest is no raid quest
13503 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13504 continue;
13506 // There should be no mixed ReqItem/ReqSource drop
13507 // This part for ReqItem drop
13508 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13510 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13511 return true;
13513 // This part - for ReqSource
13514 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; j++)
13516 // examined item is a source item
13517 if (qinfo->ReqSourceId[j] == itemid && qinfo->ReqSourceRef[j] > 0 && qinfo->ReqSourceRef[j] <= QUEST_OBJECTIVES_COUNT)
13519 uint32 idx = qinfo->ReqSourceRef[j]-1;
13521 // total count of created ReqItems and SourceItems is less than ReqItemCount
13522 if(qinfo->ReqItemId[idx] != 0 &&
13523 q_status.m_itemcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqItemCount[idx] * qinfo->ReqSourceCount[j])
13524 return true;
13526 // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
13527 if (qinfo->ReqCreatureOrGOId[idx] != 0)
13529 if(q_status.m_creatureOrGOcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqCreatureOrGOCount[idx] * qinfo->ReqSourceCount[j])
13530 return true;
13532 // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
13533 else if(qinfo->ReqSpell[idx] != 0)
13535 // not casted and need more reagents/item for use.
13536 if(!q_status.m_explored && GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13537 return true;
13543 return false;
13546 void Player::SendQuestComplete( uint32 quest_id )
13548 if( quest_id )
13550 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13551 data << uint32(quest_id);
13552 GetSession()->SendPacket( &data );
13553 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13557 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13559 uint32 questid = pQuest->GetQuestId();
13560 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13561 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13562 data << uint32(questid);
13564 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13566 data << uint32(XP);
13567 data << uint32(pQuest->GetRewOrReqMoney());
13569 else
13571 data << uint32(0);
13572 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13575 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13576 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13577 GetSession()->SendPacket( &data );
13579 if (pQuest->GetQuestCompleteScript() != 0)
13580 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13583 void Player::SendQuestFailed( uint32 quest_id )
13585 if( quest_id )
13587 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13588 data << quest_id;
13589 data << uint32(0); // failed reason (4 for inventory is full)
13590 GetSession()->SendPacket( &data );
13591 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13595 void Player::SendQuestTimerFailed( uint32 quest_id )
13597 if( quest_id )
13599 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13600 data << quest_id;
13601 GetSession()->SendPacket( &data );
13602 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13606 void Player::SendCanTakeQuestResponse( uint32 msg )
13608 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13609 data << uint32(msg);
13610 GetSession()->SendPacket( &data );
13611 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13614 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13616 if( pPlayer )
13618 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13619 data << uint64(pPlayer->GetGUID());
13620 data << uint8(msg); // valid values: 0-8
13621 GetSession()->SendPacket( &data );
13622 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13626 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13628 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13629 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13630 //data << pQuest->ReqItemId[item_idx];
13631 //data << count;
13632 GetSession()->SendPacket( &data );
13635 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13637 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13639 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13640 if (entry < 0)
13641 // client expected gameobject template id in form (id|0x80000000)
13642 entry = (-entry) | 0x80000000;
13644 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13645 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13646 data << uint32(pQuest->GetQuestId());
13647 data << uint32(entry);
13648 data << uint32(old_count + add_count);
13649 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13650 data << uint64(guid);
13651 GetSession()->SendPacket(&data);
13653 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13654 if( log_slot < MAX_QUEST_LOG_SIZE)
13655 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13658 /*********************************************************/
13659 /*** LOAD SYSTEM ***/
13660 /*********************************************************/
13662 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13664 bool delete_result = true;
13665 if(!result)
13667 // 0 1 2 3 4 5 6 7 8 9
13668 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13669 if(!result) return false;
13671 else delete_result = false;
13673 Field *fields = result->Fetch();
13675 if(!LoadValues( fields[1].GetString()))
13677 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
13678 if(delete_result) delete result;
13679 return false;
13682 // overwrite possible wrong/corrupted guid
13683 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13685 m_name = fields[2].GetCppString();
13687 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13688 SetMapId(fields[6].GetUInt32());
13689 // the instance id is not needed at character enum
13691 m_Played_time[0] = fields[7].GetUInt32();
13692 m_Played_time[1] = fields[8].GetUInt32();
13694 m_atLoginFlags = fields[9].GetUInt32();
13696 // I don't see these used anywhere ..
13697 /*_LoadGroup();
13699 _LoadBoundInstances();*/
13701 if (delete_result) delete result;
13703 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
13704 m_items[i] = NULL;
13706 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13707 m_deathState = DEAD;
13709 return true;
13712 void Player::_LoadDeclinedNames(QueryResult* result)
13714 if(!result)
13715 return;
13717 if(m_declinedname)
13718 delete m_declinedname;
13720 m_declinedname = new DeclinedName;
13721 Field *fields = result->Fetch();
13722 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13723 m_declinedname->name[i] = fields[i].GetCppString();
13725 delete result;
13728 void Player::_LoadArenaTeamInfo(QueryResult *result)
13730 // arenateamid, played_week, played_season, personal_rating
13731 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
13732 if (!result)
13733 return;
13737 Field *fields = result->Fetch();
13739 uint32 arenateamid = fields[0].GetUInt32();
13740 uint32 played_week = fields[1].GetUInt32();
13741 uint32 played_season = fields[2].GetUInt32();
13742 uint32 personal_rating = fields[3].GetUInt32();
13744 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
13745 if(!aTeam)
13747 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
13748 continue;
13750 uint8 arenaSlot = aTeam->GetSlot();
13752 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
13753 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
13754 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
13755 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
13756 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
13757 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
13759 }while (result->NextRow());
13760 delete result;
13763 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13765 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13766 if(!result)
13767 return false;
13769 Field *fields = result->Fetch();
13771 x = fields[0].GetFloat();
13772 y = fields[1].GetFloat();
13773 z = fields[2].GetFloat();
13774 o = fields[3].GetFloat();
13775 mapid = fields[4].GetUInt32();
13776 in_flight = !fields[5].GetCppString().empty();
13778 delete result;
13779 return true;
13782 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13784 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13785 if( !result )
13786 return false;
13788 Field *fields = result->Fetch();
13790 data = StrSplit(fields[0].GetCppString(), " ");
13792 delete result;
13794 return true;
13797 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13799 if(index >= data.size())
13800 return 0;
13802 return (uint32)atoi(data[index].c_str());
13805 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13807 float result;
13808 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13809 memcpy(&result, &temp, sizeof(result));
13811 return result;
13814 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13816 Tokens data;
13817 if(!LoadValuesArrayFromDB(data,guid))
13818 return 0;
13820 return GetUInt32ValueFromArray(data,index);
13823 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13825 float result;
13826 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13827 memcpy(&result, &temp, sizeof(result));
13829 return result;
13832 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
13834 //// 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
13835 //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);
13836 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
13838 if(!result)
13840 sLog.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid);
13841 return false;
13844 Field *fields = result->Fetch();
13846 uint32 dbAccountId = fields[1].GetUInt32();
13848 // check if the character's account in the db and the logged in account match.
13849 // player should be able to load/delete character only with correct account!
13850 if( dbAccountId != GetSession()->GetAccountId() )
13852 sLog.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
13853 delete result;
13854 return false;
13857 Object::_Create( guid, 0, HIGHGUID_PLAYER );
13859 m_name = fields[3].GetCppString();
13861 // check name limitations
13862 if(!ObjectMgr::IsValidName(m_name) || GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name))
13864 delete result;
13865 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
13866 return false;
13869 if(!LoadValues( fields[2].GetString()))
13871 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13872 delete result;
13873 return false;
13876 // overwrite possible wrong/corrupted guid
13877 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13879 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13880 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
13882 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), 0 );
13883 SetVisibleItemSlot(slot,NULL);
13885 if (m_items[slot])
13887 delete m_items[slot];
13888 m_items[slot] = NULL;
13892 // update money limits
13893 if(GetMoney() > MAX_MONEY_AMOUNT)
13894 SetMoney(MAX_MONEY_AMOUNT);
13896 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
13897 outDebugValues();
13899 m_race = fields[4].GetUInt8();
13900 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13901 //Other way is to saves m_team into characters table.
13902 setFactionForRace(m_race);
13903 SetCharm(0);
13905 m_class = fields[5].GetUInt8();
13907 PlayerInfo const *info = objmgr.GetPlayerInfo(m_race, m_class);
13908 if(!info)
13910 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
13911 delete result;
13912 return false;
13915 InitPrimaryProffesions(); // to max set before any spell loaded
13917 uint32 transGUID = fields[24].GetUInt32();
13918 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
13919 SetMapId(fields[9].GetUInt32());
13920 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
13922 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
13924 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
13926 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[33].GetUInt32();
13927 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
13928 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
13930 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
13932 // check arena teams integrity
13933 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
13935 uint32 arena_team_id = GetArenaTeamId(arena_slot);
13936 if(!arena_team_id)
13937 continue;
13939 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
13940 if(at->HaveMember(GetGUID()))
13941 continue;
13943 // arena team not exist or not member, cleanup fields
13944 for(int j =0; j < 6; ++j)
13945 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
13948 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
13950 if(!IsPositionValid())
13952 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());
13954 SetMapId(info->mapId);
13955 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13957 transGUID = 0;
13959 m_movementInfo.t_x = 0.0f;
13960 m_movementInfo.t_y = 0.0f;
13961 m_movementInfo.t_z = 0.0f;
13962 m_movementInfo.t_o = 0.0f;
13965 // load the player's map here if it's not already loaded
13966 Map *map = GetMap();
13967 // since the player may not be bound to the map yet, make sure subsequent
13968 // getmap calls won't create new maps
13969 SetInstanceId(map->GetInstanceId());
13971 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
13972 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
13974 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
13975 if(at)
13976 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
13977 else
13978 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());
13981 SaveRecallPosition();
13983 if (transGUID != 0)
13985 m_movementInfo.t_x = fields[20].GetFloat();
13986 m_movementInfo.t_y = fields[21].GetFloat();
13987 m_movementInfo.t_z = fields[22].GetFloat();
13988 m_movementInfo.t_o = fields[23].GetFloat();
13990 if( !MaNGOS::IsValidMapCoord(
13991 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13992 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
13993 // transport size limited
13994 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
13996 sLog.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13997 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13998 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
14000 SetMapId(info->mapId);
14001 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
14003 m_movementInfo.t_x = 0.0f;
14004 m_movementInfo.t_y = 0.0f;
14005 m_movementInfo.t_z = 0.0f;
14006 m_movementInfo.t_o = 0.0f;
14008 transGUID = 0;
14012 if (transGUID != 0)
14014 for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
14016 if( (*iter)->GetGUIDLow() == transGUID)
14018 m_transport = *iter;
14019 m_transport->AddPassenger(this);
14020 SetMapId(m_transport->GetMapId());
14021 break;
14025 if(!m_transport)
14027 sLog.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
14028 guid,transGUID);
14030 SetMapId(info->mapId);
14031 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
14033 m_movementInfo.t_x = 0.0f;
14034 m_movementInfo.t_y = 0.0f;
14035 m_movementInfo.t_z = 0.0f;
14036 m_movementInfo.t_o = 0.0f;
14038 transGUID = 0;
14042 time_t now = time(NULL);
14043 time_t logoutTime = time_t(fields[16].GetUInt64());
14045 // since last logout (in seconds)
14046 uint64 time_diff = uint64(now - logoutTime);
14048 // set value, including drunk invisibility detection
14049 // calculate sobering. after 15 minutes logged out, the player will be sober again
14050 float soberFactor;
14051 if(time_diff > 15*MINUTE)
14052 soberFactor = 0;
14053 else
14054 soberFactor = 1-time_diff/(15.0f*MINUTE);
14055 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14056 SetDrunkValue(newDrunkenValue);
14058 m_rest_bonus = fields[15].GetFloat();
14059 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14060 float bubble0 = 0.031;
14061 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14062 float bubble1 = 0.125;
14064 if((int32)fields[16].GetUInt32() > 0)
14066 float bubble = fields[17].GetUInt32() > 0
14067 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14068 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14070 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14073 m_cinematic = fields[12].GetUInt32();
14074 m_Played_time[0]= fields[13].GetUInt32();
14075 m_Played_time[1]= fields[14].GetUInt32();
14077 m_resetTalentsCost = fields[18].GetUInt32();
14078 m_resetTalentsTime = time_t(fields[19].GetUInt64());
14080 // reserve some flags
14081 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14083 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14084 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14086 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
14088 uint32 extraflags = fields[25].GetUInt32();
14090 m_stableSlots = fields[26].GetUInt32();
14091 if(m_stableSlots > 4)
14093 sLog.outError("Player can have not more 4 stable slots, but have in DB %u",uint32(m_stableSlots));
14094 m_stableSlots = 4;
14097 m_atLoginFlags = fields[27].GetUInt32();
14099 // Honor system
14100 // Update Honor kills data
14101 m_lastHonorUpdateTime = logoutTime;
14102 UpdateHonorFields();
14104 m_deathExpireTime = (time_t)fields[30].GetUInt64();
14105 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14106 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14108 std::string taxi_nodes = fields[31].GetCppString();
14110 delete result;
14112 // clear channel spell data (if saved at channel spell casting)
14113 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14114 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14116 // clear charm/summon related fields
14117 SetCharm(NULL);
14118 SetPet(NULL);
14119 SetCharmerGUID(NULL);
14120 SetOwnerGUID(NULL);
14121 SetCreatorGUID(NULL);
14123 // reset some aura modifiers before aura apply
14124 SetFarSight(NULL);
14125 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14126 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14128 // reset skill modifiers and set correct unlearn flags
14129 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; i++)
14131 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
14133 // set correct unlearn bit
14134 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
14135 if(!id) continue;
14137 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
14138 if(!pSkill) continue;
14140 // enable unlearn button for primary professions only
14141 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
14142 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
14143 else
14144 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
14147 // make sure the unit is considered out of combat for proper loading
14148 ClearInCombat();
14150 // make sure the unit is considered not in duel for proper loading
14151 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14152 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14154 // remember loaded power/health values to restore after stats initialization and modifier applying
14155 uint32 savedHealth = GetHealth();
14156 uint32 savedPower[MAX_POWERS];
14157 for(uint32 i = 0; i < MAX_POWERS; ++i)
14158 savedPower[i] = GetPower(Powers(i));
14160 // reset stats before loading any modifiers
14161 InitStatsForLevel();
14162 InitTaxiNodesForLevel();
14163 InitGlyphsForLevel();
14164 InitRunes();
14166 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14168 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14169 //_LoadMail();
14171 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14173 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14174 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14175 m_deathState = DEAD;
14177 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14179 // after spell load
14180 InitTalentForLevel();
14181 learnSkillRewardedSpells();
14183 // after spell load, learn rewarded spell if need also
14184 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14185 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14187 _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));
14189 // must be before inventory (some items required reputation check)
14190 _LoadReputation(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14192 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14194 // update items with duration and realtime
14195 UpdateItemDuration(time_diff, true);
14197 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14199 // unread mails and next delivery time, actual mails not loaded
14200 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14202 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14204 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
14205 return false;
14207 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14208 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14209 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14211 if(!HasTitle(curTitle))
14212 SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
14215 // Not finish taxi flight path
14216 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes))
14218 // problems with taxi path loading
14219 TaxiNodesEntry const* nodeEntry = NULL;
14220 if(uint32 node_id = m_taxi.GetTaxiSource())
14221 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14223 if(!nodeEntry) // don't know taxi start node, to homebind
14225 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14226 SetMapId(m_homebindMapId);
14227 Relocate( m_homebindX, m_homebindY, m_homebindZ,0.0f);
14228 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14230 else // have start node, to it
14232 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14233 SetMapId(nodeEntry->map_id);
14234 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14235 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14237 m_taxi.ClearTaxiDestinations();
14239 else if(uint32 node_id = m_taxi.GetTaxiSource())
14241 // save source node as recall coord to prevent recall and fall from sky
14242 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14243 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14244 m_recallMap = nodeEntry->map_id;
14245 m_recallX = nodeEntry->x;
14246 m_recallY = nodeEntry->y;
14247 m_recallZ = nodeEntry->z;
14249 // flight will started later
14252 // has to be called after last Relocate() in Player::LoadFromDB
14253 SetFallInformation(0, GetPositionZ());
14255 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14257 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14258 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14259 if(!isAlive())
14260 RemoveAllAurasOnDeath();
14262 //apply all stat bonuses from items and auras
14263 SetCanModifyStats(true);
14264 UpdateAllStats();
14266 // restore remembered power/health values (but not more max values)
14267 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14268 for(uint32 i = 0; i < MAX_POWERS; ++i)
14269 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14271 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14272 outDebugValues();
14274 // GM state
14275 if(GetSession()->GetSecurity() > SEC_PLAYER)
14277 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14279 default:
14280 case 0: break; // disable
14281 case 1: SetGameMaster(true); break; // enable
14282 case 2: // save state
14283 if(extraflags & PLAYER_EXTRA_GM_ON)
14284 SetGameMaster(true);
14285 break;
14288 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14290 default:
14291 case 0: break; // disable
14292 case 1: SetAcceptTicket(true); break; // enable
14293 case 2: // save state
14294 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14295 SetAcceptTicket(true);
14296 break;
14299 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14301 default:
14302 case 0: break; // disable
14303 case 1: SetGMChat(true); break; // enable
14304 case 2: // save state
14305 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14306 SetGMChat(true);
14307 break;
14310 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14312 default:
14313 case 0: break; // disable
14314 case 1: SetAcceptWhispers(true); break; // enable
14315 case 2: // save state
14316 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14317 SetAcceptWhispers(true);
14318 break;
14322 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14324 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14325 m_achievementMgr.CheckAllAchievementCriteria();
14326 return true;
14329 bool Player::isAllowedToLoot(Creature* creature)
14331 if(Player* recipient = creature->GetLootRecipient())
14333 if (recipient == this)
14334 return true;
14335 if( Group* otherGroup = recipient->GetGroup())
14337 Group* thisGroup = GetGroup();
14338 if(!thisGroup)
14339 return false;
14340 return thisGroup == otherGroup;
14342 return false;
14344 else
14345 // prevent other players from looting if the recipient got disconnected
14346 return !creature->hasLootRecipient();
14349 void Player::_LoadActions(QueryResult *result)
14351 m_actionButtons.clear();
14353 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14355 if(result)
14359 Field *fields = result->Fetch();
14361 uint8 button = fields[0].GetUInt8();
14363 addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8());
14365 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14367 while( result->NextRow() );
14369 delete result;
14373 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14375 m_Auras.clear();
14376 for (int i = 0; i < TOTAL_AURAS; i++)
14377 m_modAuras[i].clear();
14379 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14381 if(result)
14385 Field *fields = result->Fetch();
14386 uint64 caster_guid = fields[0].GetUInt64();
14387 uint32 spellid = fields[1].GetUInt32();
14388 uint32 effindex = fields[2].GetUInt32();
14389 uint32 stackcount = fields[3].GetUInt32();
14390 int32 damage = (int32)fields[4].GetUInt32();
14391 int32 maxduration = (int32)fields[5].GetUInt32();
14392 int32 remaintime = (int32)fields[6].GetUInt32();
14393 int32 remaincharges = (int32)fields[7].GetUInt32();
14395 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14396 if(!spellproto)
14398 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14399 continue;
14402 if(effindex >= 3)
14404 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14405 continue;
14408 // negative effects should continue counting down after logout
14409 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14411 if(remaintime <= int32(timediff))
14412 continue;
14414 remaintime -= timediff;
14417 // prevent wrong values of remaincharges
14418 if(spellproto->procCharges)
14420 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14421 remaincharges = spellproto->procCharges;
14423 else
14424 remaincharges = 0;
14426 //do not load single target auras (unless they were cast by the player)
14427 if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
14428 continue;
14430 for(uint32 i=0; i<stackcount; i++)
14432 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14433 if(!damage)
14434 damage = aura->GetModifier()->m_amount;
14435 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14436 AddAura(aura);
14437 sLog.outString("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14440 while( result->NextRow() );
14442 delete result;
14445 if(m_class == CLASS_WARRIOR)
14446 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14449 void Player::LoadCorpse()
14451 if( isAlive() )
14453 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14455 else
14457 if(Corpse *corpse = GetCorpse())
14459 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14461 else
14463 //Prevent Dead Player login without corpse
14464 ResurrectPlayer(0.5f);
14469 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14471 //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());
14472 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14473 //NOTE: the "order by `bag`" is important because it makes sure
14474 //the bagMap is filled before items in the bags are loaded
14475 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14476 //expected to be equipped before offhand items (TODO: fixme)
14478 uint32 zone = GetZoneId();
14480 if (result)
14482 std::list<Item*> problematicItems;
14484 // prevent items from being added to the queue when stored
14485 m_itemUpdateQueueBlocked = true;
14488 Field *fields = result->Fetch();
14489 uint32 bag_guid = fields[1].GetUInt32();
14490 uint8 slot = fields[2].GetUInt8();
14491 uint32 item_guid = fields[3].GetUInt32();
14492 uint32 item_id = fields[4].GetUInt32();
14494 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14496 if(!proto)
14498 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14499 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14500 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14501 continue;
14504 Item *item = NewItemOrBag(proto);
14506 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14508 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14509 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14510 item->FSetState(ITEM_REMOVED);
14511 item->SaveToDB(); // it also deletes item object !
14512 continue;
14515 // not allow have in alive state item limited to another map/zone
14516 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14518 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14519 item->FSetState(ITEM_REMOVED);
14520 item->SaveToDB(); // it also deletes item object !
14521 continue;
14524 // "Conjured items disappear if you are logged out for more than 15 minutes"
14525 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14527 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14528 item->FSetState(ITEM_REMOVED);
14529 item->SaveToDB(); // it also deletes item object !
14530 continue;
14533 bool success = true;
14535 if (!bag_guid)
14537 // the item is not in a bag
14538 item->SetContainer( NULL );
14539 item->SetSlot(slot);
14541 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14543 ItemPosCountVec dest;
14544 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14545 item = StoreItem(dest, item, true);
14546 else
14547 success = false;
14549 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14551 uint16 dest;
14552 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14553 QuickEquipItem(dest, item);
14554 else
14555 success = false;
14557 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14559 ItemPosCountVec dest;
14560 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14561 item = BankItem(dest, item, true);
14562 else
14563 success = false;
14566 if(success)
14568 // store bags that may contain items in them
14569 if(item->IsBag() && IsBagPos(item->GetPos()))
14570 bagMap[item_guid] = (Bag*)item;
14573 else
14575 item->SetSlot(NULL_SLOT);
14576 // the item is in a bag, find the bag
14577 std::map<uint64, Bag*>::iterator itr = bagMap.find(bag_guid);
14578 if(itr != bagMap.end())
14579 itr->second->StoreItem(slot, item, true );
14580 else
14581 success = false;
14584 // item's state may have changed after stored
14585 if (success)
14586 item->SetState(ITEM_UNCHANGED, this);
14587 else
14589 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);
14590 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14591 problematicItems.push_back(item);
14593 } while (result->NextRow());
14595 delete result;
14596 m_itemUpdateQueueBlocked = false;
14598 // send by mail problematic items
14599 while(!problematicItems.empty())
14601 // fill mail
14602 MailItemsInfo mi; // item list preparing
14604 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14606 Item* item = problematicItems.front();
14607 problematicItems.pop_front();
14609 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14612 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14614 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14617 //if(isAlive())
14618 _ApplyAllItemMods();
14621 // load mailed item which should receive current player
14622 void Player::_LoadMailedItems(Mail *mail)
14624 // data needs to be at first place for Item::LoadFromDB
14625 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);
14626 if(!result)
14627 return;
14631 Field *fields = result->Fetch();
14632 uint32 item_guid_low = fields[1].GetUInt32();
14633 uint32 item_template = fields[2].GetUInt32();
14635 mail->AddItem(item_guid_low, item_template);
14637 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14639 if(!proto)
14641 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);
14642 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14643 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14644 continue;
14647 Item *item = NewItemOrBag(proto);
14649 if(!item->LoadFromDB(item_guid_low, 0, result))
14651 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14652 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14653 item->FSetState(ITEM_REMOVED);
14654 item->SaveToDB(); // it also deletes item object !
14655 continue;
14658 AddMItem(item);
14659 } while (result->NextRow());
14661 delete result;
14664 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14666 //set a count of unread mails
14667 //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);
14668 if (resultUnread)
14670 Field *fieldMail = resultUnread->Fetch();
14671 unReadMails = fieldMail[0].GetUInt8();
14672 delete resultUnread;
14675 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14676 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14677 if (resultDelivery)
14679 Field *fieldMail = resultDelivery->Fetch();
14680 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14681 delete resultDelivery;
14685 void Player::_LoadMail()
14687 m_mail.clear();
14688 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14689 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());
14690 if(result)
14694 Field *fields = result->Fetch();
14695 Mail *m = new Mail;
14696 m->messageID = fields[0].GetUInt32();
14697 m->messageType = fields[1].GetUInt8();
14698 m->sender = fields[2].GetUInt32();
14699 m->receiver = fields[3].GetUInt32();
14700 m->subject = fields[4].GetCppString();
14701 m->itemTextId = fields[5].GetUInt32();
14702 bool has_items = fields[6].GetBool();
14703 m->expire_time = (time_t)fields[7].GetUInt64();
14704 m->deliver_time = (time_t)fields[8].GetUInt64();
14705 m->money = fields[9].GetUInt32();
14706 m->COD = fields[10].GetUInt32();
14707 m->checked = fields[11].GetUInt32();
14708 m->stationery = fields[12].GetUInt8();
14709 m->mailTemplateId = fields[13].GetInt16();
14711 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14713 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14714 m->mailTemplateId = 0;
14717 m->state = MAIL_STATE_UNCHANGED;
14719 if (has_items)
14720 _LoadMailedItems(m);
14722 m_mail.push_back(m);
14723 } while( result->NextRow() );
14724 delete result;
14726 m_mailsLoaded = true;
14729 void Player::LoadPet()
14731 //fixme: the pet should still be loaded if the player is not in world
14732 // just not added to the map
14733 if(IsInWorld())
14735 Pet *pet = new Pet;
14736 if(!pet->LoadPetFromDB(this,0,0,true))
14737 delete pet;
14741 void Player::_LoadQuestStatus(QueryResult *result)
14743 mQuestStatus.clear();
14745 uint32 slot = 0;
14747 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14748 //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());
14750 if(result)
14754 Field *fields = result->Fetch();
14756 uint32 quest_id = fields[0].GetUInt32();
14757 // used to be new, no delete?
14758 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14759 if( pQuest )
14761 // find or create
14762 QuestStatusData& questStatusData = mQuestStatus[quest_id];
14764 uint32 qstatus = fields[1].GetUInt32();
14765 if(qstatus < MAX_QUEST_STATUS)
14766 questStatusData.m_status = QuestStatus(qstatus);
14767 else
14769 questStatusData.m_status = QUEST_STATUS_NONE;
14770 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
14773 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
14774 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
14776 time_t quest_time = time_t(fields[4].GetUInt64());
14778 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
14780 AddTimedQuest( quest_id );
14782 if (quest_time <= sWorld.GetGameTime())
14783 questStatusData.m_timer = 1;
14784 else
14785 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * 1000;
14787 else
14788 quest_time = 0;
14790 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
14791 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
14792 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
14793 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
14794 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
14795 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
14796 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
14797 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
14799 questStatusData.uState = QUEST_UNCHANGED;
14801 // add to quest log
14802 if( slot < MAX_QUEST_LOG_SIZE &&
14803 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
14804 questStatusData.m_status==QUEST_STATUS_COMPLETE &&
14805 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
14807 SetQuestSlot(slot,quest_id,quest_time);
14809 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
14810 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
14812 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
14813 if(questStatusData.m_creatureOrGOcount[idx])
14814 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
14816 ++slot;
14819 if(questStatusData.m_rewarded)
14821 // learn rewarded spell if unknown
14822 learnQuestRewardedSpells(pQuest);
14824 // set rewarded title if any
14825 if(pQuest->GetCharTitleId())
14827 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
14828 SetTitle(titleEntry);
14832 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
14835 while( result->NextRow() );
14837 delete result;
14840 // clear quest log tail
14841 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
14842 SetQuestSlot(i,0);
14845 void Player::_LoadDailyQuestStatus(QueryResult *result)
14847 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
14848 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
14850 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14852 if(result)
14854 uint32 quest_daily_idx = 0;
14858 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
14860 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14861 break;
14864 Field *fields = result->Fetch();
14866 uint32 quest_id = fields[0].GetUInt32();
14868 // save _any_ from daily quest times (it must be after last reset anyway)
14869 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
14871 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14872 if( !pQuest )
14873 continue;
14875 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
14876 ++quest_daily_idx;
14878 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
14880 while( result->NextRow() );
14882 delete result;
14885 m_DailyQuestChanged = false;
14888 void Player::_LoadReputation(QueryResult *result)
14890 m_factions.clear();
14892 // Set initial reputations (so everything is nifty before DB data load)
14893 SetInitialFactions();
14895 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
14897 if(result)
14901 Field *fields = result->Fetch();
14903 FactionEntry const *factionEntry = sFactionStore.LookupEntry(fields[0].GetUInt32());
14904 if( factionEntry && (factionEntry->reputationListID >= 0))
14906 FactionState* faction = &m_factions[factionEntry->reputationListID];
14908 // update standing to current
14909 faction->Standing = int32(fields[1].GetUInt32());
14911 uint32 dbFactionFlags = fields[2].GetUInt32();
14913 if( dbFactionFlags & FACTION_FLAG_VISIBLE )
14914 SetFactionVisible(faction); // have internal checks for forced invisibility
14916 if( dbFactionFlags & FACTION_FLAG_INACTIVE)
14917 SetFactionInactive(faction,true); // have internal checks for visibility requirement
14919 if( dbFactionFlags & FACTION_FLAG_AT_WAR ) // DB at war
14920 SetFactionAtWar(faction,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
14921 else // DB not at war
14923 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
14924 if( faction->Flags & FACTION_FLAG_VISIBLE )
14925 SetFactionAtWar(faction,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
14928 // set atWar for hostile
14929 if(GetReputationRank(factionEntry) <= REP_HOSTILE)
14930 SetFactionAtWar(faction,true);
14932 // reset changed flag if values similar to saved in DB
14933 if(faction->Flags==dbFactionFlags)
14934 faction->Changed = false;
14937 while( result->NextRow() );
14939 delete result;
14943 void Player::_LoadSpells(QueryResult *result)
14945 for (PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
14946 delete itr->second;
14947 m_spells.clear();
14949 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,slot,active FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14951 if(result)
14955 Field *fields = result->Fetch();
14957 addSpell(fields[0].GetUInt16(), fields[2].GetBool(), false, true, fields[1].GetUInt16(), fields[3].GetBool());
14959 while( result->NextRow() );
14961 delete result;
14965 void Player::_LoadTutorials(QueryResult *result)
14967 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14969 if(result)
14973 Field *fields = result->Fetch();
14975 for (int iI=0; iI<8; iI++)
14976 m_Tutorials[iI] = fields[iI].GetUInt32();
14978 while( result->NextRow() );
14980 delete result;
14983 m_TutorialsChanged = false;
14986 void Player::_LoadGroup(QueryResult *result)
14988 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14989 if(result)
14991 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
14992 delete result;
14993 Group* group = objmgr.GetGroupByLeader(leaderGuid);
14994 if(group)
14996 uint8 subgroup = group->GetMemberGroup(GetGUID());
14997 SetGroup(group, subgroup);
14998 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
15000 // the group leader may change the instance difficulty while the player is offline
15001 SetDifficulty(group->GetDifficulty());
15007 void Player::_LoadBoundInstances(QueryResult *result)
15009 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15010 m_boundInstances[i].clear();
15012 Group *group = GetGroup();
15014 //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));
15015 if(result)
15019 Field *fields = result->Fetch();
15020 bool perm = fields[1].GetBool();
15021 uint32 mapId = fields[2].GetUInt32();
15022 uint32 instanceId = fields[0].GetUInt32();
15023 uint8 difficulty = fields[3].GetUInt8();
15024 time_t resetTime = (time_t)fields[4].GetUInt64();
15025 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15026 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15027 // and in that case it is not used
15029 if(!perm && group)
15031 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);
15032 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15033 continue;
15036 // since non permanent binds are always solo bind, they can always be reset
15037 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
15038 if(save) BindToInstance(save, perm, true);
15039 } while(result->NextRow());
15040 delete result;
15044 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
15046 // some instances only have one difficulty
15047 const MapEntry* entry = sMapStore.LookupEntry(mapid);
15048 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
15050 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15051 if(itr != m_boundInstances[difficulty].end())
15052 return &itr->second;
15053 else
15054 return NULL;
15057 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
15059 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15060 UnbindInstance(itr, difficulty, unload);
15063 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
15065 if(itr != m_boundInstances[difficulty].end())
15067 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15068 itr->second.save->RemovePlayer(this); // save can become invalid
15069 m_boundInstances[difficulty].erase(itr++);
15073 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15075 if(save)
15077 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15078 if(bind.save)
15080 // update the save when the group kills a boss
15081 if(permanent != bind.perm || save != bind.save)
15082 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());
15084 else
15085 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15087 if(bind.save != save)
15089 if(bind.save) bind.save->RemovePlayer(this);
15090 save->AddPlayer(this);
15093 if(permanent) save->SetCanReset(false);
15095 bind.save = save;
15096 bind.perm = permanent;
15097 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());
15098 return &bind;
15100 else
15101 return NULL;
15104 void Player::SendRaidInfo()
15106 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15108 uint32 counter = 0, i;
15109 for(i = 0; i < TOTAL_DIFFICULTIES; i++)
15110 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15111 if(itr->second.perm) counter++;
15113 data << counter;
15114 for(i = 0; i < TOTAL_DIFFICULTIES; i++)
15116 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15118 if(itr->second.perm)
15120 InstanceSave *save = itr->second.save;
15121 data << (save->GetMapId());
15122 data << (uint32)(save->GetResetTime() - time(NULL));
15123 data << save->GetInstanceId();
15124 data << uint32(counter);
15125 counter--;
15129 GetSession()->SendPacket(&data);
15133 - called on every successful teleportation to a map
15135 void Player::SendSavedInstances()
15137 bool hasBeenSaved = false;
15138 WorldPacket data;
15140 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15142 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15144 if(itr->second.perm) // only permanent binds are sent
15146 hasBeenSaved = true;
15147 break;
15152 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15153 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15154 data << uint32(hasBeenSaved);
15155 GetSession()->SendPacket(&data);
15157 if(!hasBeenSaved)
15158 return;
15160 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15162 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15164 if(itr->second.perm)
15166 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15167 data << uint32(itr->second.save->GetMapId());
15168 GetSession()->SendPacket(&data);
15174 /// convert the player's binds to the group
15175 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15177 bool has_binds = false;
15178 bool has_solo = false;
15180 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15181 assert(player_guid);
15183 // copy all binds to the group, when changing leader it's assumed the character
15184 // will not have any solo binds
15186 if(player)
15188 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15190 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15192 has_binds = true;
15193 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15194 // permanent binds are not removed
15195 if(!itr->second.perm)
15197 player->UnbindInstance(itr, i, true); // increments itr
15198 has_solo = true;
15200 else
15201 ++itr;
15206 // if the player's not online we don't know what binds it has
15207 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));
15208 // the following should not get executed when changing leaders
15209 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15212 bool Player::_LoadHomeBind(QueryResult *result)
15214 bool ok = false;
15215 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15216 if (result)
15218 Field *fields = result->Fetch();
15219 m_homebindMapId = fields[0].GetUInt32();
15220 m_homebindZoneId = fields[1].GetUInt16();
15221 m_homebindX = fields[2].GetFloat();
15222 m_homebindY = fields[3].GetFloat();
15223 m_homebindZ = fields[4].GetFloat();
15224 delete result;
15226 // accept saved data only for valid position (and non instanceable)
15227 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15228 !sMapStore.LookupEntry(m_homebindMapId)->Instanceable() )
15230 ok = true;
15232 else
15233 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15236 if(!ok)
15238 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15239 if(!info) return false;
15241 m_homebindMapId = info->mapId;
15242 m_homebindZoneId = info->zoneId;
15243 m_homebindX = info->positionX;
15244 m_homebindY = info->positionY;
15245 m_homebindZ = info->positionZ;
15247 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);
15250 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
15251 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15253 return true;
15256 /*********************************************************/
15257 /*** SAVE SYSTEM ***/
15258 /*********************************************************/
15260 void Player::SaveToDB()
15262 // delay auto save at any saves (manual, in code, or autosave)
15263 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15265 // first save/honor gain after midnight will also update the player's honor fields
15266 UpdateHonorFields();
15268 // players aren't saved on battleground maps
15269 uint32 mapid = IsBeingTeleported() ? GetTeleportDest().mapid : GetMapId();
15270 const MapEntry * me = sMapStore.LookupEntry(mapid);
15271 if(!me || me->IsBattleGroundOrArena())
15272 return;
15274 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15275 //save, far from tavern/city
15276 //save, but in tavern/city
15277 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15278 outDebugValues();
15280 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15281 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15282 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15283 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15284 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15285 uint32 tmp_displayid = GetDisplayId();
15287 // Set player sit state to standing on save, also stealth and shifted form
15288 SetByteValue(UNIT_FIELD_BYTES_1, 0, 0); // stand state
15289 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15290 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0); // stand flags?
15291 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15292 SetDisplayId(GetNativeDisplayId());
15294 bool inworld = IsInWorld();
15296 CharacterDatabase.BeginTransaction();
15298 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15300 std::string sql_name = m_name;
15301 CharacterDatabase.escape_string(sql_name);
15303 std::ostringstream ss;
15304 ss << "INSERT INTO characters (guid,account,name,race,class,"
15305 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15306 "taximask, online, cinematic, "
15307 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15308 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15309 "death_expire_time, taxi_path, arena_pending_points) VALUES ("
15310 << GetGUIDLow() << ", "
15311 << GetSession()->GetAccountId() << ", '"
15312 << sql_name << "', "
15313 << m_race << ", "
15314 << m_class << ", ";
15316 bool save_to_dest = false;
15317 if(IsBeingTeleported())
15319 // don't save to battlegrounds or arenas
15320 const MapEntry *entry = sMapStore.LookupEntry(GetTeleportDest().mapid);
15321 if(entry && entry->map_type != MAP_BATTLEGROUND && entry->map_type != MAP_ARENA)
15322 save_to_dest = true;
15325 if(!save_to_dest)
15327 ss << GetMapId() << ", "
15328 << (uint32)GetDifficulty() << ", "
15329 << finiteAlways(GetPositionX()) << ", "
15330 << finiteAlways(GetPositionY()) << ", "
15331 << finiteAlways(GetPositionZ()) << ", "
15332 << finiteAlways(GetOrientation()) << ", '";
15334 else
15336 ss << GetTeleportDest().mapid << ", "
15337 << (uint32)GetDifficulty() << ", "
15338 << finiteAlways(GetTeleportDest().x) << ", "
15339 << finiteAlways(GetTeleportDest().y) << ", "
15340 << finiteAlways(GetTeleportDest().z) << ", "
15341 << finiteAlways(GetTeleportDest().o) << ", '";
15344 uint16 i;
15345 for( i = 0; i < m_valuesCount; i++ )
15347 ss << GetUInt32Value(i) << " ";
15350 ss << "', '";
15352 for( i = 0; i < 8; i++ )
15353 ss << m_taxi.GetTaximask(i) << " ";
15355 ss << "', ";
15356 ss << (inworld ? 1 : 0);
15358 ss << ", ";
15359 ss << m_cinematic;
15361 ss << ", ";
15362 ss << m_Played_time[0];
15363 ss << ", ";
15364 ss << m_Played_time[1];
15366 ss << ", ";
15367 ss << finiteAlways(m_rest_bonus);
15368 ss << ", ";
15369 ss << (uint64)time(NULL);
15370 ss << ", ";
15371 ss << is_save_resting;
15372 ss << ", ";
15373 ss << m_resetTalentsCost;
15374 ss << ", ";
15375 ss << (uint64)m_resetTalentsTime;
15377 ss << ", ";
15378 ss << finiteAlways(m_movementInfo.t_x);
15379 ss << ", ";
15380 ss << finiteAlways(m_movementInfo.t_y);
15381 ss << ", ";
15382 ss << finiteAlways(m_movementInfo.t_z);
15383 ss << ", ";
15384 ss << finiteAlways(m_movementInfo.t_o);
15385 ss << ", ";
15386 if (m_transport)
15387 ss << m_transport->GetGUIDLow();
15388 else
15389 ss << "0";
15391 ss << ", ";
15392 ss << m_ExtraFlags;
15394 ss << ", ";
15395 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15397 ss << ", ";
15398 ss << uint32(m_atLoginFlags);
15400 ss << ", ";
15401 ss << GetZoneId();
15403 ss << ", ";
15404 ss << (uint64)m_deathExpireTime;
15406 ss << ", '";
15407 ss << m_taxi.SaveTaxiDestinationsToString();
15408 ss << "', '0' )";
15410 CharacterDatabase.Execute( ss.str().c_str() );
15412 if(m_mailsUpdated) //save mails only when needed
15413 _SaveMail();
15415 _SaveInventory();
15416 _SaveQuestStatus();
15417 _SaveDailyQuestStatus();
15418 _SaveTutorials();
15419 _SaveSpells();
15420 _SaveSpellCooldowns();
15421 _SaveActions();
15422 _SaveAuras();
15423 _SaveReputation();
15425 CharacterDatabase.CommitTransaction();
15427 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15428 SetDisplayId(tmp_displayid);
15429 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15430 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15431 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15432 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15434 // save pet (hunter pet level and experience and all type pets health/mana).
15435 if(Pet* pet = GetPet())
15436 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15437 m_achievementMgr.SaveToDB();
15440 // fast save function for item/money cheating preventing - save only inventory and money state
15441 void Player::SaveInventoryAndGoldToDB()
15443 _SaveInventory();
15444 //money is in data field
15445 SaveDataFieldToDB();
15448 void Player::_SaveActions()
15450 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15452 switch (itr->second.uState)
15454 case ACTIONBUTTON_NEW:
15455 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15456 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15457 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15458 ++itr;
15459 break;
15460 case ACTIONBUTTON_CHANGED:
15461 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15462 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15463 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15464 ++itr;
15465 break;
15466 case ACTIONBUTTON_DELETED:
15467 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15468 m_actionButtons.erase(itr++);
15469 break;
15470 default:
15471 ++itr;
15472 break;
15477 void Player::_SaveAuras()
15479 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15481 AuraMap const& auras = GetAuras();
15483 if (auras.empty())
15484 return;
15486 spellEffectPair lastEffectPair = auras.begin()->first;
15487 uint32 stackCounter = 1;
15489 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15491 if(itr == auras.end() || lastEffectPair != itr->first)
15493 AuraMap::const_iterator itr2 = itr;
15494 // save previous spellEffectPair to db
15495 itr2--;
15496 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15498 //skip all auras from spells that are passive or need a shapeshift
15499 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15501 //do not save single target auras (unless they were cast by the player)
15502 if (!(itr2->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo)))
15504 uint8 i;
15505 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15506 for (i = 0; i < 3; i++)
15507 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15508 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15509 break;
15511 if (i == 3)
15513 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15514 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15515 GetGUIDLow(), itr2->second->GetCasterGUID(), (uint32)itr2->second->GetId(), (uint32)itr2->second->GetEffIndex(), stackCounter, itr2->second->GetModifier()->m_amount,int(itr2->second->GetAuraMaxDuration()),int(itr2->second->GetAuraDuration()),int(itr2->second->GetAuraCharges()));
15520 if(itr == auras.end())
15521 break;
15524 if (lastEffectPair == itr->first)
15525 stackCounter++;
15526 else
15528 lastEffectPair = itr->first;
15529 stackCounter = 1;
15534 void Player::_SaveInventory()
15536 // force items in buyback slots to new state
15537 // and remove those that aren't already
15538 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; i++)
15540 Item *item = m_items[i];
15541 if (!item || item->GetState() == ITEM_NEW) continue;
15542 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15543 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15544 m_items[i]->FSetState(ITEM_NEW);
15547 // update enchantment durations
15548 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15550 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15553 // if no changes
15554 if (m_itemUpdateQueue.empty()) return;
15556 // do not save if the update queue is corrupt
15557 bool error = false;
15558 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15560 Item *item = m_itemUpdateQueue[i];
15561 if(!item || item->GetState() == ITEM_REMOVED) continue;
15562 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15564 if (test == NULL)
15566 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());
15567 error = true;
15569 else if (test != item)
15571 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());
15572 error = true;
15576 if (error)
15578 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15579 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15580 return;
15583 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15585 Item *item = m_itemUpdateQueue[i];
15586 if(!item) continue;
15588 Bag *container = item->GetContainer();
15589 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15591 switch(item->GetState())
15593 case ITEM_NEW:
15594 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());
15595 break;
15596 case ITEM_CHANGED:
15597 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());
15598 break;
15599 case ITEM_REMOVED:
15600 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15601 break;
15602 case ITEM_UNCHANGED:
15603 break;
15606 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15608 m_itemUpdateQueue.clear();
15611 void Player::_SaveMail()
15613 if (!m_mailsLoaded)
15614 return;
15616 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15618 Mail *m = (*itr);
15619 if (m->state == MAIL_STATE_CHANGED)
15621 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'",
15622 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15623 if(m->removedItems.size())
15625 for(std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15626 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15627 m->removedItems.clear();
15629 m->state = MAIL_STATE_UNCHANGED;
15631 else if (m->state == MAIL_STATE_DELETED)
15633 if (m->HasItems())
15634 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15635 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15636 if (m->itemTextId)
15637 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15638 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15639 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15643 //deallocate deleted mails...
15644 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15646 if ((*itr)->state == MAIL_STATE_DELETED)
15648 Mail* m = *itr;
15649 m_mail.erase(itr);
15650 delete m;
15651 itr = m_mail.begin();
15653 else
15654 ++itr;
15657 m_mailsUpdated = false;
15660 void Player::_SaveQuestStatus()
15662 // we don't need transactions here.
15663 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15665 switch (i->second.uState)
15667 case QUEST_NEW :
15668 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15669 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15670 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]);
15671 break;
15672 case QUEST_CHANGED :
15673 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' ",
15674 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 );
15675 break;
15676 case QUEST_UNCHANGED:
15677 break;
15679 i->second.uState = QUEST_UNCHANGED;
15683 void Player::_SaveDailyQuestStatus()
15685 if(!m_DailyQuestChanged)
15686 return;
15688 m_DailyQuestChanged = false;
15690 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15692 // we don't need transactions here.
15693 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15694 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15695 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15696 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
15697 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15700 void Player::_SaveReputation()
15702 for(FactionStateList::iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
15704 if (itr->second.Changed)
15706 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr->second.ID);
15707 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);
15708 itr->second.Changed = false;
15713 void Player::_SaveSpells()
15715 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
15717 ++next;
15718 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15719 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15720 if (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED)
15721 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);
15723 if (itr->second->state == PLAYERSPELL_REMOVED)
15724 _removeSpell(itr->first);
15725 else
15726 itr->second->state = PLAYERSPELL_UNCHANGED;
15730 void Player::_SaveTutorials()
15732 if(!m_TutorialsChanged)
15733 return;
15735 uint32 Rows=0;
15736 // it's better than rebuilding indexes multiple times
15737 QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID );
15738 if(result)
15740 Rows = result->Fetch()[0].GetUInt32();
15741 delete result;
15744 if (Rows)
15746 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'",
15747 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 );
15749 else
15751 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]);
15754 m_TutorialsChanged = false;
15757 void Player::outDebugValues() const
15759 if(!sLog.IsOutDebug()) // optimize disabled debug output
15760 return;
15762 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15763 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15764 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15765 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15766 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15767 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15768 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15769 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15770 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15771 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15772 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15773 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15776 /*********************************************************/
15777 /*** FLOOD FILTER SYSTEM ***/
15778 /*********************************************************/
15780 void Player::UpdateSpeakTime()
15782 // ignore chat spam protection for GMs in any mode
15783 if(GetSession()->GetSecurity() > SEC_PLAYER)
15784 return;
15786 time_t current = time (NULL);
15787 if(m_speakTime > current)
15789 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15790 if(!max_count)
15791 return;
15793 ++m_speakCount;
15794 if(m_speakCount >= max_count)
15796 // prevent overwrite mute time, if message send just before mutes set, for example.
15797 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15798 if(GetSession()->m_muteTime < new_mute)
15799 GetSession()->m_muteTime = new_mute;
15801 m_speakCount = 0;
15804 else
15805 m_speakCount = 0;
15807 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15810 bool Player::CanSpeak() const
15812 return GetSession()->m_muteTime <= time (NULL);
15815 /*********************************************************/
15816 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15817 /*********************************************************/
15819 void Player::SendAttackSwingNotInRange()
15821 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15822 GetSession()->SendPacket( &data );
15825 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15827 std::ostringstream ss;
15828 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15829 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15830 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15831 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15832 sLog.outDebug(ss.str().c_str());
15833 CharacterDatabase.Execute(ss.str().c_str());
15836 void Player::SaveDataFieldToDB()
15838 std::ostringstream ss;
15839 ss<<"UPDATE characters SET data='";
15841 for(uint16 i = 0; i < m_valuesCount; i++ )
15843 ss << GetUInt32Value(i) << " ";
15845 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
15847 CharacterDatabase.Execute(ss.str().c_str());
15850 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
15852 std::ostringstream ss2;
15853 ss2<<"UPDATE characters SET data='";
15854 int i=0;
15855 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
15857 ss2<<tokens[i]<<" ";
15859 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15861 return CharacterDatabase.Execute(ss2.str().c_str());
15864 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
15866 char buf[11];
15867 snprintf(buf,11,"%u",value);
15869 if(index >= tokens.size())
15870 return;
15872 tokens[index] = buf;
15875 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
15877 Tokens tokens;
15878 if(!LoadValuesArrayFromDB(tokens,guid))
15879 return;
15881 if(index >= tokens.size())
15882 return;
15884 char buf[11];
15885 snprintf(buf,11,"%u",value);
15886 tokens[index] = buf;
15888 SaveValuesArrayInDB(tokens,guid);
15891 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
15893 uint32 temp;
15894 memcpy(&temp, &value, sizeof(value));
15895 Player::SetUInt32ValueInDB(index, temp, guid);
15898 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
15900 Tokens tokens;
15901 if(!LoadValuesArrayFromDB(tokens, guid))
15902 return;
15904 uint32 unit_bytes0 = GetUInt32ValueFromArray(tokens, UNIT_FIELD_BYTES_0);
15905 uint8 race = unit_bytes0 & 0xFF;
15906 uint8 class_ = (unit_bytes0 >> 8) & 0xFF;
15908 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
15909 if(!info)
15910 return;
15912 unit_bytes0 &= ~(0xFF << 16);
15913 unit_bytes0 |= (gender << 16);
15914 SetUInt32ValueInArray(tokens, UNIT_FIELD_BYTES_0, unit_bytes0);
15916 SetUInt32ValueInArray(tokens, UNIT_FIELD_DISPLAYID, gender ? info->displayId_f : info->displayId_m);
15917 SetUInt32ValueInArray(tokens, UNIT_FIELD_NATIVEDISPLAYID, gender ? info->displayId_f : info->displayId_m);
15919 SetUInt32ValueInArray(tokens, PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
15921 uint32 player_bytes2 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_2);
15922 player_bytes2 &= ~0xFF;
15923 player_bytes2 |= facialHair;
15924 SetUInt32ValueInArray(tokens, PLAYER_BYTES_2, player_bytes2);
15926 uint32 player_bytes3 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_3);
15927 player_bytes3 &= ~0xFF;
15928 player_bytes3 |= gender;
15929 SetUInt32ValueInArray(tokens, PLAYER_BYTES_3, player_bytes3);
15931 SaveValuesArrayInDB(tokens, guid);
15934 void Player::SendAttackSwingNotStanding()
15936 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
15937 GetSession()->SendPacket( &data );
15940 void Player::SendAttackSwingDeadTarget()
15942 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
15943 GetSession()->SendPacket( &data );
15946 void Player::SendAttackSwingCantAttack()
15948 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
15949 GetSession()->SendPacket( &data );
15952 void Player::SendAttackSwingCancelAttack()
15954 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
15955 GetSession()->SendPacket( &data );
15958 void Player::SendAttackSwingBadFacingAttack()
15960 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
15961 GetSession()->SendPacket( &data );
15964 void Player::SendAutoRepeatCancel()
15966 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
15967 data.append(GetPackGUID()); // may be it's target guid
15968 GetSession()->SendPacket( &data );
15971 void Player::PlaySound(uint32 Sound, bool OnlySelf)
15973 WorldPacket data(SMSG_PLAY_SOUND, 4);
15974 data << Sound;
15975 if (OnlySelf)
15976 GetSession()->SendPacket( &data );
15977 else
15978 SendMessageToSet( &data, true );
15981 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
15983 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
15984 data << Area;
15985 data << Experience;
15986 GetSession()->SendPacket(&data);
15989 void Player::SendDungeonDifficulty(bool IsInGroup)
15991 uint8 val = 0x00000001;
15992 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
15993 data << (uint32)GetDifficulty();
15994 data << uint32(val);
15995 data << uint32(IsInGroup);
15996 GetSession()->SendPacket(&data);
15999 void Player::SendResetFailedNotify(uint32 mapid)
16001 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
16002 data << uint32(mapid);
16003 GetSession()->SendPacket(&data);
16006 /// Reset all solo instances and optionally send a message on success for each
16007 void Player::ResetInstances(uint8 method)
16009 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16011 // we assume that when the difficulty changes, all instances that can be reset will be
16012 uint8 dif = GetDifficulty();
16014 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
16016 InstanceSave *p = itr->second.save;
16017 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
16018 if(!entry || !p->CanReset())
16020 ++itr;
16021 continue;
16024 if(method == INSTANCE_RESET_ALL)
16026 // the "reset all instances" method can only reset normal maps
16027 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
16029 ++itr;
16030 continue;
16034 // if the map is loaded, reset it
16035 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
16036 if(map && map->IsDungeon())
16037 ((InstanceMap*)map)->Reset(method);
16039 // since this is a solo instance there should not be any players inside
16040 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16041 SendResetInstanceSuccess(p->GetMapId());
16043 p->DeleteFromDB();
16044 m_boundInstances[dif].erase(itr++);
16046 // the following should remove the instance save from the manager and delete it as well
16047 p->RemovePlayer(this);
16051 void Player::SendResetInstanceSuccess(uint32 MapId)
16053 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16054 data << MapId;
16055 GetSession()->SendPacket(&data);
16058 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16060 // TODO: find what other fail reasons there are besides players in the instance
16061 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16062 data << reason;
16063 data << MapId;
16064 GetSession()->SendPacket(&data);
16067 /*********************************************************/
16068 /*** Update timers ***/
16069 /*********************************************************/
16071 ///checks the 15 afk reports per 5 minutes limit
16072 void Player::UpdateAfkReport(time_t currTime)
16074 if(m_bgAfkReportedTimer <= currTime)
16076 m_bgAfkReportedCount = 0;
16077 m_bgAfkReportedTimer = currTime+5*MINUTE;
16081 void Player::UpdateContestedPvP(uint32 diff)
16083 if(!m_contestedPvPTimer||isInCombat())
16084 return;
16085 if(m_contestedPvPTimer <= diff)
16087 ResetContestedPvP();
16089 else
16090 m_contestedPvPTimer -= diff;
16093 void Player::UpdatePvPFlag(time_t currTime)
16095 if(!IsPvP())
16096 return;
16097 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16098 return;
16100 UpdatePvP(false);
16103 void Player::UpdateDuelFlag(time_t currTime)
16105 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16106 return;
16108 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16109 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16111 duel->startTimer = 0;
16112 duel->startTime = currTime;
16113 duel->opponent->duel->startTimer = 0;
16114 duel->opponent->duel->startTime = currTime;
16117 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16119 if(!pet)
16120 pet = GetPet();
16122 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16124 //returning of reagents only for players, so best done here
16125 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16126 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16128 if(spellInfo)
16130 for(uint32 i = 0; i < 7; ++i)
16132 if(spellInfo->Reagent[i] > 0)
16134 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16135 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16136 if( msg == EQUIP_ERR_OK )
16138 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16139 if(IsInWorld())
16140 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16145 m_temporaryUnsummonedPetNumber = 0;
16148 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16149 return;
16151 // only if current pet in slot
16152 switch(pet->getPetType())
16154 case MINI_PET:
16155 m_miniPet = 0;
16156 break;
16157 case GUARDIAN_PET:
16158 m_guardianPets.erase(pet->GetGUID());
16159 break;
16160 default:
16161 if(GetPetGUID() == pet->GetGUID())
16162 SetPet(NULL);
16163 break;
16166 pet->CombatStop();
16168 if(returnreagent)
16170 switch(pet->GetEntry())
16172 //warlock pets except imp are removed(?) when logging out
16173 case 1860:
16174 case 1863:
16175 case 417:
16176 case 17252:
16177 mode = PET_SAVE_NOT_IN_SLOT;
16178 break;
16182 pet->SavePetToDB(mode);
16184 pet->CleanupsBeforeDelete();
16185 pet->AddObjectToRemoveList();
16186 pet->m_removed = true;
16188 if(pet->isControlled())
16190 WorldPacket data(SMSG_PET_SPELLS, 8);
16191 data << uint64(0);
16192 data << uint32(0);
16193 GetSession()->SendPacket(&data);
16195 if(GetGroup())
16196 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16200 void Player::RemoveMiniPet()
16202 if(Pet* pet = GetMiniPet())
16204 pet->Remove(PET_SAVE_AS_DELETED);
16205 m_miniPet = 0;
16209 Pet* Player::GetMiniPet()
16211 if(!m_miniPet)
16212 return NULL;
16213 return ObjectAccessor::GetPet(m_miniPet);
16216 void Player::RemoveGuardians()
16218 while(!m_guardianPets.empty())
16220 uint64 guid = *m_guardianPets.begin();
16221 if(Pet* pet = ObjectAccessor::GetPet(guid))
16222 pet->Remove(PET_SAVE_AS_DELETED);
16224 m_guardianPets.erase(guid);
16228 bool Player::HasGuardianWithEntry(uint32 entry)
16230 // pet guid middle part is entry (and creature also)
16231 // and in guardian list must be guardians with same entry _always_
16232 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
16233 if(GUID_ENPART(*itr)==entry)
16234 return true;
16236 return false;
16239 void Player::Uncharm()
16241 Unit* charm = GetCharm();
16242 if(!charm)
16243 return;
16245 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16246 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16249 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16251 *data << (uint8)msgtype;
16252 *data << (uint32)language;
16253 *data << (uint64)GetGUID();
16254 *data << (uint32)language; //language 2.1.0 ?
16255 *data << (uint64)GetGUID();
16256 *data << (uint32)(text.length()+1);
16257 *data << text;
16258 *data << (uint8)chatTag();
16261 void Player::Say(const std::string& text, const uint32 language)
16263 WorldPacket data(SMSG_MESSAGECHAT, 200);
16264 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16265 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16268 void Player::Yell(const std::string& text, const uint32 language)
16270 WorldPacket data(SMSG_MESSAGECHAT, 200);
16271 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16272 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16275 void Player::TextEmote(const std::string& text)
16277 WorldPacket data(SMSG_MESSAGECHAT, 200);
16278 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16279 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16282 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16284 if (language != LANG_ADDON) // if not addon data
16285 language = LANG_UNIVERSAL; // whispers should always be readable
16287 Player *rPlayer = objmgr.GetPlayer(receiver);
16289 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16290 if(!rPlayer->isDND() || isGameMaster())
16292 WorldPacket data(SMSG_MESSAGECHAT, 200);
16293 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16294 rPlayer->GetSession()->SendPacket(&data);
16296 data.Initialize(SMSG_MESSAGECHAT, 200);
16297 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16298 GetSession()->SendPacket(&data);
16300 else
16302 // announce to player that player he is whispering to is dnd and cannot receive his message
16303 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16306 if(!isAcceptWhispers())
16308 SetAcceptWhispers(true);
16309 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16312 // announce to player that player he is whispering to is afk
16313 if(rPlayer->isAFK())
16314 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16316 // if player whisper someone, auto turn of dnd to be able to receive an answer
16317 if(isDND() && !rPlayer->isGameMaster())
16318 ToggleDND();
16321 void Player::PetSpellInitialize()
16323 Pet* pet = GetPet();
16325 if(!pet)
16326 return;
16328 sLog.outDebug("Pet Spells Groups");
16330 CharmInfo *charmInfo = pet->GetCharmInfo();
16332 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+10*4);
16333 data << uint64(pet->GetGUID());
16334 data << uint32(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16335 data << uint32(0);
16336 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16338 // action bar loop
16339 for(uint32 i = 0; i < 10; i++)
16341 data << uint32(charmInfo->GetActionBarEntry(i)->Raw);
16344 size_t spellsCountPos = data.wpos();
16346 // spells count
16347 uint8 addlist = 0;
16348 data << uint8(addlist); // placeholder
16350 if(pet->isControlled() && ((pet->getPetType() == HUNTER_PET) || ((pet->GetCreatureInfo()->type == CREATURE_TYPE_DEMON) && (getClass() == CLASS_WARLOCK))))
16352 // spells loop
16353 for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16355 if(itr->second->state == PETSPELL_REMOVED)
16356 continue;
16358 data << uint16(itr->first);
16359 data << uint16(itr->second->active); // pet spell active state isn't boolean
16360 ++addlist;
16364 data.put<uint8>(spellsCountPos, addlist);
16366 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16367 data << uint8(cooldownsCount);
16369 time_t curTime = time(NULL);
16371 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16373 time_t cooldown = 0;
16375 if(itr->second > curTime)
16376 cooldown = (itr->second - curTime) * 1000;
16378 data << uint16(itr->first); // spellid
16379 data << uint16(0); // spell category?
16380 data << uint32(itr->second); // cooldown
16381 data << uint32(0); // category cooldown
16384 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16386 time_t cooldown = 0;
16388 if(itr->second > curTime)
16389 cooldown = (itr->second - curTime) * 1000;
16391 data << uint16(itr->first); // spellid
16392 data << uint16(0); // spell category?
16393 data << uint32(0); // cooldown
16394 data << uint32(itr->second); // category cooldown
16397 GetSession()->SendPacket(&data);
16400 void Player::PossessSpellInitialize()
16402 Unit* charm = GetCharm();
16404 if(!charm)
16405 return;
16407 CharmInfo *charmInfo = charm->GetCharmInfo();
16409 if(!charmInfo)
16411 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16412 return;
16415 uint8 addlist = 0;
16416 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16418 //16
16419 data << uint64(charm->GetGUID());
16420 data << uint32(0x00000000);
16421 data << uint32(0);
16422 data << uint8(0) << uint8(0) << uint16(0);
16424 for(uint32 i = 0; i < 10; i++) //40
16426 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16429 data << uint8(addlist); //1
16431 uint8 count = 0;
16432 data << uint8(count); // cooldowns count
16434 GetSession()->SendPacket(&data);
16437 void Player::CharmSpellInitialize()
16439 Unit* charm = GetCharm();
16441 if(!charm)
16442 return;
16444 CharmInfo *charmInfo = charm->GetCharmInfo();
16445 if(!charmInfo)
16447 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16448 return;
16451 uint8 addlist = 0;
16453 if(charm->GetTypeId() != TYPEID_PLAYER)
16455 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16457 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16459 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16461 if(charmInfo->GetCharmSpell(i)->spellId)
16462 ++addlist;
16467 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16469 data << uint64(charm->GetGUID());
16470 data << uint32(0x00000000);
16471 data << uint32(0);
16472 if(charm->GetTypeId() != TYPEID_PLAYER)
16473 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
16474 else
16475 data << uint8(0) << uint8(0);
16476 data << uint16(0);
16478 for(uint32 i = 0; i < 10; i++) //40
16480 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16483 data << uint8(addlist); //1
16485 if(addlist)
16487 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16489 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16490 if(cspell->spellId)
16492 data << uint16(cspell->spellId);
16493 data << uint16(cspell->active);
16498 uint8 count = 0;
16499 data << uint8(count); // cooldowns count
16501 GetSession()->SendPacket(&data);
16504 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16506 if (!mod || !spellInfo)
16507 return false;
16509 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16511 // prevent apply to any spell except spell that trigger expire
16512 if(spell)
16514 if(mod->lastAffected != spell)
16515 return false;
16517 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16518 return false;
16521 return spellmgr.IsAffectedByMod(spellInfo, mod);
16524 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16526 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16528 for(int eff=0;eff<96;++eff)
16530 uint64 _mask = 0;
16531 uint64 _mask2= 0;
16532 if (eff<64) _mask = uint64(1) << (eff- 0);
16533 else _mask2= uint64(1) << (eff-64);
16534 if ( mod->mask & _mask || mod->mask2 & _mask2)
16536 int32 val = 0;
16537 for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16539 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16540 val += (*itr)->value;
16542 val += apply ? mod->value : -(mod->value);
16543 WorldPacket data(Opcode, (1+1+4));
16544 data << uint8(eff);
16545 data << uint8(mod->op);
16546 data << int32(val);
16547 SendDirectMessage(&data);
16551 if (apply)
16552 m_spellMods[mod->op].push_back(mod);
16553 else
16555 if (mod->charges == -1)
16556 --m_SpellModRemoveCount;
16557 m_spellMods[mod->op].remove(mod);
16558 delete mod;
16562 void Player::RemoveSpellMods(Spell const* spell)
16564 if(!spell || (m_SpellModRemoveCount == 0))
16565 return;
16567 for(int i=0;i<MAX_SPELLMOD;++i)
16569 for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16571 SpellModifier *mod = *itr;
16572 ++itr;
16574 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16576 RemoveAurasDueToSpell(mod->spellId);
16577 if (m_spellMods[i].empty())
16578 break;
16579 else
16580 itr = m_spellMods[i].begin();
16586 // send Proficiency
16587 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16589 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16590 data << pr1 << pr2;
16591 GetSession()->SendPacket (&data);
16594 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16596 QueryResult *result = NULL;
16597 if(type==10)
16598 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16599 else
16600 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16601 if(result)
16603 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.
16604 { // and SendPetitionQueryOpcode reads data from the DB
16605 Field *fields = result->Fetch();
16606 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16607 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16609 // send update if charter owner in game
16610 Player* owner = objmgr.GetPlayer(ownerguid);
16611 if(owner)
16612 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16614 } while ( result->NextRow() );
16616 delete result;
16618 if(type==10)
16619 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16620 else
16621 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16624 CharacterDatabase.BeginTransaction();
16625 if(type == 10)
16627 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16628 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16630 else
16632 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16633 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16635 CharacterDatabase.CommitTransaction();
16638 void Player::LeaveAllArenaTeams(uint64 guid)
16640 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));
16641 if(!result)
16642 return;
16646 Field *fields = result->Fetch();
16647 uint32 at_id = fields[0].GetUInt32();
16648 if(at_id != 0)
16650 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
16651 if(at)
16652 at->DelMember(guid);
16654 } while (result->NextRow());
16656 delete result;
16659 void Player::SetRestBonus (float rest_bonus_new)
16661 // Prevent resting on max level
16662 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16663 rest_bonus_new = 0;
16665 if(rest_bonus_new < 0)
16666 rest_bonus_new = 0;
16668 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16670 if(rest_bonus_new > rest_bonus_max)
16671 m_rest_bonus = rest_bonus_max;
16672 else
16673 m_rest_bonus = rest_bonus_new;
16675 // update data for client
16676 if(m_rest_bonus>10)
16677 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16678 else if(m_rest_bonus<=1)
16679 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16681 //RestTickUpdate
16682 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16685 void Player::HandleStealthedUnitsDetection()
16687 std::list<Unit*> stealthedUnits;
16689 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16690 Cell cell(p);
16691 cell.data.Part.reserved = ALL_DISTRICT;
16692 cell.SetNoCreate();
16694 MaNGOS::AnyStealthedCheck u_check;
16695 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(stealthedUnits, u_check);
16697 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16698 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16700 CellLock<GridReadGuard> cell_lock(cell, p);
16701 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
16702 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
16704 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16706 if((*i)==this)
16708 i = stealthedUnits.erase(i);
16709 continue;
16712 if ((*i)->isVisibleForOrDetect(this,true))
16715 (*i)->SendUpdateToPlayer(this);
16716 m_clientGUIDs.insert((*i)->GetGUID());
16718 #ifdef MANGOS_DEBUG
16719 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16720 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16721 #endif
16723 // target aura duration for caster show only if target exist at caster client
16724 // send data at target visibility change (adding to client)
16725 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16726 SendAurasForTarget(*i);
16728 i = stealthedUnits.erase(i);
16729 continue;
16732 ++i;
16736 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
16738 if(nodes.size() < 2)
16739 return false;
16741 // not let cheating with start flight mounted
16742 if(IsMounted())
16744 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16745 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16746 GetSession()->SendPacket(&data);
16747 return false;
16750 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16752 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16753 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16754 GetSession()->SendPacket(&data);
16755 return false;
16758 // 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
16759 if(GetSession()->isLogingOut() ||
16760 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
16761 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
16762 IsNonMeleeSpellCasted(false) ||
16763 isInCombat())
16765 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16766 data << uint32(ERR_TAXIPLAYERBUSY);
16767 GetSession()->SendPacket(&data);
16768 return false;
16771 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16772 return false;
16774 uint32 sourcenode = nodes[0];
16776 // starting node too far away (cheat?)
16777 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16778 if( !node || node->map_id != GetMapId() ||
16779 (node->x - GetPositionX())*(node->x - GetPositionX())+
16780 (node->y - GetPositionY())*(node->y - GetPositionY())+
16781 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16782 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
16784 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16785 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16786 GetSession()->SendPacket(&data);
16787 return false;
16790 // Prepare to flight start now
16792 // stop combat at start taxi flight if any
16793 CombatStop();
16795 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16796 TradeCancel(true);
16798 // clean not finished taxi path if any
16799 m_taxi.ClearTaxiDestinations();
16801 // 0 element current node
16802 m_taxi.AddTaxiDestination(sourcenode);
16804 // fill destinations path tail
16805 uint32 sourcepath = 0;
16806 uint32 totalcost = 0;
16808 uint32 prevnode = sourcenode;
16809 uint32 lastnode = 0;
16811 for(uint32 i = 1; i < nodes.size(); ++i)
16813 uint32 path, cost;
16815 lastnode = nodes[i];
16816 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16818 if(!path)
16820 m_taxi.ClearTaxiDestinations();
16821 return false;
16824 totalcost += cost;
16826 if(prevnode == sourcenode)
16827 sourcepath = path;
16829 m_taxi.AddTaxiDestination(lastnode);
16831 prevnode = lastnode;
16834 if(!mount_id) // if not provide then attempt use default.
16835 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
16837 if (mount_id == 0 || sourcepath == 0)
16839 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16840 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16841 GetSession()->SendPacket(&data);
16842 m_taxi.ClearTaxiDestinations();
16843 return false;
16846 uint32 money = GetMoney();
16848 if(npc)
16850 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16853 if(money < totalcost)
16855 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16856 data << uint32(ERR_TAXINOTENOUGHMONEY);
16857 GetSession()->SendPacket(&data);
16858 m_taxi.ClearTaxiDestinations();
16859 return false;
16862 //Checks and preparations done, DO FLIGHT
16863 ModifyMoney(-(int32)totalcost);
16865 // prevent stealth flight
16866 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16868 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16869 data << uint32(ERR_TAXIOK);
16870 GetSession()->SendPacket(&data);
16872 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16874 GetSession()->SendDoFlight(mount_id, sourcepath);
16876 return true;
16879 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16881 // last check 2.0.10
16882 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16883 data << GetGUID();
16884 data << uint8(0x0); // flags (0x1, 0x2)
16885 time_t curTime = time(NULL);
16886 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
16888 if (itr->second->state == PLAYERSPELL_REMOVED)
16889 continue;
16890 uint32 unSpellId = itr->first;
16891 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
16892 if (!spellInfo)
16894 ASSERT(spellInfo);
16895 continue;
16898 // Not send cooldown for this spells
16899 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
16900 continue;
16902 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
16904 data << unSpellId;
16905 data << unTimeMs; // in m.secs
16906 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/1000);
16909 GetSession()->SendPacket(&data);
16912 void Player::InitDataForForm(bool reapplyMods)
16914 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
16915 if(ssEntry && ssEntry->attackSpeed)
16917 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
16918 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
16919 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
16921 else
16922 SetRegularAttackTime();
16924 switch(m_form)
16926 case FORM_CAT:
16928 if(getPowerType()!=POWER_ENERGY)
16929 setPowerType(POWER_ENERGY);
16930 break;
16932 case FORM_BEAR:
16933 case FORM_DIREBEAR:
16935 if(getPowerType()!=POWER_RAGE)
16936 setPowerType(POWER_RAGE);
16937 break;
16939 default: // 0, for example
16941 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
16942 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
16943 setPowerType(Powers(cEntry->powerType));
16944 break;
16948 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16949 if (!reapplyMods)
16950 UpdateEquipSpellsAtFormChange();
16952 UpdateAttackPowerAndDamage();
16953 UpdateAttackPowerAndDamage(true);
16956 // Return true is the bought item has a max count to force refresh of window by caller
16957 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
16959 // cheating attempt
16960 if(count < 1) count = 1;
16962 if(!isAlive())
16963 return false;
16965 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
16966 if( !pProto )
16968 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
16969 return false;
16972 Creature *pCreature = ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid,UNIT_NPC_FLAG_VENDOR);
16973 if (!pCreature)
16975 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
16976 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
16977 return false;
16980 VendorItemData const* vItems = pCreature->GetVendorItems();
16981 if(!vItems || vItems->Empty())
16983 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16984 return false;
16987 size_t vendor_slot = vItems->FindItemSlot(item);
16988 if(vendor_slot >= vItems->GetItemCount())
16990 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16991 return false;
16994 VendorItem const* crItem = vItems->m_items[vendor_slot];
16996 // check current item amount if it limited
16997 if( crItem->maxcount != 0 )
16999 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
17001 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
17002 return false;
17006 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
17008 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
17009 return false;
17012 if(crItem->ExtendedCost)
17014 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17015 if(!iece)
17017 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
17018 return false;
17021 // honor points price
17022 if(GetHonorPoints() < (iece->reqhonorpoints * count))
17024 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
17025 return false;
17028 // arena points price
17029 if(GetArenaPoints() < (iece->reqarenapoints * count))
17031 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
17032 return false;
17035 // item base price
17036 for (uint8 i = 0; i < 5; ++i)
17038 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17040 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17041 return false;
17045 // check for personal arena rating requirement
17046 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
17048 // probably not the proper equip err
17049 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17050 return false;
17054 uint32 price = pProto->BuyPrice * count;
17056 // reputation discount
17057 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17059 if( GetMoney() < price )
17061 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17062 return false;
17065 uint8 bag = 0; // init for case invalid bagGUID
17067 if (bagguid != NULL_BAG && slot != NULL_SLOT)
17069 Bag *pBag;
17070 if( bagguid == GetGUID() )
17072 bag = INVENTORY_SLOT_BAG_0;
17074 else
17076 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;i++)
17078 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
17079 if( pBag )
17081 if( bagguid == pBag->GetGUID() )
17083 bag = i;
17084 break;
17091 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
17093 ItemPosCountVec dest;
17094 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17095 if( msg != EQUIP_ERR_OK )
17097 SendEquipError( msg, NULL, NULL );
17098 return false;
17101 ModifyMoney( -(int32)price );
17102 if(crItem->ExtendedCost) // case for new honor system
17104 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17105 if(iece->reqhonorpoints)
17106 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17107 if(iece->reqarenapoints)
17108 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17109 for (uint8 i = 0; i < 5; ++i)
17111 if(iece->reqitem[i])
17112 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17116 if(Item *it = StoreNewItem( dest, item, true ))
17118 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17120 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17121 data << pCreature->GetGUID();
17122 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17123 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17124 data << (uint32)count;
17125 GetSession()->SendPacket(&data);
17127 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17130 else if( IsEquipmentPos( bag, slot ) )
17132 if(pProto->BuyCount * count != 1)
17134 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17135 return false;
17138 uint16 dest;
17139 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17140 if( msg != EQUIP_ERR_OK )
17142 SendEquipError( msg, NULL, NULL );
17143 return false;
17146 ModifyMoney( -(int32)price );
17147 if(crItem->ExtendedCost) // case for new honor system
17149 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17150 if(iece->reqhonorpoints)
17151 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17152 if(iece->reqarenapoints)
17153 ModifyArenaPoints( - int32(iece->reqarenapoints));
17154 for (uint8 i = 0; i < 5; ++i)
17156 if(iece->reqitem[i])
17157 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17161 if(Item *it = EquipNewItem( dest, item, true ))
17163 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17165 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17166 data << pCreature->GetGUID();
17167 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17168 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17169 data << (uint32)count;
17170 GetSession()->SendPacket(&data);
17172 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17174 AutoUnequipOffhandIfNeed();
17177 else
17179 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17180 return false;
17183 return crItem->maxcount!=0;
17186 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17188 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17189 // the personal rating of the arena team must match the required limit as well
17190 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17191 uint32 max_personal_rating = 0;
17192 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17194 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17196 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17197 uint32 t_rating = at->GetRating();
17198 p_rating = p_rating<t_rating? p_rating : t_rating;
17199 if(max_personal_rating < p_rating)
17200 max_personal_rating = p_rating;
17203 return max_personal_rating;
17206 void Player::UpdateHomebindTime(uint32 time)
17208 // GMs never get homebind timer online
17209 if (m_InstanceValid || isGameMaster())
17211 if(m_HomebindTimer) // instance valid, but timer not reset
17213 // hide reminder
17214 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17215 data << uint32(0);
17216 data << uint32(0);
17217 GetSession()->SendPacket(&data);
17219 // instance is valid, reset homebind timer
17220 m_HomebindTimer = 0;
17222 else if (m_HomebindTimer > 0)
17224 if (time >= m_HomebindTimer)
17226 // teleport to homebind location
17227 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
17229 else
17230 m_HomebindTimer -= time;
17232 else
17234 // instance is invalid, start homebind timer
17235 m_HomebindTimer = 60000;
17236 // send message to player
17237 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17238 data << m_HomebindTimer;
17239 data << uint32(1);
17240 GetSession()->SendPacket(&data);
17241 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17245 void Player::UpdatePvP(bool state, bool ovrride)
17247 if(!state || ovrride)
17249 SetPvP(state);
17250 if(Pet* pet = GetPet())
17251 pet->SetPvP(state);
17252 if(Unit* charmed = GetCharm())
17253 charmed->SetPvP(state);
17255 pvpInfo.endTimer = 0;
17257 else
17259 if(pvpInfo.endTimer != 0)
17260 pvpInfo.endTimer = time(NULL);
17261 else
17263 SetPvP(state);
17265 if(Pet* pet = GetPet())
17266 pet->SetPvP(state);
17267 if(Unit* charmed = GetCharm())
17268 charmed->SetPvP(state);
17273 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17275 SpellCooldown sc;
17276 sc.end = end_time;
17277 sc.itemid = itemid;
17278 m_spellCooldowns[spellid] = sc;
17281 void Player::SendCooldownEvent(SpellEntry const *spellInfo)
17283 if ( !(spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) )
17284 return;
17286 // Get spell cooldown
17287 int32 cooldown = GetSpellRecoveryTime(spellInfo);
17288 // Apply spellmods
17289 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, cooldown);
17290 if (cooldown < 0)
17291 cooldown = 0;
17292 // Add cooldown
17293 AddSpellCooldown(spellInfo->Id, 0, time(NULL) + cooldown / 1000);
17294 // Send activate
17295 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17296 data << spellInfo->Id;
17297 data << GetGUID();
17298 SendDirectMessage(&data);
17300 //slot to be excluded while counting
17301 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17303 if(!enchantmentcondition)
17304 return true;
17306 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17308 if(!Condition)
17309 return true;
17311 uint8 curcount[4] = {0, 0, 0, 0};
17313 //counting current equipped gem colors
17314 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17316 if(i == slot)
17317 continue;
17318 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17319 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17321 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17323 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17324 if(!enchant_id)
17325 continue;
17327 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17328 if(!enchantEntry)
17329 continue;
17331 uint32 gemid = enchantEntry->GemID;
17332 if(!gemid)
17333 continue;
17335 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17336 if(!gemProto)
17337 continue;
17339 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17340 if(!gemProperty)
17341 continue;
17343 uint8 GemColor = gemProperty->color;
17345 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17347 if(tmpcolormask & GemColor)
17348 ++curcount[b];
17354 bool activate = true;
17356 for(int i = 0; i < 5; i++)
17358 if(!Condition->Color[i])
17359 continue;
17361 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17363 // if have <CompareColor> use them as count, else use <value> from Condition
17364 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17366 switch(Condition->Comparator[i])
17368 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17369 activate &= (_cur_gem < _cmp_gem) ? true : false;
17370 break;
17371 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17372 activate &= (_cur_gem > _cmp_gem) ? true : false;
17373 break;
17374 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17375 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17376 break;
17380 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");
17382 return activate;
17385 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17387 //cycle all equipped items
17388 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17390 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17391 if(slot == exceptslot)
17392 continue;
17394 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17396 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17397 continue;
17399 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17401 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17402 if(!enchant_id)
17403 continue;
17405 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17406 if(!enchantEntry)
17407 continue;
17409 uint32 condition = enchantEntry->EnchantmentCondition;
17410 if(condition)
17412 //was enchant active with/without item?
17413 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17414 //should it now be?
17415 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17417 // ignore item gem conditions
17418 //if state changed, (dis)apply enchant
17419 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17426 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17427 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17429 //cycle all equipped items
17430 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17432 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17433 if(slot == exceptslot)
17434 continue;
17436 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17438 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17439 continue;
17441 //cycle all (gem)enchants
17442 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17444 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17445 if(!enchant_id) //if no enchant go to next enchant(slot)
17446 continue;
17448 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17449 if(!enchantEntry)
17450 continue;
17452 //only metagems to be (de)activated, so only enchants with condition
17453 uint32 condition = enchantEntry->EnchantmentCondition;
17454 if(condition)
17455 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17460 void Player::LeaveBattleground(bool teleportToEntryPoint)
17462 if(BattleGround *bg = GetBattleGround())
17464 bool need_debuf = bg->isBattleGround() && (bg->GetStatus() == STATUS_IN_PROGRESS) && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER);
17466 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17468 // call after remove to be sure that player resurrected for correct cast
17469 if(need_debuf)
17470 CastSpell(this, 26013, true); // Deserter
17474 bool Player::CanJoinToBattleground() const
17476 // check Deserter debuff
17477 if(GetDummyAura(26013))
17478 return false;
17480 return true;
17483 bool Player::CanReportAfkDueToLimit()
17485 // a player can complain about 15 people per 5 minutes
17486 if(m_bgAfkReportedCount >= 15)
17487 return false;
17488 ++m_bgAfkReportedCount;
17489 return true;
17492 ///This player has been blamed to be inactive in a battleground
17493 void Player::ReportedAfkBy(Player* reporter)
17495 BattleGround *bg = GetBattleGround();
17496 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17497 return;
17499 // check if player has 'Idle' or 'Inactive' debuff
17500 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17502 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17503 // 3 players have to complain to apply debuff
17504 if(m_bgAfkReporter.size() >= 3)
17506 // cast 'Idle' spell
17507 CastSpell(this, 43680, true);
17508 m_bgAfkReporter.clear();
17513 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17515 // gamemaster in GM mode see all, including ghosts
17516 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17517 return true;
17519 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17520 if (InBattleGround())
17522 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17523 return false;
17524 return true;
17527 // Live player see live player or dead player with not realized corpse
17528 if(pl->isAlive() || pl->m_deathTimer > 0)
17530 return isAlive() || m_deathTimer > 0;
17533 // Ghost see other friendly ghosts, that's for sure
17534 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17535 return true;
17537 // Dead player see live players near own corpse
17538 if(isAlive())
17540 Corpse *corpse = pl->GetCorpse();
17541 if(corpse)
17543 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17544 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17545 return true;
17549 // and not see any other
17550 return false;
17553 bool Player::IsVisibleGloballyFor( Player* u ) const
17555 if(!u)
17556 return false;
17558 // Always can see self
17559 if (u==this)
17560 return true;
17562 // Visible units, always are visible for all players
17563 if (GetVisibility() == VISIBILITY_ON)
17564 return true;
17566 // GMs are visible for higher gms (or players are visible for gms)
17567 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17568 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17570 // non faction visibility non-breakable for non-GMs
17571 if (GetVisibility() == VISIBILITY_OFF)
17572 return false;
17574 // non-gm stealth/invisibility not hide from global player lists
17575 return true;
17578 void Player::UpdateVisibilityOf(WorldObject* target)
17580 if(HaveAtClient(target))
17582 if(!target->isVisibleForInState(this,true))
17584 target->DestroyForPlayer(this);
17585 m_clientGUIDs.erase(target->GetGUID());
17587 #ifdef MANGOS_DEBUG
17588 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17589 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17590 #endif
17593 else
17595 if(target->isVisibleForInState(this,false))
17597 target->SendUpdateToPlayer(this);
17598 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17599 m_clientGUIDs.insert(target->GetGUID());
17601 #ifdef MANGOS_DEBUG
17602 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17603 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17604 #endif
17606 // target aura duration for caster show only if target exist at caster client
17607 // send data at target visibility change (adding to client)
17608 if(target!=this && target->isType(TYPEMASK_UNIT))
17609 SendAurasForTarget((Unit*)target);
17611 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17612 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17617 template<class T>
17618 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17620 s64.insert(target->GetGUID());
17623 template<>
17624 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17626 if(!target->IsTransport())
17627 s64.insert(target->GetGUID());
17630 template<class T>
17631 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17633 if(HaveAtClient(target))
17635 if(!target->isVisibleForInState(this,true))
17637 target->BuildOutOfRangeUpdateBlock(&data);
17638 m_clientGUIDs.erase(target->GetGUID());
17640 #ifdef MANGOS_DEBUG
17641 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17642 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));
17643 #endif
17646 else
17648 if(target->isVisibleForInState(this,false))
17650 visibleNow.insert(target);
17651 target->BuildUpdate(data_updates);
17652 target->BuildCreateUpdateBlockForPlayer(&data, this);
17653 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17655 #ifdef MANGOS_DEBUG
17656 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17657 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));
17658 #endif
17663 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17664 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17665 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17666 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17667 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17669 void Player::InitPrimaryProffesions()
17671 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17674 void Player::SendComboPoints()
17676 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17677 if (combotarget)
17679 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17680 data.append(combotarget->GetPackGUID());
17681 data << uint8(m_comboPoints);
17682 GetSession()->SendPacket(&data);
17686 void Player::AddComboPoints(Unit* target, int8 count)
17688 if(!count)
17689 return;
17691 // without combo points lost (duration checked in aura)
17692 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17694 if(target->GetGUID() == m_comboTarget)
17696 m_comboPoints += count;
17698 else
17700 if(m_comboTarget)
17701 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17702 target->RemoveComboPointHolder(GetGUIDLow());
17704 m_comboTarget = target->GetGUID();
17705 m_comboPoints = count;
17707 target->AddComboPointHolder(GetGUIDLow());
17710 if (m_comboPoints > 5) m_comboPoints = 5;
17711 if (m_comboPoints < 0) m_comboPoints = 0;
17713 SendComboPoints();
17716 void Player::ClearComboPoints()
17718 if(!m_comboTarget)
17719 return;
17721 // without combopoints lost (duration checked in aura)
17722 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17724 m_comboPoints = 0;
17726 SendComboPoints();
17728 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17729 target->RemoveComboPointHolder(GetGUIDLow());
17731 m_comboTarget = 0;
17734 void Player::SetGroup(Group *group, int8 subgroup)
17736 if(group == NULL) m_group.unlink();
17737 else
17739 // never use SetGroup without a subgroup unless you specify NULL for group
17740 assert(subgroup >= 0);
17741 m_group.link(group, this);
17742 m_group.setSubGroup((uint8)subgroup);
17746 void Player::SendInitialPacketsBeforeAddToMap()
17748 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
17749 data << uint32(0); // unknown, may be rest state time or experience
17750 GetSession()->SendPacket(&data);
17752 // Homebind
17753 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17754 data << m_homebindX << m_homebindY << m_homebindZ;
17755 data << (uint32) m_homebindMapId;
17756 data << (uint32) m_homebindZoneId;
17757 GetSession()->SendPacket(&data);
17759 // SMSG_SET_PROFICIENCY
17760 // SMSG_UPDATE_AURA_DURATION
17762 // tutorial stuff
17763 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
17764 for (int i = 0; i < 8; ++i)
17765 data << uint32( GetTutorialInt(i) );
17766 GetSession()->SendPacket(&data);
17768 SendInitialSpells();
17770 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17771 data << uint32(0); // count, for(count) uint32;
17772 GetSession()->SendPacket(&data);
17774 SendInitialActionButtons();
17775 SendInitialReputations();
17776 m_achievementMgr.SendAllAchievementData();
17777 UpdateZone(GetZoneId());
17778 SendInitWorldStates();
17780 // SMSG_SET_AURA_SINGLE
17782 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
17783 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
17784 data << (float)0.01666667f; // game speed
17785 GetSession()->SendPacket( &data );
17787 data.Initialize(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
17788 data << uint32(0x00000000); // on blizz it increments periodically
17789 GetSession()->SendPacket(&data);
17791 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17792 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
17793 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
17795 m_mover = this;
17798 void Player::SendInitialPacketsAfterAddToMap()
17800 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
17801 data << uint32(0x00000000); // on blizz it increments periodically
17802 GetSession()->SendPacket(&data);
17804 CastSpell(this, 836, true); // LOGINEFFECT
17806 // set some aura effects that send packet to player client after add player to map
17807 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17808 // same auras state lost at far teleport, send it one more time in this case also
17809 static const AuraType auratypes[] =
17811 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
17812 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
17813 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
17815 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
17817 Unit::AuraList const& auraList = GetAurasByType(*itr);
17818 if(!auraList.empty())
17819 auraList.front()->ApplyModifier(true,true);
17822 if(HasAuraType(SPELL_AURA_MOD_STUN))
17823 SetMovement(MOVE_ROOT);
17825 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17826 if(HasAuraType(SPELL_AURA_MOD_ROOT))
17828 WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
17829 data.append(GetPackGUID());
17830 data << (uint32)2;
17831 SendMessageToSet(&data,true);
17834 SendAurasForTarget(this);
17835 SendEnchantmentDurations(); // must be after add to map
17836 SendItemDurations(); // must be after add to map
17839 void Player::SendUpdateToOutOfRangeGroupMembers()
17841 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
17842 return;
17843 if(Group* group = GetGroup())
17844 group->UpdatePlayerOutOfRange(this);
17846 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
17847 m_auraUpdateMask = 0;
17848 if(Pet *pet = GetPet())
17849 pet->ResetAuraUpdateMask();
17852 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
17854 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
17855 data << uint32(mapid);
17856 data << uint8(reason); // transfer abort reason
17857 switch(reason)
17859 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
17860 case TRANSFER_ABORT_DIFFICULTY:
17861 case TRANSFER_ABORT_UNIQUE_MESSAGE:
17862 data << uint8(arg);
17863 break;
17865 GetSession()->SendPacket(&data);
17868 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
17870 // type of warning, based on the time remaining until reset
17871 uint32 type;
17872 if(time > 3600)
17873 type = RAID_INSTANCE_WELCOME;
17874 else if(time > 900 && time <= 3600)
17875 type = RAID_INSTANCE_WARNING_HOURS;
17876 else if(time > 300 && time <= 900)
17877 type = RAID_INSTANCE_WARNING_MIN;
17878 else
17879 type = RAID_INSTANCE_WARNING_MIN_SOON;
17880 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
17881 data << uint32(type);
17882 data << uint32(mapid);
17883 data << uint32(time);
17884 GetSession()->SendPacket(&data);
17887 void Player::ApplyEquipCooldown( Item * pItem )
17889 for(int i = 0; i <5; ++i)
17891 _Spell const& spellData = pItem->GetProto()->Spells[i];
17893 // no spell
17894 if( !spellData.SpellId )
17895 continue;
17897 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17898 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
17899 continue;
17901 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
17903 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
17904 data << pItem->GetGUID();
17905 data << uint32(spellData.SpellId);
17906 GetSession()->SendPacket(&data);
17910 void Player::resetSpells()
17912 // not need after this call
17913 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
17915 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
17916 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
17919 // make full copy of map (spells removed and marked as deleted at another spell remove
17920 // and we can't use original map for safe iterative with visit each spell at loop end
17921 PlayerSpellMap smap = GetSpellMap();
17923 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
17924 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
17926 learnDefaultSpells();
17927 learnQuestRewardedSpells();
17930 void Player::learnDefaultSpells(bool loading)
17932 // learn default race/class spells
17933 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
17934 std::list<CreateSpellPair>::const_iterator spell_itr;
17935 for (spell_itr = info->spell.begin(); spell_itr!=info->spell.end(); ++spell_itr)
17937 uint16 tspell = spell_itr->first;
17938 if (tspell)
17940 sLog.outDebug("PLAYER: Adding initial spell, id = %u",tspell);
17941 if(loading || !spell_itr->second) // not care about passive spells or loading case
17942 addSpell(tspell,spell_itr->second);
17943 else // but send in normal spell in game learn case
17944 learnSpell(tspell);
17949 void Player::learnQuestRewardedSpells(Quest const* quest)
17951 uint32 spell_id = quest->GetRewSpellCast();
17953 // skip quests without rewarded spell
17954 if( !spell_id )
17955 return;
17957 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
17958 if(!spellInfo)
17959 return;
17961 // check learned spells state
17962 bool found = false;
17963 for(int i=0; i < 3; ++i)
17965 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
17967 found = true;
17968 break;
17972 // skip quests with not teaching spell or already known spell
17973 if(!found)
17974 return;
17976 // prevent learn non first rank unknown profession and second specialization for same profession)
17977 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
17978 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
17980 // not have first rank learned (unlearned prof?)
17981 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
17982 if( !HasSpell(first_spell) )
17983 return;
17985 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
17986 if(!learnedInfo)
17987 return;
17989 // specialization
17990 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
17992 // search other specialization for same prof
17993 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17995 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
17996 continue;
17998 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
17999 if(!itrInfo)
18000 return;
18002 // compare only specializations
18003 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18004 continue;
18006 // compare same chain spells
18007 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18008 continue;
18010 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18011 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18012 return;
18017 CastSpell( this, spell_id, true);
18020 void Player::learnQuestRewardedSpells()
18022 // learn spells received from quest completing
18023 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18025 // skip no rewarded quests
18026 if(!itr->second.m_rewarded)
18027 continue;
18029 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18030 if( !quest )
18031 continue;
18033 learnQuestRewardedSpells(quest);
18037 void Player::learnSkillRewardedSpells(uint32 skill_id )
18039 uint32 raceMask = getRaceMask();
18040 uint32 classMask = getClassMask();
18041 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18043 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18044 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18045 continue;
18046 // Check race if set
18047 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18048 continue;
18049 // Check class if set
18050 if (pAbility->classmask && !(pAbility->classmask & classMask))
18051 continue;
18053 if (sSpellStore.LookupEntry(pAbility->spellId))
18055 // Ok need learn spell
18056 learnSpell(pAbility->spellId);
18061 void Player::learnSkillRewardedSpells()
18063 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
18065 if(!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
18066 continue;
18068 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
18070 learnSkillRewardedSpells(pskill);
18074 void Player::SendAurasForTarget(Unit *target)
18076 if(target->GetVisibleAuras()->empty()) // speedup things
18077 return;
18079 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18080 data.append(target->GetPackGUID());
18082 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18083 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18085 for(uint32 j = 0; j < 3; ++j)
18087 if(Aura *aura = target->GetAura(itr->second, j))
18089 data << uint8(aura->GetAuraSlot());
18090 data << uint32(aura->GetId());
18092 if(aura->GetId())
18094 uint8 auraFlags = aura->GetAuraFlags();
18095 // flags
18096 data << uint8(auraFlags);
18097 // level
18098 data << uint8(aura->GetAuraLevel());
18099 // charges
18100 data << uint8(aura->GetAuraCharges());
18102 if(!(auraFlags & AFLAG_NOT_CASTER))
18104 data << uint8(0); // packed GUID of someone (caster?)
18107 if(auraFlags & AFLAG_DURATION) // include aura duration
18109 data << uint32(aura->GetAuraMaxDuration());
18110 data << uint32(aura->GetAuraDuration());
18113 break;
18118 GetSession()->SendPacket(&data);
18121 void Player::SetDailyQuestStatus( uint32 quest_id )
18123 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18125 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18127 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18128 m_lastDailyQuestTime = time(NULL); // last daily quest time
18129 m_DailyQuestChanged = true;
18130 break;
18135 void Player::ResetDailyQuestStatus()
18137 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18138 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18140 // DB data deleted in caller
18141 m_DailyQuestChanged = false;
18142 m_lastDailyQuestTime = 0;
18145 BattleGround* Player::GetBattleGround() const
18147 if(GetBattleGroundId()==0)
18148 return NULL;
18150 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
18153 bool Player::InArena() const
18155 BattleGround *bg = GetBattleGround();
18156 if(!bg || !bg->isArena())
18157 return false;
18159 return true;
18162 bool Player::GetBGAccessByLevel(uint32 bgTypeId) const
18164 // get a template bg instead of running one
18165 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18166 if(!bg)
18167 return false;
18169 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18170 return false;
18172 return true;
18175 uint32 Player::GetMinLevelForBattleGroundQueueId(uint32 queue_id)
18177 if(queue_id < 1)
18178 return 0;
18180 if(queue_id >=7)
18181 queue_id = 7;
18183 return 10*(queue_id+1);
18186 uint32 Player::GetMaxLevelForBattleGroundQueueId(uint32 queue_id)
18188 if(queue_id >=7)
18189 return 255; // hardcoded max level
18191 return 10*(queue_id+2)-1;
18194 uint32 Player::GetBattleGroundQueueIdFromLevel() const
18196 uint32 level = getLevel();
18197 if(level <= 19)
18198 return 0;
18199 else if (level > 79)
18200 return 7;
18201 else
18202 return level/10 - 1; // 20..29 -> 1, 30-39 -> 2, ...
18204 assert(bgTypeId < MAX_BATTLEGROUND_TYPES);
18205 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18206 assert(bg);
18207 return (getLevel() - bg->GetMinLevel()) / 10;*/
18210 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18212 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18213 if(!vendor_faction)
18214 return 1.0f;
18216 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18217 if(rank <= REP_NEUTRAL)
18218 return 1.0f;
18220 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18223 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18225 uint32 racemask = getRaceMask();
18226 uint32 classmask = getClassMask();
18228 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
18229 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
18231 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
18233 // skip wrong race skills
18234 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18235 return false;
18237 // skip wrong class skills
18238 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18239 return false;
18241 return true;
18244 bool Player::HasQuestForGO(int32 GOId)
18246 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
18248 QuestStatusData qs=i->second;
18249 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18251 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
18252 if(!qinfo)
18253 continue;
18255 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18256 continue;
18258 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
18260 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18261 continue;
18263 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18264 return true;
18268 return false;
18271 void Player::UpdateForQuestsGO()
18273 if(m_clientGUIDs.empty())
18274 return;
18276 UpdateData udata;
18277 WorldPacket packet;
18278 for(ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18280 if(IS_GAMEOBJECT_GUID(*itr))
18282 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18283 if(obj)
18284 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18287 udata.BuildPacket(&packet);
18288 GetSession()->SendPacket(&packet);
18291 void Player::SummonIfPossible(bool agree)
18293 if(!agree)
18295 m_summon_expire = 0;
18296 return;
18299 // expire and auto declined
18300 if(m_summon_expire < time(NULL))
18301 return;
18303 // stop taxi flight at summon
18304 if(isInFlight())
18306 GetMotionMaster()->MovementExpired();
18307 m_taxi.ClearTaxiDestinations();
18310 // drop flag at summon
18311 if(BattleGround *bg = GetBattleGround())
18312 bg->EventPlayerDroppedFlag(this);
18314 m_summon_expire = 0;
18316 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18319 void Player::RemoveItemDurations( Item *item )
18321 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18323 if(*itr==item)
18325 m_itemDuration.erase(itr);
18326 break;
18331 void Player::AddItemDurations( Item *item )
18333 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18335 m_itemDuration.push_back(item);
18336 item->SendTimeUpdate(this);
18340 void Player::AutoUnequipOffhandIfNeed()
18342 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18343 if(!offItem)
18344 return;
18346 // need unequip for 2h-weapon without TitanGrip
18347 if (!IsTwoHandUsed())
18348 return;
18350 ItemPosCountVec off_dest;
18351 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18352 if( off_msg == EQUIP_ERR_OK )
18354 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18355 StoreItem( off_dest, offItem, true );
18357 else
18359 sLog.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
18363 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18365 if(spellInfo->EquippedItemClass < 0)
18366 return true;
18368 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18369 // for optimize check 2 used cases only
18370 switch(spellInfo->EquippedItemClass)
18372 case ITEM_CLASS_WEAPON:
18374 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18375 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18376 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18377 return true;
18378 break;
18380 case ITEM_CLASS_ARMOR:
18382 // tabard not have dependent spells
18383 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18384 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18385 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18386 return true;
18388 // shields can be equipped to offhand slot
18389 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18390 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18391 return true;
18393 // ranged slot can have some armor subclasses
18394 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18395 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18396 return true;
18398 break;
18400 default:
18401 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18402 break;
18405 return false;
18408 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18410 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18411 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18412 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18413 return true;
18415 // Check no reagent use mask
18416 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18417 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18418 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18419 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18420 return true;
18422 return false;
18425 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18427 AuraMap& auras = GetAuras();
18428 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
18430 Aura* aura = itr->second;
18432 // skip passive (passive item dependent spells work in another way) and not self applied auras
18433 SpellEntry const* spellInfo = aura->GetSpellProto();
18434 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18436 ++itr;
18437 continue;
18440 // skip if not item dependent or have alternative item
18441 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18443 ++itr;
18444 continue;
18447 // no alt item, remove aura, restart check
18448 RemoveAurasDueToSpell(aura->GetId());
18449 itr = auras.begin();
18452 // currently casted spells can be dependent from item
18453 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
18455 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18456 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18457 InterruptSpell(i);
18461 uint32 Player::GetResurrectionSpellId()
18463 // search priceless resurrection possibilities
18464 uint32 prio = 0;
18465 uint32 spell_id = 0;
18466 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18467 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18469 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18470 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18472 switch((*itr)->GetId())
18474 case 20707: spell_id = 3026; break; // rank 1
18475 case 20762: spell_id = 20758; break; // rank 2
18476 case 20763: spell_id = 20759; break; // rank 3
18477 case 20764: spell_id = 20760; break; // rank 4
18478 case 20765: spell_id = 20761; break; // rank 5
18479 case 27239: spell_id = 27240; break; // rank 6
18480 default:
18481 sLog.outError("Unhandled spell %%u: S.Resurrection",(*itr)->GetId());
18482 continue;
18485 prio = 3;
18487 // Twisting Nether // prio: 2 (max)
18488 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18490 prio = 2;
18491 spell_id = 23700;
18495 // Reincarnation (passive spell) // prio: 1
18496 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18497 spell_id = 21169;
18499 return spell_id;
18502 // Used in triggers for check "Only to targets that grant experience or honor" req
18503 bool Player::isHonorOrXPTarget(Unit* pVictim)
18505 uint32 v_level = pVictim->getLevel();
18506 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
18508 // Victim level less gray level
18509 if(v_level<=k_grey)
18510 return false;
18512 if(pVictim->GetTypeId() == TYPEID_UNIT)
18514 if (((Creature*)pVictim)->isTotem() ||
18515 ((Creature*)pVictim)->isPet() ||
18516 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
18517 return false;
18519 return true;
18522 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18524 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18526 // prepare data for near group iteration (PvP and !PvP cases)
18527 uint32 xp = 0;
18528 bool honored_kill = false;
18530 if(Group *pGroup = GetGroup())
18532 uint32 count = 0;
18533 uint32 sum_level = 0;
18534 Player* member_with_max_level = NULL;
18535 Player* not_gray_member_with_max_level = NULL;
18537 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18539 if(member_with_max_level)
18541 /// not get Xp in PvP or no not gray players in group
18542 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18544 /// skip in check PvP case (for speed, not used)
18545 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18546 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18547 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18549 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18551 Player* pGroupGuy = itr->getSource();
18552 if(!pGroupGuy)
18553 continue;
18555 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18556 continue; // member (alive or dead) or his corpse at req. distance
18558 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18559 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18560 honored_kill = true;
18562 // xp and reputation only in !PvP case
18563 if(!PvP)
18565 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18567 // if is in dungeon then all receive full reputation at kill
18568 // rewarded any alive/dead/near_corpse group member
18569 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18571 // XP updated only for alive group member
18572 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18573 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18575 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18577 pGroupGuy->GiveXP(itr_xp, pVictim);
18578 if(Pet* pet = pGroupGuy->GetPet())
18579 pet->GivePetXP(itr_xp/2);
18582 // quest objectives updated only for alive group member or dead but with not released body
18583 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18585 // normal creature (not pet/etc) can be only in !PvP case
18586 if(pVictim->GetTypeId()==TYPEID_UNIT)
18587 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18593 else // if (!pGroup)
18595 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18597 // honor can be in PvP and !PvP (racial leader) cases
18598 if(RewardHonor(pVictim,1))
18599 honored_kill = true;
18601 // xp and reputation only in !PvP case
18602 if(!PvP)
18604 RewardReputation(pVictim,1);
18605 GiveXP(xp, pVictim);
18607 if(Pet* pet = GetPet())
18608 pet->GivePetXP(xp);
18610 // normal creature (not pet/etc) can be only in !PvP case
18611 if(pVictim->GetTypeId()==TYPEID_UNIT)
18612 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18615 return xp || honored_kill;
18618 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18620 if(pRewardSource->GetDistance(this) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
18621 return true;
18623 if(isAlive())
18624 return false;
18626 Corpse* corpse = GetCorpse();
18627 if(!corpse)
18628 return false;
18630 return pRewardSource->GetDistance(corpse) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE);
18633 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18635 Item* item = GetWeaponForAttack(attType,true);
18637 // unarmed only with base attack
18638 if(attType != BASE_ATTACK && !item)
18639 return 0;
18641 // weapon skill or (unarmed for base attack)
18642 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
18643 return GetBaseSkillValue(skill);
18646 void Player::ResurectUsingRequestData()
18648 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
18649 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18651 ResurrectPlayer(0.0f,false);
18653 if(GetMaxHealth() > m_resurrectHealth)
18654 SetHealth( m_resurrectHealth );
18655 else
18656 SetHealth( GetMaxHealth() );
18658 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18659 SetPower(POWER_MANA, m_resurrectMana );
18660 else
18661 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18663 SetPower(POWER_RAGE, 0 );
18665 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18667 SpawnCorpseBones();
18670 void Player::SetClientControl(Unit* target, uint8 allowMove)
18672 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18673 data.append(target->GetPackGUID());
18674 data << uint8(allowMove);
18675 GetSession()->SendPacket(&data);
18678 void Player::UpdateZoneDependentAuras( uint32 newZone )
18680 // remove new continent flight forms
18681 uint32 v_map = GetVirtualMapForMapAndZone(GetMapId(), newZone);
18682 if( !isGameMaster() && v_map != 530 && v_map != 571)
18684 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18685 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18688 // Some spells applied at enter into zone (with subzones)
18689 // Human Illusion
18690 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
18691 if ( newZone == 2367 ) // Old Hillsbrad Foothills
18693 uint32 spellid = 0;
18694 // all horde races
18695 if( GetTeam() == HORDE )
18696 spellid = getGender() == GENDER_FEMALE ? 35481 : 35480;
18697 // and some alliance races
18698 else if( getRace() == RACE_NIGHTELF || getRace() == RACE_DRAENEI )
18699 spellid = getGender() == GENDER_FEMALE ? 35483 : 35482;
18701 if(spellid && !HasAura(spellid,0) )
18702 CastSpell(this,spellid,true);
18706 void Player::UpdateAreaDependentAuras( uint32 newArea )
18708 // remove auras from spells with area limitations
18709 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
18711 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18712 if(GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea)!=0)
18713 RemoveAura(iter);
18714 else
18715 ++iter;
18718 // some auras applied at subzone enter
18719 switch(newArea)
18721 // Dragonmaw Illusion
18722 case 3759: // Netherwing Ledge
18723 case 3939: // Dragonmaw Fortress
18724 case 3966: // Dragonmaw Base Camp
18725 if( GetDummyAura(40214) )
18727 if( !HasAura(40216,0) )
18728 CastSpell(this,40216,true);
18729 if( !HasAura(42016,0) )
18730 CastSpell(this,42016,true);
18732 break;
18733 // Dominion Over Acherus
18734 case 4281: // Acherus: The Ebon Hold
18735 case 4342: // Acherus: The Ebon Hold
18736 if( HasSpell(51721) )
18737 if( !HasAura(51721,0) )
18738 CastSpell(this,51721,true);
18739 break;
18743 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18745 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18746 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18748 return copseReclaimDelay[0];
18751 time_t now = time(NULL);
18752 // 0..2 full period
18753 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18754 return copseReclaimDelay[count];
18757 void Player::UpdateCorpseReclaimDelay()
18759 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18761 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18762 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18763 return;
18765 time_t now = time(NULL);
18766 if(now < m_deathExpireTime)
18768 // full and partly periods 1..3
18769 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18770 if(count < MAX_DEATH_COUNT)
18771 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
18772 else
18773 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
18775 else
18776 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
18779 void Player::SendCorpseReclaimDelay(bool load)
18781 Corpse* corpse = GetCorpse();
18782 if(!corpse)
18783 return;
18785 uint32 delay;
18786 if(load)
18788 if(corpse->GetGhostTime() > m_deathExpireTime)
18789 return;
18791 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
18793 uint32 count;
18794 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18795 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18797 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
18798 if(count>=MAX_DEATH_COUNT)
18799 count = MAX_DEATH_COUNT-1;
18801 else
18802 count=0;
18804 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
18806 time_t now = time(NULL);
18807 if(now >= expected_time)
18808 return;
18810 delay = expected_time-now;
18812 else
18813 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
18815 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18816 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
18817 data << uint32(delay*1000);
18818 GetSession()->SendPacket( &data );
18821 Player* Player::GetNextRandomRaidMember(float radius)
18823 Group *pGroup = GetGroup();
18824 if(!pGroup)
18825 return NULL;
18827 std::vector<Player*> nearMembers;
18828 nearMembers.reserve(pGroup->GetMembersCount());
18830 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18832 Player* Target = itr->getSource();
18834 // IsHostileTo check duel and controlled by enemy
18835 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
18836 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
18837 nearMembers.push_back(Target);
18840 if (nearMembers.empty())
18841 return NULL;
18843 uint32 randTarget = urand(0,nearMembers.size()-1);
18844 return nearMembers[randTarget];
18847 PartyResult Player::CanUninviteFromGroup() const
18849 const Group* grp = GetGroup();
18850 if(!grp)
18851 return PARTY_RESULT_YOU_NOT_IN_GROUP;
18853 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
18854 return PARTY_RESULT_YOU_NOT_LEADER;
18856 if(InBattleGround())
18857 return PARTY_RESULT_INVITE_RESTRICTED;
18859 return PARTY_RESULT_OK;
18862 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
18864 float water_z = m->GetWaterLevel(x,y);
18865 float height_z = m->GetHeight(x,y,z, false); // use .map base surface height
18866 uint8 flag1 = m->GetTerrainType(x,y);
18868 //!Underwater check, not in water if underground or above water level
18869 if (height_z <= INVALID_HEIGHT || z < (height_z-2) || z > (water_z - 2) )
18870 m_isunderwater &= 0x7A;
18871 else if ((z < (water_z - 2)) && (flag1 & 0x01))
18872 m_isunderwater |= 0x01;
18874 //!in lava check, anywhere under lava level
18875 if ((height_z <= INVALID_HEIGHT || z < (height_z - 0)) && (flag1 == 0x00) && IsInWater())
18876 m_isunderwater |= 0x80;
18879 void Player::SetCanParry( bool value )
18881 if(m_canParry==value)
18882 return;
18884 m_canParry = value;
18885 UpdateParryPercentage();
18888 void Player::SetCanBlock( bool value )
18890 if(m_canBlock==value)
18891 return;
18893 m_canBlock = value;
18894 UpdateBlockPercentage();
18897 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
18899 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
18900 if(itr->pos == pos)
18901 return true;
18903 return false;
18906 bool Player::isAllowUseBattleGroundObject()
18908 return ( //InBattleGround() && // in battleground - not need, check in other cases
18909 !IsMounted() && // not mounted
18910 !HasStealthAura() && // not stealthed
18911 !HasInvisibilityAura() && // not invisible
18912 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
18913 isAlive() // live player
18917 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
18919 uint32 level = getLevel();
18921 if(level > GT_MAX_LEVEL)
18922 level = GT_MAX_LEVEL; // max level in this dbc
18924 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
18925 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
18926 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
18928 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
18929 return 0;
18931 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
18933 if(!bsc) // shouldn't happen
18934 return 0xFFFFFFFF;
18936 float cost = 0;
18938 if(hairstyle != newhairstyle)
18939 cost += bsc->cost; // full price
18941 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
18942 cost += bsc->cost * 0.5f; // +1/2 of price
18944 if(facialhair != newfacialhair)
18945 cost += bsc->cost * 0.75f; // +3/4 of price
18947 return uint32(cost);
18950 void Player::InitGlyphsForLevel()
18952 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
18953 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
18954 if(gs->Order)
18955 SetGlyphSlot(gs->Order - 1, gs->Id);
18957 uint32 level = getLevel();
18958 uint32 value = 0;
18960 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
18961 if(level >= 15)
18962 value |= (0x01 | 0x02);
18963 if(level >= 30)
18964 value |= 0x04;
18965 if(level >= 50)
18966 value |= 0x08;
18967 if(level >= 70)
18968 value |= 0x10;
18969 if(level >= 80)
18970 value |= 0x20;
18972 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
18975 void Player::EnterVehicle(Vehicle *vehicle)
18977 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
18978 if(!ve)
18979 return;
18981 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
18982 if(!veSeat)
18983 return;
18985 vehicle->SetCharmerGUID(GetGUID());
18986 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
18987 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNKNOWN5);
18988 vehicle->setFaction(getFaction());
18990 SetCharm(vehicle); // charm
18991 SetFarSight(vehicle->GetGUID()); // set view
18993 SetClientControl(vehicle, 1); // redirect controls to vehicle
18995 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
18996 GetSession()->SendPacket(&data);
18998 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
18999 data.append(GetPackGUID());
19000 data << uint32(0); // counter?
19001 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
19002 data << uint16(0); // special flags
19003 data << uint32(getMSTime()); // time
19004 data << vehicle->GetPositionX(); // x
19005 data << vehicle->GetPositionY(); // y
19006 data << vehicle->GetPositionZ(); // z
19007 data << vehicle->GetOrientation(); // o
19008 // transport part, TODO: load/calculate seat offsets
19009 data << uint64(vehicle->GetGUID()); // transport guid
19010 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19011 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19012 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19013 data << float(0); // transport orientation
19014 data << uint32(getMSTime()); // transport time
19015 data << uint8(0); // seat
19016 // end of transport part
19017 data << uint32(0); // fall time
19018 GetSession()->SendPacket(&data);
19020 data.Initialize(SMSG_PET_SPELLS, 8+4+4+4+4*10+1+1);
19021 data << uint64(vehicle->GetGUID());
19022 data << uint32(0x00000000);
19023 data << uint32(0x00000000);
19024 data << uint32(0x00000101);
19026 for(uint32 i = 0; i < 10; ++i)
19027 data << uint16(0) << uint8(0) << uint8(i+8);
19029 data << uint8(0);
19030 data << uint8(0);
19031 GetSession()->SendPacket(&data);
19034 void Player::ExitVehicle(Vehicle *vehicle)
19036 vehicle->SetCharmerGUID(0);
19037 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19038 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNKNOWN5);
19039 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19041 SetCharm(NULL);
19042 SetFarSight(NULL);
19044 SetClientControl(vehicle, 0);
19046 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19047 data.append(GetPackGUID());
19048 data << uint32(0); // counter?
19049 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19050 data << uint16(0x40); // special flags
19051 data << uint32(getMSTime()); // time
19052 data << vehicle->GetPositionX(); // x
19053 data << vehicle->GetPositionY(); // y
19054 data << vehicle->GetPositionZ(); // z
19055 data << vehicle->GetOrientation(); // o
19056 data << uint32(0); // fall time
19057 GetSession()->SendPacket(&data);
19059 data.Initialize(SMSG_PET_SPELLS, 8+4);
19060 data << uint64(0);
19061 data << uint32(0);
19062 GetSession()->SendPacket(&data);
19064 // only for flyable vehicles?
19065 CastSpell(this, 45472, true); // Parachute
19068 bool Player::HasTitle(uint32 bitIndex)
19070 if (bitIndex > 128)
19071 return false;
19073 uint32 fieldIndexOffset = bitIndex/32;
19074 uint32 flag = 1 << (bitIndex%32);
19075 return HasFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19078 void Player::SetTitle(CharTitlesEntry const* title)
19080 uint32 fieldIndexOffset = title->bit_index/32;
19081 uint32 flag = 1 << (title->bit_index%32);
19082 SetFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19085 void Player::ConvertRune(uint8 index, uint8 newType)
19087 SetCurrentRune(index, newType);
19089 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19090 data << uint8(index);
19091 data << uint8(newType);
19092 GetSession()->SendPacket(&data);
19095 void Player::ResyncRunes(uint8 count)
19097 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19098 for(uint32 i = 0; i < count; ++i)
19100 data << uint8(GetCurrentRune(i)); // rune type
19101 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
19103 GetSession()->SendPacket(&data);
19106 void Player::AddRunePower(uint8 index)
19108 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19109 data << uint32(1 << index); // mask (0x00-0x3F probably)
19110 GetSession()->SendPacket(&data);
19113 void Player::InitRunes()
19115 if(getClass() != CLASS_DEATH_KNIGHT)
19116 return;
19118 m_runes = new Runes;
19120 m_runes->runeState = 0;
19122 for(uint32 i = 0; i < MAX_RUNES; ++i)
19124 SetBaseRune(i, i / 2); // init base types
19125 SetCurrentRune(i, i / 2); // init current types
19126 SetRuneCooldown(i, 0); // reset cooldowns
19127 m_runes->SetRuneState(i);
19130 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19131 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);