Added missing talent points update at player/pet level change.
[AHbot.git] / src / game / Player.cpp
blob8d3fff91a75ce95de6b33617a2572dabe3a31320
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Language.h"
21 #include "Database/DatabaseEnv.h"
22 #include "Log.h"
23 #include "Opcodes.h"
24 #include "SpellMgr.h"
25 #include "World.h"
26 #include "WorldPacket.h"
27 #include "WorldSession.h"
28 #include "UpdateMask.h"
29 #include "Player.h"
30 #include "Vehicle.h"
31 #include "SkillDiscovery.h"
32 #include "QuestDef.h"
33 #include "GossipDef.h"
34 #include "UpdateData.h"
35 #include "Channel.h"
36 #include "ChannelMgr.h"
37 #include "MapManager.h"
38 #include "MapInstanced.h"
39 #include "InstanceSaveMgr.h"
40 #include "GridNotifiers.h"
41 #include "GridNotifiersImpl.h"
42 #include "CellImpl.h"
43 #include "ObjectMgr.h"
44 #include "ObjectAccessor.h"
45 #include "CreatureAI.h"
46 #include "Formulas.h"
47 #include "Group.h"
48 #include "Guild.h"
49 #include "Pet.h"
50 #include "Util.h"
51 #include "Transports.h"
52 #include "Weather.h"
53 #include "BattleGround.h"
54 #include "BattleGroundMgr.h"
55 #include "ArenaTeam.h"
56 #include "Chat.h"
57 #include "Database/DatabaseImpl.h"
58 #include "Spell.h"
59 #include "SocialMgr.h"
60 #include "AchievementMgr.h"
62 #include <cmath>
64 #define ZONE_UPDATE_INTERVAL (1*IN_MILISECONDS)
66 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
67 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
68 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
70 #define SKILL_VALUE(x) PAIR32_LOPART(x)
71 #define SKILL_MAX(x) PAIR32_HIPART(x)
72 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
74 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
75 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
76 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
78 enum CharacterFlags
80 CHARACTER_FLAG_NONE = 0x00000000,
81 CHARACTER_FLAG_UNK1 = 0x00000001,
82 CHARACTER_FLAG_UNK2 = 0x00000002,
83 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
84 CHARACTER_FLAG_UNK4 = 0x00000008,
85 CHARACTER_FLAG_UNK5 = 0x00000010,
86 CHARACTER_FLAG_UNK6 = 0x00000020,
87 CHARACTER_FLAG_UNK7 = 0x00000040,
88 CHARACTER_FLAG_UNK8 = 0x00000080,
89 CHARACTER_FLAG_UNK9 = 0x00000100,
90 CHARACTER_FLAG_UNK10 = 0x00000200,
91 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
92 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
93 CHARACTER_FLAG_UNK13 = 0x00001000,
94 CHARACTER_FLAG_GHOST = 0x00002000,
95 CHARACTER_FLAG_RENAME = 0x00004000,
96 CHARACTER_FLAG_UNK16 = 0x00008000,
97 CHARACTER_FLAG_UNK17 = 0x00010000,
98 CHARACTER_FLAG_UNK18 = 0x00020000,
99 CHARACTER_FLAG_UNK19 = 0x00040000,
100 CHARACTER_FLAG_UNK20 = 0x00080000,
101 CHARACTER_FLAG_UNK21 = 0x00100000,
102 CHARACTER_FLAG_UNK22 = 0x00200000,
103 CHARACTER_FLAG_UNK23 = 0x00400000,
104 CHARACTER_FLAG_UNK24 = 0x00800000,
105 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
106 CHARACTER_FLAG_DECLINED = 0x02000000,
107 CHARACTER_FLAG_UNK27 = 0x04000000,
108 CHARACTER_FLAG_UNK28 = 0x08000000,
109 CHARACTER_FLAG_UNK29 = 0x10000000,
110 CHARACTER_FLAG_UNK30 = 0x20000000,
111 CHARACTER_FLAG_UNK31 = 0x40000000,
112 CHARACTER_FLAG_UNK32 = 0x80000000
115 // corpse reclaim times
116 #define DEATH_EXPIRE_STEP (5*MINUTE)
117 #define MAX_DEATH_COUNT 3
119 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
121 //== PlayerTaxi ================================================
123 PlayerTaxi::PlayerTaxi()
125 // Taxi nodes
126 memset(m_taximask, 0, sizeof(m_taximask));
129 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
131 // class specific initial known nodes
132 switch(chrClass)
134 case CLASS_DEATH_KNIGHT:
136 for(int i = 0; i < TaxiMaskSize; ++i)
137 m_taximask[i] |= sOldContinentsNodesMask[i];
138 break;
142 // race specific initial known nodes: capital and taxi hub masks
143 switch(race)
145 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
146 case RACE_ORC: SetTaximaskNode(23); break; // Orc
147 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
148 case RACE_NIGHTELF: SetTaximaskNode(26);
149 SetTaximaskNode(27); break; // Night Elf
150 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
151 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
152 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
153 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
154 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
155 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
158 // new continent starting masks (It will be accessible only at new map)
159 switch(Player::TeamForRace(race))
161 case ALLIANCE: SetTaximaskNode(100); break;
162 case HORDE: SetTaximaskNode(99); break;
164 // level dependent taxi hubs
165 if(level>=68)
166 SetTaximaskNode(213); //Shattered Sun Staging Area
169 void PlayerTaxi::LoadTaxiMask(const char* data)
171 Tokens tokens = StrSplit(data, " ");
173 int index;
174 Tokens::iterator iter;
175 for (iter = tokens.begin(), index = 0;
176 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
178 // load and set bits only for existed taxi nodes
179 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
183 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
185 if(all)
187 for (uint8 i=0; i<TaxiMaskSize; ++i)
188 data << uint32(sTaxiNodesMask[i]); // all existed nodes
190 else
192 for (uint8 i=0; i<TaxiMaskSize; ++i)
193 data << uint32(m_taximask[i]); // known nodes
197 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team )
199 ClearTaxiDestinations();
201 Tokens tokens = StrSplit(values," ");
203 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
205 uint32 node = uint32(atol(iter->c_str()));
206 AddTaxiDestination(node);
209 if(m_TaxiDestinations.empty())
210 return true;
212 // Check integrity
213 if(m_TaxiDestinations.size() < 2)
214 return false;
216 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
218 uint32 cost;
219 uint32 path;
220 objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
221 if(!path)
222 return false;
225 // can't load taxi path without mount set (quest taxi path?)
226 if(!objmgr.GetTaxiMount(GetTaxiSource(),team))
227 return false;
229 return true;
232 std::string PlayerTaxi::SaveTaxiDestinationsToString()
234 if(m_TaxiDestinations.empty())
235 return "";
237 std::ostringstream ss;
239 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
240 ss << m_TaxiDestinations[i] << " ";
242 return ss.str();
245 uint32 PlayerTaxi::GetCurrentTaxiPath() const
247 if(m_TaxiDestinations.size() < 2)
248 return 0;
250 uint32 path;
251 uint32 cost;
253 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
255 return path;
258 std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
260 ss << "'";
261 for(int i = 0; i < TaxiMaskSize; ++i)
262 ss << taxi.m_taximask[i] << " ";
263 ss << "'";
264 return ss;
267 //== Player ====================================================
269 UpdateMask Player::updateVisualBits;
271 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this), m_reputationMgr(this)
273 m_transport = 0;
275 m_speakTime = 0;
276 m_speakCount = 0;
278 m_objectType |= TYPEMASK_PLAYER;
279 m_objectTypeId = TYPEID_PLAYER;
281 m_valuesCount = PLAYER_END;
283 m_session = session;
285 m_divider = 0;
287 m_ExtraFlags = 0;
288 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
289 SetAcceptTicket(true);
291 // players always accept
292 if(GetSession()->GetSecurity() == SEC_PLAYER)
293 SetAcceptWhispers(true);
295 m_curSelection = 0;
296 m_lootGuid = 0;
298 m_comboTarget = 0;
299 m_comboPoints = 0;
301 m_usedTalentCount = 0;
302 m_questRewardTalentCount = 0;
304 m_regenTimer = 0;
305 m_weaponChangeTimer = 0;
307 m_zoneUpdateId = 0;
308 m_zoneUpdateTimer = 0;
310 m_areaUpdateId = 0;
312 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
314 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
315 // this must help in case next save after mass player load after server startup
316 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
318 clearResurrectRequestData();
320 m_SpellModRemoveCount = 0;
322 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
324 m_social = NULL;
326 // group is initialized in the reference constructor
327 SetGroupInvite(NULL);
328 m_groupUpdateMask = 0;
329 m_auraUpdateMask = 0;
331 duel = NULL;
333 m_GuildIdInvited = 0;
334 m_ArenaTeamIdInvited = 0;
336 m_atLoginFlags = AT_LOGIN_NONE;
338 mSemaphoreTeleport_Near = false;
339 mSemaphoreTeleport_Far = false;
341 pTrader = 0;
342 ClearTrade();
344 m_cinematic = 0;
346 PlayerTalkClass = new PlayerMenu( GetSession() );
347 m_currentBuybackSlot = BUYBACK_SLOT_START;
349 m_DailyQuestChanged = false;
350 m_lastDailyQuestTime = 0;
352 for (int i=0; i<MAX_TIMERS; ++i)
353 m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
355 m_MirrorTimerFlags = UNDERWATER_NONE;
356 m_MirrorTimerFlagsLast = UNDERWATER_NONE;
357 m_isInWater = false;
358 m_drunkTimer = 0;
359 m_drunk = 0;
360 m_restTime = 0;
361 m_deathTimer = 0;
362 m_deathExpireTime = 0;
364 m_swingErrorMsg = 0;
366 m_DetectInvTimer = 1*IN_MILISECONDS;
368 m_bgBattleGroundID = 0;
369 m_bgTypeID = BATTLEGROUND_TYPE_NONE;
370 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
372 m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
373 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
375 m_bgTeam = 0;
377 m_logintime = time(NULL);
378 m_Last_tick = m_logintime;
379 m_WeaponProficiency = 0;
380 m_ArmorProficiency = 0;
381 m_canParry = false;
382 m_canBlock = false;
383 m_canDualWield = false;
384 m_canTitanGrip = false;
385 m_ammoDPS = 0.0f;
387 m_temporaryUnsummonedPetNumber = 0;
388 //cache for UNIT_CREATED_BY_SPELL to allow
389 //returning reagents for temporarily removed pets
390 //when dying/logging out
391 m_oldpetspell = 0;
393 ////////////////////Rest System/////////////////////
394 time_inn_enter=0;
395 inn_pos_mapid=0;
396 inn_pos_x=0;
397 inn_pos_y=0;
398 inn_pos_z=0;
399 m_rest_bonus=0;
400 rest_type=REST_TYPE_NO;
401 ////////////////////Rest System/////////////////////
403 m_mailsLoaded = false;
404 m_mailsUpdated = false;
405 unReadMails = 0;
406 m_nextMailDelivereTime = 0;
408 m_resetTalentsCost = 0;
409 m_resetTalentsTime = 0;
410 m_itemUpdateQueueBlocked = false;
412 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
413 m_forced_speed_changes[i] = 0;
415 m_stableSlots = 0;
417 /////////////////// Instance System /////////////////////
419 m_HomebindTimer = 0;
420 m_InstanceValid = true;
421 m_dungeonDifficulty = DIFFICULTY_NORMAL;
423 m_lastPotionId = 0;
425 for (int i = 0; i < BASEMOD_END; ++i)
427 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
428 m_auraBaseMod[i][PCT_MOD] = 1.0f;
431 for (int i = 0; i < MAX_COMBAT_RATING; ++i)
432 m_baseRatingValue[i] = 0;
434 m_baseSpellDamage = 0;
435 m_baseSpellHealing = 0;
436 m_baseFeralAP = 0;
437 m_baseManaRegen = 0;
439 // Honor System
440 m_lastHonorUpdateTime = time(NULL);
442 // Player summoning
443 m_summon_expire = 0;
444 m_summon_mapid = 0;
445 m_summon_x = 0.0f;
446 m_summon_y = 0.0f;
447 m_summon_z = 0.0f;
449 //Default movement to run mode
450 m_unit_movement_flags = 0;
452 m_mover = this;
454 m_miniPet = 0;
455 m_bgAfkReportedTimer = 0;
456 m_contestedPvPTimer = 0;
458 m_declinedname = NULL;
459 m_runes = NULL;
461 m_lastFallTime = 0;
462 m_lastFallZ = 0;
465 Player::~Player ()
467 CleanupsBeforeDelete();
469 // it must be unloaded already in PlayerLogout and accessed only for loggined player
470 //m_social = NULL;
472 // Note: buy back item already deleted from DB when player was saved
473 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
475 if(m_items[i])
476 delete m_items[i];
478 CleanupChannels();
480 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
481 delete itr->second;
483 //all mailed items should be deleted, also all mail should be deallocated
484 for (PlayerMails::const_iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
485 delete *itr;
487 for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
488 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
490 delete PlayerTalkClass;
492 if (m_transport)
494 m_transport->RemovePassenger(this);
497 for(size_t x = 0; x < ItemSetEff.size(); x++)
498 if(ItemSetEff[x])
499 delete ItemSetEff[x];
501 // clean up player-instance binds, may unload some instance saves
502 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
503 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
504 itr->second.save->RemovePlayer(this);
506 delete m_declinedname;
507 delete m_runes;
510 void Player::CleanupsBeforeDelete()
512 if(m_uint32Values) // only for fully created Object
514 TradeCancel(false);
515 DuelComplete(DUEL_INTERUPTED);
517 Unit::CleanupsBeforeDelete();
520 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 )
522 //FIXME: outfitId not used in player creating
524 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
526 m_name = name;
528 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
529 if(!info)
531 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
532 return false;
535 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
536 m_items[i] = NULL;
538 m_race = race;
539 m_class = class_;
541 SetMapId(info->mapId);
542 Relocate(info->positionX,info->positionY,info->positionZ);
544 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
545 if(!cEntry)
547 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
548 return false;
551 uint8 powertype = cEntry->powerType;
553 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
554 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
556 switch(gender)
558 case GENDER_FEMALE:
559 SetDisplayId(info->displayId_f );
560 SetNativeDisplayId(info->displayId_f );
561 break;
562 case GENDER_MALE:
563 SetDisplayId(info->displayId_m );
564 SetNativeDisplayId(info->displayId_m );
565 break;
566 default:
567 sLog.outError("Invalid gender %u for player",gender);
568 return false;
569 break;
572 setFactionForRace(m_race);
574 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
576 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
577 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
578 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
579 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
580 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
581 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
583 // -1 is default value
584 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
586 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
587 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
588 SetByteValue(PLAYER_BYTES_3, 0, gender);
590 SetUInt32Value( PLAYER_GUILDID, 0 );
591 SetUInt32Value( PLAYER_GUILDRANK, 0 );
592 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
594 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
595 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
596 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
597 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
598 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
599 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
600 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
602 // set starting level
603 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
604 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
605 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
607 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
609 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
610 if(gm_level > start_level)
611 start_level = gm_level;
614 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
616 InitRunes();
618 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
619 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
620 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
622 // Played time
623 m_Last_tick = time(NULL);
624 m_Played_time[0] = 0;
625 m_Played_time[1] = 0;
627 // base stats and related field values
628 InitStatsForLevel();
629 InitTaxiNodesForLevel();
630 InitGlyphsForLevel();
631 InitTalentForLevel();
632 InitPrimaryProffesions(); // to max set before any spell added
634 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
635 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
636 SetHealth(GetMaxHealth());
637 if (getPowerType()==POWER_MANA)
639 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
640 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
643 if(getPowerType() == POWER_RUNIC_POWER)
645 SetPower(POWER_RUNE, 8);
646 SetMaxPower(POWER_RUNE, 8);
647 SetPower(POWER_RUNIC_POWER, 0);
648 SetMaxPower(POWER_RUNIC_POWER, 1000);
651 // original spells
652 learnDefaultSpells();
654 // original action bar
655 std::list<uint16>::const_iterator action_itr[4];
656 for(int i=0; i<4; ++i)
657 action_itr[i] = info->action[i].begin();
659 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
661 uint16 taction[4];
662 for(int i=0; i<4 ;++i)
663 taction[i] = (*action_itr[i]);
665 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
667 for(int i=0; i<4 ;++i)
668 ++action_itr[i];
671 // original items
672 CharStartOutfitEntry const* oEntry = NULL;
673 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
675 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
677 if(entry->RaceClassGender == RaceClassGender)
679 oEntry = entry;
680 break;
685 if(oEntry)
687 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
689 if(oEntry->ItemId[j] <= 0)
690 continue;
692 uint32 item_id = oEntry->ItemId[j];
695 // Hack for not existed item id in dbc 3.0.3
696 if(item_id==40582)
697 continue;
699 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
700 if(!iProto)
702 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
703 continue;
706 // max stack by default (mostly 1), 1 for infinity stackable
707 uint32 count = iProto->Stackable > 0 ? uint32(iProto->Stackable) : 1;
709 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
711 switch(iProto->Spells[0].SpellCategory)
713 case 11: // food
714 if(iProto->Stackable > 4)
715 count = 4;
716 break;
717 case 59: // drink
718 if(iProto->Stackable > 2)
719 count = 2;
720 break;
724 StoreNewItemInBestSlots(item_id, count);
728 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
729 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
731 // bags and main-hand weapon must equipped at this moment
732 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
733 // or ammo not equipped in special bag
734 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
736 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
738 uint16 eDest;
739 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
740 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
741 if( msg == EQUIP_ERR_OK )
743 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
744 EquipItem( eDest, pItem, true);
746 // move other items to more appropriate slots (ammo not equipped in special bag)
747 else
749 ItemPosCountVec sDest;
750 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
751 if( msg == EQUIP_ERR_OK )
753 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
754 pItem = StoreItem( sDest, pItem, true);
757 // if this is ammo then use it
758 msg = CanUseAmmo( pItem->GetEntry() );
759 if( msg == EQUIP_ERR_OK )
760 SetAmmo( pItem->GetEntry() );
764 // all item positions resolved
766 return true;
769 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
771 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
773 // attempt equip by one
774 while(titem_amount > 0)
776 uint16 eDest;
777 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
778 if( msg != EQUIP_ERR_OK )
779 break;
781 EquipNewItem( eDest, titem_id, true);
782 AutoUnequipOffhandIfNeed();
783 --titem_amount;
786 if(titem_amount == 0)
787 return true; // equipped
789 // attempt store
790 ItemPosCountVec sDest;
791 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
792 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
793 if( msg == EQUIP_ERR_OK )
795 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
796 return true; // stored
799 // item can't be added
800 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
801 return false;
804 void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
806 if (MaxValue == DISABLED_MIRROR_TIMER)
808 if (CurrentValue!=DISABLED_MIRROR_TIMER)
809 StopMirrorTimer(Type);
810 return;
812 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
813 data << (uint32)Type;
814 data << CurrentValue;
815 data << MaxValue;
816 data << Regen;
817 data << (uint8)0;
818 data << (uint32)0; // spell id
819 GetSession()->SendPacket( &data );
822 void Player::StopMirrorTimer(MirrorTimerType Type)
824 m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
825 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
826 data << (uint32)Type;
827 GetSession()->SendPacket( &data );
830 void Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
832 if(!isAlive() || isGameMaster())
833 return;
835 // Absorb, resist some environmental damage type
836 uint32 absorb = 0;
837 uint32 resist = 0;
838 if (type == DAMAGE_LAVA)
839 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
840 else if (type == DAMAGE_SLIME)
841 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
843 damage-=absorb+resist;
845 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
846 data << uint64(GetGUID());
847 data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
848 data << uint32(damage);
849 data << uint32(absorb);
850 data << uint32(resist);
851 SendMessageToSet(&data, true);
853 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
855 if(!isAlive())
857 if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
859 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
860 DurabilityLossAll(0.10f,false);
861 // durability lost message
862 WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
863 GetSession()->SendPacket(&data2);
866 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
870 int32 Player::getMaxTimer(MirrorTimerType timer)
872 switch (timer)
874 case FATIGUE_TIMER:
875 return MINUTE*IN_MILISECONDS;
876 case BREATH_TIMER:
878 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
879 return DISABLED_MIRROR_TIMER;
880 int32 UnderWaterTime = 3*MINUTE*IN_MILISECONDS;
881 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
882 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
883 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
884 return UnderWaterTime;
886 case FIRE_TIMER:
888 if (!isAlive())
889 return DISABLED_MIRROR_TIMER;
890 return 1*IN_MILISECONDS;
892 default:
893 return 0;
895 return 0;
898 void Player::UpdateMirrorTimers()
900 // Desync flags for update on next HandleDrowning
901 if (m_MirrorTimerFlags)
902 m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
905 void Player::HandleDrowning(uint32 time_diff)
907 if (!m_MirrorTimerFlags)
908 return;
910 // In water
911 if (m_MirrorTimerFlags & UNDERWATER_INWATER)
913 // Breath timer not activated - activate it
914 if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
916 m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
917 SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
919 else // If activated - do tick
921 m_MirrorTimer[BREATH_TIMER]-=time_diff;
922 // Timer limit - need deal damage
923 if (m_MirrorTimer[BREATH_TIMER] < 0)
925 m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILISECONDS;
926 // Calculate and deal damage
927 // TODO: Check this formula
928 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
929 EnvironmentalDamage(DAMAGE_DROWNING, damage);
931 else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
932 SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
935 else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
937 int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
938 // Need breath regen
939 m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
940 if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
941 StopMirrorTimer(BREATH_TIMER);
942 else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
943 SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
946 // In dark water
947 if (m_MirrorTimerFlags & UNDERWARER_INDARKWATER)
949 // Fatigue timer not activated - activate it
950 if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
952 m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
953 SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
955 else
957 m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
958 // Timer limit - need deal damage or teleport ghost to graveyard
959 if (m_MirrorTimer[FATIGUE_TIMER] < 0)
961 m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILISECONDS;
962 if (isAlive()) // Calculate and deal damage
964 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
965 EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
967 else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
968 RepopAtGraveyard();
970 else if (!(m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER))
971 SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
974 else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
976 int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
977 m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
978 if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
979 StopMirrorTimer(FATIGUE_TIMER);
980 else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER)
981 SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
984 if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
986 // Breath timer not activated - activate it
987 if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
988 m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
989 else
991 m_MirrorTimer[FIRE_TIMER]-=time_diff;
992 if (m_MirrorTimer[FIRE_TIMER] < 0)
994 m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILISECONDS;
995 // Calculate and deal damage
996 // TODO: Check this formula
997 uint32 damage = urand(600, 700);
998 if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
999 EnvironmentalDamage(DAMAGE_LAVA, damage);
1000 else
1001 EnvironmentalDamage(DAMAGE_SLIME, damage);
1005 else
1006 m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
1008 // Recheck timers flag
1009 m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
1010 for (int i = 0; i< MAX_TIMERS; ++i)
1011 if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
1013 m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
1014 break;
1016 m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
1019 ///The player sobers by 256 every 10 seconds
1020 void Player::HandleSobering()
1022 m_drunkTimer = 0;
1024 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
1025 SetDrunkValue(drunk);
1028 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
1030 if(value >= 23000)
1031 return DRUNKEN_SMASHED;
1032 if(value >= 12800)
1033 return DRUNKEN_DRUNK;
1034 if(value & 0xFFFE)
1035 return DRUNKEN_TIPSY;
1036 return DRUNKEN_SOBER;
1039 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
1041 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1043 m_drunk = newDrunkenValue;
1044 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
1046 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1048 // special drunk invisibility detection
1049 if(newDrunkenState >= DRUNKEN_DRUNK)
1050 m_detectInvisibilityMask |= (1<<6);
1051 else
1052 m_detectInvisibilityMask &= ~(1<<6);
1054 if(newDrunkenState == oldDrunkenState)
1055 return;
1057 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1058 data << uint64(GetGUID());
1059 data << uint32(newDrunkenState);
1060 data << uint32(itemId);
1062 SendMessageToSet(&data, true);
1065 void Player::Update( uint32 p_time )
1067 if(!IsInWorld())
1068 return;
1070 // undelivered mail
1071 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1073 SendNewMail();
1074 ++unReadMails;
1076 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1077 m_nextMailDelivereTime = 0;
1080 Unit::Update( p_time );
1082 // update player only attacks
1083 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1085 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1088 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1090 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1093 time_t now = time (NULL);
1095 UpdatePvPFlag(now);
1097 UpdateContestedPvP(p_time);
1099 UpdateDuelFlag(now);
1101 CheckDuelDistance(now);
1103 UpdateAfkReport(now);
1105 // Update items that have just a limited lifetime
1106 if (now>m_Last_tick)
1107 UpdateItemDuration(uint32(now- m_Last_tick));
1109 if (!m_timedquests.empty())
1111 std::set<uint32>::iterator iter = m_timedquests.begin();
1112 while (iter != m_timedquests.end())
1114 QuestStatusData& q_status = mQuestStatus[*iter];
1115 if( q_status.m_timer <= p_time )
1117 uint32 quest_id = *iter;
1118 ++iter; // current iter will be removed in FailTimedQuest
1119 FailTimedQuest( quest_id );
1121 else
1123 q_status.m_timer -= p_time;
1124 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1125 ++iter;
1130 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1132 Unit *pVictim = getVictim();
1133 if (pVictim && !IsNonMeleeSpellCasted(false))
1135 // default combat reach 10
1136 // TODO add weapon,skill check
1138 float pldistance = ATTACK_DISTANCE;
1140 if (isAttackReady(BASE_ATTACK))
1142 if(!IsWithinDistInMap(pVictim, pldistance))
1144 setAttackTimer(BASE_ATTACK,100);
1145 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1147 SendAttackSwingNotInRange();
1148 m_swingErrorMsg = 1;
1151 //120 degrees of radiant range
1152 else if( !HasInArc( 2*M_PI/3, pVictim ))
1154 setAttackTimer(BASE_ATTACK,100);
1155 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1157 SendAttackSwingBadFacingAttack();
1158 m_swingErrorMsg = 2;
1161 else
1163 m_swingErrorMsg = 0; // reset swing error state
1165 // prevent base and off attack in same time, delay attack at 0.2 sec
1166 if(haveOffhandWeapon())
1168 uint32 off_att = getAttackTimer(OFF_ATTACK);
1169 if(off_att < ATTACK_DISPLAY_DELAY)
1170 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1172 AttackerStateUpdate(pVictim, BASE_ATTACK);
1173 resetAttackTimer(BASE_ATTACK);
1177 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1179 if(!IsWithinDistInMap(pVictim, pldistance))
1181 setAttackTimer(OFF_ATTACK,100);
1183 else if( !HasInArc( 2*M_PI/3, pVictim ))
1185 setAttackTimer(OFF_ATTACK,100);
1187 else
1189 // prevent base and off attack in same time, delay attack at 0.2 sec
1190 uint32 base_att = getAttackTimer(BASE_ATTACK);
1191 if(base_att < ATTACK_DISPLAY_DELAY)
1192 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1193 // do attack
1194 AttackerStateUpdate(pVictim, OFF_ATTACK);
1195 resetAttackTimer(OFF_ATTACK);
1199 Unit *owner = pVictim->GetOwner();
1200 Unit *u = owner ? owner : pVictim;
1201 if(u->IsPvP() && (!duel || duel->opponent != u))
1203 UpdatePvP(true);
1204 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1209 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1211 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1213 int time_inn = time(NULL)-GetTimeInnEnter();
1214 if (time_inn >= 10) //freeze update
1216 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1217 //speed collect rest bonus (section/in hour)
1218 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1219 UpdateInnerTime(time(NULL));
1224 if(m_regenTimer > 0)
1226 if(p_time >= m_regenTimer)
1227 m_regenTimer = 0;
1228 else
1229 m_regenTimer -= p_time;
1232 if (m_weaponChangeTimer > 0)
1234 if(p_time >= m_weaponChangeTimer)
1235 m_weaponChangeTimer = 0;
1236 else
1237 m_weaponChangeTimer -= p_time;
1240 if (m_zoneUpdateTimer > 0)
1242 if(p_time >= m_zoneUpdateTimer)
1244 uint32 newzone, newarea;
1245 GetZoneAndAreaId(newzone,newarea);
1247 if( m_zoneUpdateId != newzone )
1248 UpdateZone(newzone,newarea); // also update area
1249 else
1251 // use area updates as well
1252 // needed for free far all arenas for example
1253 if( m_areaUpdateId != newarea )
1254 UpdateArea(newarea);
1256 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1259 else
1260 m_zoneUpdateTimer -= p_time;
1263 if (isAlive())
1265 RegenerateAll();
1268 if (m_deathState == JUST_DIED)
1270 KillPlayer();
1273 if(m_nextSave > 0)
1275 if(p_time >= m_nextSave)
1277 // m_nextSave reseted in SaveToDB call
1278 SaveToDB();
1279 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1281 else
1283 m_nextSave -= p_time;
1287 //Handle Water/drowning
1288 HandleDrowning(p_time);
1290 //Handle detect stealth players
1291 if (m_DetectInvTimer > 0)
1293 if (p_time >= m_DetectInvTimer)
1295 m_DetectInvTimer = 3000;
1296 HandleStealthedUnitsDetection();
1298 else
1299 m_DetectInvTimer -= p_time;
1302 // Played time
1303 if (now > m_Last_tick)
1305 uint32 elapsed = uint32(now - m_Last_tick);
1306 m_Played_time[0] += elapsed; // Total played time
1307 m_Played_time[1] += elapsed; // Level played time
1308 m_Last_tick = now;
1311 if (m_drunk)
1313 m_drunkTimer += p_time;
1315 if (m_drunkTimer > 10*IN_MILISECONDS)
1316 HandleSobering();
1319 // not auto-free ghost from body in instances
1320 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1322 if(p_time >= m_deathTimer)
1324 m_deathTimer = 0;
1325 BuildPlayerRepop();
1326 RepopAtGraveyard();
1328 else
1329 m_deathTimer -= p_time;
1332 UpdateEnchantTime(p_time);
1333 UpdateHomebindTime(p_time);
1335 // group update
1336 SendUpdateToOutOfRangeGroupMembers();
1338 Pet* pet = GetPet();
1339 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1341 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1342 return;
1346 void Player::setDeathState(DeathState s)
1348 uint32 ressSpellId = 0;
1350 bool cur = isAlive();
1352 if(s == JUST_DIED && cur)
1354 // drunken state is cleared on death
1355 SetDrunkValue(0);
1356 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1357 ClearComboPoints();
1359 clearResurrectRequestData();
1361 // remove form before other mods to prevent incorrect stats calculation
1362 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1364 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1365 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1367 // remove uncontrolled pets
1368 RemoveMiniPet();
1369 RemoveGuardians();
1371 // save value before aura remove in Unit::setDeathState
1372 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1374 // passive spell
1375 if(!ressSpellId)
1376 ressSpellId = GetResurrectionSpellId();
1377 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1378 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
1379 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
1381 Unit::setDeathState(s);
1383 // restore resurrection spell id for player after aura remove
1384 if(s == JUST_DIED && cur && ressSpellId)
1385 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1387 if(isAlive() && !cur)
1389 //clear aura case after resurrection by another way (spells will be applied before next death)
1390 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1392 // restore default warrior stance
1393 if(getClass()== CLASS_WARRIOR)
1394 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1398 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1400 Field *fields = result->Fetch();
1402 *p_data << uint64(GetGUID());
1403 *p_data << m_name;
1405 *p_data << uint8(getRace());
1406 uint8 pClass = getClass();
1407 *p_data << uint8(pClass);
1408 *p_data << uint8(getGender());
1410 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1411 *p_data << uint8(bytes);
1412 *p_data << uint8(bytes >> 8);
1413 *p_data << uint8(bytes >> 16);
1414 *p_data << uint8(bytes >> 24);
1416 bytes = GetUInt32Value(PLAYER_BYTES_2);
1417 *p_data << uint8(bytes);
1419 *p_data << uint8(getLevel()); // player level
1420 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1421 uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY(),GetPositionZ());
1422 sLog.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId);
1423 *p_data << uint32(zoneId);
1424 *p_data << uint32(GetMapId());
1426 *p_data << GetPositionX();
1427 *p_data << GetPositionY();
1428 *p_data << GetPositionZ();
1430 // guild id
1431 *p_data << (result ? fields[13].GetUInt32() : 0);
1433 uint32 char_flags = 0;
1434 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1435 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1436 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1437 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1438 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1439 char_flags |= CHARACTER_FLAG_GHOST;
1440 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1441 char_flags |= CHARACTER_FLAG_RENAME;
1442 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) && (fields[14].GetCppString() != ""))
1443 char_flags |= CHARACTER_FLAG_DECLINED;
1445 *p_data << uint32(char_flags); // character flags
1446 // character customize (flags?)
1447 *p_data << uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE) ? 1 : 0);
1448 *p_data << uint8(1); // unknown
1450 // Pets info
1452 uint32 petDisplayId = 0;
1453 uint32 petLevel = 0;
1454 uint32 petFamily = 0;
1456 // show pet at selection character in character list only for non-ghost character
1457 if(result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER))
1459 uint32 entry = fields[10].GetUInt32();
1460 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1461 if(cInfo)
1463 petDisplayId = fields[11].GetUInt32();
1464 petLevel = fields[12].GetUInt32();
1465 petFamily = cInfo->family;
1469 *p_data << uint32(petDisplayId);
1470 *p_data << uint32(petLevel);
1471 *p_data << uint32(petFamily);
1474 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1476 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2);
1477 uint32 item_id = GetUInt32Value(visualbase);
1478 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1479 SpellItemEnchantmentEntry const *enchant = NULL;
1481 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot<=TEMP_ENCHANTMENT_SLOT; enchantSlot++)
1483 uint32 enchantId = GetUInt32Value(visualbase+1+enchantSlot);
1484 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1485 break;
1488 if (proto != NULL)
1490 *p_data << uint32(proto->DisplayInfoID);
1491 *p_data << uint8(proto->InventoryType);
1492 *p_data << uint32(enchant ? enchant->aura_id : 0);
1494 else
1496 *p_data << uint32(0);
1497 *p_data << uint8(0);
1498 *p_data << uint32(0); // enchant?
1501 *p_data << uint32(0); // first bag display id
1502 *p_data << uint8(0); // first bag inventory type
1503 *p_data << uint32(0); // enchant?
1506 bool Player::ToggleAFK()
1508 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1510 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1512 // afk player not allowed in battleground
1513 if(state && InBattleGround())
1514 LeaveBattleground();
1516 return state;
1519 bool Player::ToggleDND()
1521 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1523 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1526 uint8 Player::chatTag() const
1528 // it's bitmask
1529 // 0x8 - ??
1530 // 0x4 - gm
1531 // 0x2 - dnd
1532 // 0x1 - afk
1533 if(isGMChat())
1534 return 4;
1535 else if(isDND())
1536 return 3;
1537 if(isAFK())
1538 return 1;
1539 else
1540 return 0;
1543 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1545 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1547 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1548 return false;
1551 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1552 Pet* pet = GetPet();
1554 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1556 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1557 // don't let gm level > 1 either
1558 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1559 return false;
1561 // client without expansion support
1562 if(GetSession()->Expansion() < mEntry->Expansion())
1564 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1566 if(GetTransport())
1567 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1569 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1571 return false; // normal client can't teleport to this map...
1573 else
1575 sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
1578 // if we were on a transport, leave
1579 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1581 m_transport->RemovePassenger(this);
1582 m_transport = NULL;
1583 m_movementInfo.t_x = 0.0f;
1584 m_movementInfo.t_y = 0.0f;
1585 m_movementInfo.t_z = 0.0f;
1586 m_movementInfo.t_o = 0.0f;
1587 m_movementInfo.t_time = 0;
1590 // The player was ported to another map and looses the duel immediately.
1591 // We have to perform this check before the teleport, otherwise the
1592 // ObjectAccessor won't find the flag.
1593 if (duel && GetMapId()!=mapid)
1595 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
1596 if (obj)
1597 DuelComplete(DUEL_FLED);
1600 // reset movement flags at teleport, because player will continue move with these flags after teleport
1601 m_movementInfo.flags = 0;
1603 if ((GetMapId() == mapid) && (!m_transport))
1605 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1607 //same map, only remove pet if out of range for new position
1608 if(pet && pet->GetDistance(x,y,z) >= OWNER_MAX_DISTANCE)
1609 UnsummonPetTemporaryIfAny();
1612 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1613 CombatStop();
1615 // this will be used instead of the current location in SaveToDB
1616 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1617 SetFallInformation(0, z);
1619 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1620 // at client packet MSG_MOVE_TELEPORT_ACK
1621 SetSemaphoreTeleportNear(true);
1622 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1623 if(!GetSession()->PlayerLogout())
1625 WorldPacket data;
1626 BuildTeleportAckMsg(&data, x, y, z, orientation);
1627 GetSession()->SendPacket(&data);
1630 else
1632 // far teleport to another map
1633 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1634 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1636 // Check enter rights before map getting to avoid creating instance copy for player
1637 // this check not dependent from map instance copy and same for all instance copies of selected map
1638 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1639 return false;
1641 // If the map is not created, assume it is possible to enter it.
1642 // It will be created in the WorldPortAck.
1643 Map *map = MapManager::Instance().FindMap(mapid);
1644 if (!map || map->CanEnter(this))
1646 SetSelection(0);
1648 CombatStop();
1650 ResetContestedPvP();
1652 // remove player from battleground on far teleport (when changing maps)
1653 if(BattleGround const* bg = GetBattleGround())
1655 // Note: at battleground join battleground id set before teleport
1656 // and we already will found "current" battleground
1657 // just need check that this is targeted map or leave
1658 if(bg->GetMapId() != mapid)
1659 LeaveBattleground(false); // don't teleport to entry point
1662 // remove pet on map change
1663 if (pet)
1664 UnsummonPetTemporaryIfAny();
1666 // remove all dyn objects
1667 RemoveAllDynObjects();
1669 // stop spellcasting
1670 // not attempt interrupt teleportation spell at caster teleport
1671 if(!(options & TELE_TO_SPELL))
1672 if(IsNonMeleeSpellCasted(true))
1673 InterruptNonMeleeSpells(true);
1675 if(!GetSession()->PlayerLogout())
1677 // send transfer packets
1678 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1679 data << uint32(mapid);
1680 if (m_transport)
1682 data << m_transport->GetEntry() << GetMapId();
1684 GetSession()->SendPacket(&data);
1686 data.Initialize(SMSG_NEW_WORLD, (20));
1687 if (m_transport)
1689 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1691 else
1693 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1695 GetSession()->SendPacket( &data );
1696 SendSavedInstances();
1698 // remove from old map now
1699 if(oldmap) oldmap->Remove(this, false);
1702 // new final coordinates
1703 float final_x = x;
1704 float final_y = y;
1705 float final_z = z;
1706 float final_o = orientation;
1708 if(m_transport)
1710 final_x += m_movementInfo.t_x;
1711 final_y += m_movementInfo.t_y;
1712 final_z += m_movementInfo.t_z;
1713 final_o += m_movementInfo.t_o;
1716 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1717 SetFallInformation(0, final_z);
1718 // if the player is saved before worldportack (at logout for example)
1719 // this will be used instead of the current location in SaveToDB
1721 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
1723 // move packet sent by client always after far teleport
1724 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1725 SetSemaphoreTeleportFar(true);
1727 else
1728 return false;
1730 return true;
1733 void Player::AddToWorld()
1735 ///- Do not add/remove the player from the object storage
1736 ///- It will crash when updating the ObjectAccessor
1737 ///- The player should only be added when logging in
1738 Unit::AddToWorld();
1740 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1742 if(m_items[i])
1743 m_items[i]->AddToWorld();
1747 void Player::RemoveFromWorld()
1749 // cleanup
1750 if(IsInWorld())
1752 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1753 Uncharm();
1754 UnsummonAllTotems();
1755 RemoveMiniPet();
1756 RemoveGuardians();
1759 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1761 if(m_items[i])
1762 m_items[i]->RemoveFromWorld();
1765 ///- Do not add/remove the player from the object storage
1766 ///- It will crash when updating the ObjectAccessor
1767 ///- The player should only be removed when logging out
1768 Unit::RemoveFromWorld();
1771 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1773 float addRage;
1775 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1777 if(attacker)
1779 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1781 // talent who gave more rage on attack
1782 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1784 else
1786 addRage = damage/rageconversion*2.5;
1788 // Berserker Rage effect
1789 if(HasAura(18499,0))
1790 addRage *= 1.3;
1793 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1795 ModifyPower(POWER_RAGE, uint32(addRage*10));
1798 void Player::RegenerateAll()
1800 if (m_regenTimer != 0)
1801 return;
1802 uint32 regenDelay = 2000;
1804 // Not in combat or they have regeneration
1805 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1806 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1808 RegenerateHealth();
1809 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1811 Regenerate(POWER_RAGE);
1812 if(getClass() == CLASS_DEATH_KNIGHT)
1813 Regenerate(POWER_RUNIC_POWER);
1817 Regenerate( POWER_ENERGY );
1819 Regenerate( POWER_MANA );
1821 if(getClass() == CLASS_DEATH_KNIGHT)
1822 Regenerate( POWER_RUNE );
1824 m_regenTimer = regenDelay;
1827 void Player::Regenerate(Powers power)
1829 uint32 curValue = GetPower(power);
1830 uint32 maxValue = GetMaxPower(power);
1832 float addvalue = 0.0f;
1834 switch (power)
1836 case POWER_MANA:
1838 bool recentCast = IsUnderLastManaUseEffect();
1839 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1840 if (recentCast)
1842 // Mangos Updates Mana in intervals of 2s, which is correct
1843 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1845 else
1847 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1849 } break;
1850 case POWER_RAGE: // Regenerate rage
1852 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1853 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1854 } break;
1855 case POWER_ENERGY: // Regenerate energy (rogue)
1856 addvalue = 20;
1857 break;
1858 case POWER_RUNIC_POWER:
1860 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1861 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1862 } break;
1863 case POWER_RUNE:
1865 for(uint32 i = 0; i < MAX_RUNES; ++i)
1866 if(uint8 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1867 SetRuneCooldown(i, cd - 1); // ... by 2 sec (because update is every 2 sec)
1868 } break;
1869 case POWER_FOCUS:
1870 case POWER_HAPPINESS:
1871 case POWER_HEALTH:
1872 break;
1875 // Mana regen calculated in Player::UpdateManaRegen()
1876 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1877 if(power != POWER_MANA)
1879 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1880 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1881 if ((*i)->GetModifier()->m_miscvalue == power)
1882 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1885 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
1887 curValue += uint32(addvalue);
1888 if (curValue > maxValue)
1889 curValue = maxValue;
1891 else
1893 if(curValue <= uint32(addvalue))
1894 curValue = 0;
1895 else
1896 curValue -= uint32(addvalue);
1898 SetPower(power, curValue);
1901 void Player::RegenerateHealth()
1903 uint32 curValue = GetHealth();
1904 uint32 maxValue = GetMaxHealth();
1906 if (curValue >= maxValue) return;
1908 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1910 float addvalue = 0.0f;
1912 // polymorphed case
1913 if ( IsPolymorphed() )
1914 addvalue = GetMaxHealth()/3;
1915 // normal regen case (maybe partly in combat case)
1916 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1918 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1919 if (!isInCombat())
1921 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1922 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1923 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1925 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1926 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1928 if(!IsStandState())
1929 addvalue *= 1.5;
1932 // always regeneration bonus (including combat)
1933 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1935 if(addvalue < 0)
1936 addvalue = 0;
1938 ModifyHealth(int32(addvalue));
1941 bool Player::CanInteractWithNPCs(bool alive) const
1943 if(alive && !isAlive())
1944 return false;
1945 if(isInFlight())
1946 return false;
1948 return true;
1951 Creature*
1952 Player::GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask)
1954 // unit checks
1955 if (!guid)
1956 return NULL;
1958 if(!IsInWorld())
1959 return NULL;
1961 // exist (we need look pets also for some interaction (quest/etc)
1962 Creature *unit = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
1963 if (!unit)
1964 return NULL;
1966 // player check
1967 if(!CanInteractWithNPCs(!unit->isSpiritService()))
1968 return NULL;
1970 // appropriate npc type
1971 if(npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
1972 return NULL;
1974 // alive or spirit healer
1975 if(!unit->isAlive() && (!unit->isSpiritService() || isAlive() ))
1976 return NULL;
1978 // not allow interaction under control, but allow with own pets
1979 if(unit->GetCharmerGUID())
1980 return NULL;
1982 // not enemy
1983 if( unit->IsHostileTo(this))
1984 return NULL;
1986 // not unfriendly
1987 if(FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction()))
1988 if(factionTemplate->faction)
1989 if(FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
1990 if(faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
1991 return NULL;
1993 // not too far
1994 if(!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE))
1995 return NULL;
1997 return unit;
2000 GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const
2002 if(GameObject *go = GetMap()->GetGameObject(guid))
2004 if(go->GetGoType() == type)
2006 float maxdist;
2007 switch(type)
2009 // TODO: find out how the client calculates the maximal usage distance to spellless working
2010 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2011 case GAMEOBJECT_TYPE_GUILD_BANK:
2012 case GAMEOBJECT_TYPE_MAILBOX:
2013 maxdist = 10.0f;
2014 break;
2015 case GAMEOBJECT_TYPE_FISHINGHOLE:
2016 maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
2017 break;
2018 default:
2019 maxdist = INTERACTION_DISTANCE;
2020 break;
2023 if (go->IsWithinDistInMap(this, maxdist))
2024 return go;
2026 sLog.outError("IsGameObjectOfTypeInRange: GameObject '%s' [GUID: %u] is too far away from player %s [GUID: %u] to be used by him (distance=%f, maximal 10 is allowed)", go->GetGOInfo()->name,
2027 go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
2030 return NULL;
2033 bool Player::IsUnderWater() const
2035 return IsInWater() &&
2036 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2039 void Player::SetInWater(bool apply)
2041 if(m_isInWater==apply)
2042 return;
2044 //define player in water by opcodes
2045 //move player's guid into HateOfflineList of those mobs
2046 //which can't swim and move guid back into ThreatList when
2047 //on surface.
2048 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2049 m_isInWater = apply;
2051 // remove auras that need water/land
2052 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
2054 getHostilRefManager().updateThreatTables();
2057 void Player::SetGameMaster(bool on)
2059 if(on)
2061 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
2062 setFaction(35);
2063 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2065 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2066 ResetContestedPvP();
2068 getHostilRefManager().setOnlineOfflineState(false);
2069 CombatStop();
2071 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
2073 else
2075 // restore phase
2076 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
2077 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2079 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2080 setFactionForRace(getRace());
2081 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2083 // restore FFA PvP Server state
2084 if(sWorld.IsFFAPvPRealm())
2085 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2087 // restore FFA PvP area state, remove not allowed for GM mounts
2088 UpdateArea(m_areaUpdateId);
2090 getHostilRefManager().setOnlineOfflineState(true);
2093 ObjectAccessor::UpdateVisibilityForPlayer(this);
2096 void Player::SetGMVisible(bool on)
2098 if(on)
2100 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2102 // Reapply stealth/invisibility if active or show if not any
2103 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2104 SetVisibility(VISIBILITY_GROUP_STEALTH);
2105 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2106 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2107 else
2108 SetVisibility(VISIBILITY_ON);
2110 else
2112 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2114 SetAcceptWhispers(false);
2115 SetGameMaster(true);
2117 SetVisibility(VISIBILITY_OFF);
2121 bool Player::IsGroupVisibleFor(Player* p) const
2123 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2125 default: return IsInSameGroupWith(p);
2126 case 1: return IsInSameRaidWith(p);
2127 case 2: return GetTeam()==p->GetTeam();
2131 bool Player::IsInSameGroupWith(Player const* p) const
2133 return p==this || GetGroup() != NULL &&
2134 GetGroup() == p->GetGroup() &&
2135 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2138 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2139 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2140 void Player::UninviteFromGroup()
2142 Group* group = GetGroupInvite();
2143 if(!group)
2144 return;
2146 group->RemoveInvite(this);
2148 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2150 if(group->IsCreated())
2152 group->Disband(true);
2153 objmgr.RemoveGroup(group);
2155 else
2156 group->RemoveAllInvites();
2158 delete group;
2162 void Player::RemoveFromGroup(Group* group, uint64 guid)
2164 if(group)
2166 if (group->RemoveMember(guid, 0) <= 1)
2168 // group->Disband(); already disbanded in RemoveMember
2169 objmgr.RemoveGroup(group);
2170 delete group;
2171 // removemember sets the player's group pointer to NULL
2176 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2178 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2179 data << uint64(victim ? victim->GetGUID() : 0); // guid
2180 data << uint32(GivenXP+RestXP); // given experience
2181 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2182 if(victim)
2184 data << uint32(GivenXP); // experience without rested bonus
2185 data << float(1); // 1 - none 0 - 100% group bonus output
2187 data << uint8(0); // new 2.4.0
2188 GetSession()->SendPacket(&data);
2191 void Player::GiveXP(uint32 xp, Unit* victim)
2193 if ( xp < 1 )
2194 return;
2196 if(!isAlive())
2197 return;
2199 uint32 level = getLevel();
2201 // XP to money conversion processed in Player::RewardQuest
2202 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2203 return;
2205 // handle SPELL_AURA_MOD_XP_PCT auras
2206 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2207 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2208 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2210 // XP resting bonus for kill
2211 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2213 SendLogXPGain(xp,victim,rested_bonus_xp);
2215 uint32 curXP = GetUInt32Value(PLAYER_XP);
2216 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2217 uint32 newXP = curXP + xp + rested_bonus_xp;
2219 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2221 newXP -= nextLvlXP;
2223 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2224 GiveLevel(level + 1);
2226 level = getLevel();
2227 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2230 SetUInt32Value(PLAYER_XP, newXP);
2233 // Update player to next level
2234 // Current player experience not update (must be update by caller)
2235 void Player::GiveLevel(uint32 level)
2237 if ( level == getLevel() )
2238 return;
2240 PlayerLevelInfo info;
2241 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2243 PlayerClassLevelInfo classInfo;
2244 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2246 // send levelup info to client
2247 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2248 data << uint32(level);
2249 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2250 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2251 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2252 data << uint32(0);
2253 data << uint32(0);
2254 data << uint32(0);
2255 data << uint32(0);
2256 data << uint32(0);
2257 data << uint32(0);
2258 // end for
2259 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2260 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2262 GetSession()->SendPacket(&data);
2264 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level));
2266 //update level, max level of skills
2267 if(getLevel()!= level)
2268 m_Played_time[1] = 0; // Level Played Time reset
2269 SetLevel(level);
2270 UpdateSkillsForLevel ();
2272 // save base values (bonuses already included in stored stats
2273 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2274 SetCreateStat(Stats(i), info.stats[i]);
2276 SetCreateHealth(classInfo.basehealth);
2277 SetCreateMana(classInfo.basemana);
2279 InitTalentForLevel();
2280 InitTaxiNodesForLevel();
2281 InitGlyphsForLevel();
2283 UpdateAllStats();
2285 // set current level health and mana/energy to maximum after applying all mods.
2286 SetHealth(GetMaxHealth());
2287 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2288 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2289 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2290 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2291 SetPower(POWER_FOCUS, 0);
2292 SetPower(POWER_HAPPINESS, 0);
2294 // give level to summoned pet
2295 Pet* pet = GetPet();
2296 if(pet && pet->getPetType()==SUMMON_PET)
2297 pet->GivePetLevel(level);
2298 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2301 void Player::InitTalentForLevel()
2303 uint32 level = getLevel();
2304 // talents base at level diff ( talents = level - 9 but some can be used already)
2305 if(level < 10)
2307 // Remove all talent points
2308 if(m_usedTalentCount > 0) // Free any used talents
2310 resetTalents(true);
2311 SetFreeTalentPoints(0);
2314 else
2316 uint32 talentPointsForLevel = CalculateTalentsPoints();
2318 // if used more that have then reset
2319 if(m_usedTalentCount > talentPointsForLevel)
2321 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2322 resetTalents(true);
2323 else
2324 SetFreeTalentPoints(0);
2326 // else update amount of free points
2327 else
2328 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2331 SendTalentsInfoData(false); // update at client
2334 void Player::InitStatsForLevel(bool reapplyMods)
2336 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2337 _RemoveAllStatBonuses();
2339 PlayerClassLevelInfo classInfo;
2340 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2342 PlayerLevelInfo info;
2343 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2345 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2346 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel()));
2348 UpdateSkillsForLevel ();
2350 // set default cast time multiplier
2351 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2353 // reset size before reapply auras
2354 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2356 // save base values (bonuses already included in stored stats
2357 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2358 SetCreateStat(Stats(i), info.stats[i]);
2360 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2361 SetStat(Stats(i), info.stats[i]);
2363 SetCreateHealth(classInfo.basehealth);
2365 //set create powers
2366 SetCreateMana(classInfo.basemana);
2368 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2370 InitStatBuffMods();
2372 //reset rating fields values
2373 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2374 SetUInt32Value(index, 0);
2376 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2377 for (int i = 0; i < 7; ++i)
2379 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2380 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2381 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2384 //reset attack power, damage and attack speed fields
2385 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2386 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2387 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2389 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2390 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2391 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2392 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2393 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2394 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2396 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2397 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2398 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2399 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2400 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2401 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2403 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2404 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2405 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2406 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2408 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2409 for (uint8 i = 0; i < 7; ++i)
2410 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2412 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2413 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2414 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2416 // Dodge percentage
2417 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2419 // set armor (resistance 0) to original value (create_agility*2)
2420 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2421 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2422 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2423 // set other resistance to original value (0)
2424 for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
2426 SetResistance(SpellSchools(i), 0);
2427 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2428 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2431 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2432 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2433 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2435 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
2436 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2438 // Reset no reagent cost field
2439 for(int i = 0; i < 3; ++i)
2440 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2441 // Init data for form but skip reapply item mods for form
2442 InitDataForForm(reapplyMods);
2444 // save new stats
2445 for (int i = POWER_MANA; i < MAX_POWERS; ++i)
2446 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2448 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2450 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2451 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2453 // cleanup unit flags (will be re-applied if need at aura load).
2454 RemoveFlag( UNIT_FIELD_FLAGS,
2455 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2456 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2457 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2458 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2459 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2460 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2462 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2464 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2465 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2467 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2468 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2470 // restore if need some important flags
2471 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2473 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2474 _ApplyAllStatBonuses();
2476 // set current level health and mana/energy to maximum after applying all mods.
2477 SetHealth(GetMaxHealth());
2478 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2479 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2480 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2481 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2482 SetPower(POWER_FOCUS, 0);
2483 SetPower(POWER_HAPPINESS, 0);
2484 SetPower(POWER_RUNIC_POWER, 0);
2487 void Player::SendInitialSpells()
2489 time_t curTime = time(NULL);
2490 time_t infTime = curTime + MONTH/2;
2492 uint16 spellCount = 0;
2494 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2495 data << uint8(0);
2497 size_t countPos = data.wpos();
2498 data << uint16(spellCount); // spell count placeholder
2500 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2502 if(itr->second->state == PLAYERSPELL_REMOVED)
2503 continue;
2505 if(!itr->second->active || itr->second->disabled)
2506 continue;
2508 data << uint32(itr->first);
2509 data << uint16(0); // it's not slot id
2511 spellCount +=1;
2514 data.put<uint16>(countPos,spellCount); // write real count value
2516 uint16 spellCooldowns = m_spellCooldowns.size();
2517 data << uint16(spellCooldowns);
2518 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2520 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2521 if(!sEntry)
2522 continue;
2524 // not send infinity cooldown
2525 if(itr->second.end > infTime)
2526 continue;
2528 data << uint32(itr->first);
2530 time_t cooldown = 0;
2531 if(itr->second.end > curTime)
2532 cooldown = (itr->second.end-curTime)*IN_MILISECONDS;
2534 data << uint16(itr->second.itemid); // cast item id
2535 data << uint16(sEntry->Category); // spell category
2536 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2538 data << uint32(0); // cooldown
2539 data << uint32(cooldown); // category cooldown
2541 else
2543 data << uint32(cooldown); // cooldown
2544 data << uint32(0); // category cooldown
2548 GetSession()->SendPacket(&data);
2550 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2553 void Player::RemoveMail(uint32 id)
2555 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2557 if ((*itr)->messageID == id)
2559 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2560 m_mail.erase(itr);
2561 return;
2566 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2568 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2569 data << (uint32) mailId;
2570 data << (uint32) mailAction;
2571 data << (uint32) mailError;
2572 if ( mailError == MAIL_ERR_BAG_FULL )
2573 data << (uint32) equipError;
2574 else if( mailAction == MAIL_ITEM_TAKEN )
2576 data << (uint32) item_guid; // item guid low?
2577 data << (uint32) item_count; // item count?
2579 GetSession()->SendPacket(&data);
2582 void Player::SendNewMail()
2584 // deliver undelivered mail
2585 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2586 data << (uint32) 0;
2587 GetSession()->SendPacket(&data);
2590 void Player::UpdateNextMailTimeAndUnreads()
2592 // calculate next delivery time (min. from non-delivered mails
2593 // and recalculate unReadMail
2594 time_t cTime = time(NULL);
2595 m_nextMailDelivereTime = 0;
2596 unReadMails = 0;
2597 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2599 if((*itr)->deliver_time > cTime)
2601 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2602 m_nextMailDelivereTime = (*itr)->deliver_time;
2604 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2605 ++unReadMails;
2609 void Player::AddNewMailDeliverTime(time_t deliver_time)
2611 if(deliver_time <= time(NULL)) // ready now
2613 ++unReadMails;
2614 SendNewMail();
2616 else // not ready and no have ready mails
2618 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2619 m_nextMailDelivereTime = deliver_time;
2623 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2625 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2626 if (!spellInfo)
2628 // do character spell book cleanup (all characters)
2629 if(!IsInWorld() && !learning) // spell load case
2631 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2632 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2634 else
2635 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2637 return false;
2640 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2642 // do character spell book cleanup (all characters)
2643 if(!IsInWorld() && !learning) // spell load case
2645 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2646 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2648 else
2649 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2651 return false;
2654 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2656 bool dependent_set = false;
2657 bool disabled_case = false;
2658 bool superceded_old = false;
2660 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2661 if (itr != m_spells.end())
2663 uint32 next_active_spell_id = 0;
2664 // fix activate state for non-stackable low rank (and find next spell for !active case)
2665 if(!SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2667 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2668 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2670 if(HasSpell(next_itr->second))
2672 // high rank already known so this must !active
2673 active = false;
2674 next_active_spell_id = next_itr->second;
2675 break;
2680 // not do anything if already known in expected state
2681 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2682 itr->second->dependent == dependent && itr->second->disabled == disabled)
2684 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2685 itr->second->state = PLAYERSPELL_UNCHANGED;
2687 return false;
2690 // dependent spell known as not dependent, overwrite state
2691 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2693 itr->second->dependent = dependent;
2694 if (itr->second->state != PLAYERSPELL_NEW)
2695 itr->second->state = PLAYERSPELL_CHANGED;
2696 dependent_set = true;
2699 // update active state for known spell
2700 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2702 itr->second->active = active;
2704 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2705 itr->second->state = PLAYERSPELL_UNCHANGED;
2706 else if(itr->second->state != PLAYERSPELL_NEW)
2707 itr->second->state = PLAYERSPELL_CHANGED;
2709 if(active)
2711 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2712 CastSpell (this,spell_id,true);
2714 else if(IsInWorld())
2716 if(next_active_spell_id)
2718 // update spell ranks in spellbook and action bar
2719 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2720 data << uint32(spell_id);
2721 data << uint32(next_active_spell_id);
2722 GetSession()->SendPacket( &data );
2724 else
2726 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2727 data << uint32(spell_id);
2728 GetSession()->SendPacket(&data);
2732 return active; // learn (show in spell book if active now)
2735 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2737 if(itr->second->state != PLAYERSPELL_NEW)
2738 itr->second->state = PLAYERSPELL_CHANGED;
2739 itr->second->disabled = disabled;
2741 if(disabled)
2742 return false;
2744 disabled_case = true;
2746 else switch(itr->second->state)
2748 case PLAYERSPELL_UNCHANGED: // known saved spell
2749 return false;
2750 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2752 delete itr->second;
2753 m_spells.erase(itr);
2754 state = PLAYERSPELL_CHANGED;
2755 break; // need re-add
2757 default: // known not saved yet spell (new or modified)
2759 // can be in case spell loading but learned at some previous spell loading
2760 if(!IsInWorld() && !learning && !dependent_set)
2761 itr->second->state = PLAYERSPELL_UNCHANGED;
2763 return false;
2768 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2770 // talent: unlearn all other talent ranks (high and low)
2771 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2773 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2775 for(int i=0; i < MAX_TALENT_RANK; ++i)
2777 // skip learning spell and no rank spell case
2778 uint32 rankSpellId = talentInfo->RankID[i];
2779 if(!rankSpellId || rankSpellId==spell_id)
2780 continue;
2782 removeSpell(rankSpellId);
2786 // non talent spell: learn low ranks (recursive call)
2787 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2789 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
2790 addSpell(prev_spell,active,true,true,disabled);
2791 else // at normal learning
2792 learnSpell(prev_spell,true);
2795 PlayerSpell *newspell = new PlayerSpell;
2796 newspell->state = state;
2797 newspell->active = active;
2798 newspell->dependent = dependent;
2799 newspell->disabled = disabled;
2801 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2802 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2804 for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
2806 if(itr2->second->state == PLAYERSPELL_REMOVED) continue;
2807 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
2808 if(!i_spellInfo) continue;
2810 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
2812 if(itr2->second->active)
2814 if(spellmgr.IsHighRankOfSpell(spell_id,itr2->first))
2816 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2818 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2819 data << uint32(itr2->first);
2820 data << uint32(spell_id);
2821 GetSession()->SendPacket( &data );
2824 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2825 itr2->second->active = false;
2826 if(itr2->second->state != PLAYERSPELL_NEW)
2827 itr2->second->state = PLAYERSPELL_CHANGED;
2828 superceded_old = true; // new spell replace old in action bars and spell book.
2830 else if(spellmgr.IsHighRankOfSpell(itr2->first,spell_id))
2832 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2834 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2835 data << uint32(spell_id);
2836 data << uint32(itr2->first);
2837 GetSession()->SendPacket( &data );
2840 // mark new spell as disable (not learned yet for client and will not learned)
2841 newspell->active = false;
2842 if(newspell->state != PLAYERSPELL_NEW)
2843 newspell->state = PLAYERSPELL_CHANGED;
2850 m_spells[spell_id] = newspell;
2852 // return false if spell disabled
2853 if (newspell->disabled)
2854 return false;
2857 uint32 talentCost = GetTalentSpellCost(spell_id);
2859 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2860 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2861 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2863 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2864 CastSpell(this, spell_id, true);
2866 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2867 else if (IsPassiveSpell(spell_id))
2869 if(IsNeedCastPassiveSpellAtLearn(spellInfo))
2870 CastSpell(this, spell_id, true);
2872 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2874 CastSpell(this, spell_id, true);
2875 return false;
2878 // update used talent points count
2879 m_usedTalentCount += talentCost;
2881 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2882 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2884 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2885 SetFreePrimaryProffesions(freeProfs-1);
2888 // add dependent skills
2889 uint16 maxskill = GetMaxSkillValueForLevel();
2891 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2893 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2894 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2896 if(spellLearnSkill)
2898 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2899 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2901 if(skill_value < spellLearnSkill->value)
2902 skill_value = spellLearnSkill->value;
2904 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2906 if(skill_max_value < new_skill_max_value)
2907 skill_max_value = new_skill_max_value;
2909 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2911 else
2913 // not ranked skills
2914 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2916 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2917 if(!pSkill)
2918 continue;
2920 if(HasSkill(pSkill->id))
2921 continue;
2923 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2924 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2925 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
2927 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2929 case SKILL_RANGE_LANGUAGE:
2930 SetSkill(pSkill->id, 300, 300 );
2931 break;
2932 case SKILL_RANGE_LEVEL:
2933 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2934 break;
2935 case SKILL_RANGE_MONO:
2936 SetSkill(pSkill->id, 1, 1 );
2937 break;
2938 default:
2939 break;
2945 // learn dependent spells
2946 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2947 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2949 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
2951 if(!itr2->second.autoLearned)
2953 if(!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
2954 addSpell(itr2->second.spell,itr2->second.active,true,true,false);
2955 else // at normal learning
2956 learnSpell(itr2->second.spell,true);
2960 if(!GetSession()->PlayerLoading())
2962 // not ranked skills
2963 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2965 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
2966 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
2969 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
2972 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2973 return active && !disabled && !superceded_old;
2976 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
2978 bool need_cast = false;
2980 switch(spellInfo->Id)
2982 // some spells not have stance data expacted cast at form change or present
2983 case 5420: need_cast = (m_form == FORM_TREE); break;
2984 case 5419: need_cast = (m_form == FORM_TRAVEL); break;
2985 case 7376: need_cast = (m_form == FORM_DEFENSIVESTANCE); break;
2986 case 7381: need_cast = (m_form == FORM_BERSERKERSTANCE); break;
2987 case 21156: need_cast = (m_form == FORM_BATTLESTANCE); break;
2988 case 21178: need_cast = (m_form == FORM_BEAR || m_form == FORM_DIREBEAR); break;
2989 case 33948: need_cast = (m_form == FORM_FLIGHT); break;
2990 case 34764: need_cast = (m_form == FORM_FLIGHT); break;
2991 case 40121: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2992 case 40122: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2993 // another spells have proper stance data
2994 default: need_cast = !spellInfo->Stances || m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))); break;
2997 //Check CasterAuraStates
2998 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
3001 void Player::learnSpell(uint32 spell_id, bool dependent)
3003 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3005 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
3006 bool active = disabled ? itr->second->active : true;
3008 bool learning = addSpell(spell_id,active,true,dependent,false);
3010 // learn all disabled higher ranks (recursive)
3011 if(disabled)
3013 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3014 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
3016 PlayerSpellMap::iterator iter = m_spells.find(i->second);
3017 if (iter != m_spells.end() && iter->second->disabled)
3018 learnSpell(i->second,false);
3022 // prevent duplicated entires in spell book, also not send if not in world (loading)
3023 if(!learning || !IsInWorld ())
3024 return;
3026 WorldPacket data(SMSG_LEARNED_SPELL, 4);
3027 data << uint32(spell_id);
3028 GetSession()->SendPacket(&data);
3031 void Player::removeSpell(uint32 spell_id, bool disabled, bool update_action_bar_for_low_rank)
3033 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3034 if (itr == m_spells.end())
3035 return;
3037 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
3038 return;
3040 // unlearn non talent higher ranks (recursive)
3041 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3042 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
3043 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
3044 removeSpell(itr2->second,disabled);
3046 bool cur_active = itr->second->active;
3047 bool cur_dependent = itr->second->dependent;
3049 if (disabled)
3051 itr->second->disabled = disabled;
3052 if(itr->second->state != PLAYERSPELL_NEW)
3053 itr->second->state = PLAYERSPELL_CHANGED;
3055 else
3057 if(itr->second->state == PLAYERSPELL_NEW)
3059 delete itr->second;
3060 m_spells.erase(itr);
3062 else
3063 itr->second->state = PLAYERSPELL_REMOVED;
3066 RemoveAurasDueToSpell(spell_id);
3068 // remove pet auras
3069 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
3070 RemovePetAura(petSpell);
3072 // free talent points
3073 uint32 talentCosts = GetTalentSpellCost(spell_id);
3074 if(talentCosts > 0)
3076 if(talentCosts < m_usedTalentCount)
3077 m_usedTalentCount -= talentCosts;
3078 else
3079 m_usedTalentCount = 0;
3082 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3083 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3085 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
3086 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
3087 SetFreePrimaryProffesions(freeProfs);
3090 // remove dependent skill
3091 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
3092 if(spellLearnSkill)
3094 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
3095 if(!prev_spell) // first rank, remove skill
3096 SetSkill(spellLearnSkill->skill,0,0);
3097 else
3099 // search prev. skill setting by spell ranks chain
3100 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
3101 while(!prevSkill && prev_spell)
3103 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
3104 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
3107 if(!prevSkill) // not found prev skill setting, remove skill
3108 SetSkill(spellLearnSkill->skill,0,0);
3109 else // set to prev. skill setting values
3111 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3112 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3114 if(skill_value > prevSkill->value)
3115 skill_value = prevSkill->value;
3117 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3119 if(skill_max_value > new_skill_max_value)
3120 skill_max_value = new_skill_max_value;
3122 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3127 else
3129 // not ranked skills
3130 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
3131 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
3133 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
3135 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3136 if(!pSkill)
3137 continue;
3139 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3140 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3141 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
3143 // not reset skills for professions and racial abilities
3144 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3145 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
3146 continue;
3148 SetSkill(pSkill->id, 0, 0 );
3153 // remove dependent spells
3154 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
3155 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
3157 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
3158 removeSpell(itr2->second.spell, disabled);
3160 // activate lesser rank in spellbook/action bar, and cast it if need
3161 bool prev_activate = false;
3163 if(uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id))
3165 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3167 // if talent then lesser rank also talent and need learn
3168 if(talentCosts)
3169 learnSpell (prev_id,false);
3170 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3171 else if(cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
3173 // need manually update dependence state (learn spell ignore like attempts)
3174 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3175 if (prev_itr != m_spells.end())
3177 if(prev_itr->second->dependent != cur_dependent)
3179 prev_itr->second->dependent = cur_dependent;
3180 if(prev_itr->second->state != PLAYERSPELL_NEW)
3181 prev_itr->second->state = PLAYERSPELL_CHANGED;
3184 // now re-learn if need re-activate
3185 if(cur_active && !prev_itr->second->active)
3187 if(addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3189 if(update_action_bar_for_low_rank)
3191 // downgrade spell ranks in spellbook and action bar
3192 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
3193 data << uint32(spell_id);
3194 data << uint32(prev_id);
3195 GetSession()->SendPacket( &data );
3196 prev_activate = true;
3204 // remove from spell book if not replaced by lesser rank
3205 if(!prev_activate)
3207 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3208 data << uint32(spell_id);
3209 GetSession()->SendPacket(&data);
3213 void Player::RemoveArenaSpellCooldowns()
3215 // remove cooldowns on spells that has < 15 min CD
3216 SpellCooldowns::iterator itr, next;
3217 // iterate spell cooldowns
3218 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3220 next = itr;
3221 ++next;
3222 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3223 // check if spellentry is present and if the cooldown is less than 15 mins
3224 if( entry &&
3225 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3226 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3228 // notify player
3229 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3230 data << uint32(itr->first);
3231 data << uint64(GetGUID());
3232 GetSession()->SendPacket(&data);
3233 // remove cooldown
3234 m_spellCooldowns.erase(itr);
3239 void Player::RemoveAllSpellCooldown()
3241 if(!m_spellCooldowns.empty())
3243 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3245 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3246 data << uint32(itr->first);
3247 data << uint64(GetGUID());
3248 GetSession()->SendPacket(&data);
3250 m_spellCooldowns.clear();
3254 void Player::_LoadSpellCooldowns(QueryResult *result)
3256 // some cooldowns can be already set at aura loading...
3258 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3260 if(result)
3262 time_t curTime = time(NULL);
3266 Field *fields = result->Fetch();
3268 uint32 spell_id = fields[0].GetUInt32();
3269 uint32 item_id = fields[1].GetUInt32();
3270 time_t db_time = (time_t)fields[2].GetUInt64();
3272 if(!sSpellStore.LookupEntry(spell_id))
3274 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3275 continue;
3278 // skip outdated cooldown
3279 if(db_time <= curTime)
3280 continue;
3282 AddSpellCooldown(spell_id, item_id, db_time);
3284 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3286 while( result->NextRow() );
3288 delete result;
3292 void Player::_SaveSpellCooldowns()
3294 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3296 time_t curTime = time(NULL);
3297 time_t infTime = curTime + MONTH/2;
3299 // remove outdated and save active
3300 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3302 if(itr->second.end <= curTime)
3303 m_spellCooldowns.erase(itr++);
3304 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3306 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));
3307 ++itr;
3309 else
3310 ++itr;
3314 uint32 Player::resetTalentsCost() const
3316 // The first time reset costs 1 gold
3317 if(m_resetTalentsCost < 1*GOLD)
3318 return 1*GOLD;
3319 // then 5 gold
3320 else if(m_resetTalentsCost < 5*GOLD)
3321 return 5*GOLD;
3322 // After that it increases in increments of 5 gold
3323 else if(m_resetTalentsCost < 10*GOLD)
3324 return 10*GOLD;
3325 else
3327 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3328 if(months > 0)
3330 // This cost will be reduced by a rate of 5 gold per month
3331 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3332 // to a minimum of 10 gold.
3333 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3335 else
3337 // After that it increases in increments of 5 gold
3338 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3339 // until it hits a cap of 50 gold.
3340 if(new_cost > 50*GOLD)
3341 new_cost = 50*GOLD;
3342 return new_cost;
3347 bool Player::resetTalents(bool no_cost)
3349 // not need after this call
3350 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3352 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3353 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3356 uint32 talentPointsForLevel = CalculateTalentsPoints();
3358 if (m_usedTalentCount == 0)
3360 SetFreeTalentPoints(talentPointsForLevel);
3361 return false;
3364 uint32 cost = 0;
3366 if(!no_cost)
3368 cost = resetTalentsCost();
3370 if (GetMoney() < cost)
3372 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3373 return false;
3377 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
3379 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3381 if (!talentInfo) continue;
3383 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3385 if(!talentTabInfo)
3386 continue;
3388 // unlearn only talents for character class
3389 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3390 // to prevent unexpected lost normal learned spell skip another class talents
3391 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3392 continue;
3394 for (int j = 0; j < MAX_TALENT_RANK; ++j)
3396 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3398 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3400 ++itr;
3401 continue;
3404 // remove learned spells (all ranks)
3405 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3407 // unlearn if first rank is talent or learned by talent
3408 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3410 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3411 itr = GetSpellMap().begin();
3412 continue;
3414 else
3415 ++itr;
3420 SetFreeTalentPoints(talentPointsForLevel);
3422 if(!no_cost)
3424 ModifyMoney(-(int32)cost);
3425 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3426 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
3428 m_resetTalentsCost = cost;
3429 m_resetTalentsTime = time(NULL);
3432 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3433 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3435 if(m_canTitanGrip)
3437 m_canTitanGrip = false;
3438 if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET))
3439 AutoUnequipOffhandIfNeed();
3442 return true;
3445 Mail* Player::GetMail(uint32 id)
3447 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3449 if ((*itr)->messageID == id)
3451 return (*itr);
3454 return NULL;
3457 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3459 if(target == this)
3461 Object::_SetCreateBits(updateMask, target);
3463 else
3465 for(uint16 index = 0; index < m_valuesCount; index++)
3467 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3468 updateMask->SetBit(index);
3473 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3475 if(target == this)
3477 Object::_SetUpdateBits(updateMask, target);
3479 else
3481 Object::_SetUpdateBits(updateMask, target);
3482 *updateMask &= updateVisualBits;
3486 void Player::InitVisibleBits()
3488 updateVisualBits.SetCount(PLAYER_END);
3490 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3491 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3492 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3493 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3494 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3495 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3496 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3497 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3498 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3499 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3500 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3501 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3502 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3503 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3504 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3505 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3506 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3507 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3508 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3509 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3510 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3511 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3512 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3513 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3514 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3515 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3516 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3517 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3518 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3519 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3520 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3521 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3522 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3523 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3524 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3525 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3526 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3527 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3528 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3529 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3530 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3531 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3532 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3533 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3534 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3535 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3536 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3537 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3538 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3539 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3540 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3541 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3542 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3543 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3544 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3546 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3547 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3548 updateVisualBits.SetBit(PLAYER_FLAGS);
3549 updateVisualBits.SetBit(PLAYER_GUILDID);
3550 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3551 updateVisualBits.SetBit(PLAYER_BYTES);
3552 updateVisualBits.SetBit(PLAYER_BYTES_2);
3553 updateVisualBits.SetBit(PLAYER_BYTES_3);
3554 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3555 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3557 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3558 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3559 updateVisualBits.SetBit(i);
3561 // Players visible items are not inventory stuff
3562 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3564 uint32 offset = i * 2;
3566 // item entry
3567 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset);
3568 // enchant
3569 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset);
3572 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3575 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3577 for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
3579 if(m_items[i] == NULL)
3580 continue;
3582 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3585 if(target == this)
3587 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3589 if(m_items[i] == NULL)
3590 continue;
3592 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3594 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3596 if(m_items[i] == NULL)
3597 continue;
3599 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3603 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3606 void Player::DestroyForPlayer( Player *target ) const
3608 Unit::DestroyForPlayer( target );
3610 for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
3612 if(m_items[i] == NULL)
3613 continue;
3615 m_items[i]->DestroyForPlayer( target );
3618 if(target == this)
3620 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3622 if(m_items[i] == NULL)
3623 continue;
3625 m_items[i]->DestroyForPlayer( target );
3627 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3629 if(m_items[i] == NULL)
3630 continue;
3632 m_items[i]->DestroyForPlayer( target );
3637 bool Player::HasSpell(uint32 spell) const
3639 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3640 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3641 !itr->second->disabled);
3644 bool Player::HasActiveSpell(uint32 spell) const
3646 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3647 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3648 itr->second->active && !itr->second->disabled);
3651 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3653 if (!trainer_spell)
3654 return TRAINER_SPELL_RED;
3656 if (!trainer_spell->learnedSpell)
3657 return TRAINER_SPELL_RED;
3659 // known spell
3660 if(HasSpell(trainer_spell->learnedSpell))
3661 return TRAINER_SPELL_GRAY;
3663 // check race/class requirement
3664 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3665 return TRAINER_SPELL_RED;
3667 // check level requirement
3668 if(getLevel() < trainer_spell->reqLevel)
3669 return TRAINER_SPELL_RED;
3671 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learnedSpell))
3673 // check prev.rank requirement
3674 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3675 return TRAINER_SPELL_RED;
3677 // check additional spell requirement
3678 if(spell_chain->req && !HasSpell(spell_chain->req))
3679 return TRAINER_SPELL_RED;
3682 // check skill requirement
3683 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3684 return TRAINER_SPELL_RED;
3686 // exist, already checked at loading
3687 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3689 // secondary prof. or not prof. spell
3690 uint32 skill = spell->EffectMiscValue[1];
3692 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3693 return TRAINER_SPELL_GREEN;
3695 // check primary prof. limit
3696 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3697 return TRAINER_SPELL_GREEN_DISABLED;
3699 return TRAINER_SPELL_GREEN;
3702 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3704 uint32 guid = GUID_LOPART(playerguid);
3706 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3707 // bones will be deleted by corpse/bones deleting thread shortly
3708 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3710 // remove from guild
3711 uint32 guildId = GetGuildIdFromDB(playerguid);
3712 if(guildId != 0)
3714 Guild* guild = objmgr.GetGuildById(guildId);
3715 if(guild)
3716 guild->DelMember(guid);
3719 // remove from arena teams
3720 LeaveAllArenaTeams(playerguid);
3722 // the player was uninvited already on logout so just remove from group
3723 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3724 if(resultGroup)
3726 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3727 delete resultGroup;
3728 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3729 if(group)
3731 RemoveFromGroup(group, playerguid);
3735 // remove signs from petitions (also remove petitions if owner);
3736 RemovePetitionsAndSigns(playerguid, 10);
3738 // return back all mails with COD and Item 0 1 2 3 4 5 6
3739 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);
3740 if(resultMail)
3744 Field *fields = resultMail->Fetch();
3746 uint32 mail_id = fields[0].GetUInt32();
3747 uint16 mailTemplateId= fields[1].GetUInt16();
3748 uint32 sender = fields[2].GetUInt32();
3749 std::string subject = fields[3].GetCppString();
3750 uint32 itemTextId = fields[4].GetUInt32();
3751 uint32 money = fields[5].GetUInt32();
3752 bool has_items = fields[6].GetBool();
3754 //we can return mail now
3755 //so firstly delete the old one
3756 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3758 MailItemsInfo mi;
3759 if(has_items)
3761 // data needs to be at first place for Item::LoadFromDB
3762 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);
3763 if(resultItems)
3767 Field *fields2 = resultItems->Fetch();
3769 uint32 item_guidlow = fields2[1].GetUInt32();
3770 uint32 item_template = fields2[2].GetUInt32();
3772 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3773 if(!itemProto)
3775 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3776 continue;
3779 Item *pItem = NewItemOrBag(itemProto);
3780 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3782 pItem->FSetState(ITEM_REMOVED);
3783 pItem->SaveToDB(); // it also deletes item object !
3784 continue;
3787 mi.AddItem(item_guidlow, item_template, pItem);
3789 while (resultItems->NextRow());
3791 delete resultItems;
3795 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3797 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3799 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3801 while (resultMail->NextRow());
3803 delete resultMail;
3806 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3807 // Get guids of character's pets, will deleted in transaction
3808 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3810 // NOW we can finally clear other DB data related to character
3811 CharacterDatabase.BeginTransaction();
3812 if (resultPets)
3816 Field *fields3 = resultPets->Fetch();
3817 uint32 petguidlow = fields3[0].GetUInt32();
3818 Pet::DeleteFromDB(petguidlow);
3819 } while (resultPets->NextRow());
3820 delete resultPets;
3823 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3824 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3825 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3826 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3827 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3828 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3829 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3830 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3831 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3832 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3833 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3834 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3835 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3836 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3837 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3838 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3839 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3840 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3841 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3842 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3843 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3844 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3845 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid);
3846 CharacterDatabase.CommitTransaction();
3848 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3849 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3852 void Player::SetMovement(PlayerMovementType pType)
3854 WorldPacket data;
3855 switch(pType)
3857 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3858 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3859 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3860 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3861 default:
3862 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3863 return;
3865 data.append(GetPackGUID());
3866 data << uint32(0);
3867 GetSession()->SendPacket( &data );
3870 /* Preconditions:
3871 - a resurrectable corpse must not be loaded for the player (only bones)
3872 - the player must be in world
3874 void Player::BuildPlayerRepop()
3876 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3877 data.append(GetPackGUID());
3878 GetSession()->SendPacket(&data);
3880 if(getRace() == RACE_NIGHTELF)
3881 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)
3882 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3884 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3885 // there must be SMSG.STOP_MIRROR_TIMER
3886 // there we must send 888 opcode
3888 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3889 if(GetCorpse())
3891 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3892 assert(false);
3895 // create a corpse and place it at the player's location
3896 CreateCorpse();
3897 Corpse *corpse = GetCorpse();
3898 if(!corpse)
3900 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3901 return;
3903 GetMap()->Add(corpse);
3905 // convert player body to ghost
3906 SetHealth( 1 );
3908 SetMovement(MOVE_WATER_WALK);
3909 if(!GetSession()->isLogingOut())
3910 SetMovement(MOVE_UNROOT);
3912 // BG - remove insignia related
3913 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3915 SendCorpseReclaimDelay();
3917 // to prevent cheating
3918 corpse->ResetGhostTime();
3920 StopMirrorTimers(); //disable timers(bars)
3922 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3924 // set and clear other
3925 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
3928 void Player::SendDelayResponse(const uint32 ml_seconds)
3930 //FIXME: is this delay time arg really need? 50msec by default in code
3931 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3932 data << (uint32)time(NULL);
3933 data << (uint32)0;
3934 GetSession()->SendPacket( &data );
3937 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
3939 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3940 data << uint32(-1);
3941 data << float(0);
3942 data << float(0);
3943 data << float(0);
3944 GetSession()->SendPacket(&data);
3946 // speed change, land walk
3948 // remove death flag + set aura
3949 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3950 if(getRace() == RACE_NIGHTELF)
3951 RemoveAurasDueToSpell(20584); // speed bonuses
3952 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3954 setDeathState(ALIVE);
3956 SetMovement(MOVE_LAND_WALK);
3957 SetMovement(MOVE_UNROOT);
3959 m_deathTimer = 0;
3961 // set health/powers (0- will be set in caller)
3962 if(restore_percent>0.0f)
3964 SetHealth(uint32(GetMaxHealth()*restore_percent));
3965 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3966 SetPower(POWER_RAGE, 0);
3967 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3970 // trigger update zone for alive state zone updates
3971 uint32 newzone, newarea;
3972 GetZoneAndAreaId(newzone,newarea);
3973 UpdateZone(newzone,newarea);
3975 // update visibility
3976 ObjectAccessor::UpdateVisibilityForPlayer(this);
3978 if(!applySickness)
3979 return;
3981 //Characters from level 1-10 are not affected by resurrection sickness.
3982 //Characters from level 11-19 will suffer from one minute of sickness
3983 //for each level they are above 10.
3984 //Characters level 20 and up suffer from ten minutes of sickness.
3985 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3987 if(int32(getLevel()) >= startLevel)
3989 // set resurrection sickness
3990 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
3992 // not full duration
3993 if(int32(getLevel()) < startLevel+9)
3995 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
3997 for(int i =0; i < 3; ++i)
3999 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
4001 Aur->SetAuraDuration(delta*IN_MILISECONDS);
4002 Aur->SendAuraUpdate(false);
4009 void Player::KillPlayer()
4011 SetMovement(MOVE_ROOT);
4013 StopMirrorTimers(); //disable timers(bars)
4015 setDeathState(CORPSE);
4016 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4018 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
4019 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
4021 // 6 minutes until repop at graveyard
4022 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
4024 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4026 // don't create corpse at this moment, player might be falling
4028 // update visibility
4029 ObjectAccessor::UpdateObjectVisibility(this);
4032 void Player::CreateCorpse()
4034 // prevent existence 2 corpse for player
4035 SpawnCorpseBones();
4037 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
4039 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
4040 SetPvPDeath(false);
4042 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
4044 delete corpse;
4045 return;
4048 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
4049 _pb = GetUInt32Value(PLAYER_BYTES);
4050 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
4052 uint8 race = (uint8)(_uf);
4053 uint8 skin = (uint8)(_pb);
4054 uint8 face = (uint8)(_pb >> 8);
4055 uint8 hairstyle = (uint8)(_pb >> 16);
4056 uint8 haircolor = (uint8)(_pb >> 24);
4057 uint8 facialhair = (uint8)(_pb2);
4059 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
4060 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
4062 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
4063 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
4065 uint32 flags = CORPSE_FLAG_UNK2;
4066 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
4067 flags |= CORPSE_FLAG_HIDE_HELM;
4068 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
4069 flags |= CORPSE_FLAG_HIDE_CLOAK;
4070 if(InBattleGround() && !InArena())
4071 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
4072 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4074 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4076 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4078 uint32 iDisplayID;
4079 uint16 iIventoryType;
4080 uint32 _cfi;
4081 for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
4083 if(m_items[i])
4085 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4086 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
4088 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
4089 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
4093 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4094 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4095 assert(entry);
4096 if(entry->map_type != MAP_BATTLEGROUND)
4097 corpse->SaveToDB();
4099 // register for player, but not show
4100 ObjectAccessor::Instance().AddCorpse(corpse);
4103 void Player::SpawnCorpseBones()
4105 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4106 SaveToDB(); // prevent loading as ghost without corpse
4109 Corpse* Player::GetCorpse() const
4111 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4114 void Player::DurabilityLossAll(double percent, bool inventory)
4116 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4117 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4118 DurabilityLoss(pItem,percent);
4120 if(inventory)
4122 // bags not have durability
4123 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4125 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4126 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4127 DurabilityLoss(pItem,percent);
4129 // keys not have durability
4130 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4132 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4133 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4134 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4135 if(Item* pItem = GetItemByPos( i, j ))
4136 DurabilityLoss(pItem,percent);
4140 void Player::DurabilityLoss(Item* item, double percent)
4142 if(!item )
4143 return;
4145 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4147 if(!pMaxDurability)
4148 return;
4150 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4152 if(pDurabilityLoss < 1 )
4153 pDurabilityLoss = 1;
4155 DurabilityPointsLoss(item,pDurabilityLoss);
4158 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4160 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4161 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4162 DurabilityPointsLoss(pItem,points);
4164 if(inventory)
4166 // bags not have durability
4167 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4169 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4170 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4171 DurabilityPointsLoss(pItem,points);
4173 // keys not have durability
4174 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4176 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4177 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4178 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4179 if(Item* pItem = GetItemByPos( i, j ))
4180 DurabilityPointsLoss(pItem,points);
4184 void Player::DurabilityPointsLoss(Item* item, int32 points)
4186 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4187 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4188 int32 pNewDurability = pOldDurability - points;
4190 if (pNewDurability < 0)
4191 pNewDurability = 0;
4192 else if (pNewDurability > pMaxDurability)
4193 pNewDurability = pMaxDurability;
4195 if (pOldDurability != pNewDurability)
4197 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4198 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4199 _ApplyItemMods(item,item->GetSlot(), false);
4201 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4203 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4204 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4205 _ApplyItemMods(item,item->GetSlot(), true);
4207 item->SetState(ITEM_CHANGED, this);
4211 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4213 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4214 DurabilityPointsLoss(pItem,1);
4217 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4219 uint32 TotalCost = 0;
4220 // equipped, backpack, bags itself
4221 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4222 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4224 // bank, buyback and keys not repaired
4226 // items in inventory bags
4227 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
4228 for(int i = 0; i < MAX_BAG_SIZE; ++i)
4229 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4230 return TotalCost;
4233 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4235 Item* item = GetItemByPos(pos);
4237 uint32 TotalCost = 0;
4238 if(!item)
4239 return TotalCost;
4241 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4242 if(!maxDurability)
4243 return TotalCost;
4245 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4247 if(cost)
4249 uint32 LostDurability = maxDurability - curDurability;
4250 if(LostDurability>0)
4252 ItemPrototype const *ditemProto = item->GetProto();
4254 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4255 if(!dcost)
4257 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4258 return TotalCost;
4261 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4262 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4263 if(!dQualitymodEntry)
4265 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4266 return TotalCost;
4269 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4270 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4272 costs = uint32(costs * discountMod);
4274 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4275 costs = 1;
4277 if (guildBank)
4279 if (GetGuildId()==0)
4281 DEBUG_LOG("You are not member of a guild");
4282 return TotalCost;
4285 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4286 if (!pGuild)
4287 return TotalCost;
4289 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4291 DEBUG_LOG("You do not have rights to withdraw for repairs");
4292 return TotalCost;
4295 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4297 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4298 return TotalCost;
4301 if (pGuild->GetGuildBankMoney() < costs)
4303 DEBUG_LOG("There is not enough money in bank");
4304 return TotalCost;
4307 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4308 TotalCost = costs;
4310 else if (GetMoney() < costs)
4312 DEBUG_LOG("You do not have enough money");
4313 return TotalCost;
4315 else
4316 ModifyMoney( -int32(costs) );
4320 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4321 item->SetState(ITEM_CHANGED, this);
4323 // reapply mods for total broken and repaired item if equipped
4324 if(IsEquipmentPos(pos) && !curDurability)
4325 _ApplyItemMods(item,pos & 255, true);
4326 return TotalCost;
4329 void Player::RepopAtGraveyard()
4331 // note: this can be called also when the player is alive
4332 // for example from WorldSession::HandleMovementOpcodes
4334 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4336 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4337 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4339 ResurrectPlayer(0.5f);
4340 SpawnCorpseBones();
4343 WorldSafeLocsEntry const *ClosestGrave = NULL;
4345 // Special handle for battleground maps
4346 if( BattleGround *bg = GetBattleGround() )
4347 ClosestGrave = bg->GetClosestGraveYard(this);
4348 else
4349 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4351 // stop countdown until repop
4352 m_deathTimer = 0;
4354 // if no grave found, stay at the current location
4355 // and don't show spirit healer location
4356 if(ClosestGrave)
4358 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4359 if(isDead()) // not send if alive, because it used in TeleportTo()
4361 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4362 data << ClosestGrave->map_id;
4363 data << ClosestGrave->x;
4364 data << ClosestGrave->y;
4365 data << ClosestGrave->z;
4366 GetSession()->SendPacket(&data);
4371 void Player::JoinedChannel(Channel *c)
4373 m_channels.push_back(c);
4376 void Player::LeftChannel(Channel *c)
4378 m_channels.remove(c);
4381 void Player::CleanupChannels()
4383 while(!m_channels.empty())
4385 Channel* ch = *m_channels.begin();
4386 m_channels.erase(m_channels.begin()); // remove from player's channel list
4387 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4388 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4389 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4392 sLog.outDebug("Player: channels cleaned up!");
4395 void Player::UpdateLocalChannels(uint32 newZone )
4397 if(m_channels.empty())
4398 return;
4400 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4401 if(!current_zone)
4402 return;
4404 ChannelMgr* cMgr = channelMgr(GetTeam());
4405 if(!cMgr)
4406 return;
4408 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4410 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4412 next = i; ++next;
4414 // skip non built-in channels
4415 if(!(*i)->IsConstant())
4416 continue;
4418 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4419 if(!ch)
4420 continue;
4422 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4423 continue;
4425 // new channel
4426 char new_channel_name_buf[100];
4427 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4428 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4430 if((*i)!=new_channel)
4432 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4434 // leave old channel
4435 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4436 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4437 LeftChannel(*i); // remove from player's channel list
4438 cMgr->LeftChannel(name); // delete if empty
4441 sLog.outDebug("Player: channels cleaned up!");
4444 void Player::LeaveLFGChannel()
4446 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4448 if((*i)->IsLFG())
4450 (*i)->Leave(GetGUID());
4451 break;
4456 void Player::UpdateDefense()
4458 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4460 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4462 // update dependent from defense skill part
4463 UpdateDefenseBonusesMod();
4467 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4469 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4471 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4472 return;
4475 float val = 1.0f;
4477 switch(modType)
4479 case FLAT_MOD:
4480 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4481 break;
4482 case PCT_MOD:
4483 if(amount <= -100.0f)
4484 amount = -200.0f;
4486 val = (100.0f + amount) / 100.0f;
4487 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4488 break;
4491 if(!CanModifyStats())
4492 return;
4494 switch(modGroup)
4496 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4497 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4498 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4499 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4500 default: break;
4504 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4506 if(modGroup >= BASEMOD_END || modType > MOD_END)
4508 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4509 return 0.0f;
4512 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4513 return 0.0f;
4515 return m_auraBaseMod[modGroup][modType];
4518 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4520 if(modGroup >= BASEMOD_END)
4522 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4523 return 0.0f;
4526 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4527 return 0.0f;
4529 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4532 uint32 Player::GetShieldBlockValue() const
4534 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4536 value = (value < 0) ? 0 : value;
4538 return uint32(value);
4541 float Player::GetMeleeCritFromAgility()
4543 uint32 level = getLevel();
4544 uint32 pclass = getClass();
4546 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4548 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4549 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4550 if (critBase==NULL || critRatio==NULL)
4551 return 0.0f;
4553 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4554 return crit*100.0f;
4557 float Player::GetDodgeFromAgility()
4559 // Table for base dodge values
4560 float dodge_base[MAX_CLASSES] = {
4561 0.0075f, // Warrior
4562 0.00652f, // Paladin
4563 -0.0545f, // Hunter
4564 -0.0059f, // Rogue
4565 0.03183f, // Priest
4566 0.0114f, // DK
4567 0.0167f, // Shaman
4568 0.034575f, // Mage
4569 0.02011f, // Warlock
4570 0.0f, // ??
4571 -0.0187f // Druid
4573 // Crit/agility to dodge/agility coefficient multipliers
4574 float crit_to_dodge[MAX_CLASSES] = {
4575 1.1f, // Warrior
4576 1.0f, // Paladin
4577 1.6f, // Hunter
4578 2.0f, // Rogue
4579 1.0f, // Priest
4580 1.0f, // DK?
4581 1.0f, // Shaman
4582 1.0f, // Mage
4583 1.0f, // Warlock
4584 0.0f, // ??
4585 1.7f // Druid
4588 uint32 level = getLevel();
4589 uint32 pclass = getClass();
4591 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4593 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4594 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4595 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4596 return 0.0f;
4598 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4599 return dodge*100.0f;
4602 float Player::GetSpellCritFromIntellect()
4604 uint32 level = getLevel();
4605 uint32 pclass = getClass();
4607 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4609 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4610 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4611 if (critBase==NULL || critRatio==NULL)
4612 return 0.0f;
4614 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4615 return crit*100.0f;
4618 float Player::GetRatingCoefficient(CombatRating cr) const
4620 uint32 level = getLevel();
4622 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4624 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4625 if (Rating == NULL)
4626 return 1.0f; // By default use minimum coefficient (not must be called)
4628 return Rating->ratio;
4631 float Player::GetRatingBonusValue(CombatRating cr) const
4633 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4636 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4638 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.2f;
4639 if (melee>33.0f) melee = 33.0f;
4640 return uint32 (melee * damage /100.0f);
4643 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4645 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.2f;
4646 if (ranged>33.0f) ranged=33.0f;
4647 return uint32 (ranged * damage /100.0f);
4650 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4652 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.2f;
4653 // In wow script resilience limited to 33%
4654 if (spell>33.0f)
4655 spell = 33.0f;
4656 return uint32 (spell * damage / 100.0f);
4659 uint32 Player::GetDotDamageReduction(uint32 damage) const
4661 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4662 // Dot resilience not limited (limit it by 100%)
4663 if (spellDot > 100.0f)
4664 spellDot = 100.0f;
4665 return uint32 (spellDot * damage / 100.0f);
4668 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4670 switch (attType)
4672 case BASE_ATTACK:
4673 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4674 case OFF_ATTACK:
4675 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4676 default:
4677 break;
4679 return 0.0f;
4682 float Player::OCTRegenHPPerSpirit()
4684 uint32 level = getLevel();
4685 uint32 pclass = getClass();
4687 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4689 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4690 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4691 if (baseRatio==NULL || moreRatio==NULL)
4692 return 0.0f;
4694 // Formula from PaperDollFrame script
4695 float spirit = GetStat(STAT_SPIRIT);
4696 float baseSpirit = spirit;
4697 if (baseSpirit>50) baseSpirit = 50;
4698 float moreSpirit = spirit - baseSpirit;
4699 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4700 return regen;
4703 float Player::OCTRegenMPPerSpirit()
4705 uint32 level = getLevel();
4706 uint32 pclass = getClass();
4708 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4710 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4711 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4712 if (moreRatio==NULL)
4713 return 0.0f;
4715 // Formula get from PaperDollFrame script
4716 float spirit = GetStat(STAT_SPIRIT);
4717 float regen = spirit * moreRatio->ratio;
4718 return regen;
4721 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4723 m_baseRatingValue[cr]+=(apply ? value : -value);
4725 int32 amount = uint32(m_baseRatingValue[cr]);
4726 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4727 // stat used stored in miscValueB for this aura
4728 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4729 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4730 if ((*i)->GetMiscValue() & (1<<cr))
4731 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4732 if (amount < 0)
4733 amount = 0;
4734 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4736 float RatingCoeffecient = GetRatingCoefficient(cr);
4737 float RatingChange = 0.0f;
4739 bool affectStats = CanModifyStats();
4741 switch (cr)
4743 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4744 case CR_DEFENSE_SKILL:
4745 UpdateDefenseBonusesMod();
4746 break;
4747 case CR_DODGE:
4748 UpdateDodgePercentage();
4749 break;
4750 case CR_PARRY:
4751 UpdateParryPercentage();
4752 break;
4753 case CR_BLOCK:
4754 UpdateBlockPercentage();
4755 break;
4756 case CR_HIT_MELEE:
4757 UpdateMeleeHitChances();
4758 break;
4759 case CR_HIT_RANGED:
4760 UpdateRangedHitChances();
4761 break;
4762 case CR_HIT_SPELL:
4763 UpdateSpellHitChances();
4764 break;
4765 case CR_CRIT_MELEE:
4766 if(affectStats)
4768 UpdateCritPercentage(BASE_ATTACK);
4769 UpdateCritPercentage(OFF_ATTACK);
4771 break;
4772 case CR_CRIT_RANGED:
4773 if(affectStats)
4774 UpdateCritPercentage(RANGED_ATTACK);
4775 break;
4776 case CR_CRIT_SPELL:
4777 if(affectStats)
4778 UpdateAllSpellCritChances();
4779 break;
4780 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4781 case CR_HIT_TAKEN_RANGED:
4782 break;
4783 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4784 break;
4785 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4786 case CR_CRIT_TAKEN_RANGED:
4787 break;
4788 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4789 break;
4790 case CR_HASTE_MELEE:
4791 RatingChange = value / RatingCoeffecient;
4792 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4793 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4794 break;
4795 case CR_HASTE_RANGED:
4796 RatingChange = value / RatingCoeffecient;
4797 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4798 break;
4799 case CR_HASTE_SPELL:
4800 RatingChange = value / RatingCoeffecient;
4801 ApplyCastTimePercentMod(RatingChange,apply);
4802 break;
4803 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4804 case CR_WEAPON_SKILL_OFFHAND:
4805 case CR_WEAPON_SKILL_RANGED:
4806 break;
4807 case CR_EXPERTISE:
4808 if(affectStats)
4810 UpdateExpertise(BASE_ATTACK);
4811 UpdateExpertise(OFF_ATTACK);
4813 break;
4814 case CR_ARMOR_PENETRATION:
4815 break;
4819 void Player::SetRegularAttackTime()
4821 for(int i = 0; i < MAX_ATTACK; ++i)
4823 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4824 if(tmpitem && !tmpitem->IsBroken())
4826 ItemPrototype const *proto = tmpitem->GetProto();
4827 if(proto->Delay)
4828 SetAttackTime(WeaponAttackType(i), proto->Delay);
4829 else
4830 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4835 //skill+step, checking for max value
4836 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4838 if(!skill_id)
4839 return false;
4841 uint16 i=0;
4842 for (; i < PLAYER_MAX_SKILLS; ++i)
4843 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4844 break;
4846 if(i>=PLAYER_MAX_SKILLS)
4847 return false;
4849 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4850 uint32 value = SKILL_VALUE(data);
4851 uint32 max = SKILL_MAX(data);
4853 if ((!max) || (!value) || (value >= max))
4854 return false;
4856 if (value*512 < max*urand(0,512))
4858 uint32 new_value = value+step;
4859 if(new_value > max)
4860 new_value = max;
4862 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4863 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
4864 return true;
4867 return false;
4870 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4872 if ( SkillValue >= GrayLevel )
4873 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4874 if ( SkillValue >= GreenLevel )
4875 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4876 if ( SkillValue >= YellowLevel )
4877 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4878 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4881 bool Player::UpdateCraftSkill(uint32 spellid)
4883 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4885 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4886 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4888 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4890 if(_spell_idx->second->skillId)
4892 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4894 // Alchemy Discoveries here
4895 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4896 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4898 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4899 learnSpell(discoveredSpell,false);
4902 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4904 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4905 _spell_idx->second->max_value,
4906 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4907 _spell_idx->second->min_value),
4908 craft_skill_gain);
4911 return false;
4914 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4916 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4918 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4920 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4921 switch (SkillId)
4923 case SKILL_HERBALISM:
4924 case SKILL_LOCKPICKING:
4925 case SKILL_JEWELCRAFTING:
4926 case SKILL_INSCRIPTION:
4927 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4928 case SKILL_SKINNING:
4929 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4930 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4931 else
4932 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4933 case SKILL_MINING:
4934 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4935 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4936 else
4937 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4939 return false;
4942 bool Player::UpdateFishingSkill()
4944 sLog.outDebug("UpdateFishingSkill");
4946 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4948 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4950 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4952 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4955 // levels sync. with spell requirement for skill levels to learn
4956 // bonus abilities in sSkillLineAbilityStore
4957 // Used only to avoid scan DBC at each skill grow
4958 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
4960 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4962 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4963 if ( !SkillId )
4964 return false;
4966 if(Chance <= 0) // speedup in 0 chance case
4968 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4969 return false;
4972 uint16 i=0;
4973 for (; i < PLAYER_MAX_SKILLS; ++i)
4974 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4975 if ( i >= PLAYER_MAX_SKILLS )
4976 return false;
4978 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4979 uint16 SkillValue = SKILL_VALUE(data);
4980 uint16 MaxValue = SKILL_MAX(data);
4982 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4983 return false;
4985 int32 Roll = irand(1,1000);
4987 if ( Roll <= Chance )
4989 uint32 new_value = SkillValue+step;
4990 if(new_value > MaxValue)
4991 new_value = MaxValue;
4993 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
4994 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
4996 if((SkillValue < *bsl && new_value >= *bsl))
4998 learnSkillRewardedSpells( SkillId, new_value);
4999 break;
5002 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
5003 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
5004 return true;
5007 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5008 return false;
5011 void Player::UpdateWeaponSkill (WeaponAttackType attType)
5013 // no skill gain in pvp
5014 Unit *pVictim = getVictim();
5015 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
5016 return;
5018 if(IsInFeralForm())
5019 return; // always maximized SKILL_FERAL_COMBAT in fact
5021 if(m_form == FORM_TREE)
5022 return; // use weapon but not skill up
5024 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
5026 switch(attType)
5028 case BASE_ATTACK:
5030 Item *tmpitem = GetWeaponForAttack(attType,true);
5032 if (!tmpitem)
5033 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
5034 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
5035 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5036 break;
5038 case OFF_ATTACK:
5039 case RANGED_ATTACK:
5041 Item *tmpitem = GetWeaponForAttack(attType,true);
5042 if (tmpitem)
5043 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5044 break;
5047 UpdateAllCritPercentages();
5050 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
5052 uint32 plevel = getLevel(); // if defense than pVictim == attacker
5053 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
5054 uint32 moblevel = pVictim->getLevelForTarget(this);
5055 if(moblevel < greylevel)
5056 return;
5058 if (moblevel > plevel + 5)
5059 moblevel = plevel + 5;
5061 uint32 lvldif = moblevel - greylevel;
5062 if(lvldif < 3)
5063 lvldif = 3;
5065 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
5066 if(skilldif <= 0)
5067 return;
5069 float chance = float(3 * lvldif * skilldif) / plevel;
5070 if(!defence)
5072 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5073 chance *= 0.1f * GetStat(STAT_INTELLECT);
5076 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5078 if(roll_chance_f(chance))
5080 if(defence)
5081 UpdateDefense();
5082 else
5083 UpdateWeaponSkill(attType);
5085 else
5086 return;
5089 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5091 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5092 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
5094 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5095 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5096 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5098 if(talent) // permanent bonus stored in high part
5099 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5100 else // temporary/item bonus stored in low part
5101 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5102 return;
5106 void Player::UpdateSkillsForLevel()
5108 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5109 uint32 maxSkill = GetMaxSkillValueForLevel();
5111 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5113 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5114 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5116 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5118 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5119 if(!pSkill)
5120 continue;
5122 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5123 continue;
5125 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5126 uint32 max = SKILL_MAX(data);
5127 uint32 val = SKILL_VALUE(data);
5129 /// update only level dependent max skill values
5130 if(max!=1)
5132 /// miximize skill always
5133 if(alwaysMaxSkill)
5134 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
5135 /// update max skill value if current max skill not maximized
5136 else if(max != maxconfskill)
5137 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
5142 void Player::UpdateSkillsToMaxSkillsForLevel()
5144 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5145 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5147 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5148 if( IsProfessionOrRidingSkill(pskill))
5149 continue;
5150 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5152 uint32 max = SKILL_MAX(data);
5154 if(max > 1)
5155 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
5157 if(pskill == SKILL_DEFENSE)
5158 UpdateDefenseBonusesMod();
5162 // This functions sets a skill line value (and adds if doesn't exist yet)
5163 // To "remove" a skill line, set it's values to zero
5164 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5166 if(!id)
5167 return;
5169 uint16 i=0;
5170 for (; i < PLAYER_MAX_SKILLS; ++i)
5171 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
5173 if(i<PLAYER_MAX_SKILLS) //has skill
5175 if(currVal)
5177 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5178 learnSkillRewardedSpells(id, currVal);
5179 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5180 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5182 else //remove
5184 // clear skill fields
5185 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
5186 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
5187 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5189 // remove all spells that related to this skill
5190 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5191 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5192 if (pAbility->skillId==id)
5193 removeSpell(spellmgr.GetFirstSpellInChain(pAbility->spellId));
5196 else if(currVal) //add
5198 for (i=0; i < PLAYER_MAX_SKILLS; ++i)
5199 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5201 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5202 if(!pSkill)
5204 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5205 return;
5207 // enable unlearn button for primary professions only
5208 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5209 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5210 else
5211 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5212 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5213 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5214 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5216 // apply skill bonuses
5217 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5219 // temporary bonuses
5220 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5221 for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
5222 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5223 (*j)->ApplyModifier(true);
5225 // permanent bonuses
5226 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5227 for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
5228 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5229 (*j)->ApplyModifier(true);
5231 // Learn all spells for skill
5232 learnSkillRewardedSpells(id, currVal);
5233 return;
5238 bool Player::HasSkill(uint32 skill) const
5240 if(!skill)return false;
5241 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5243 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5245 return true;
5248 return false;
5251 uint16 Player::GetSkillValue(uint32 skill) const
5253 if(!skill)
5254 return 0;
5256 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5258 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5260 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5262 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5263 result += SKILL_TEMP_BONUS(bonus);
5264 result += SKILL_PERM_BONUS(bonus);
5265 return result < 0 ? 0 : result;
5268 return 0;
5271 uint16 Player::GetMaxSkillValue(uint32 skill) const
5273 if(!skill)return 0;
5274 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5276 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5278 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5280 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5281 result += SKILL_TEMP_BONUS(bonus);
5282 result += SKILL_PERM_BONUS(bonus);
5283 return result < 0 ? 0 : result;
5286 return 0;
5289 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5291 if(!skill)return 0;
5292 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5294 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5296 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5299 return 0;
5302 uint16 Player::GetBaseSkillValue(uint32 skill) const
5304 if(!skill)return 0;
5305 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5307 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5309 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5310 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5311 return result < 0 ? 0 : result;
5314 return 0;
5317 uint16 Player::GetPureSkillValue(uint32 skill) const
5319 if(!skill)return 0;
5320 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5322 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5324 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5327 return 0;
5330 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5332 if(!skill)
5333 return 0;
5335 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5337 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5339 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5343 return 0;
5346 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5348 if(!skill)
5349 return 0;
5351 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5353 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5355 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5359 return 0;
5362 void Player::SendInitialActionButtons() const
5364 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5366 WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
5367 data << uint8(0); // can be 0, 1, 2
5368 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5370 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5371 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5373 data << uint16(itr->second.action);
5374 data << uint8(itr->second.misc);
5375 data << uint8(itr->second.type);
5377 else
5379 data << uint32(0);
5383 GetSession()->SendPacket( &data );
5384 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5387 bool Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5389 if(button >= MAX_ACTION_BUTTONS)
5391 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5392 return false;
5395 // check cheating with adding non-known spells to action bar
5396 if(type==ACTION_BUTTON_SPELL)
5398 if(!sSpellStore.LookupEntry(action))
5400 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5401 return false;
5404 if(!HasSpell(action))
5406 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5407 return false;
5411 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5413 if (buttonItr==m_actionButtons.end())
5414 { // just add new button
5415 m_actionButtons[button] = ActionButton(action,type,misc);
5417 else
5418 { // change state of current button
5419 ActionButtonUpdateState uState = buttonItr->second.uState;
5420 buttonItr->second = ActionButton(action,type,misc);
5421 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5424 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5425 return true;
5428 void Player::removeActionButton(uint8 button)
5430 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5431 if (buttonItr==m_actionButtons.end())
5432 return;
5434 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5435 m_actionButtons.erase(buttonItr); // new and not saved
5436 else
5437 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5439 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5442 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5444 // prevent crash when a bad coord is sent by the client
5445 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5447 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5448 return false;
5451 Map *m = GetMap();
5453 const float old_x = GetPositionX();
5454 const float old_y = GetPositionY();
5455 const float old_z = GetPositionZ();
5456 const float old_r = GetOrientation();
5458 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5460 if (teleport || old_x != x || old_y != y || old_z != z)
5461 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5462 else
5463 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5465 // move and update visible state if need
5466 m->PlayerRelocation(this, x, y, z, orientation);
5468 // reread after Map::Relocation
5469 m = GetMap();
5470 x = GetPositionX();
5471 y = GetPositionY();
5472 z = GetPositionZ();
5474 // group update
5475 if(GetGroup() && (old_x != x || old_y != y))
5476 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5479 // code block for underwater state update
5480 UpdateUnderwaterState(m, x, y, z);
5482 CheckExploreSystem();
5484 return true;
5487 void Player::SaveRecallPosition()
5489 m_recallMap = GetMapId();
5490 m_recallX = GetPositionX();
5491 m_recallY = GetPositionY();
5492 m_recallZ = GetPositionZ();
5493 m_recallO = GetOrientation();
5496 void Player::SendMessageToSet(WorldPacket *data, bool self)
5498 GetMap()->MessageBroadcast(this, data, self);
5501 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5503 GetMap()->MessageDistBroadcast(this, data, dist, self);
5506 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5508 GetMap()->MessageDistBroadcast(this, data, dist, self,own_team_only);
5511 void Player::SendDirectMessage(WorldPacket *data)
5513 GetSession()->SendPacket(data);
5516 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5518 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5519 data << uint32(CinematicSequenceId);
5520 SendDirectMessage(&data);
5523 void Player::SendMovieStart(uint32 MovieId)
5525 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5526 data << uint32(MovieId);
5527 SendDirectMessage(&data);
5530 void Player::CheckExploreSystem()
5532 if (!isAlive())
5533 return;
5535 if (isInFlight())
5536 return;
5538 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5539 if(areaFlag==0xffff)
5540 return;
5541 int offset = areaFlag / 32;
5543 if(offset >= 128)
5545 sLog.outError("Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < 128 ).",areaFlag,GetPositionX(),GetPositionY(),offset,offset);
5546 return;
5549 uint32 val = (uint32)(1 << (areaFlag % 32));
5550 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5552 if( !(currFields & val) )
5554 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5556 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5558 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5559 if(!p)
5561 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5563 else if(p->area_level > 0)
5565 uint32 area = p->ID;
5566 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5568 SendExplorationExperience(area,0);
5570 else
5572 int32 diff = int32(getLevel()) - p->area_level;
5573 uint32 XP = 0;
5574 if (diff < -5)
5576 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5578 else if (diff > 5)
5580 int32 exploration_percent = (100-((diff-5)*5));
5581 if (exploration_percent > 100)
5582 exploration_percent = 100;
5583 else if (exploration_percent < 0)
5584 exploration_percent = 0;
5586 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5588 else
5590 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5593 GiveXP( XP, NULL );
5594 SendExplorationExperience(area,XP);
5596 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5601 uint32 Player::TeamForRace(uint8 race)
5603 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5604 if(!rEntry)
5606 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5607 return ALLIANCE;
5610 switch(rEntry->TeamID)
5612 case 7: return ALLIANCE;
5613 case 1: return HORDE;
5616 sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5617 return ALLIANCE;
5620 uint32 Player::getFactionForRace(uint8 race)
5622 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5623 if(!rEntry)
5625 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5626 return 0;
5629 return rEntry->FactionID;
5632 void Player::setFactionForRace(uint8 race)
5634 m_team = TeamForRace(race);
5635 setFaction( getFactionForRace(race) );
5638 ReputationRank Player::GetReputationRank(uint32 faction) const
5640 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
5641 return GetReputationMgr().GetRank(factionEntry);
5644 //Calculate total reputation percent player gain with quest/creature level
5645 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5647 float percent = 100.0f;
5649 float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL);
5651 if(rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
5652 percent *= rate;
5654 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5656 percent += rep > 0 ? repMod : -repMod;
5658 if(percent <= 0.0f)
5659 return 0;
5661 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5664 //Calculates how many reputation points player gains in victim's enemy factions
5665 void Player::RewardReputation(Unit *pVictim, float rate)
5667 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5668 return;
5670 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5672 if(!Rep)
5673 return;
5675 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5677 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
5678 donerep1 = int32(donerep1*rate);
5679 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5680 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
5681 if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5682 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
5684 // Wiki: Team factions value divided by 2
5685 if (factionEntry1 && Rep->is_teamaward1)
5687 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5688 if(team1_factionEntry)
5689 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
5693 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5695 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
5696 donerep2 = int32(donerep2*rate);
5697 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5698 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
5699 if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5700 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
5702 // Wiki: Team factions value divided by 2
5703 if (factionEntry2 && Rep->is_teamaward2)
5705 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5706 if(team2_factionEntry)
5707 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
5712 //Calculate how many reputation points player gain with the quest
5713 void Player::RewardReputation(Quest const *pQuest)
5715 // quest reputation reward/loss
5716 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5718 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5720 int32 rep = CalculateReputationGain(GetQuestLevel(pQuest),pQuest->RewRepValue[i],true);
5721 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5722 if(factionEntry)
5723 GetReputationMgr().ModifyReputation(factionEntry, rep);
5727 // TODO: implement reputation spillover
5730 void Player::UpdateArenaFields(void)
5732 /* arena calcs go here */
5735 void Player::UpdateHonorFields()
5737 /// called when rewarding honor and at each save
5738 uint64 now = time(NULL);
5739 uint64 today = uint64(time(NULL) / DAY) * DAY;
5741 if(m_lastHonorUpdateTime < today)
5743 uint64 yesterday = today - DAY;
5745 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5747 // update yesterday's contribution
5748 if(m_lastHonorUpdateTime >= yesterday )
5750 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5752 // this is the first update today, reset today's contribution
5753 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5754 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5756 else
5758 // no honor/kills yesterday or today, reset
5759 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5760 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5764 m_lastHonorUpdateTime = now;
5767 ///Calculate the amount of honor gained based on the victim
5768 ///and the size of the group for which the honor is divided
5769 ///An exact honor value can also be given (overriding the calcs)
5770 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5772 // do not reward honor in arenas, but enable onkill spellproc
5773 if(InArena())
5775 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
5776 return false;
5778 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
5779 return false;
5781 return true;
5784 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5785 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5786 return false;
5788 uint64 victim_guid = 0;
5789 uint32 victim_rank = 0;
5791 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5792 UpdateHonorFields();
5794 if(honor <= 0)
5796 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5797 return false;
5799 victim_guid = uVictim->GetGUID();
5801 if( uVictim->GetTypeId() == TYPEID_PLAYER )
5803 Player *pVictim = (Player *)uVictim;
5805 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
5806 return false;
5808 float f = 1; //need for total kills (?? need more info)
5809 uint32 k_grey = 0;
5810 uint32 k_level = getLevel();
5811 uint32 v_level = pVictim->getLevel();
5814 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5815 // [0] Just name
5816 // [1..14] Alliance honor titles and player name
5817 // [15..28] Horde honor titles and player name
5818 // [29..38] Other title and player name
5819 // [39+] Nothing
5820 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
5821 // Get Killer titles, CharTitlesEntry::bit_index
5822 // Ranks:
5823 // title[1..14] -> rank[5..18]
5824 // title[15..28] -> rank[5..18]
5825 // title[other] -> 0
5826 if (victim_title == 0)
5827 victim_guid = 0; // Don't show HK: <rank> message, only log.
5828 else if (victim_title < 15)
5829 victim_rank = victim_title + 4;
5830 else if (victim_title < 29)
5831 victim_rank = victim_title - 14 + 4;
5832 else
5833 victim_guid = 0; // Don't show HK: <rank> message, only log.
5836 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
5838 if(v_level<=k_grey)
5839 return false;
5841 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
5843 int32 v_rank =1; //need more info
5845 honor = ((f * diff_level * (190 + v_rank*10))/6);
5846 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
5848 // count the number of playerkills in one day
5849 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
5850 // and those in a lifetime
5851 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
5852 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
5854 else
5856 Creature *cVictim = (Creature *)uVictim;
5858 if (!cVictim->isRacialLeader())
5859 return false;
5861 honor = 100; // ??? need more info
5862 victim_rank = 19; // HK: Leader
5866 if (uVictim != NULL)
5868 honor *= sWorld.getRate(RATE_HONOR);
5870 if(groupsize > 1)
5871 honor /= groupsize;
5873 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5876 // honor - for show honor points in log
5877 // victim_guid - for show victim name in log
5878 // victim_rank [1..4] HK: <dishonored rank>
5879 // victim_rank [5..19] HK: <alliance\horde rank>
5880 // victim_rank [0,20+] HK: <>
5881 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
5882 data << (uint32) honor;
5883 data << (uint64) victim_guid;
5884 data << (uint32) victim_rank;
5886 GetSession()->SendPacket(&data);
5888 // add honor points
5889 ModifyHonorPoints(int32(honor));
5891 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
5892 return true;
5895 void Player::ModifyHonorPoints( int32 value )
5897 if(value < 0)
5899 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
5900 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
5901 else
5902 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
5904 else
5905 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
5908 void Player::ModifyArenaPoints( int32 value )
5910 if(value < 0)
5912 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
5913 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
5914 else
5915 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
5917 else
5918 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
5921 uint32 Player::GetGuildIdFromDB(uint64 guid)
5923 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
5924 if(!result)
5925 return 0;
5927 uint32 id = result->Fetch()[0].GetUInt32();
5928 delete result;
5929 return id;
5932 uint32 Player::GetRankFromDB(uint64 guid)
5934 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
5935 if( result )
5937 uint32 v = result->Fetch()[0].GetUInt32();
5938 delete result;
5939 return v;
5941 else
5942 return 0;
5945 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
5947 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);
5948 if(!result)
5949 return 0;
5951 uint32 id = (*result)[0].GetUInt32();
5952 delete result;
5953 return id;
5956 uint32 Player::GetZoneIdFromDB(uint64 guid)
5958 uint32 guidLow = GUID_LOPART(guid);
5959 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
5960 if (!result)
5961 return 0;
5962 Field* fields = result->Fetch();
5963 uint32 zone = fields[0].GetUInt32();
5964 delete result;
5966 if (!zone)
5968 // stored zone is zero, use generic and slow zone detection
5969 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
5970 if( !result )
5971 return 0;
5972 fields = result->Fetch();
5973 uint32 map = fields[0].GetUInt32();
5974 float posx = fields[1].GetFloat();
5975 float posy = fields[2].GetFloat();
5976 float posz = fields[3].GetFloat();
5977 delete result;
5979 zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
5981 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
5984 return zone;
5987 void Player::UpdateArea(uint32 newArea)
5989 // FFA_PVP flags are area and not zone id dependent
5990 // so apply them accordingly
5991 m_areaUpdateId = newArea;
5993 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
5995 if(area && (area->flags & AREA_FLAG_ARENA))
5997 if(!isGameMaster())
5998 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6000 else
6002 // remove ffa flag only if not ffapvp realm
6003 // removal in sanctuaries and capitals is handled in zone update
6004 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6005 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6008 UpdateAreaDependentAuras(newArea);
6011 void Player::UpdateZone(uint32 newZone, uint32 newArea)
6013 if(m_zoneUpdateId != newZone)
6014 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
6016 m_zoneUpdateId = newZone;
6017 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6019 // zone changed, so area changed as well, update it
6020 UpdateArea(newArea);
6022 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6023 if(!zone)
6024 return;
6026 if (sWorld.getConfig(CONFIG_WEATHER))
6028 Weather *wth = sWorld.FindWeather(zone->ID);
6029 if(wth)
6031 wth->SendWeatherUpdateToPlayer(this);
6033 else
6035 if(!sWorld.AddWeather(zone->ID))
6037 // send fine weather packet to remove old zone's weather
6038 Weather::SendFineWeatherUpdateToPlayer(this);
6043 pvpInfo.inHostileArea =
6044 GetTeam() == ALLIANCE && zone->team == AREATEAM_HORDE ||
6045 GetTeam() == HORDE && zone->team == AREATEAM_ALLY ||
6046 sWorld.IsPvPRealm() && zone->team == AREATEAM_NONE ||
6047 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6049 if(pvpInfo.inHostileArea) // in hostile area
6051 if(!IsPvP() || pvpInfo.endTimer != 0)
6052 UpdatePvP(true, true);
6054 else // in friendly area
6056 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6057 pvpInfo.endTimer = time(0); // start toggle-off
6060 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6062 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6063 if(sWorld.IsFFAPvPRealm())
6064 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6066 else
6068 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6071 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6073 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6074 SetRestType(REST_TYPE_IN_CITY);
6075 InnEnter(time(0),GetMapId(),0,0,0);
6077 if(sWorld.IsFFAPvPRealm())
6078 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6080 else // anywhere else
6082 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6084 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6086 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6088 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6089 SetRestType(REST_TYPE_NO);
6091 if(sWorld.IsFFAPvPRealm())
6092 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6095 else // not in tavern (leave city then)
6097 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6098 SetRestType(REST_TYPE_NO);
6100 // Set player to FFA PVP when not in rested environment.
6101 if(sWorld.IsFFAPvPRealm())
6102 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6107 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6108 // if player resurrected at teleport this will be applied in resurrect code
6109 if(isAlive())
6110 DestroyZoneLimitedItem( true, newZone );
6112 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6113 AutoUnequipOffhandIfNeed();
6115 // recent client version not send leave/join channel packets for built-in local channels
6116 UpdateLocalChannels( newZone );
6118 // group update
6119 if(GetGroup())
6120 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6122 UpdateZoneDependentAuras(newZone);
6125 //If players are too far way of duel flag... then player loose the duel
6126 void Player::CheckDuelDistance(time_t currTime)
6128 if(!duel)
6129 return;
6131 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6132 GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
6133 if(!obj)
6134 return;
6136 if(duel->outOfBound == 0)
6138 if(!IsWithinDistInMap(obj, 50))
6140 duel->outOfBound = currTime;
6142 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6143 GetSession()->SendPacket(&data);
6146 else
6148 if(IsWithinDistInMap(obj, 40))
6150 duel->outOfBound = 0;
6152 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6153 GetSession()->SendPacket(&data);
6155 else if(currTime >= (duel->outOfBound+10))
6157 DuelComplete(DUEL_FLED);
6162 void Player::DuelComplete(DuelCompleteType type)
6164 // duel not requested
6165 if(!duel)
6166 return;
6168 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6169 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6170 GetSession()->SendPacket(&data);
6171 duel->opponent->GetSession()->SendPacket(&data);
6173 if(type != DUEL_INTERUPTED)
6175 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6176 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6177 data << duel->opponent->GetName();
6178 data << GetName();
6179 SendMessageToSet(&data,true);
6182 // cool-down duel spell
6183 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6185 data<<GetGUID();
6186 data<<uint8(0x0);
6188 data<<(uint32)7266;
6189 data<<uint32(0x0);
6190 GetSession()->SendPacket(&data);
6191 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6192 data<<duel->opponent->GetGUID();
6193 data<<uint8(0x0);
6194 data<<(uint32)7266;
6195 data<<uint32(0x0);
6196 duel->opponent->GetSession()->SendPacket(&data);*/
6198 //Remove Duel Flag object
6199 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
6200 if(obj)
6201 duel->initiator->RemoveGameObject(obj,true);
6203 /* remove auras */
6204 std::vector<uint32> auras2remove;
6205 AuraMap const& vAuras = duel->opponent->GetAuras();
6206 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6208 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6209 auras2remove.push_back(i->second->GetId());
6212 for(size_t i=0; i<auras2remove.size(); ++i)
6213 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6215 auras2remove.clear();
6216 AuraMap const& auras = GetAuras();
6217 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6219 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6220 auras2remove.push_back(i->second->GetId());
6222 for(size_t i=0; i<auras2remove.size(); ++i)
6223 RemoveAurasDueToSpell(auras2remove[i]);
6225 // cleanup combo points
6226 if(GetComboTarget()==duel->opponent->GetGUID())
6227 ClearComboPoints();
6228 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6229 ClearComboPoints();
6231 if(duel->opponent->GetComboTarget()==GetGUID())
6232 duel->opponent->ClearComboPoints();
6233 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6234 duel->opponent->ClearComboPoints();
6236 //cleanups
6237 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6238 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6239 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6240 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6242 delete duel->opponent->duel;
6243 duel->opponent->duel = NULL;
6244 delete duel;
6245 duel = NULL;
6248 //---------------------------------------------------------//
6250 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6252 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6253 return;
6255 // not apply/remove mods for broken item
6256 if(item->IsBroken())
6257 return;
6259 ItemPrototype const *proto = item->GetProto();
6261 if(!proto)
6262 return;
6264 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6266 uint32 attacktype = Player::GetAttackBySlot(slot);
6267 if(attacktype < MAX_ATTACK)
6268 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6270 _ApplyItemBonuses(proto,slot,apply);
6272 if( slot==EQUIPMENT_SLOT_RANGED )
6273 _ApplyAmmoBonuses();
6275 ApplyItemEquipSpell(item,apply);
6276 ApplyEnchantment(item, apply);
6278 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6279 CorrectMetaGemEnchants(slot, apply);
6281 sLog.outDebug("_ApplyItemMods complete.");
6284 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6286 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6287 return;
6289 for (int i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6291 uint32 statType = 0;
6292 int32 val = 0;
6294 if(proto->ScalingStatDistribution)
6296 if(ScalingStatDistributionEntry const *ssd = sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution))
6298 statType = ssd->StatMod[i];
6300 if(uint32 modifier = ssd->Modifier[i])
6302 uint32 level = ((getLevel() > ssd->MaxLevel) ? ssd->MaxLevel : getLevel());
6303 if(ScalingStatValuesEntry const *ssv = sScalingStatValuesStore.LookupEntry(level))
6305 uint32 multiplier = ssv->Multiplier[proto->GetScalingStatValuesColumn()];
6306 val = (multiplier * modifier) / 10000;
6311 else
6313 statType = proto->ItemStat[i].ItemStatType;
6314 val = proto->ItemStat[i].ItemStatValue;
6317 if(val == 0)
6318 continue;
6320 switch (statType)
6322 case ITEM_MOD_MANA:
6323 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6324 break;
6325 case ITEM_MOD_HEALTH: // modify HP
6326 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6327 break;
6328 case ITEM_MOD_AGILITY: // modify agility
6329 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6330 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6331 break;
6332 case ITEM_MOD_STRENGTH: //modify strength
6333 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6334 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6335 break;
6336 case ITEM_MOD_INTELLECT: //modify intellect
6337 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6338 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6339 break;
6340 case ITEM_MOD_SPIRIT: //modify spirit
6341 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6342 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6343 break;
6344 case ITEM_MOD_STAMINA: //modify stamina
6345 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6346 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6347 break;
6348 case ITEM_MOD_DEFENSE_SKILL_RATING:
6349 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6350 break;
6351 case ITEM_MOD_DODGE_RATING:
6352 ApplyRatingMod(CR_DODGE, int32(val), apply);
6353 break;
6354 case ITEM_MOD_PARRY_RATING:
6355 ApplyRatingMod(CR_PARRY, int32(val), apply);
6356 break;
6357 case ITEM_MOD_BLOCK_RATING:
6358 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6359 break;
6360 case ITEM_MOD_HIT_MELEE_RATING:
6361 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6362 break;
6363 case ITEM_MOD_HIT_RANGED_RATING:
6364 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6365 break;
6366 case ITEM_MOD_HIT_SPELL_RATING:
6367 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6368 break;
6369 case ITEM_MOD_CRIT_MELEE_RATING:
6370 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6371 break;
6372 case ITEM_MOD_CRIT_RANGED_RATING:
6373 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6374 break;
6375 case ITEM_MOD_CRIT_SPELL_RATING:
6376 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6377 break;
6378 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6379 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6380 break;
6381 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6382 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6383 break;
6384 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6385 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6386 break;
6387 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6388 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6389 break;
6390 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6391 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6392 break;
6393 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6394 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6395 break;
6396 case ITEM_MOD_HASTE_MELEE_RATING:
6397 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6398 break;
6399 case ITEM_MOD_HASTE_RANGED_RATING:
6400 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6401 break;
6402 case ITEM_MOD_HASTE_SPELL_RATING:
6403 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6404 break;
6405 case ITEM_MOD_HIT_RATING:
6406 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6407 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6408 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6409 break;
6410 case ITEM_MOD_CRIT_RATING:
6411 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6412 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6413 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6414 break;
6415 case ITEM_MOD_HIT_TAKEN_RATING:
6416 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6417 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6418 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6419 break;
6420 case ITEM_MOD_CRIT_TAKEN_RATING:
6421 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6422 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6423 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6424 break;
6425 case ITEM_MOD_RESILIENCE_RATING:
6426 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6427 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6428 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6429 break;
6430 case ITEM_MOD_HASTE_RATING:
6431 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6432 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6433 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6434 break;
6435 case ITEM_MOD_EXPERTISE_RATING:
6436 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6437 break;
6438 case ITEM_MOD_ATTACK_POWER:
6439 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6440 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6441 break;
6442 case ITEM_MOD_RANGED_ATTACK_POWER:
6443 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6444 break;
6445 case ITEM_MOD_FERAL_ATTACK_POWER:
6446 ApplyFeralAPBonus(int32(val), apply);
6447 break;
6448 case ITEM_MOD_SPELL_HEALING_DONE:
6449 ApplySpellHealingBonus(int32(val), apply);
6450 break;
6451 case ITEM_MOD_SPELL_DAMAGE_DONE:
6452 ApplySpellDamageBonus(int32(val), apply);
6453 break;
6454 case ITEM_MOD_MANA_REGENERATION:
6455 ApplyManaRegenBonus(int32(val), apply);
6456 break;
6457 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6458 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6459 break;
6460 case ITEM_MOD_SPELL_POWER:
6461 ApplySpellHealingBonus(int32(val), apply);
6462 ApplySpellDamageBonus(int32(val), apply);
6463 break;
6467 if (proto->Armor)
6468 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6470 if (proto->Block)
6471 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6473 if (proto->HolyRes)
6474 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6476 if (proto->FireRes)
6477 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6479 if (proto->NatureRes)
6480 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6482 if (proto->FrostRes)
6483 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6485 if (proto->ShadowRes)
6486 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6488 if (proto->ArcaneRes)
6489 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6491 WeaponAttackType attType = BASE_ATTACK;
6492 float damage = 0.0f;
6494 if( slot == EQUIPMENT_SLOT_RANGED && (
6495 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6496 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6498 attType = RANGED_ATTACK;
6500 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6502 attType = OFF_ATTACK;
6505 if (proto->Damage[0].DamageMin > 0 )
6507 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6508 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6509 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6512 if (proto->Damage[0].DamageMax > 0 )
6514 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6515 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6518 // Druids get feral AP bonus from weapon dps
6519 if(getClass() == CLASS_DRUID)
6521 int32 feral_bonus = proto->getFeralBonus();
6522 if (feral_bonus > 0)
6523 ApplyFeralAPBonus(feral_bonus, apply);
6526 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6527 return;
6529 if (proto->Delay)
6531 if(slot == EQUIPMENT_SLOT_RANGED)
6532 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6533 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6534 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6535 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6536 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6539 if(CanModifyStats() && (damage || proto->Delay))
6540 UpdateDamagePhysical(attType);
6543 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6545 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6546 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6547 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6549 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6550 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6551 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6553 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6554 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6555 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6558 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6560 // generic not weapon specific case processes in aura code
6561 if(aura->GetSpellProto()->EquippedItemClass == -1)
6562 return;
6564 BaseModGroup mod = BASEMOD_END;
6565 switch(attackType)
6567 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6568 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6569 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6570 default: return;
6573 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6575 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6579 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6581 // ignore spell mods for not wands
6582 Modifier const* modifier = aura->GetModifier();
6583 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6584 return;
6586 // generic not weapon specific case processes in aura code
6587 if(aura->GetSpellProto()->EquippedItemClass == -1)
6588 return;
6590 UnitMods unitMod = UNIT_MOD_END;
6591 switch(attackType)
6593 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6594 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6595 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6596 default: return;
6599 UnitModifierType unitModType = TOTAL_VALUE;
6600 switch(modifier->m_auraname)
6602 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6603 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6604 default: return;
6607 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6609 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6613 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6615 if(!item)
6616 return;
6618 ItemPrototype const *proto = item->GetProto();
6619 if(!proto)
6620 return;
6622 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6624 _Spell const& spellData = proto->Spells[i];
6626 // no spell
6627 if(!spellData.SpellId )
6628 continue;
6630 // wrong triggering type
6631 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6632 continue;
6634 // check if it is valid spell
6635 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6636 if(!spellproto)
6637 continue;
6639 ApplyEquipSpell(spellproto,item,apply,form_change);
6643 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6645 if(apply)
6647 // Cannot be used in this stance/form
6648 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
6649 return;
6651 if(form_change) // check aura active state from other form
6653 bool found = false;
6654 for (int k=0; k < 3; ++k)
6656 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6657 for (AuraMap::const_iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6659 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6661 found = true;
6662 break;
6665 if(found)
6666 break;
6669 if(found) // and skip re-cast already active aura at form change
6670 return;
6673 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6675 CastSpell(this,spellInfo,true,item);
6677 else
6679 if(form_change) // check aura compatibility
6681 // Cannot be used in this stance/form
6682 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
6683 return; // and remove only not compatible at form change
6686 if(item)
6687 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6688 else
6689 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6693 void Player::UpdateEquipSpellsAtFormChange()
6695 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6697 if(m_items[i] && !m_items[i]->IsBroken())
6699 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6700 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6704 // item set bonuses not dependent from item broken state
6705 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6707 ItemSetEffect* eff = ItemSetEff[setindex];
6708 if(!eff)
6709 continue;
6711 for(uint32 y=0;y<8; ++y)
6713 SpellEntry const* spellInfo = eff->spells[y];
6714 if(!spellInfo)
6715 continue;
6717 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6718 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6723 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
6725 if(!item || item->IsBroken())
6726 return;
6728 ItemPrototype const *proto = item->GetProto();
6729 if(!proto)
6730 return;
6732 if (!Target || Target == this )
6733 return;
6735 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6737 _Spell const& spellData = proto->Spells[i];
6739 // no spell
6740 if(!spellData.SpellId )
6741 continue;
6743 // wrong triggering type
6744 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6745 continue;
6747 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6748 if(!spellInfo)
6750 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6751 continue;
6754 // not allow proc extra attack spell at extra attack
6755 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6756 return;
6758 float chance = spellInfo->procChance;
6760 if(spellData.SpellPPMRate)
6762 uint32 WeaponSpeed = GetAttackTime(attType);
6763 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6765 else if(chance > 100.0f)
6767 chance = GetWeaponProcChance();
6770 if (roll_chance_f(chance))
6771 CastSpell(Target, spellInfo->Id, true, item);
6774 // item combat enchantments
6775 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6777 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6778 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6779 if(!pEnchant) continue;
6780 for (int s=0;s<3;s++)
6782 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6783 continue;
6785 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6786 if (!spellInfo)
6788 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6789 continue;
6792 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6793 if (roll_chance_f(chance))
6795 if(IsPositiveSpell(pEnchant->spellid[s]))
6796 CastSpell(this, pEnchant->spellid[s], true, item);
6797 else
6798 CastSpell(Target, pEnchant->spellid[s], true, item);
6804 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
6806 ItemPrototype const* proto = item->GetProto();
6807 // special learning case
6808 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
6810 uint32 learn_spell_id = proto->Spells[0].SpellId;
6811 uint32 learning_spell_id = proto->Spells[1].SpellId;
6813 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
6814 if(!spellInfo)
6816 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
6817 SendEquipError(EQUIP_ERR_NONE,item,NULL);
6818 return;
6821 Spell *spell = new Spell(this, spellInfo, false);
6822 spell->m_CastItem = item;
6823 spell->m_cast_count = cast_count; //set count of casts
6824 spell->m_currentBasePoints[0] = learning_spell_id;
6825 spell->prepare(&targets);
6826 return;
6829 // use triggered flag only for items with many spell casts and for not first cast
6830 int count = 0;
6832 // item spells casted at use
6833 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6835 _Spell const& spellData = proto->Spells[i];
6837 // no spell
6838 if(!spellData.SpellId)
6839 continue;
6841 // wrong triggering type
6842 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
6843 continue;
6845 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6846 if(!spellInfo)
6848 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
6849 continue;
6852 Spell *spell = new Spell(this, spellInfo, (count > 0));
6853 spell->m_CastItem = item;
6854 spell->m_cast_count = cast_count; // set count of casts
6855 spell->m_glyphIndex = glyphIndex; // glyph index
6856 spell->prepare(&targets);
6858 ++count;
6861 // Item enchantments spells casted at use
6862 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6864 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6865 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6866 if(!pEnchant) continue;
6867 for (int s=0;s<3;s++)
6869 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
6870 continue;
6872 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6873 if (!spellInfo)
6875 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6876 continue;
6879 Spell *spell = new Spell(this, spellInfo, (count > 0));
6880 spell->m_CastItem = item;
6881 spell->m_cast_count = cast_count; // set count of casts
6882 spell->m_glyphIndex = glyphIndex; // glyph index
6883 spell->prepare(&targets);
6885 ++count;
6890 void Player::_RemoveAllItemMods()
6892 sLog.outDebug("_RemoveAllItemMods start.");
6894 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6896 if(m_items[i])
6898 ItemPrototype const *proto = m_items[i]->GetProto();
6899 if(!proto)
6900 continue;
6902 // item set bonuses not dependent from item broken state
6903 if(proto->ItemSet)
6904 RemoveItemsSetItem(this,proto);
6906 if(m_items[i]->IsBroken())
6907 continue;
6909 ApplyItemEquipSpell(m_items[i],false);
6910 ApplyEnchantment(m_items[i], false);
6914 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6916 if(m_items[i])
6918 if(m_items[i]->IsBroken())
6919 continue;
6920 ItemPrototype const *proto = m_items[i]->GetProto();
6921 if(!proto)
6922 continue;
6924 uint32 attacktype = Player::GetAttackBySlot(i);
6925 if(attacktype < MAX_ATTACK)
6926 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
6928 _ApplyItemBonuses(proto,i, false);
6930 if( i == EQUIPMENT_SLOT_RANGED )
6931 _ApplyAmmoBonuses();
6935 sLog.outDebug("_RemoveAllItemMods complete.");
6938 void Player::_ApplyAllItemMods()
6940 sLog.outDebug("_ApplyAllItemMods start.");
6942 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6944 if(m_items[i])
6946 if(m_items[i]->IsBroken())
6947 continue;
6949 ItemPrototype const *proto = m_items[i]->GetProto();
6950 if(!proto)
6951 continue;
6953 uint32 attacktype = Player::GetAttackBySlot(i);
6954 if(attacktype < MAX_ATTACK)
6955 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
6957 _ApplyItemBonuses(proto,i, true);
6959 if( i == EQUIPMENT_SLOT_RANGED )
6960 _ApplyAmmoBonuses();
6964 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6966 if(m_items[i])
6968 ItemPrototype const *proto = m_items[i]->GetProto();
6969 if(!proto)
6970 continue;
6972 // item set bonuses not dependent from item broken state
6973 if(proto->ItemSet)
6974 AddItemsSetItem(this,m_items[i]);
6976 if(m_items[i]->IsBroken())
6977 continue;
6979 ApplyItemEquipSpell(m_items[i],true);
6980 ApplyEnchantment(m_items[i], true);
6984 sLog.outDebug("_ApplyAllItemMods complete.");
6987 void Player::_ApplyAmmoBonuses()
6989 // check ammo
6990 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
6991 if(!ammo_id)
6992 return;
6994 float currentAmmoDPS;
6996 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
6997 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
6998 currentAmmoDPS = 0.0f;
6999 else
7000 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7002 if(currentAmmoDPS == GetAmmoDPS())
7003 return;
7005 m_ammoDPS = currentAmmoDPS;
7007 if(CanModifyStats())
7008 UpdateDamagePhysical(RANGED_ATTACK);
7011 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7013 if(!ammo_proto)
7014 return false;
7016 // check ranged weapon
7017 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7018 if(!weapon || weapon->IsBroken() )
7019 return false;
7021 ItemPrototype const* weapon_proto = weapon->GetProto();
7022 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7023 return false;
7025 // check ammo ws. weapon compatibility
7026 switch(weapon_proto->SubClass)
7028 case ITEM_SUBCLASS_WEAPON_BOW:
7029 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7030 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7031 return false;
7032 break;
7033 case ITEM_SUBCLASS_WEAPON_GUN:
7034 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7035 return false;
7036 break;
7037 default:
7038 return false;
7041 return true;
7044 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7045 Called by remove insignia spell effect */
7046 void Player::RemovedInsignia(Player* looterPlr)
7048 if (!GetBattleGroundId())
7049 return;
7051 // If not released spirit, do it !
7052 if(m_deathTimer > 0)
7054 m_deathTimer = 0;
7055 BuildPlayerRepop();
7056 RepopAtGraveyard();
7059 Corpse *corpse = GetCorpse();
7060 if (!corpse)
7061 return;
7063 // We have to convert player corpse to bones, not to be able to resurrect there
7064 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7065 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7066 if (!bones)
7067 return;
7069 // Now we must make bones lootable, and send player loot
7070 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7072 // We store the level of our player in the gold field
7073 // We retrieve this information at Player::SendLoot()
7074 bones->loot.gold = getLevel();
7075 bones->lootRecipient = looterPlr;
7076 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7079 void Player::SendLootRelease( uint64 guid )
7081 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7082 data << uint64(guid) << uint8(1);
7083 SendDirectMessage( &data );
7086 void Player::SendLoot(uint64 guid, LootType loot_type)
7088 if (uint64 lguid = GetLootGUID())
7089 m_session->DoLootRelease(lguid);
7091 Loot *loot = 0;
7092 PermissionTypes permission = ALL_PERMISSION;
7094 sLog.outDebug("Player::SendLoot");
7095 if (IS_GAMEOBJECT_GUID(guid))
7097 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7098 GameObject *go = GetMap()->GetGameObject(guid);
7100 // not check distance for GO in case owned GO (fishing bobber case, for example)
7101 // And permit out of range GO with no owner in case fishing hole
7102 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7104 SendLootRelease(guid);
7105 return;
7108 loot = &go->loot;
7110 if (go->getLootState() == GO_READY)
7112 uint32 lootid = go->GetLootId();
7114 if (lootid)
7116 sLog.outDebug(" if(lootid)");
7117 loot->clear();
7118 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7121 if (loot_type == LOOT_FISHING)
7122 go->getFishLoot(loot,this);
7124 go->SetLootState(GO_ACTIVATED);
7127 else if (IS_ITEM_GUID(guid))
7129 Item *item = GetItemByGuid( guid );
7131 if (!item)
7133 SendLootRelease(guid);
7134 return;
7137 loot = &item->loot;
7139 if (!item->m_lootGenerated)
7141 item->m_lootGenerated = true;
7142 loot->clear();
7144 switch(loot_type)
7146 case LOOT_DISENCHANTING:
7147 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7148 break;
7149 case LOOT_PROSPECTING:
7150 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7151 break;
7152 case LOOT_MILLING:
7153 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7154 break;
7155 default:
7156 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7157 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7158 break;
7162 else if (IS_CORPSE_GUID(guid)) // remove insignia
7164 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7166 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7168 SendLootRelease(guid);
7169 return;
7172 loot = &bones->loot;
7174 if (!bones->lootForBody)
7176 bones->lootForBody = true;
7177 uint32 pLevel = bones->loot.gold;
7178 bones->loot.clear();
7179 // It may need a better formula
7180 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7181 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7184 if (bones->lootRecipient != this)
7185 permission = NONE_PERMISSION;
7187 else
7189 Creature *creature = GetMap()->GetCreature(guid);
7191 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7192 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7194 SendLootRelease(guid);
7195 return;
7198 if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7200 SendLootRelease(guid);
7201 return;
7204 loot = &creature->loot;
7206 if (loot_type == LOOT_PICKPOCKETING)
7208 if (!creature->lootForPickPocketed)
7210 creature->lootForPickPocketed = true;
7211 loot->clear();
7213 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7214 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7216 // Generate extra money for pick pocket loot
7217 const uint32 a = urand(0, creature->getLevel()/2);
7218 const uint32 b = urand(0, getLevel()/2);
7219 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7222 else
7224 // the player whose group may loot the corpse
7225 Player *recipient = creature->GetLootRecipient();
7226 if (!recipient)
7228 creature->SetLootRecipient(this);
7229 recipient = this;
7232 if (creature->lootForPickPocketed)
7234 creature->lootForPickPocketed = false;
7235 loot->clear();
7238 if (!creature->lootForBody)
7240 creature->lootForBody = true;
7241 loot->clear();
7243 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7244 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7246 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7248 if (Group* group = recipient->GetGroup())
7250 group->UpdateLooterGuid(creature,true);
7252 switch (group->GetLootMethod())
7254 case GROUP_LOOT:
7255 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7256 group->GroupLoot(recipient->GetGUID(), loot, creature);
7257 break;
7258 case NEED_BEFORE_GREED:
7259 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7260 break;
7261 case MASTER_LOOT:
7262 group->MasterLoot(recipient->GetGUID(), loot, creature);
7263 break;
7264 default:
7265 break;
7270 // possible only if creature->lootForBody && loot->empty() at spell cast check
7271 if (loot_type == LOOT_SKINNING)
7273 loot->clear();
7274 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7276 // set group rights only for loot_type != LOOT_SKINNING
7277 else
7279 if(Group* group = GetGroup())
7281 if (group == recipient->GetGroup())
7283 if (group->GetLootMethod() == FREE_FOR_ALL)
7284 permission = ALL_PERMISSION;
7285 else if (group->GetLooterGuid() == GetGUID())
7287 if (group->GetLootMethod() == MASTER_LOOT)
7288 permission = MASTER_PERMISSION;
7289 else
7290 permission = ALL_PERMISSION;
7292 else
7293 permission = GROUP_PERMISSION;
7295 else
7296 permission = NONE_PERMISSION;
7298 else if (recipient == this)
7299 permission = ALL_PERMISSION;
7300 else
7301 permission = NONE_PERMISSION;
7306 SetLootGUID(guid);
7308 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7309 switch(loot_type)
7311 case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
7312 case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
7313 default: break;
7316 // need know merged fishing/corpse loot type for achievements
7317 loot->loot_type = loot_type;
7319 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7321 data << uint64(guid);
7322 data << uint8(loot_type);
7323 data << LootView(*loot, this, permission);
7325 SendDirectMessage(&data);
7327 // add 'this' player as one of the players that are looting 'loot'
7328 if (permission != NONE_PERMISSION)
7329 loot->AddLooter(GetGUID());
7331 if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
7332 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7335 void Player::SendNotifyLootMoneyRemoved()
7337 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7338 GetSession()->SendPacket( &data );
7341 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7343 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7344 data << uint8(lootSlot);
7345 GetSession()->SendPacket( &data );
7348 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7350 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7351 data << Field;
7352 data << Value;
7353 GetSession()->SendPacket(&data);
7356 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7358 // data depends on zoneid/mapid...
7359 BattleGround* bg = GetBattleGround();
7360 uint16 NumberOfFields = 0;
7361 uint32 mapid = GetMapId();
7363 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7365 // may be exist better way to do this...
7366 switch(zoneid)
7368 case 0:
7369 case 1:
7370 case 4:
7371 case 8:
7372 case 10:
7373 case 11:
7374 case 12:
7375 case 36:
7376 case 38:
7377 case 40:
7378 case 41:
7379 case 51:
7380 case 267:
7381 case 1519:
7382 case 1537:
7383 case 2257:
7384 case 2918:
7385 NumberOfFields = 8;
7386 break;
7387 case 139:
7388 NumberOfFields = 41;
7389 break;
7390 case 1377:
7391 NumberOfFields = 15;
7392 break;
7393 case 2597:
7394 NumberOfFields = 83;
7395 break;
7396 case 3277:
7397 NumberOfFields = 16;
7398 break;
7399 case 3358:
7400 case 3820:
7401 NumberOfFields = 40;
7402 break;
7403 case 3483:
7404 NumberOfFields = 27;
7405 break;
7406 case 3518:
7407 NumberOfFields = 39;
7408 break;
7409 case 3519:
7410 NumberOfFields = 38;
7411 break;
7412 case 3521:
7413 NumberOfFields = 37;
7414 break;
7415 case 3698:
7416 case 3702:
7417 case 3968:
7418 NumberOfFields = 11;
7419 break;
7420 case 3703:
7421 NumberOfFields = 11;
7422 break;
7423 default:
7424 NumberOfFields = 12;
7425 break;
7428 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7429 data << uint32(mapid); // mapid
7430 data << uint32(zoneid); // zone id
7431 data << uint32(areaid); // area id, new 2.1.0
7432 data << uint16(NumberOfFields); // count of uint64 blocks
7433 data << uint32(0x8d8) << uint32(0x0); // 1
7434 data << uint32(0x8d7) << uint32(0x0); // 2
7435 data << uint32(0x8d6) << uint32(0x0); // 3
7436 data << uint32(0x8d5) << uint32(0x0); // 4
7437 data << uint32(0x8d4) << uint32(0x0); // 5
7438 data << uint32(0x8d3) << uint32(0x0); // 6
7439 // 7 1 - Arena season in progress, 0 - end of season
7440 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7441 // 8 Arena season id
7442 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7443 if(mapid == 530) // Outland
7445 data << uint32(0x9bf) << uint32(0x0); // 7
7446 data << uint32(0x9bd) << uint32(0xF); // 8
7447 data << uint32(0x9bb) << uint32(0xF); // 9
7449 switch(zoneid)
7451 case 1:
7452 case 11:
7453 case 12:
7454 case 38:
7455 case 40:
7456 case 51:
7457 case 1519:
7458 case 1537:
7459 case 2257:
7460 break;
7461 case 2597: // AV
7462 data << uint32(0x7ae) << uint32(0x1); // 7
7463 data << uint32(0x532) << uint32(0x1); // 8
7464 data << uint32(0x531) << uint32(0x0); // 9
7465 data << uint32(0x52e) << uint32(0x0); // 10
7466 data << uint32(0x571) << uint32(0x0); // 11
7467 data << uint32(0x570) << uint32(0x0); // 12
7468 data << uint32(0x567) << uint32(0x1); // 13
7469 data << uint32(0x566) << uint32(0x1); // 14
7470 data << uint32(0x550) << uint32(0x1); // 15
7471 data << uint32(0x544) << uint32(0x0); // 16
7472 data << uint32(0x536) << uint32(0x0); // 17
7473 data << uint32(0x535) << uint32(0x1); // 18
7474 data << uint32(0x518) << uint32(0x0); // 19
7475 data << uint32(0x517) << uint32(0x0); // 20
7476 data << uint32(0x574) << uint32(0x0); // 21
7477 data << uint32(0x573) << uint32(0x0); // 22
7478 data << uint32(0x572) << uint32(0x0); // 23
7479 data << uint32(0x56f) << uint32(0x0); // 24
7480 data << uint32(0x56e) << uint32(0x0); // 25
7481 data << uint32(0x56d) << uint32(0x0); // 26
7482 data << uint32(0x56c) << uint32(0x0); // 27
7483 data << uint32(0x56b) << uint32(0x0); // 28
7484 data << uint32(0x56a) << uint32(0x1); // 29
7485 data << uint32(0x569) << uint32(0x1); // 30
7486 data << uint32(0x568) << uint32(0x1); // 13
7487 data << uint32(0x565) << uint32(0x0); // 32
7488 data << uint32(0x564) << uint32(0x0); // 33
7489 data << uint32(0x563) << uint32(0x0); // 34
7490 data << uint32(0x562) << uint32(0x0); // 35
7491 data << uint32(0x561) << uint32(0x0); // 36
7492 data << uint32(0x560) << uint32(0x0); // 37
7493 data << uint32(0x55f) << uint32(0x0); // 38
7494 data << uint32(0x55e) << uint32(0x0); // 39
7495 data << uint32(0x55d) << uint32(0x0); // 40
7496 data << uint32(0x3c6) << uint32(0x4); // 41
7497 data << uint32(0x3c4) << uint32(0x6); // 42
7498 data << uint32(0x3c2) << uint32(0x4); // 43
7499 data << uint32(0x516) << uint32(0x1); // 44
7500 data << uint32(0x515) << uint32(0x0); // 45
7501 data << uint32(0x3b6) << uint32(0x6); // 46
7502 data << uint32(0x55c) << uint32(0x0); // 47
7503 data << uint32(0x55b) << uint32(0x0); // 48
7504 data << uint32(0x55a) << uint32(0x0); // 49
7505 data << uint32(0x559) << uint32(0x0); // 50
7506 data << uint32(0x558) << uint32(0x0); // 51
7507 data << uint32(0x557) << uint32(0x0); // 52
7508 data << uint32(0x556) << uint32(0x0); // 53
7509 data << uint32(0x555) << uint32(0x0); // 54
7510 data << uint32(0x554) << uint32(0x1); // 55
7511 data << uint32(0x553) << uint32(0x1); // 56
7512 data << uint32(0x552) << uint32(0x1); // 57
7513 data << uint32(0x551) << uint32(0x1); // 58
7514 data << uint32(0x54f) << uint32(0x0); // 59
7515 data << uint32(0x54e) << uint32(0x0); // 60
7516 data << uint32(0x54d) << uint32(0x1); // 61
7517 data << uint32(0x54c) << uint32(0x0); // 62
7518 data << uint32(0x54b) << uint32(0x0); // 63
7519 data << uint32(0x545) << uint32(0x0); // 64
7520 data << uint32(0x543) << uint32(0x1); // 65
7521 data << uint32(0x542) << uint32(0x0); // 66
7522 data << uint32(0x540) << uint32(0x0); // 67
7523 data << uint32(0x53f) << uint32(0x0); // 68
7524 data << uint32(0x53e) << uint32(0x0); // 69
7525 data << uint32(0x53d) << uint32(0x0); // 70
7526 data << uint32(0x53c) << uint32(0x0); // 71
7527 data << uint32(0x53b) << uint32(0x0); // 72
7528 data << uint32(0x53a) << uint32(0x1); // 73
7529 data << uint32(0x539) << uint32(0x0); // 74
7530 data << uint32(0x538) << uint32(0x0); // 75
7531 data << uint32(0x537) << uint32(0x0); // 76
7532 data << uint32(0x534) << uint32(0x0); // 77
7533 data << uint32(0x533) << uint32(0x0); // 78
7534 data << uint32(0x530) << uint32(0x0); // 79
7535 data << uint32(0x52f) << uint32(0x0); // 80
7536 data << uint32(0x52d) << uint32(0x1); // 81
7537 break;
7538 case 3277: // WS
7539 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7540 bg->FillInitialWorldStates(data);
7541 else
7543 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7544 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7545 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7546 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7547 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7548 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7549 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7550 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7552 break;
7553 case 3358: // AB
7554 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7555 bg->FillInitialWorldStates(data);
7556 else
7558 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7559 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7560 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7561 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7562 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7563 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7564 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7565 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7566 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7567 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7568 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7569 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7570 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7571 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7572 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7573 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7574 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7575 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7576 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7577 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7578 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7579 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7580 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7581 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7582 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7583 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7584 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7585 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7586 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7587 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7588 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7589 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7591 break;
7592 case 3820: // EY
7593 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7594 bg->FillInitialWorldStates(data);
7595 else
7597 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7598 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7599 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7600 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7601 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7602 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7603 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7604 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7605 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7606 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7607 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7608 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7609 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7610 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7611 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7612 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7613 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7614 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7615 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7616 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7617 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7618 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7619 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7620 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7621 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7622 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7623 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7624 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7625 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7626 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7627 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7628 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7629 // and some more ... unknown
7631 break;
7632 case 3483: // Hellfire Peninsula
7633 data << uint32(0x9ba) << uint32(0x1); // 10
7634 data << uint32(0x9b9) << uint32(0x1); // 11
7635 data << uint32(0x9b5) << uint32(0x0); // 12
7636 data << uint32(0x9b4) << uint32(0x1); // 13
7637 data << uint32(0x9b3) << uint32(0x0); // 14
7638 data << uint32(0x9b2) << uint32(0x0); // 15
7639 data << uint32(0x9b1) << uint32(0x1); // 16
7640 data << uint32(0x9b0) << uint32(0x0); // 17
7641 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7642 data << uint32(0x9ac) << uint32(0x0); // 19
7643 data << uint32(0x9a8) << uint32(0x0); // 20
7644 data << uint32(0x9a7) << uint32(0x0); // 21
7645 data << uint32(0x9a6) << uint32(0x1); // 22
7646 break;
7647 case 3519: // Terokkar Forest
7648 data << uint32(0xa41) << uint32(0x0); // 10
7649 data << uint32(0xa40) << uint32(0x14); // 11
7650 data << uint32(0xa3f) << uint32(0x0); // 12
7651 data << uint32(0xa3e) << uint32(0x0); // 13
7652 data << uint32(0xa3d) << uint32(0x5); // 14
7653 data << uint32(0xa3c) << uint32(0x0); // 15
7654 data << uint32(0xa87) << uint32(0x0); // 16
7655 data << uint32(0xa86) << uint32(0x0); // 17
7656 data << uint32(0xa85) << uint32(0x0); // 18
7657 data << uint32(0xa84) << uint32(0x0); // 19
7658 data << uint32(0xa83) << uint32(0x0); // 20
7659 data << uint32(0xa82) << uint32(0x0); // 21
7660 data << uint32(0xa81) << uint32(0x0); // 22
7661 data << uint32(0xa80) << uint32(0x0); // 23
7662 data << uint32(0xa7e) << uint32(0x0); // 24
7663 data << uint32(0xa7d) << uint32(0x0); // 25
7664 data << uint32(0xa7c) << uint32(0x0); // 26
7665 data << uint32(0xa7b) << uint32(0x0); // 27
7666 data << uint32(0xa7a) << uint32(0x0); // 28
7667 data << uint32(0xa79) << uint32(0x0); // 29
7668 data << uint32(0x9d0) << uint32(0x5); // 30
7669 data << uint32(0x9ce) << uint32(0x0); // 31
7670 data << uint32(0x9cd) << uint32(0x0); // 32
7671 data << uint32(0x9cc) << uint32(0x0); // 33
7672 data << uint32(0xa88) << uint32(0x0); // 34
7673 data << uint32(0xad0) << uint32(0x0); // 35
7674 data << uint32(0xacf) << uint32(0x1); // 36
7675 break;
7676 case 3521: // Zangarmarsh
7677 data << uint32(0x9e1) << uint32(0x0); // 10
7678 data << uint32(0x9e0) << uint32(0x0); // 11
7679 data << uint32(0x9df) << uint32(0x0); // 12
7680 data << uint32(0xa5d) << uint32(0x1); // 13
7681 data << uint32(0xa5c) << uint32(0x0); // 14
7682 data << uint32(0xa5b) << uint32(0x1); // 15
7683 data << uint32(0xa5a) << uint32(0x0); // 16
7684 data << uint32(0xa59) << uint32(0x1); // 17
7685 data << uint32(0xa58) << uint32(0x0); // 18
7686 data << uint32(0xa57) << uint32(0x0); // 19
7687 data << uint32(0xa56) << uint32(0x0); // 20
7688 data << uint32(0xa55) << uint32(0x1); // 21
7689 data << uint32(0xa54) << uint32(0x0); // 22
7690 data << uint32(0x9e7) << uint32(0x0); // 23
7691 data << uint32(0x9e6) << uint32(0x0); // 24
7692 data << uint32(0x9e5) << uint32(0x0); // 25
7693 data << uint32(0xa00) << uint32(0x0); // 26
7694 data << uint32(0x9ff) << uint32(0x1); // 27
7695 data << uint32(0x9fe) << uint32(0x0); // 28
7696 data << uint32(0x9fd) << uint32(0x0); // 29
7697 data << uint32(0x9fc) << uint32(0x1); // 30
7698 data << uint32(0x9fb) << uint32(0x0); // 31
7699 data << uint32(0xa62) << uint32(0x0); // 32
7700 data << uint32(0xa61) << uint32(0x1); // 33
7701 data << uint32(0xa60) << uint32(0x1); // 34
7702 data << uint32(0xa5f) << uint32(0x0); // 35
7703 break;
7704 case 3698: // Nagrand Arena
7705 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
7706 bg->FillInitialWorldStates(data);
7707 else
7709 data << uint32(0xa0f) << uint32(0x0); // 7
7710 data << uint32(0xa10) << uint32(0x0); // 8
7711 data << uint32(0xa11) << uint32(0x0); // 9 show
7713 break;
7714 case 3702: // Blade's Edge Arena
7715 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
7716 bg->FillInitialWorldStates(data);
7717 else
7719 data << uint32(0x9f0) << uint32(0x0); // 7 gold
7720 data << uint32(0x9f1) << uint32(0x0); // 8 green
7721 data << uint32(0x9f3) << uint32(0x0); // 9 show
7723 break;
7724 case 3968: // Ruins of Lordaeron
7725 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
7726 bg->FillInitialWorldStates(data);
7727 else
7729 data << uint32(0xbb8) << uint32(0x0); // 7 gold
7730 data << uint32(0xbb9) << uint32(0x0); // 8 green
7731 data << uint32(0xbba) << uint32(0x0); // 9 show
7733 break;
7734 case 3703: // Shattrath City
7735 break;
7736 default:
7737 data << uint32(0x914) << uint32(0x0); // 7
7738 data << uint32(0x913) << uint32(0x0); // 8
7739 data << uint32(0x912) << uint32(0x0); // 9
7740 data << uint32(0x915) << uint32(0x0); // 10
7741 break;
7743 GetSession()->SendPacket(&data);
7746 uint32 Player::GetXPRestBonus(uint32 xp)
7748 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7750 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7751 rested_bonus = xp;
7753 SetRestBonus( GetRestBonus() - rested_bonus);
7755 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7756 return rested_bonus;
7759 void Player::SetBindPoint(uint64 guid)
7761 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7762 data << uint64(guid);
7763 GetSession()->SendPacket( &data );
7766 void Player::SendTalentWipeConfirm(uint64 guid)
7768 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7769 data << uint64(guid);
7770 data << uint32(resetTalentsCost());
7771 GetSession()->SendPacket( &data );
7774 void Player::SendPetSkillWipeConfirm()
7776 Pet* pet = GetPet();
7777 if(!pet)
7778 return;
7779 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7780 data << pet->GetGUID();
7781 data << uint32(pet->resetTalentsCost());
7782 GetSession()->SendPacket( &data );
7785 /*********************************************************/
7786 /*** STORAGE SYSTEM ***/
7787 /*********************************************************/
7789 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7791 assert(i < 3);
7792 if(i < 2 && item)
7794 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7795 return;
7796 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7797 if(charges == 0)
7798 return;
7799 if(charges > 1)
7800 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7801 else if(charges <= 1)
7803 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7804 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7809 void Player::SetSheath( uint32 sheathed )
7811 switch (sheathed)
7813 case SHEATH_STATE_UNARMED: // no prepared weapon
7814 SetVirtualItemSlot(0,NULL);
7815 SetVirtualItemSlot(1,NULL);
7816 SetVirtualItemSlot(2,NULL);
7817 break;
7818 case SHEATH_STATE_MELEE: // prepared melee weapon
7820 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7821 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7822 SetVirtualItemSlot(2,NULL);
7823 }; break;
7824 case SHEATH_STATE_RANGED: // prepared ranged weapon
7825 SetVirtualItemSlot(0,NULL);
7826 SetVirtualItemSlot(1,NULL);
7827 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7828 break;
7829 default:
7830 SetVirtualItemSlot(0,NULL);
7831 SetVirtualItemSlot(1,NULL);
7832 SetVirtualItemSlot(2,NULL);
7833 break;
7835 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
7838 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7840 uint8 pClass = getClass();
7842 uint8 slots[4];
7843 slots[0] = NULL_SLOT;
7844 slots[1] = NULL_SLOT;
7845 slots[2] = NULL_SLOT;
7846 slots[3] = NULL_SLOT;
7847 switch( proto->InventoryType )
7849 case INVTYPE_HEAD:
7850 slots[0] = EQUIPMENT_SLOT_HEAD;
7851 break;
7852 case INVTYPE_NECK:
7853 slots[0] = EQUIPMENT_SLOT_NECK;
7854 break;
7855 case INVTYPE_SHOULDERS:
7856 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7857 break;
7858 case INVTYPE_BODY:
7859 slots[0] = EQUIPMENT_SLOT_BODY;
7860 break;
7861 case INVTYPE_CHEST:
7862 slots[0] = EQUIPMENT_SLOT_CHEST;
7863 break;
7864 case INVTYPE_ROBE:
7865 slots[0] = EQUIPMENT_SLOT_CHEST;
7866 break;
7867 case INVTYPE_WAIST:
7868 slots[0] = EQUIPMENT_SLOT_WAIST;
7869 break;
7870 case INVTYPE_LEGS:
7871 slots[0] = EQUIPMENT_SLOT_LEGS;
7872 break;
7873 case INVTYPE_FEET:
7874 slots[0] = EQUIPMENT_SLOT_FEET;
7875 break;
7876 case INVTYPE_WRISTS:
7877 slots[0] = EQUIPMENT_SLOT_WRISTS;
7878 break;
7879 case INVTYPE_HANDS:
7880 slots[0] = EQUIPMENT_SLOT_HANDS;
7881 break;
7882 case INVTYPE_FINGER:
7883 slots[0] = EQUIPMENT_SLOT_FINGER1;
7884 slots[1] = EQUIPMENT_SLOT_FINGER2;
7885 break;
7886 case INVTYPE_TRINKET:
7887 slots[0] = EQUIPMENT_SLOT_TRINKET1;
7888 slots[1] = EQUIPMENT_SLOT_TRINKET2;
7889 break;
7890 case INVTYPE_CLOAK:
7891 slots[0] = EQUIPMENT_SLOT_BACK;
7892 break;
7893 case INVTYPE_WEAPON:
7895 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7897 // suggest offhand slot only if know dual wielding
7898 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7899 if(CanDualWield())
7900 slots[1] = EQUIPMENT_SLOT_OFFHAND;
7901 break;
7903 case INVTYPE_SHIELD:
7904 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7905 break;
7906 case INVTYPE_RANGED:
7907 slots[0] = EQUIPMENT_SLOT_RANGED;
7908 break;
7909 case INVTYPE_2HWEAPON:
7910 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7911 if (CanDualWield() && CanTitanGrip())
7912 slots[1] = EQUIPMENT_SLOT_OFFHAND;
7913 break;
7914 case INVTYPE_TABARD:
7915 slots[0] = EQUIPMENT_SLOT_TABARD;
7916 break;
7917 case INVTYPE_WEAPONMAINHAND:
7918 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7919 break;
7920 case INVTYPE_WEAPONOFFHAND:
7921 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7922 break;
7923 case INVTYPE_HOLDABLE:
7924 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7925 break;
7926 case INVTYPE_THROWN:
7927 slots[0] = EQUIPMENT_SLOT_RANGED;
7928 break;
7929 case INVTYPE_RANGEDRIGHT:
7930 slots[0] = EQUIPMENT_SLOT_RANGED;
7931 break;
7932 case INVTYPE_BAG:
7933 slots[0] = INVENTORY_SLOT_BAG_START + 0;
7934 slots[1] = INVENTORY_SLOT_BAG_START + 1;
7935 slots[2] = INVENTORY_SLOT_BAG_START + 2;
7936 slots[3] = INVENTORY_SLOT_BAG_START + 3;
7937 break;
7938 case INVTYPE_RELIC:
7940 switch(proto->SubClass)
7942 case ITEM_SUBCLASS_ARMOR_LIBRAM:
7943 if (pClass == CLASS_PALADIN)
7944 slots[0] = EQUIPMENT_SLOT_RANGED;
7945 break;
7946 case ITEM_SUBCLASS_ARMOR_IDOL:
7947 if (pClass == CLASS_DRUID)
7948 slots[0] = EQUIPMENT_SLOT_RANGED;
7949 break;
7950 case ITEM_SUBCLASS_ARMOR_TOTEM:
7951 if (pClass == CLASS_SHAMAN)
7952 slots[0] = EQUIPMENT_SLOT_RANGED;
7953 break;
7954 case ITEM_SUBCLASS_ARMOR_MISC:
7955 if (pClass == CLASS_WARLOCK)
7956 slots[0] = EQUIPMENT_SLOT_RANGED;
7957 break;
7958 case ITEM_SUBCLASS_ARMOR_SIGIL:
7959 if (pClass == CLASS_DEATH_KNIGHT)
7960 slots[0] = EQUIPMENT_SLOT_RANGED;
7961 break;
7963 break;
7965 default :
7966 return NULL_SLOT;
7969 if( slot != NULL_SLOT )
7971 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
7973 for (int i = 0; i < 4; ++i)
7975 if ( slots[i] == slot )
7976 return slot;
7980 else
7982 // search free slot at first
7983 for (int i = 0; i < 4; ++i)
7985 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
7987 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
7988 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
7989 return slots[i];
7993 // if not found free and can swap return first appropriate from used
7994 for (int i = 0; i < 4; ++i)
7996 if ( slots[i] != NULL_SLOT && swap )
7997 return slots[i];
8001 // no free position
8002 return NULL_SLOT;
8005 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8007 Item *pItem;
8008 uint32 tempcount = 0;
8010 uint8 res = EQUIP_ERR_OK;
8012 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
8014 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8015 if( pItem && pItem->GetEntry() == item )
8017 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8018 if(ires==EQUIP_ERR_OK)
8020 tempcount += pItem->GetCount();
8021 if( tempcount >= count )
8022 return EQUIP_ERR_OK;
8024 else
8025 res = ires;
8028 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8030 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8031 if( pItem && pItem->GetEntry() == item )
8033 tempcount += pItem->GetCount();
8034 if( tempcount >= count )
8035 return EQUIP_ERR_OK;
8038 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8040 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8041 if( pItem && pItem->GetEntry() == item )
8043 tempcount += pItem->GetCount();
8044 if( tempcount >= count )
8045 return EQUIP_ERR_OK;
8048 Bag *pBag;
8049 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8051 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8052 if( pBag )
8054 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8056 pItem = GetItemByPos( i, j );
8057 if( pItem && pItem->GetEntry() == item )
8059 tempcount += pItem->GetCount();
8060 if( tempcount >= count )
8061 return EQUIP_ERR_OK;
8067 // not found req. item count and have unequippable items
8068 return res;
8071 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8073 uint32 count = 0;
8074 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8076 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8077 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8078 count += pItem->GetCount();
8080 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8082 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8083 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8084 count += pItem->GetCount();
8086 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8088 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8089 if( pBag )
8090 count += pBag->GetItemCount(item,skipItem);
8093 if(skipItem && skipItem->GetProto()->GemProperties)
8095 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8097 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8098 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8099 count += pItem->GetGemCountWithID(item);
8103 if(inBankAlso)
8105 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8107 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8108 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8109 count += pItem->GetCount();
8111 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8113 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8114 if( pBag )
8115 count += pBag->GetItemCount(item,skipItem);
8118 if(skipItem && skipItem->GetProto()->GemProperties)
8120 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8122 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8123 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8124 count += pItem->GetGemCountWithID(item);
8129 return count;
8132 Item* Player::GetItemByGuid( uint64 guid ) const
8134 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8136 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8137 if( pItem && pItem->GetGUID() == guid )
8138 return pItem;
8140 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8142 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8143 if( pItem && pItem->GetGUID() == guid )
8144 return pItem;
8147 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8149 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8150 if( pBag )
8152 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8154 Item* pItem = pBag->GetItemByPos( j );
8155 if( pItem && pItem->GetGUID() == guid )
8156 return pItem;
8160 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8162 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8163 if( pBag )
8165 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8167 Item* pItem = pBag->GetItemByPos( j );
8168 if( pItem && pItem->GetGUID() == guid )
8169 return pItem;
8174 return NULL;
8177 Item* Player::GetItemByPos( uint16 pos ) const
8179 uint8 bag = pos >> 8;
8180 uint8 slot = pos & 255;
8181 return GetItemByPos( bag, slot );
8184 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8186 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8187 return m_items[slot];
8188 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8189 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8191 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8192 if ( pBag )
8193 return pBag->GetItemByPos(slot);
8195 return NULL;
8198 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8200 uint16 slot;
8201 switch (attackType)
8203 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8204 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8205 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8206 default: return NULL;
8209 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8210 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8211 return NULL;
8213 if(!useable)
8214 return item;
8216 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8217 return NULL;
8219 return item;
8222 Item* Player::GetShield(bool useable) const
8224 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8225 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8226 return NULL;
8228 if(!useable)
8229 return item;
8231 if( item->IsBroken())
8232 return NULL;
8234 return item;
8237 uint32 Player::GetAttackBySlot( uint8 slot )
8239 switch(slot)
8241 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8242 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8243 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8244 default: return MAX_ATTACK;
8248 bool Player::HasBankBagSlot( uint8 slot ) const
8250 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8251 if( slot < maxslot )
8252 return true;
8253 return false;
8256 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8258 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8259 return true;
8260 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8261 return true;
8262 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8263 return true;
8264 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8265 return true;
8266 return false;
8269 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8271 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8272 return true;
8273 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8274 return true;
8275 return false;
8278 bool Player::IsBankPos( uint8 bag, uint8 slot )
8280 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8281 return true;
8282 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8283 return true;
8284 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8285 return true;
8286 return false;
8289 bool Player::IsBagPos( uint16 pos )
8291 uint8 bag = pos >> 8;
8292 uint8 slot = pos & 255;
8293 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8294 return true;
8295 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8296 return true;
8297 return false;
8300 bool Player::IsValidPos( uint8 bag, uint8 slot )
8302 // post selected
8303 if(bag == NULL_BAG)
8304 return true;
8306 if (bag == INVENTORY_SLOT_BAG_0)
8308 // any post selected
8309 if (slot == NULL_SLOT)
8310 return true;
8312 // equipment
8313 if (slot < EQUIPMENT_SLOT_END)
8314 return true;
8316 // bag equip slots
8317 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8318 return true;
8320 // backpack slots
8321 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8322 return true;
8324 // keyring slots
8325 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8326 return true;
8328 // bank main slots
8329 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8330 return true;
8332 // bank bag slots
8333 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8334 return true;
8336 return false;
8339 // bag content slots
8340 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8342 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8343 if(!pBag)
8344 return false;
8346 // any post selected
8347 if (slot == NULL_SLOT)
8348 return true;
8350 return slot < pBag->GetBagSize();
8353 // bank bag content slots
8354 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8356 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8357 if(!pBag)
8358 return false;
8360 // any post selected
8361 if (slot == NULL_SLOT)
8362 return true;
8364 return slot < pBag->GetBagSize();
8367 // where this?
8368 return false;
8372 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8374 uint32 tempcount = 0;
8375 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8377 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8378 if( pItem && pItem->GetEntry() == item )
8380 tempcount += pItem->GetCount();
8381 if( tempcount >= count )
8382 return true;
8385 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8387 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8388 if( pItem && pItem->GetEntry() == item )
8390 tempcount += pItem->GetCount();
8391 if( tempcount >= count )
8392 return true;
8395 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8397 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8399 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8401 Item* pItem = GetItemByPos( i, j );
8402 if( pItem && pItem->GetEntry() == item )
8404 tempcount += pItem->GetCount();
8405 if( tempcount >= count )
8406 return true;
8412 if(inBankAlso)
8414 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8416 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8417 if( pItem && pItem->GetEntry() == item )
8419 tempcount += pItem->GetCount();
8420 if( tempcount >= count )
8421 return true;
8424 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8426 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8428 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8430 Item* pItem = GetItemByPos( i, j );
8431 if( pItem && pItem->GetEntry() == item )
8433 tempcount += pItem->GetCount();
8434 if( tempcount >= count )
8435 return true;
8442 return false;
8445 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8447 uint32 tempcount = 0;
8448 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8450 if(i==int(except_slot))
8451 continue;
8453 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8454 if( pItem && pItem->GetEntry() == item)
8456 tempcount += pItem->GetCount();
8457 if( tempcount >= count )
8458 return true;
8462 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8463 if (pProto && pProto->GemProperties)
8465 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8467 if(i==int(except_slot))
8468 continue;
8470 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8471 if( pItem && pItem->GetProto()->Socket[0].Color)
8473 tempcount += pItem->GetGemCountWithID(item);
8474 if( tempcount >= count )
8475 return true;
8480 return false;
8483 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8485 uint32 tempcount = 0;
8486 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8488 if(i==int(except_slot))
8489 continue;
8491 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8492 if (!pItem)
8493 continue;
8495 ItemPrototype const *pProto = pItem->GetProto();
8496 if (!pProto)
8497 continue;
8499 if (pProto->ItemLimitCategory == limitCategory)
8501 tempcount += pItem->GetCount();
8502 if( tempcount >= count )
8503 return true;
8506 if( pProto->Socket[0].Color)
8508 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8509 if( tempcount >= count )
8510 return true;
8514 return false;
8517 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8519 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8520 if( !pProto )
8522 if(no_space_count)
8523 *no_space_count = count;
8524 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8527 // no maximum
8528 if(pProto->MaxCount <= 0)
8529 return EQUIP_ERR_OK;
8531 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8533 if (curcount + count > uint32(pProto->MaxCount))
8535 if(no_space_count)
8536 *no_space_count = count +curcount - pProto->MaxCount;
8537 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8540 return EQUIP_ERR_OK;
8543 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8545 Item *pItem;
8546 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8548 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8549 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8550 return true;
8552 for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8554 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8555 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8556 return true;
8558 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8560 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8562 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8564 pItem = GetItemByPos( i, j );
8565 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8566 return true;
8570 return false;
8573 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8575 Item* pItem2 = GetItemByPos( bag, slot );
8577 // ignore move item (this slot will be empty at move)
8578 if(pItem2==pSrcItem)
8579 pItem2 = NULL;
8581 uint32 need_space;
8583 // empty specific slot - check item fit to slot
8584 if( !pItem2 || swap )
8586 if( bag == INVENTORY_SLOT_BAG_0 )
8588 // keyring case
8589 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8590 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8592 // currencytoken case (disabled until proper implement)
8593 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8594 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8596 // prevent cheating
8597 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8598 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8600 else
8602 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8603 if( !pBag )
8604 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8606 ItemPrototype const* pBagProto = pBag->GetProto();
8607 if( !pBagProto )
8608 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8610 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8611 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8614 // non empty stack with space
8615 need_space = pProto->GetMaxStackSize();
8617 // non empty slot, check item type
8618 else
8620 // check item type
8621 if(pItem2->GetEntry() != pProto->ItemId)
8622 return EQUIP_ERR_ITEM_CANT_STACK;
8624 // check free space
8625 if(pItem2->GetCount() >= pProto->GetMaxStackSize())
8626 return EQUIP_ERR_ITEM_CANT_STACK;
8628 // free stack space or infinity
8629 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8632 if(need_space > count)
8633 need_space = count;
8635 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8636 if(!newPosition.isContainedIn(dest))
8638 dest.push_back(newPosition);
8639 count -= need_space;
8641 return EQUIP_ERR_OK;
8644 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
8646 // skip specific bag already processed in first called _CanStoreItem_InBag
8647 if(bag==skip_bag)
8648 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8650 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8651 if( !pBag )
8652 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8654 ItemPrototype const* pBagProto = pBag->GetProto();
8655 if( !pBagProto )
8656 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8658 // specialized bag mode or non-specilized
8659 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8660 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8662 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8663 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8665 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8667 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8668 if(j==skip_slot)
8669 continue;
8671 Item* pItem2 = GetItemByPos( bag, j );
8673 // ignore move item (this slot will be empty at move)
8674 if(pItem2==pSrcItem)
8675 pItem2 = NULL;
8677 // if merge skip empty, if !merge skip non-empty
8678 if((pItem2!=NULL)!=merge)
8679 continue;
8681 if( pItem2 )
8683 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8685 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8686 if(need_space > count)
8687 need_space = count;
8689 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8690 if(!newPosition.isContainedIn(dest))
8692 dest.push_back(newPosition);
8693 count -= need_space;
8695 if(count==0)
8696 return EQUIP_ERR_OK;
8700 else
8702 uint32 need_space = pProto->GetMaxStackSize();
8703 if(need_space > count)
8704 need_space = count;
8706 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8707 if(!newPosition.isContainedIn(dest))
8709 dest.push_back(newPosition);
8710 count -= need_space;
8712 if(count==0)
8713 return EQUIP_ERR_OK;
8717 return EQUIP_ERR_OK;
8720 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
8722 for(uint32 j = slot_begin; j < slot_end; ++j)
8724 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8725 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8726 continue;
8728 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8730 // ignore move item (this slot will be empty at move)
8731 if(pItem2==pSrcItem)
8732 pItem2 = NULL;
8734 // if merge skip empty, if !merge skip non-empty
8735 if((pItem2!=NULL)!=merge)
8736 continue;
8738 if( pItem2 )
8740 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8742 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8743 if(need_space > count)
8744 need_space = count;
8745 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8746 if(!newPosition.isContainedIn(dest))
8748 dest.push_back(newPosition);
8749 count -= need_space;
8751 if(count==0)
8752 return EQUIP_ERR_OK;
8756 else
8758 uint32 need_space = pProto->GetMaxStackSize();
8759 if(need_space > count)
8760 need_space = count;
8762 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8763 if(!newPosition.isContainedIn(dest))
8765 dest.push_back(newPosition);
8766 count -= need_space;
8768 if(count==0)
8769 return EQUIP_ERR_OK;
8773 return EQUIP_ERR_OK;
8776 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8778 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8780 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8781 if( !pProto )
8783 if(no_space_count)
8784 *no_space_count = count;
8785 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8788 if(pItem && pItem->IsBindedNotWith(GetGUID()))
8790 if(no_space_count)
8791 *no_space_count = count;
8792 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8795 // check count of items (skip for auto move for same player from bank)
8796 uint32 no_similar_count = 0; // can't store this amount similar items
8797 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8798 if(res!=EQUIP_ERR_OK)
8800 if(count==no_similar_count)
8802 if(no_space_count)
8803 *no_space_count = no_similar_count;
8804 return res;
8806 count -= no_similar_count;
8809 // in specific slot
8810 if( bag != NULL_BAG && slot != NULL_SLOT )
8812 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8813 if(res!=EQUIP_ERR_OK)
8815 if(no_space_count)
8816 *no_space_count = count + no_similar_count;
8817 return res;
8820 if(count==0)
8822 if(no_similar_count==0)
8823 return EQUIP_ERR_OK;
8825 if(no_space_count)
8826 *no_space_count = count + no_similar_count;
8827 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8831 // not specific slot or have space for partly store only in specific slot
8833 // in specific bag
8834 if( bag != NULL_BAG )
8836 // search stack in bag for merge to
8837 if( pProto->Stackable != 1 )
8839 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8841 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8842 if(res!=EQUIP_ERR_OK)
8844 if(no_space_count)
8845 *no_space_count = count + no_similar_count;
8846 return res;
8849 if(count==0)
8851 if(no_similar_count==0)
8852 return EQUIP_ERR_OK;
8854 if(no_space_count)
8855 *no_space_count = count + no_similar_count;
8856 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8859 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8860 if(res!=EQUIP_ERR_OK)
8862 if(no_space_count)
8863 *no_space_count = count + no_similar_count;
8864 return res;
8867 if(count==0)
8869 if(no_similar_count==0)
8870 return EQUIP_ERR_OK;
8872 if(no_space_count)
8873 *no_space_count = count + no_similar_count;
8874 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8877 else // equipped bag
8879 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8880 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
8881 if(res!=EQUIP_ERR_OK)
8882 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
8884 if(res!=EQUIP_ERR_OK)
8886 if(no_space_count)
8887 *no_space_count = count + no_similar_count;
8888 return res;
8891 if(count==0)
8893 if(no_similar_count==0)
8894 return EQUIP_ERR_OK;
8896 if(no_space_count)
8897 *no_space_count = count + no_similar_count;
8898 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8903 // search free slot in bag for place to
8904 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8906 // search free slot - keyring case
8907 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
8909 uint32 keyringSize = GetMaxKeyringSize();
8910 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
8911 if(res!=EQUIP_ERR_OK)
8913 if(no_space_count)
8914 *no_space_count = count + no_similar_count;
8915 return res;
8918 if(count==0)
8920 if(no_similar_count==0)
8921 return EQUIP_ERR_OK;
8923 if(no_space_count)
8924 *no_space_count = count + no_similar_count;
8925 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8928 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8929 if(res!=EQUIP_ERR_OK)
8931 if(no_space_count)
8932 *no_space_count = count + no_similar_count;
8933 return res;
8936 if(count==0)
8938 if(no_similar_count==0)
8939 return EQUIP_ERR_OK;
8941 if(no_space_count)
8942 *no_space_count = count + no_similar_count;
8943 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8946 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
8948 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8949 if(res!=EQUIP_ERR_OK)
8951 if(no_space_count)
8952 *no_space_count = count + no_similar_count;
8953 return res;
8956 if(count==0)
8958 if(no_similar_count==0)
8959 return EQUIP_ERR_OK;
8961 if(no_space_count)
8962 *no_space_count = count + no_similar_count;
8963 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8967 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
8968 if(res!=EQUIP_ERR_OK)
8970 if(no_space_count)
8971 *no_space_count = count + no_similar_count;
8972 return res;
8975 if(count==0)
8977 if(no_similar_count==0)
8978 return EQUIP_ERR_OK;
8980 if(no_space_count)
8981 *no_space_count = count + no_similar_count;
8982 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8985 else // equipped bag
8987 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
8988 if(res!=EQUIP_ERR_OK)
8989 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
8991 if(res!=EQUIP_ERR_OK)
8993 if(no_space_count)
8994 *no_space_count = count + no_similar_count;
8995 return res;
8998 if(count==0)
9000 if(no_similar_count==0)
9001 return EQUIP_ERR_OK;
9003 if(no_space_count)
9004 *no_space_count = count + no_similar_count;
9005 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9010 // not specific bag or have space for partly store only in specific bag
9012 // search stack for merge to
9013 if( pProto->Stackable != 1 )
9015 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9016 if(res!=EQUIP_ERR_OK)
9018 if(no_space_count)
9019 *no_space_count = count + no_similar_count;
9020 return res;
9023 if(count==0)
9025 if(no_similar_count==0)
9026 return EQUIP_ERR_OK;
9028 if(no_space_count)
9029 *no_space_count = count + no_similar_count;
9030 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9033 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9034 if(res!=EQUIP_ERR_OK)
9036 if(no_space_count)
9037 *no_space_count = count + no_similar_count;
9038 return res;
9041 if(count==0)
9043 if(no_similar_count==0)
9044 return EQUIP_ERR_OK;
9046 if(no_space_count)
9047 *no_space_count = count + no_similar_count;
9048 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9051 if( pProto->BagFamily )
9053 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9055 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9056 if(res!=EQUIP_ERR_OK)
9057 continue;
9059 if(count==0)
9061 if(no_similar_count==0)
9062 return EQUIP_ERR_OK;
9064 if(no_space_count)
9065 *no_space_count = count + no_similar_count;
9066 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9071 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9073 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9074 if(res!=EQUIP_ERR_OK)
9075 continue;
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 // search free slot - special bag case
9090 if( pProto->BagFamily )
9092 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9094 uint32 keyringSize = GetMaxKeyringSize();
9095 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9096 if(res!=EQUIP_ERR_OK)
9098 if(no_space_count)
9099 *no_space_count = count + no_similar_count;
9100 return res;
9103 if(count==0)
9105 if(no_similar_count==0)
9106 return EQUIP_ERR_OK;
9108 if(no_space_count)
9109 *no_space_count = count + no_similar_count;
9110 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9113 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9115 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9116 if(res!=EQUIP_ERR_OK)
9118 if(no_space_count)
9119 *no_space_count = count + no_similar_count;
9120 return res;
9123 if(count==0)
9125 if(no_similar_count==0)
9126 return EQUIP_ERR_OK;
9128 if(no_space_count)
9129 *no_space_count = count + no_similar_count;
9130 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9134 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9136 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9137 if(res!=EQUIP_ERR_OK)
9138 continue;
9140 if(count==0)
9142 if(no_similar_count==0)
9143 return EQUIP_ERR_OK;
9145 if(no_space_count)
9146 *no_space_count = count + no_similar_count;
9147 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9152 // search free slot
9153 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9154 if(res!=EQUIP_ERR_OK)
9156 if(no_space_count)
9157 *no_space_count = count + no_similar_count;
9158 return res;
9161 if(count==0)
9163 if(no_similar_count==0)
9164 return EQUIP_ERR_OK;
9166 if(no_space_count)
9167 *no_space_count = count + no_similar_count;
9168 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9171 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9173 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9174 if(res!=EQUIP_ERR_OK)
9175 continue;
9177 if(count==0)
9179 if(no_similar_count==0)
9180 return EQUIP_ERR_OK;
9182 if(no_space_count)
9183 *no_space_count = count + no_similar_count;
9184 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9188 if(no_space_count)
9189 *no_space_count = count + no_similar_count;
9191 return EQUIP_ERR_INVENTORY_FULL;
9194 //////////////////////////////////////////////////////////////////////////
9195 uint8 Player::CanStoreItems( Item **pItems,int count) const
9197 Item *pItem2;
9199 // fill space table
9200 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9201 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9202 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9203 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9205 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9206 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9207 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9208 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9210 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9212 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9214 if (pItem2 && !pItem2->IsInTrade())
9216 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9220 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
9222 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9224 if (pItem2 && !pItem2->IsInTrade())
9226 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9230 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9232 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9234 if (pItem2 && !pItem2->IsInTrade())
9236 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9240 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9242 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9244 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9246 pItem2 = GetItemByPos( i, j );
9247 if (pItem2 && !pItem2->IsInTrade())
9249 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9255 // check free space for all items
9256 for (int k=0;k<count;k++)
9258 Item *pItem = pItems[k];
9260 // no item
9261 if (!pItem) continue;
9263 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9264 ItemPrototype const *pProto = pItem->GetProto();
9266 // strange item
9267 if( !pProto )
9268 return EQUIP_ERR_ITEM_NOT_FOUND;
9270 // item it 'bind'
9271 if(pItem->IsBindedNotWith(GetGUID()))
9272 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9274 Bag *pBag;
9275 ItemPrototype const *pBagProto;
9277 // item is 'one item only'
9278 uint8 res = CanTakeMoreSimilarItems(pItem);
9279 if(res != EQUIP_ERR_OK)
9280 return res;
9282 // search stack for merge to
9283 if( pProto->Stackable != 1 )
9285 bool b_found = false;
9287 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
9289 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9290 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9292 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9293 b_found = true;
9294 break;
9297 if (b_found) continue;
9299 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; t++)
9301 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9302 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9304 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9305 b_found = true;
9306 break;
9309 if (b_found) continue;
9311 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9313 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9314 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9316 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9317 b_found = true;
9318 break;
9321 if (b_found) continue;
9323 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9325 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9326 if( pBag )
9328 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9330 pItem2 = GetItemByPos( t, j );
9331 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9333 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9334 b_found = true;
9335 break;
9340 if (b_found) continue;
9343 // special bag case
9344 if( pProto->BagFamily )
9346 bool b_found = false;
9347 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9349 uint32 keyringSize = GetMaxKeyringSize();
9350 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9352 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9354 inv_keys[t-KEYRING_SLOT_START] = 1;
9355 b_found = true;
9356 break;
9361 if (b_found) continue;
9363 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9365 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9367 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9369 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9370 b_found = true;
9371 break;
9376 if (b_found) continue;
9378 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9380 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9381 if( pBag )
9383 pBagProto = pBag->GetProto();
9385 // not plain container check
9386 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9387 ItemCanGoIntoBag(pProto,pBagProto) )
9389 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9391 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9393 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9394 b_found = true;
9395 break;
9401 if (b_found) continue;
9404 // search free slot
9405 bool b_found = false;
9406 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9408 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9410 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9411 b_found = true;
9412 break;
9415 if (b_found) continue;
9417 // search free slot in bags
9418 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9420 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9421 if( pBag )
9423 pBagProto = pBag->GetProto();
9425 // special bag already checked
9426 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9427 continue;
9429 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9431 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9433 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9434 b_found = true;
9435 break;
9441 // no free slot found?
9442 if (!b_found)
9443 return EQUIP_ERR_INVENTORY_FULL;
9446 return EQUIP_ERR_OK;
9449 //////////////////////////////////////////////////////////////////////////
9450 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9452 dest = 0;
9453 Item *pItem = Item::CreateItem( item, 1, this );
9454 if( pItem )
9456 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9457 delete pItem;
9458 return result;
9461 return EQUIP_ERR_ITEM_NOT_FOUND;
9464 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9466 dest = 0;
9467 if( pItem )
9469 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9470 ItemPrototype const *pProto = pItem->GetProto();
9471 if( pProto )
9473 if(pItem->IsBindedNotWith(GetGUID()))
9474 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9476 // check count of items (skip for auto move for same player from bank)
9477 uint8 res = CanTakeMoreSimilarItems(pItem);
9478 if(res != EQUIP_ERR_OK)
9479 return res;
9481 // check this only in game
9482 if(not_loading)
9484 // May be here should be more stronger checks; STUNNED checked
9485 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9486 if (hasUnitState(UNIT_STAT_STUNNED))
9487 return EQUIP_ERR_YOU_ARE_STUNNED;
9489 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9490 // - combat
9491 // - in-progress arenas
9492 if( !pProto->CanChangeEquipStateInCombat() )
9494 if( isInCombat() )
9495 return EQUIP_ERR_NOT_IN_COMBAT;
9497 if(BattleGround* bg = GetBattleGround())
9498 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9499 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9502 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9503 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9505 if(IsNonMeleeSpellCasted(false))
9506 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9509 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9510 if( eslot == NULL_SLOT )
9511 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9513 uint8 msg = CanUseItem( pItem , not_loading );
9514 if( msg != EQUIP_ERR_OK )
9515 return msg;
9516 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9517 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9519 // if swap ignore item (equipped also)
9520 if(uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9521 return res2;
9523 // check unique-equipped special item classes
9524 if (pProto->Class == ITEM_CLASS_QUIVER)
9526 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9528 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9530 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9532 if( pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot ) )
9534 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9535 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9536 else
9537 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9544 uint32 type = pProto->InventoryType;
9546 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9548 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9550 if(!CanDualWield())
9551 return EQUIP_ERR_CANT_DUAL_WIELD;
9553 else if (type == INVTYPE_2HWEAPON)
9555 if(!CanDualWield() || !CanTitanGrip())
9556 return EQUIP_ERR_CANT_DUAL_WIELD;
9559 if(IsTwoHandUsed())
9560 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9563 // equip two-hand weapon case (with possible unequip 2 items)
9564 if( type == INVTYPE_2HWEAPON )
9566 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9568 if (!CanTitanGrip())
9569 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9571 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9572 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9574 if (!CanTitanGrip())
9576 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9577 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9578 ItemPosCountVec off_dest;
9579 if( offItem && (!not_loading ||
9580 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9581 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
9582 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9585 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9586 return EQUIP_ERR_OK;
9589 if( !swap )
9590 return EQUIP_ERR_ITEM_NOT_FOUND;
9591 else
9592 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9595 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9597 // Applied only to equipped items and bank bags
9598 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9599 return EQUIP_ERR_OK;
9601 Item* pItem = GetItemByPos(pos);
9603 // Applied only to existed equipped item
9604 if( !pItem )
9605 return EQUIP_ERR_OK;
9607 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9609 ItemPrototype const *pProto = pItem->GetProto();
9610 if( !pProto )
9611 return EQUIP_ERR_ITEM_NOT_FOUND;
9613 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9614 // - combat
9615 // - in-progress arenas
9616 if( !pProto->CanChangeEquipStateInCombat() )
9618 if( isInCombat() )
9619 return EQUIP_ERR_NOT_IN_COMBAT;
9621 if(BattleGround* bg = GetBattleGround())
9622 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9623 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9626 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9627 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9629 return EQUIP_ERR_OK;
9632 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9634 if( !pItem )
9635 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9637 uint32 count = pItem->GetCount();
9639 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9640 ItemPrototype const *pProto = pItem->GetProto();
9641 if( !pProto )
9642 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9644 if( pItem->IsBindedNotWith(GetGUID()) )
9645 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9647 // check count of items (skip for auto move for same player from bank)
9648 uint8 res = CanTakeMoreSimilarItems(pItem);
9649 if(res != EQUIP_ERR_OK)
9650 return res;
9652 // in specific slot
9653 if( bag != NULL_BAG && slot != NULL_SLOT )
9655 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9657 if (!pItem->IsBag())
9658 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9660 if( !HasBankBagSlot( slot ) )
9661 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9663 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
9664 return cantuse;
9667 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9668 if(res!=EQUIP_ERR_OK)
9669 return res;
9671 if(count==0)
9672 return EQUIP_ERR_OK;
9675 // not specific slot or have space for partly store only in specific slot
9677 // in specific bag
9678 if( bag != NULL_BAG )
9680 if( pProto->InventoryType == INVTYPE_BAG )
9682 Bag *pBag = (Bag*)pItem;
9683 if( pBag && !pBag->IsEmpty() )
9684 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9687 // search stack in bag for merge to
9688 if( pProto->Stackable != 1 )
9690 if( bag == INVENTORY_SLOT_BAG_0 )
9692 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9693 if(res!=EQUIP_ERR_OK)
9694 return res;
9696 if(count==0)
9697 return EQUIP_ERR_OK;
9699 else
9701 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9702 if(res!=EQUIP_ERR_OK)
9703 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9705 if(res!=EQUIP_ERR_OK)
9706 return res;
9708 if(count==0)
9709 return EQUIP_ERR_OK;
9713 // search free slot in bag
9714 if( bag == INVENTORY_SLOT_BAG_0 )
9716 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9717 if(res!=EQUIP_ERR_OK)
9718 return res;
9720 if(count==0)
9721 return EQUIP_ERR_OK;
9723 else
9725 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9726 if(res!=EQUIP_ERR_OK)
9727 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9729 if(res!=EQUIP_ERR_OK)
9730 return res;
9732 if(count==0)
9733 return EQUIP_ERR_OK;
9737 // not specific bag or have space for partly store only in specific bag
9739 // search stack for merge to
9740 if( pProto->Stackable != 1 )
9742 // in slots
9743 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9744 if(res!=EQUIP_ERR_OK)
9745 return res;
9747 if(count==0)
9748 return EQUIP_ERR_OK;
9750 // in special bags
9751 if( pProto->BagFamily )
9753 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9755 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9756 if(res!=EQUIP_ERR_OK)
9757 continue;
9759 if(count==0)
9760 return EQUIP_ERR_OK;
9764 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9766 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9767 if(res!=EQUIP_ERR_OK)
9768 continue;
9770 if(count==0)
9771 return EQUIP_ERR_OK;
9775 // search free place in special bag
9776 if( pProto->BagFamily )
9778 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9780 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9781 if(res!=EQUIP_ERR_OK)
9782 continue;
9784 if(count==0)
9785 return EQUIP_ERR_OK;
9789 // search free space
9790 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9791 if(res!=EQUIP_ERR_OK)
9792 return res;
9794 if(count==0)
9795 return EQUIP_ERR_OK;
9797 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9799 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9800 if(res!=EQUIP_ERR_OK)
9801 continue;
9803 if(count==0)
9804 return EQUIP_ERR_OK;
9806 return EQUIP_ERR_BANK_FULL;
9809 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
9811 if( pItem )
9813 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
9814 if( !isAlive() && not_loading )
9815 return EQUIP_ERR_YOU_ARE_DEAD;
9816 //if( isStunned() )
9817 // return EQUIP_ERR_YOU_ARE_STUNNED;
9818 ItemPrototype const *pProto = pItem->GetProto();
9819 if( pProto )
9821 if( pItem->IsBindedNotWith(GetGUID()) )
9822 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9823 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9824 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9825 if( pItem->GetSkill() != 0 )
9827 if( GetSkillValue( pItem->GetSkill() ) == 0 )
9828 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9830 if( pProto->RequiredSkill != 0 )
9832 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9833 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9834 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9835 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9837 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9838 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9839 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
9840 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9841 if( getLevel() < pProto->RequiredLevel )
9842 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9843 return EQUIP_ERR_OK;
9846 return EQUIP_ERR_ITEM_NOT_FOUND;
9849 bool Player::CanUseItem( ItemPrototype const *pProto )
9851 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9853 if( pProto )
9855 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9856 return false;
9857 if( pProto->RequiredSkill != 0 )
9859 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9860 return false;
9861 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9862 return false;
9864 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9865 return false;
9866 if( getLevel() < pProto->RequiredLevel )
9867 return false;
9868 return true;
9870 return false;
9873 uint8 Player::CanUseAmmo( uint32 item ) const
9875 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
9876 if( !isAlive() )
9877 return EQUIP_ERR_YOU_ARE_DEAD;
9878 //if( isStunned() )
9879 // return EQUIP_ERR_YOU_ARE_STUNNED;
9880 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
9881 if( pProto )
9883 if( pProto->InventoryType!= INVTYPE_AMMO )
9884 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
9885 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9886 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9887 if( pProto->RequiredSkill != 0 )
9889 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9890 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9891 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9892 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9894 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9895 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9896 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
9897 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9899 if( getLevel() < pProto->RequiredLevel )
9900 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9902 // Requires No Ammo
9903 if(GetDummyAura(46699))
9904 return EQUIP_ERR_BAG_FULL6;
9906 return EQUIP_ERR_OK;
9908 return EQUIP_ERR_ITEM_NOT_FOUND;
9911 void Player::SetAmmo( uint32 item )
9913 if(!item)
9914 return;
9916 // already set
9917 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
9918 return;
9920 // check ammo
9921 if(item)
9923 uint8 msg = CanUseAmmo( item );
9924 if( msg != EQUIP_ERR_OK )
9926 SendEquipError( msg, NULL, NULL );
9927 return;
9931 SetUInt32Value(PLAYER_AMMO_ID, item);
9933 _ApplyAmmoBonuses();
9936 void Player::RemoveAmmo()
9938 SetUInt32Value(PLAYER_AMMO_ID, 0);
9940 m_ammoDPS = 0.0f;
9942 if(CanModifyStats())
9943 UpdateDamagePhysical(RANGED_ATTACK);
9946 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9947 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
9949 uint32 count = 0;
9950 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
9951 count += itr->count;
9953 Item *pItem = Item::CreateItem( item, count, this );
9954 if( pItem )
9956 ItemAddedQuestCheck( item, count );
9957 if(randomPropertyId)
9958 pItem->SetItemRandomProperties(randomPropertyId);
9959 pItem = StoreItem( dest, pItem, update );
9961 return pItem;
9964 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
9966 if( !pItem )
9967 return NULL;
9969 Item* lastItem = pItem;
9970 uint32 entry = pItem->GetEntry();
9971 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
9973 uint16 pos = itr->pos;
9974 uint32 count = itr->count;
9976 ++itr;
9978 if(itr == dest.end())
9980 lastItem = _StoreItem(pos,pItem,count,false,update);
9981 break;
9984 lastItem = _StoreItem(pos,pItem,count,true,update);
9986 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
9987 return lastItem;
9990 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9991 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
9993 if( !pItem )
9994 return NULL;
9996 uint8 bag = pos >> 8;
9997 uint8 slot = pos & 255;
9999 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10001 Item *pItem2 = GetItemByPos( bag, slot );
10003 if (!pItem2)
10005 if (clone)
10006 pItem = pItem->CloneItem(count,this);
10007 else
10008 pItem->SetCount(count);
10010 if (!pItem)
10011 return NULL;
10013 if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10014 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10015 (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10016 pItem->SetBinding( true );
10018 if (bag == INVENTORY_SLOT_BAG_0)
10020 m_items[slot] = pItem;
10021 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10022 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10023 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10025 pItem->SetSlot( slot );
10026 pItem->SetContainer( NULL );
10028 // need update known currency
10029 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10030 UpdateKnownCurrencies(pItem->GetEntry(),true);
10032 if (IsInWorld() && update)
10034 pItem->AddToWorld();
10035 pItem->SendUpdateToPlayer( this );
10038 pItem->SetState(ITEM_CHANGED, this);
10040 else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10042 pBag->StoreItem( slot, pItem, update );
10043 if( IsInWorld() && update )
10045 pItem->AddToWorld();
10046 pItem->SendUpdateToPlayer( this );
10048 pItem->SetState(ITEM_CHANGED, this);
10049 pBag->SetState(ITEM_CHANGED, this);
10052 AddEnchantmentDurations(pItem);
10053 AddItemDurations(pItem);
10055 return pItem;
10057 else
10059 if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10060 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10061 (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10062 pItem2->SetBinding( true );
10064 pItem2->SetCount( pItem2->GetCount() + count );
10065 if (IsInWorld() && update)
10066 pItem2->SendUpdateToPlayer( this );
10068 if (!clone)
10070 // delete item (it not in any slot currently)
10071 if (IsInWorld() && update)
10073 pItem->RemoveFromWorld();
10074 pItem->DestroyForPlayer( this );
10077 RemoveEnchantmentDurations(pItem);
10078 RemoveItemDurations(pItem);
10080 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10081 pItem->SetState(ITEM_REMOVED, this);
10084 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10085 AddEnchantmentDurations(pItem2);
10087 pItem2->SetState(ITEM_CHANGED, this);
10089 return pItem2;
10093 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10095 if (Item *pItem = Item::CreateItem( item, 1, this ))
10097 ItemAddedQuestCheck( item, 1 );
10098 return EquipItem( pos, pItem, update );
10101 return NULL;
10104 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10107 AddEnchantmentDurations(pItem);
10108 AddItemDurations(pItem);
10110 uint8 bag = pos >> 8;
10111 uint8 slot = pos & 255;
10113 Item *pItem2 = GetItemByPos( bag, slot );
10115 if( !pItem2 )
10117 VisualizeItem( slot, pItem);
10119 if(isAlive())
10121 ItemPrototype const *pProto = pItem->GetProto();
10123 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10124 if(pProto && pProto->ItemSet)
10125 AddItemsSetItem(this,pItem);
10127 _ApplyItemMods(pItem, slot, true);
10129 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10131 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10133 if (getClass() == CLASS_ROGUE)
10134 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10136 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10138 if (!spellProto)
10139 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10140 else
10142 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10144 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10145 data << uint64(GetGUID());
10146 data << uint8(1);
10147 data << uint32(cooldownSpell);
10148 data << uint32(0);
10149 GetSession()->SendPacket(&data);
10154 if( IsInWorld() && update )
10156 pItem->AddToWorld();
10157 pItem->SendUpdateToPlayer( this );
10160 ApplyEquipCooldown(pItem);
10162 if( slot == EQUIPMENT_SLOT_MAINHAND )
10163 UpdateExpertise(BASE_ATTACK);
10164 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10165 UpdateExpertise(OFF_ATTACK);
10167 else
10169 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10170 if( IsInWorld() && update )
10171 pItem2->SendUpdateToPlayer( this );
10173 // delete item (it not in any slot currently)
10174 //pItem->DeleteFromDB();
10175 if( IsInWorld() && update )
10177 pItem->RemoveFromWorld();
10178 pItem->DestroyForPlayer( this );
10181 RemoveEnchantmentDurations(pItem);
10182 RemoveItemDurations(pItem);
10184 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10185 pItem->SetState(ITEM_REMOVED, this);
10186 pItem2->SetState(ITEM_CHANGED, this);
10188 ApplyEquipCooldown(pItem2);
10190 return pItem2;
10193 // only for full equip instead adding to stack
10194 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10196 return pItem;
10199 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10201 if( pItem )
10203 AddEnchantmentDurations(pItem);
10204 AddItemDurations(pItem);
10206 uint8 slot = pos & 255;
10207 VisualizeItem( slot, pItem);
10209 if( IsInWorld() )
10211 pItem->AddToWorld();
10212 pItem->SendUpdateToPlayer( this );
10217 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10219 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10220 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10221 // entry // Size: 1
10222 // inspected enchantments // Size: 6
10223 // ? // Size: 5
10224 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10225 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10226 // // = 16
10228 if(pItem)
10230 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
10231 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), pItem->GetEnchantmentId(EnchantmentSlot(0)));
10233 else
10235 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
10236 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
10240 void Player::VisualizeItem( uint8 slot, Item *pItem)
10242 if(!pItem)
10243 return;
10245 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10246 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10247 pItem->SetBinding( true );
10249 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10251 m_items[slot] = pItem;
10252 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10253 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10254 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10255 pItem->SetSlot( slot );
10256 pItem->SetContainer( NULL );
10258 if( slot < EQUIPMENT_SLOT_END )
10259 SetVisibleItemSlot(slot,pItem);
10261 pItem->SetState(ITEM_CHANGED, this);
10264 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10266 // note: removeitem does not actually change the item
10267 // it only takes the item out of storage temporarily
10268 // note2: if removeitem is to be used for delinking
10269 // the item must be removed from the player's updatequeue
10271 Item *pItem = GetItemByPos( bag, slot );
10272 if( pItem )
10274 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10276 RemoveEnchantmentDurations(pItem);
10277 RemoveItemDurations(pItem);
10279 if( bag == INVENTORY_SLOT_BAG_0 )
10281 if ( slot < INVENTORY_SLOT_BAG_END )
10283 ItemPrototype const *pProto = pItem->GetProto();
10284 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10286 if(pProto && pProto->ItemSet)
10287 RemoveItemsSetItem(this,pProto);
10289 _ApplyItemMods(pItem, slot, false);
10291 // remove item dependent auras and casts (only weapon and armor slots)
10292 if(slot < EQUIPMENT_SLOT_END)
10294 RemoveItemDependentAurasAndCasts(pItem);
10296 // remove held enchantments, update expertise
10297 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10299 if (pItem->GetItemSuffixFactor())
10301 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10302 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10304 else
10306 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10307 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10310 UpdateExpertise(BASE_ATTACK);
10312 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10313 UpdateExpertise(OFF_ATTACK);
10316 // need update known currency
10317 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10318 UpdateKnownCurrencies(pItem->GetEntry(),false);
10320 m_items[slot] = NULL;
10321 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10323 if ( slot < EQUIPMENT_SLOT_END )
10324 SetVisibleItemSlot(slot,NULL);
10326 else
10328 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10329 if( pBag )
10330 pBag->RemoveItem(slot, update);
10332 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10333 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10334 pItem->SetSlot( NULL_SLOT );
10335 if( IsInWorld() && update )
10336 pItem->SendUpdateToPlayer( this );
10340 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10341 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10343 if(Item* it = GetItemByPos(bag,slot))
10345 ItemRemovedQuestCheck(it->GetEntry(),it->GetCount());
10346 RemoveItem( bag,slot,update);
10347 it->RemoveFromUpdateQueueOf(this);
10348 if(it->IsInWorld())
10350 it->RemoveFromWorld();
10351 it->DestroyForPlayer( this );
10356 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10357 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10359 // update quest counters
10360 ItemAddedQuestCheck(pItem->GetEntry(),pItem->GetCount());
10362 // store item
10363 Item* pLastItem = StoreItem( dest, pItem, update);
10365 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10366 if(pLastItem==pItem)
10368 // update owner for last item (this can be original item with wrong owner
10369 if(pLastItem->GetOwnerGUID() != GetGUID())
10370 pLastItem->SetOwnerGUID(GetGUID());
10372 // if this original item then it need create record in inventory
10373 // in case trade we already have item in other player inventory
10374 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10378 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10380 Item *pItem = GetItemByPos( bag, slot );
10381 if( pItem )
10383 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10385 // start from destroy contained items (only equipped bag can have its)
10386 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10388 for (int i = 0; i < MAX_BAG_SIZE; ++i)
10389 DestroyItem(slot,i,update);
10392 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10393 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10395 RemoveEnchantmentDurations(pItem);
10396 RemoveItemDurations(pItem);
10398 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10400 if( bag == INVENTORY_SLOT_BAG_0 )
10402 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10404 // equipment and equipped bags can have applied bonuses
10405 if ( slot < INVENTORY_SLOT_BAG_END )
10407 ItemPrototype const *pProto = pItem->GetProto();
10409 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10410 if(pProto && pProto->ItemSet)
10411 RemoveItemsSetItem(this,pProto);
10413 _ApplyItemMods(pItem, slot, false);
10416 if ( slot < EQUIPMENT_SLOT_END )
10418 // remove item dependent auras and casts (only weapon and armor slots)
10419 RemoveItemDependentAurasAndCasts(pItem);
10421 // update expertise
10422 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10423 UpdateExpertise(BASE_ATTACK);
10424 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10425 UpdateExpertise(OFF_ATTACK);
10427 // equipment visual show
10428 SetVisibleItemSlot(slot,NULL);
10430 // need update known currency
10431 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10432 UpdateKnownCurrencies(pItem->GetEntry(),false);
10434 m_items[slot] = NULL;
10436 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10437 pBag->RemoveItem(slot, update);
10439 if( IsInWorld() && update )
10441 pItem->RemoveFromWorld();
10442 pItem->DestroyForPlayer(this);
10445 //pItem->SetOwnerGUID(0);
10446 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10447 pItem->SetSlot( NULL_SLOT );
10448 pItem->SetState(ITEM_REMOVED, this);
10452 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10454 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10455 uint32 remcount = 0;
10457 // in inventory
10458 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10460 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10462 if (pItem->GetEntry() == item)
10464 if (pItem->GetCount() + remcount <= count)
10466 // all items in inventory can unequipped
10467 remcount += pItem->GetCount();
10468 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10470 if (remcount >=count)
10471 return;
10473 else
10475 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10476 pItem->SetCount( pItem->GetCount() - count + remcount );
10477 if (IsInWorld() & update)
10478 pItem->SendUpdateToPlayer( this );
10479 pItem->SetState(ITEM_CHANGED, this);
10480 return;
10486 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10488 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10490 if (pItem->GetEntry() == item)
10492 if (pItem->GetCount() + remcount <= count)
10494 // all keys can be unequipped
10495 remcount += pItem->GetCount();
10496 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10498 if (remcount >=count)
10499 return;
10501 else
10503 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10504 pItem->SetCount( pItem->GetCount() - count + remcount );
10505 if (IsInWorld() & update)
10506 pItem->SendUpdateToPlayer( this );
10507 pItem->SetState(ITEM_CHANGED, this);
10508 return;
10514 // in inventory bags
10515 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10517 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10519 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10521 if(Item* pItem = pBag->GetItemByPos(j))
10523 if (pItem->GetEntry() == item)
10525 // all items in bags can be unequipped
10526 if (pItem->GetCount() + remcount <= count)
10528 remcount += pItem->GetCount();
10529 DestroyItem( i, j, update );
10531 if (remcount >=count)
10532 return;
10534 else
10536 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10537 pItem->SetCount( pItem->GetCount() - count + remcount );
10538 if (IsInWorld() && update)
10539 pItem->SendUpdateToPlayer( this );
10540 pItem->SetState(ITEM_CHANGED, this);
10541 return;
10549 // in equipment and bag list
10550 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10552 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10554 if (pItem && pItem->GetEntry() == item)
10556 if (pItem->GetCount() + remcount <= count)
10558 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
10560 remcount += pItem->GetCount();
10561 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10563 if (remcount >=count)
10564 return;
10567 else
10569 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10570 pItem->SetCount( pItem->GetCount() - count + remcount );
10571 if (IsInWorld() & update)
10572 pItem->SendUpdateToPlayer( this );
10573 pItem->SetState(ITEM_CHANGED, this);
10574 return;
10581 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10583 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10585 // in inventory
10586 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10587 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10588 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone))
10589 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10591 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10592 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10593 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone))
10594 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10596 // in inventory bags
10597 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10598 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10599 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10600 if (Item* pItem = pBag->GetItemByPos(j))
10601 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone))
10602 DestroyItem( i, j, update);
10604 // in equipment and bag list
10605 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10606 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10607 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone))
10608 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10611 void Player::DestroyConjuredItems( bool update )
10613 // used when entering arena
10614 // destroys all conjured items
10615 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10617 // in inventory
10618 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10619 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10620 if (pItem->IsConjuredConsumable())
10621 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10623 // in inventory bags
10624 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10625 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10626 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10627 if (Item* pItem = pBag->GetItemByPos(j))
10628 if (pItem->IsConjuredConsumable())
10629 DestroyItem( i, j, update);
10631 // in equipment and bag list
10632 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10633 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10634 if (pItem->IsConjuredConsumable())
10635 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10638 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10640 if(!pItem)
10641 return;
10643 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10645 if( pItem->GetCount() <= count )
10647 count-= pItem->GetCount();
10649 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10651 else
10653 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10654 pItem->SetCount( pItem->GetCount() - count );
10655 count = 0;
10656 if( IsInWorld() & update )
10657 pItem->SendUpdateToPlayer( this );
10658 pItem->SetState(ITEM_CHANGED, this);
10662 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10664 uint8 srcbag = src >> 8;
10665 uint8 srcslot = src & 255;
10667 uint8 dstbag = dst >> 8;
10668 uint8 dstslot = dst & 255;
10670 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10671 if( !pSrcItem )
10673 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10674 return;
10677 // not let split all items (can be only at cheating)
10678 if(pSrcItem->GetCount() == count)
10680 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10681 return;
10684 // not let split more existed items (can be only at cheating)
10685 if(pSrcItem->GetCount() < count)
10687 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10688 return;
10691 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10693 //best error message found for attempting to split while looting
10694 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10695 return;
10698 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10699 Item *pNewItem = pSrcItem->CloneItem( count, this );
10700 if( !pNewItem )
10702 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10703 return;
10706 if( IsInventoryPos( dst ) )
10708 // change item amount before check (for unique max count check)
10709 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10711 ItemPosCountVec dest;
10712 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10713 if( msg != EQUIP_ERR_OK )
10715 delete pNewItem;
10716 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10717 SendEquipError( msg, pSrcItem, NULL );
10718 return;
10721 if( IsInWorld() )
10722 pSrcItem->SendUpdateToPlayer( this );
10723 pSrcItem->SetState(ITEM_CHANGED, this);
10724 StoreItem( dest, pNewItem, true);
10726 else if( IsBankPos ( dst ) )
10728 // change item amount before check (for unique max count check)
10729 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10731 ItemPosCountVec dest;
10732 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
10733 if( msg != EQUIP_ERR_OK )
10735 delete pNewItem;
10736 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10737 SendEquipError( msg, pSrcItem, NULL );
10738 return;
10741 if( IsInWorld() )
10742 pSrcItem->SendUpdateToPlayer( this );
10743 pSrcItem->SetState(ITEM_CHANGED, this);
10744 BankItem( dest, pNewItem, true);
10746 else if( IsEquipmentPos ( dst ) )
10748 // change item amount before check (for unique max count check), provide space for splitted items
10749 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10751 uint16 dest;
10752 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
10753 if( msg != EQUIP_ERR_OK )
10755 delete pNewItem;
10756 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10757 SendEquipError( msg, pSrcItem, NULL );
10758 return;
10761 if( IsInWorld() )
10762 pSrcItem->SendUpdateToPlayer( this );
10763 pSrcItem->SetState(ITEM_CHANGED, this);
10764 EquipItem( dest, pNewItem, true);
10765 AutoUnequipOffhandIfNeed();
10769 void Player::SwapItem( uint16 src, uint16 dst )
10771 uint8 srcbag = src >> 8;
10772 uint8 srcslot = src & 255;
10774 uint8 dstbag = dst >> 8;
10775 uint8 dstslot = dst & 255;
10777 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10778 Item *pDstItem = GetItemByPos( dstbag, dstslot );
10780 if( !pSrcItem )
10781 return;
10783 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
10785 if(!isAlive() )
10787 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
10788 return;
10791 // SRC checks
10793 if(pSrcItem->m_lootGenerated) // prevent swap looting item
10795 //best error message found for attempting to swap while looting
10796 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
10797 return;
10800 // check unequip potability for equipped items and bank bags
10801 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
10803 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10804 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty());
10805 if(msg != EQUIP_ERR_OK)
10807 SendEquipError( msg, pSrcItem, pDstItem );
10808 return;
10812 // prevent put equipped/bank bag in self
10813 if( IsBagPos ( src ) && srcslot == dstbag)
10815 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
10816 return;
10819 // DST checks
10821 if (pDstItem)
10823 if(pDstItem->m_lootGenerated) // prevent swap looting item
10825 //best error message found for attempting to swap while looting
10826 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
10827 return;
10830 // check unequip potability for equipped items and bank bags
10831 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
10833 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10834 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty());
10835 if(msg != EQUIP_ERR_OK)
10837 SendEquipError( msg, pSrcItem, pDstItem );
10838 return;
10843 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
10844 // or swap empty bag with another empty or not empty bag (with items exchange)
10846 // Move case
10847 if( !pDstItem )
10849 if( IsInventoryPos( dst ) )
10851 ItemPosCountVec dest;
10852 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
10853 if( msg != EQUIP_ERR_OK )
10855 SendEquipError( msg, pSrcItem, NULL );
10856 return;
10859 RemoveItem(srcbag, srcslot, true);
10860 StoreItem( dest, pSrcItem, true);
10862 else if( IsBankPos ( dst ) )
10864 ItemPosCountVec dest;
10865 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
10866 if( msg != EQUIP_ERR_OK )
10868 SendEquipError( msg, pSrcItem, NULL );
10869 return;
10872 RemoveItem(srcbag, srcslot, true);
10873 BankItem( dest, pSrcItem, true);
10875 else if( IsEquipmentPos ( dst ) )
10877 uint16 dest;
10878 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
10879 if( msg != EQUIP_ERR_OK )
10881 SendEquipError( msg, pSrcItem, NULL );
10882 return;
10885 RemoveItem(srcbag, srcslot, true);
10886 EquipItem( dest, pSrcItem, true);
10887 AutoUnequipOffhandIfNeed();
10890 return;
10893 // attempt merge to / fill target item
10894 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
10896 uint8 msg;
10897 ItemPosCountVec sDest;
10898 uint16 eDest;
10899 if( IsInventoryPos( dst ) )
10900 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
10901 else if( IsBankPos ( dst ) )
10902 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
10903 else if( IsEquipmentPos ( dst ) )
10904 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
10905 else
10906 return;
10908 // can be merge/fill
10909 if(msg == EQUIP_ERR_OK)
10911 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
10913 RemoveItem(srcbag, srcslot, true);
10915 if( IsInventoryPos( dst ) )
10916 StoreItem( sDest, pSrcItem, true);
10917 else if( IsBankPos ( dst ) )
10918 BankItem( sDest, pSrcItem, true);
10919 else if( IsEquipmentPos ( dst ) )
10921 EquipItem( eDest, pSrcItem, true);
10922 AutoUnequipOffhandIfNeed();
10925 else
10927 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
10928 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
10929 pSrcItem->SetState(ITEM_CHANGED, this);
10930 pDstItem->SetState(ITEM_CHANGED, this);
10931 if( IsInWorld() )
10933 pSrcItem->SendUpdateToPlayer( this );
10934 pDstItem->SendUpdateToPlayer( this );
10937 return;
10941 // impossible merge/fill, do real swap
10942 uint8 msg;
10944 // check src->dest move possibility
10945 ItemPosCountVec sDest;
10946 uint16 eDest = 0;
10947 if( IsInventoryPos( dst ) )
10948 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
10949 else if( IsBankPos( dst ) )
10950 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
10951 else if( IsEquipmentPos( dst ) )
10953 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
10954 if( msg == EQUIP_ERR_OK )
10955 msg = CanUnequipItem( eDest, true );
10958 if( msg != EQUIP_ERR_OK )
10960 SendEquipError( msg, pSrcItem, pDstItem );
10961 return;
10964 // check dest->src move possibility
10965 ItemPosCountVec sDest2;
10966 uint16 eDest2 = 0;
10967 if( IsInventoryPos( src ) )
10968 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
10969 else if( IsBankPos( src ) )
10970 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
10971 else if( IsEquipmentPos( src ) )
10973 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
10974 if( msg == EQUIP_ERR_OK )
10975 msg = CanUnequipItem( eDest2, true);
10978 if( msg != EQUIP_ERR_OK )
10980 SendEquipError( msg, pDstItem, pSrcItem );
10981 return;
10984 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
10985 if(pSrcItem->IsBag() && pDstItem->IsBag())
10987 Bag* emptyBag = NULL;
10988 Bag* fullBag = NULL;
10989 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
10991 emptyBag = (Bag*)pSrcItem;
10992 fullBag = (Bag*)pDstItem;
10994 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
10996 emptyBag = (Bag*)pDstItem;
10997 fullBag = (Bag*)pSrcItem;
11000 // bag swap (with items exchange) case
11001 if(emptyBag && fullBag)
11003 ItemPrototype const* emotyProto = emptyBag->GetProto();
11005 uint32 count = 0;
11007 for(int i=0; i < fullBag->GetBagSize(); ++i)
11009 Item *bagItem = fullBag->GetItemByPos(i);
11010 if (!bagItem)
11011 continue;
11013 ItemPrototype const* bagItemProto = bagItem->GetProto();
11014 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11016 // one from items not go to empry target bag
11017 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11018 return;
11021 ++count;
11025 if (count > emptyBag->GetBagSize())
11027 // too small targeted bag
11028 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11029 return;
11032 // Items swap
11033 count = 0; // will pos in new bag
11034 for(int i=0; i< fullBag->GetBagSize(); ++i)
11036 Item *bagItem = fullBag->GetItemByPos(i);
11037 if (!bagItem)
11038 continue;
11040 fullBag->RemoveItem(i, true);
11041 emptyBag->StoreItem(count, bagItem, true);
11042 bagItem->SetState(ITEM_CHANGED, this);
11044 ++count;
11049 // now do moves, remove...
11050 RemoveItem(dstbag, dstslot, false);
11051 RemoveItem(srcbag, srcslot, false);
11053 // add to dest
11054 if( IsInventoryPos( dst ) )
11055 StoreItem(sDest, pSrcItem, true);
11056 else if( IsBankPos( dst ) )
11057 BankItem(sDest, pSrcItem, true);
11058 else if( IsEquipmentPos( dst ) )
11059 EquipItem(eDest, pSrcItem, true);
11061 // add to src
11062 if( IsInventoryPos( src ) )
11063 StoreItem(sDest2, pDstItem, true);
11064 else if( IsBankPos( src ) )
11065 BankItem(sDest2, pDstItem, true);
11066 else if( IsEquipmentPos( src ) )
11067 EquipItem(eDest2, pDstItem, true);
11069 AutoUnequipOffhandIfNeed();
11072 void Player::AddItemToBuyBackSlot( Item *pItem )
11074 if( pItem )
11076 uint32 slot = m_currentBuybackSlot;
11077 // if current back slot non-empty search oldest or free
11078 if(m_items[slot])
11080 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11081 uint32 oldest_slot = BUYBACK_SLOT_START;
11083 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11085 // found empty
11086 if(!m_items[i])
11088 slot = i;
11089 break;
11092 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11094 if(oldest_time > i_time)
11096 oldest_time = i_time;
11097 oldest_slot = i;
11101 // find oldest
11102 slot = oldest_slot;
11105 RemoveItemFromBuyBackSlot( slot, true );
11106 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11108 m_items[slot] = pItem;
11109 time_t base = time(NULL);
11110 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11111 uint32 eslot = slot - BUYBACK_SLOT_START;
11113 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
11114 ItemPrototype const *pProto = pItem->GetProto();
11115 if( pProto )
11116 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11117 else
11118 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11119 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11121 // move to next (for non filled list is move most optimized choice)
11122 if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
11123 ++m_currentBuybackSlot;
11127 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11129 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11130 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11131 return m_items[slot];
11132 return NULL;
11135 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11137 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11138 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11140 Item *pItem = m_items[slot];
11141 if( pItem )
11143 pItem->RemoveFromWorld();
11144 if(del) pItem->SetState(ITEM_REMOVED, this);
11147 m_items[slot] = NULL;
11149 uint32 eslot = slot - BUYBACK_SLOT_START;
11150 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
11151 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11152 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11154 // if current backslot is filled set to now free slot
11155 if(m_items[m_currentBuybackSlot])
11156 m_currentBuybackSlot = slot;
11160 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11162 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg);
11163 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11164 data << uint8(msg);
11166 if(msg)
11168 data << uint64(pItem ? pItem->GetGUID() : 0);
11169 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11170 data << uint8(0); // not 0 there...
11172 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11174 uint32 level = 0;
11176 if(pItem)
11177 if(ItemPrototype const* proto = pItem->GetProto())
11178 level = proto->RequiredLevel;
11180 data << uint32(level); // new 2.4.0
11183 GetSession()->SendPacket(&data);
11186 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11188 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11189 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11190 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11191 data << uint32(item);
11192 if( param > 0 )
11193 data << uint32(param);
11194 data << uint8(msg);
11195 GetSession()->SendPacket(&data);
11198 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11200 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11201 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11202 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11203 data << uint64(guid);
11204 if( param > 0 )
11205 data << uint32(param);
11206 data << uint8(msg);
11207 GetSession()->SendPacket(&data);
11210 void Player::ClearTrade()
11212 tradeGold = 0;
11213 acceptTrade = false;
11214 for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
11215 tradeItems[i] = NULL_SLOT;
11218 void Player::TradeCancel(bool sendback)
11220 if(pTrader)
11222 // send yellow "Trade canceled" message to both traders
11223 WorldSession* ws;
11224 ws = GetSession();
11225 if(sendback)
11226 ws->SendCancelTrade();
11227 ws = pTrader->GetSession();
11228 if(!ws->PlayerLogout())
11229 ws->SendCancelTrade();
11231 // cleanup
11232 ClearTrade();
11233 pTrader->ClearTrade();
11234 // prevent loss of reference
11235 pTrader->pTrader = NULL;
11236 pTrader = NULL;
11240 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11242 if(m_itemDuration.empty())
11243 return;
11245 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);
11247 for(ItemDurationList::const_iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
11249 Item* item = *itr;
11250 ++itr; // current element can be erased in UpdateDuration
11252 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11253 item->UpdateDuration(this,time);
11257 void Player::UpdateEnchantTime(uint32 time)
11259 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11261 assert(itr->item);
11262 next=itr;
11263 if(!itr->item->GetEnchantmentId(itr->slot))
11265 next = m_enchantDuration.erase(itr);
11267 else if(itr->leftduration <= time)
11269 ApplyEnchantment(itr->item,itr->slot,false,false);
11270 itr->item->ClearEnchantment(itr->slot);
11271 next = m_enchantDuration.erase(itr);
11273 else if(itr->leftduration > time)
11275 itr->leftduration -= time;
11276 ++next;
11281 void Player::AddEnchantmentDurations(Item *item)
11283 for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
11285 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11286 continue;
11288 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11289 if( duration > 0 )
11290 AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
11294 void Player::RemoveEnchantmentDurations(Item *item)
11296 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
11298 if(itr->item == item)
11300 // save duration in item
11301 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
11302 itr = m_enchantDuration.erase(itr);
11304 else
11305 ++itr;
11309 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11311 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11312 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11314 next = itr;
11315 if(itr->slot==slot)
11317 if(itr->item && itr->item->GetEnchantmentId(slot))
11319 // remove from stats
11320 ApplyEnchantment(itr->item,slot,false,false);
11321 // remove visual
11322 itr->item->ClearEnchantment(slot);
11324 // remove from update list
11325 next = m_enchantDuration.erase(itr);
11327 else
11328 ++next;
11331 // remove enchants from inventory items
11332 // NOTE: no need to remove these from stats, since these aren't equipped
11333 // in inventory
11334 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11336 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11337 if( pItem && pItem->GetEnchantmentId(slot) )
11338 pItem->ClearEnchantment(slot);
11341 // in inventory bags
11342 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11344 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11345 if( pBag )
11347 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11349 Item* pItem = pBag->GetItemByPos(j);
11350 if( pItem && pItem->GetEnchantmentId(slot) )
11351 pItem->ClearEnchantment(slot);
11357 // duration == 0 will remove item enchant
11358 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11360 if(!item)
11361 return;
11363 if(slot >= MAX_ENCHANTMENT_SLOT)
11364 return;
11366 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11368 if(itr->item == item && itr->slot == slot)
11370 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
11371 m_enchantDuration.erase(itr);
11372 break;
11375 if(item && duration > 0 )
11377 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
11378 m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
11382 void Player::ApplyEnchantment(Item *item,bool apply)
11384 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11385 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11388 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
11390 if(!item)
11391 return;
11393 if(!item->IsEquipped())
11394 return;
11396 if(slot >= MAX_ENCHANTMENT_SLOT)
11397 return;
11399 uint32 enchant_id = item->GetEnchantmentId(slot);
11400 if(!enchant_id)
11401 return;
11403 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11404 if(!pEnchant)
11405 return;
11407 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11408 return;
11410 if (!item->IsBroken())
11412 for (int s=0; s<3; s++)
11414 uint32 enchant_display_type = pEnchant->type[s];
11415 uint32 enchant_amount = pEnchant->amount[s];
11416 uint32 enchant_spell_id = pEnchant->spellid[s];
11418 switch(enchant_display_type)
11420 case ITEM_ENCHANTMENT_TYPE_NONE:
11421 break;
11422 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11423 // processed in Player::CastItemCombatSpell
11424 break;
11425 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11426 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11427 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11428 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11429 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11430 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11431 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11432 break;
11433 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11434 if(enchant_spell_id)
11436 if(apply)
11438 int32 basepoints = 0;
11439 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11440 if (item->GetItemRandomPropertyId())
11442 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11443 if (item_rand)
11445 // Search enchant_amount
11446 for (int k=0; k<3; k++)
11448 if(item_rand->enchant_id[k] == enchant_id)
11450 basepoints = int32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11451 break;
11456 // Cast custom spell vs all equal basepoints getted from enchant_amount
11457 if (basepoints)
11458 CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
11459 else
11460 CastSpell(this,enchant_spell_id,true,item);
11462 else
11463 RemoveAurasDueToItemSpell(item,enchant_spell_id);
11465 break;
11466 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11467 if (!enchant_amount)
11469 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11470 if(item_rand)
11472 for (int k=0; k<3; k++)
11474 if(item_rand->enchant_id[k] == enchant_id)
11476 enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11477 break;
11483 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11484 break;
11485 case ITEM_ENCHANTMENT_TYPE_STAT:
11487 if (!enchant_amount)
11489 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11490 if(item_rand_suffix)
11492 for (int k=0; k<3; k++)
11494 if(item_rand_suffix->enchant_id[k] == enchant_id)
11496 enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11497 break;
11503 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11504 switch (enchant_spell_id)
11506 case ITEM_MOD_AGILITY:
11507 sLog.outDebug("+ %u AGILITY",enchant_amount);
11508 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11509 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11510 break;
11511 case ITEM_MOD_STRENGTH:
11512 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11513 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11514 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11515 break;
11516 case ITEM_MOD_INTELLECT:
11517 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11518 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11519 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11520 break;
11521 case ITEM_MOD_SPIRIT:
11522 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11523 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11524 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11525 break;
11526 case ITEM_MOD_STAMINA:
11527 sLog.outDebug("+ %u STAMINA",enchant_amount);
11528 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11529 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11530 break;
11531 case ITEM_MOD_DEFENSE_SKILL_RATING:
11532 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11533 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11534 break;
11535 case ITEM_MOD_DODGE_RATING:
11536 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11537 sLog.outDebug("+ %u DODGE", enchant_amount);
11538 break;
11539 case ITEM_MOD_PARRY_RATING:
11540 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11541 sLog.outDebug("+ %u PARRY", enchant_amount);
11542 break;
11543 case ITEM_MOD_BLOCK_RATING:
11544 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11545 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11546 break;
11547 case ITEM_MOD_HIT_MELEE_RATING:
11548 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11549 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11550 break;
11551 case ITEM_MOD_HIT_RANGED_RATING:
11552 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11553 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11554 break;
11555 case ITEM_MOD_HIT_SPELL_RATING:
11556 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11557 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11558 break;
11559 case ITEM_MOD_CRIT_MELEE_RATING:
11560 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11561 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11562 break;
11563 case ITEM_MOD_CRIT_RANGED_RATING:
11564 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11565 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11566 break;
11567 case ITEM_MOD_CRIT_SPELL_RATING:
11568 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11569 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11570 break;
11571 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11572 // in Enchantments
11573 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11574 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11575 // break;
11576 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11577 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11578 // break;
11579 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11580 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11581 // break;
11582 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11583 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11584 // break;
11585 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11586 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11587 // break;
11588 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11589 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11590 // break;
11591 // case ITEM_MOD_HASTE_MELEE_RATING:
11592 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11593 // break;
11594 // case ITEM_MOD_HASTE_RANGED_RATING:
11595 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11596 // break;
11597 case ITEM_MOD_HASTE_SPELL_RATING:
11598 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11599 break;
11600 case ITEM_MOD_HIT_RATING:
11601 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11602 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11603 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11604 sLog.outDebug("+ %u HIT", enchant_amount);
11605 break;
11606 case ITEM_MOD_CRIT_RATING:
11607 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11608 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11609 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11610 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11611 break;
11612 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11613 // case ITEM_MOD_HIT_TAKEN_RATING:
11614 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11615 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11616 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11617 // break;
11618 // case ITEM_MOD_CRIT_TAKEN_RATING:
11619 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11620 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11621 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11622 // break;
11623 case ITEM_MOD_RESILIENCE_RATING:
11624 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11625 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11626 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11627 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11628 break;
11629 case ITEM_MOD_HASTE_RATING:
11630 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11631 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11632 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11633 sLog.outDebug("+ %u HASTE", enchant_amount);
11634 break;
11635 case ITEM_MOD_EXPERTISE_RATING:
11636 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11637 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11638 break;
11639 case ITEM_MOD_ATTACK_POWER:
11640 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
11641 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11642 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
11643 break;
11644 case ITEM_MOD_RANGED_ATTACK_POWER:
11645 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11646 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
11647 break;
11648 case ITEM_MOD_FERAL_ATTACK_POWER:
11649 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
11650 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
11651 break;
11652 case ITEM_MOD_SPELL_HEALING_DONE:
11653 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11654 sLog.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount);
11655 break;
11656 case ITEM_MOD_SPELL_DAMAGE_DONE:
11657 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11658 sLog.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount);
11659 break;
11660 case ITEM_MOD_MANA_REGENERATION:
11661 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
11662 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
11663 break;
11664 case ITEM_MOD_ARMOR_PENETRATION_RATING:
11665 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
11666 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
11667 break;
11668 case ITEM_MOD_SPELL_POWER:
11669 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11670 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11671 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
11672 break;
11673 default:
11674 break;
11676 break;
11678 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11680 if(getClass() == CLASS_SHAMAN)
11682 float addValue = 0.0f;
11683 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11685 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11686 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11688 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11690 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11691 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11694 break;
11696 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
11697 // processed in Player::CastItemUseSpell
11698 break;
11699 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
11700 // nothing do..
11701 break;
11702 default:
11703 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
11704 break;
11705 } /*switch(enchant_display_type)*/
11706 } /*for*/
11709 // visualize enchantment at player and equipped items
11710 if(slot == PERM_ENCHANTMENT_SLOT)
11712 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), apply ? item->GetEnchantmentId(slot) : 0);
11715 if(apply_dur)
11717 if(apply)
11719 // set duration
11720 uint32 duration = item->GetEnchantmentDuration(slot);
11721 if(duration > 0)
11722 AddEnchantmentDuration(item,slot,duration);
11724 else
11726 // duration == 0 will remove EnchantDuration
11727 AddEnchantmentDuration(item,slot,0);
11732 void Player::SendEnchantmentDurations()
11734 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11736 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
11740 void Player::SendItemDurations()
11742 for(ItemDurationList::const_iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
11744 (*itr)->SendTimeUpdate(this);
11748 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11750 if(!item) // prevent crash
11751 return;
11753 // last check 2.0.10
11754 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11755 data << GetGUID(); // player GUID
11756 data << uint32(received); // 0=looted, 1=from npc
11757 data << uint32(created); // 0=received, 1=created
11758 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11759 data << (uint8)item->GetBagSlot(); // bagslot
11760 // item slot, but when added to stack: 0xFFFFFFFF
11761 data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
11762 data << uint32(item->GetEntry()); // item id
11763 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11764 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11765 data << uint32(count); // count of items
11766 data << GetItemCount(item->GetEntry()); // count of items in inventory
11768 if (broadcast && GetGroup())
11769 GetGroup()->BroadcastPacket(&data, true);
11770 else
11771 GetSession()->SendPacket(&data);
11774 /*********************************************************/
11775 /*** QUEST SYSTEM ***/
11776 /*********************************************************/
11778 void Player::PrepareQuestMenu( uint64 guid )
11780 Object *pObject;
11781 QuestRelations* pObjectQR;
11782 QuestRelations* pObjectQIR;
11784 // pets also can have quests
11785 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
11786 if( pCreature )
11788 pObject = (Object*)pCreature;
11789 pObjectQR = &objmgr.mCreatureQuestRelations;
11790 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11792 else
11794 GameObject *pGameObject = GetMap()->GetGameObject(guid);
11795 if( pGameObject )
11797 pObject = (Object*)pGameObject;
11798 pObjectQR = &objmgr.mGOQuestRelations;
11799 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11801 else
11802 return;
11805 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11806 qm.ClearMenu();
11808 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
11810 uint32 quest_id = i->second;
11811 QuestStatus status = GetQuestStatus( quest_id );
11812 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
11813 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
11814 else if ( status == QUEST_STATUS_INCOMPLETE )
11815 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
11816 else if (status == QUEST_STATUS_AVAILABLE )
11817 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11820 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
11822 uint32 quest_id = i->second;
11823 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11824 if(!pQuest) continue;
11826 QuestStatus status = GetQuestStatus( quest_id );
11828 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
11829 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
11830 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
11831 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11835 void Player::SendPreparedQuest( uint64 guid )
11837 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
11838 if( questMenu.Empty() )
11839 return;
11841 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
11843 uint32 status = qmi0.m_qIcon;
11845 // single element case
11846 if ( questMenu.MenuItemCount() == 1 )
11848 // Auto open -- maybe also should verify there is no greeting
11849 uint32 quest_id = qmi0.m_qId;
11850 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11851 if ( pQuest )
11853 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
11854 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
11855 else if( status == DIALOG_STATUS_INCOMPLETE )
11856 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
11857 // Send completable on repeatable quest if player don't have quest
11858 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
11859 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
11860 else
11861 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
11864 // multiply entries
11865 else
11867 QEmote qe;
11868 qe._Delay = 0;
11869 qe._Emote = 0;
11870 std::string title = "";
11872 // need pet case for some quests
11873 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
11874 if( pCreature )
11876 uint32 textid = pCreature->GetNpcTextId();
11877 GossipText const* gossiptext = objmgr.GetGossipText(textid);
11878 if( !gossiptext )
11880 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11881 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11882 title = "";
11884 else
11886 qe = gossiptext->Options[0].Emotes[0];
11888 if(!gossiptext->Options[0].Text_0.empty())
11890 title = gossiptext->Options[0].Text_0;
11892 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11893 if (loc_idx >= 0)
11895 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11896 if (nl)
11898 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
11899 title = nl->Text_0[0][loc_idx];
11903 else
11905 title = gossiptext->Options[0].Text_1;
11907 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11908 if (loc_idx >= 0)
11910 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11911 if (nl)
11913 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
11914 title = nl->Text_1[0][loc_idx];
11920 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
11924 bool Player::IsActiveQuest( uint32 quest_id ) const
11926 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
11928 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
11931 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
11933 Object *pObject;
11934 QuestRelations* pObjectQR;
11935 QuestRelations* pObjectQIR;
11937 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
11938 if( pCreature )
11940 pObject = (Object*)pCreature;
11941 pObjectQR = &objmgr.mCreatureQuestRelations;
11942 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11944 else
11946 GameObject *pGameObject = GetMap()->GetGameObject(guid);
11947 if( pGameObject )
11949 pObject = (Object*)pGameObject;
11950 pObjectQR = &objmgr.mGOQuestRelations;
11951 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11953 else
11954 return NULL;
11957 uint32 nextQuestID = pQuest->GetNextQuestInChain();
11958 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
11960 if (itr->second == nextQuestID)
11961 return objmgr.GetQuestTemplate(nextQuestID);
11964 return NULL;
11967 bool Player::CanSeeStartQuest( Quest const *pQuest )
11969 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
11970 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
11971 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
11972 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
11974 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
11977 return false;
11980 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
11982 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
11983 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
11984 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
11985 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
11986 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
11987 && SatisfyQuestDay( pQuest, msg );
11990 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
11992 if( !SatisfyQuestLog( msg ) )
11993 return false;
11995 uint32 srcitem = pQuest->GetSrcItemId();
11996 if( srcitem > 0 )
11998 uint32 count = pQuest->GetSrcItemCount();
11999 ItemPosCountVec dest;
12000 uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12002 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12003 if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12004 return true;
12005 else if( msg2 != EQUIP_ERR_OK )
12007 SendEquipError( msg2, NULL, NULL );
12008 return false;
12011 return true;
12014 bool Player::CanCompleteQuest( uint32 quest_id )
12016 if( quest_id )
12018 QuestStatusData& q_status = mQuestStatus[quest_id];
12019 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12020 return false; // not allow re-complete quest
12022 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12024 if(!qInfo)
12025 return false;
12027 // auto complete quest
12028 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12029 return true;
12031 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12034 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12036 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12038 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12039 return false;
12043 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12045 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12047 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12048 continue;
12050 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12051 return false;
12055 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12056 return false;
12058 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12059 return false;
12061 if ( qInfo->GetRewOrReqMoney() < 0 )
12063 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12064 return false;
12067 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12068 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12069 return false;
12071 return true;
12074 return false;
12077 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12079 // Solve problem that player don't have the quest and try complete it.
12080 // if repeatable she must be able to complete event if player don't have it.
12081 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12082 if( !CanTakeQuest(pQuest, false) )
12083 return false;
12085 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12086 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12087 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12088 return false;
12090 if( !CanRewardQuest(pQuest, false) )
12091 return false;
12093 return true;
12096 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12098 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12099 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12100 return false;
12102 // daily quest can't be rewarded (25 daily quest already completed)
12103 if(!SatisfyQuestDay(pQuest,true))
12104 return false;
12106 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12107 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12108 return false;
12110 // prevent receive reward with quest items in bank
12111 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12113 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12115 if( pQuest->ReqItemCount[i]!= 0 &&
12116 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12118 if(msg)
12119 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12120 return false;
12125 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12126 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12127 return false;
12129 return true;
12132 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12134 // prevent receive reward with quest items in bank or for not completed quest
12135 if(!CanRewardQuest(pQuest,msg))
12136 return false;
12138 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12140 if( pQuest->RewChoiceItemId[reward] )
12142 ItemPosCountVec dest;
12143 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12144 if( res != EQUIP_ERR_OK )
12146 SendEquipError( res, NULL, NULL );
12147 return false;
12152 if ( pQuest->GetRewItemsCount() > 0 )
12154 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12156 if( pQuest->RewItemId[i] )
12158 ItemPosCountVec dest;
12159 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12160 if( res != EQUIP_ERR_OK )
12162 SendEquipError( res, NULL, NULL );
12163 return false;
12169 return true;
12172 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12174 uint16 log_slot = FindQuestSlot( 0 );
12175 assert(log_slot < MAX_QUEST_LOG_SIZE);
12177 uint32 quest_id = pQuest->GetQuestId();
12179 // if not exist then created with set uState==NEW and rewarded=false
12180 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12182 // check for repeatable quests status reset
12183 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12184 questStatusData.m_explored = false;
12186 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12188 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12189 questStatusData.m_itemcount[i] = 0;
12192 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12194 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12195 questStatusData.m_creatureOrGOcount[i] = 0;
12198 GiveQuestSourceItem( pQuest );
12199 AdjustQuestReqItemCount( pQuest, questStatusData );
12201 if( pQuest->GetRepObjectiveFaction() )
12202 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
12203 GetReputationMgr().SetVisible(factionEntry);
12205 uint32 qtime = 0;
12206 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12208 uint32 limittime = pQuest->GetLimitTime();
12210 // shared timed quest
12211 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12212 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
12214 AddTimedQuest( quest_id );
12215 questStatusData.m_timer = limittime * IN_MILISECONDS;
12216 qtime = static_cast<uint32>(time(NULL)) + limittime;
12218 else
12219 questStatusData.m_timer = 0;
12221 SetQuestSlot(log_slot, quest_id, qtime);
12223 if (questStatusData.uState != QUEST_NEW)
12224 questStatusData.uState = QUEST_CHANGED;
12226 //starting initial quest script
12227 if(questGiver && pQuest->GetQuestStartScript()!=0)
12228 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12230 // Some spells applied at quest activation
12231 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,true);
12232 if(saBounds.first != saBounds.second)
12234 uint32 zone, area;
12235 GetZoneAndAreaId(zone,area);
12237 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12238 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12239 if( !HasAura(itr->second->spellId,0) )
12240 CastSpell(this,itr->second->spellId,true);
12243 UpdateForQuestsGO();
12246 void Player::CompleteQuest( uint32 quest_id )
12248 if( quest_id )
12250 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12252 uint16 log_slot = FindQuestSlot( quest_id );
12253 if( log_slot < MAX_QUEST_LOG_SIZE)
12254 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12256 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12258 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12259 RewardQuest(qInfo,0,this,false);
12260 else
12261 SendQuestComplete( quest_id );
12266 void Player::IncompleteQuest( uint32 quest_id )
12268 if( quest_id )
12270 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12272 uint16 log_slot = FindQuestSlot( quest_id );
12273 if( log_slot < MAX_QUEST_LOG_SIZE)
12274 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12278 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12280 uint32 quest_id = pQuest->GetQuestId();
12282 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i )
12284 if ( pQuest->ReqItemId[i] )
12285 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12288 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12289 // SetTimedQuest( 0 );
12290 m_timedquests.erase(pQuest->GetQuestId());
12292 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12294 if( pQuest->RewChoiceItemId[reward] )
12296 ItemPosCountVec dest;
12297 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12299 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12300 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12305 if ( pQuest->GetRewItemsCount() > 0 )
12307 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12309 if( pQuest->RewItemId[i] )
12311 ItemPosCountVec dest;
12312 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12314 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12315 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12321 RewardReputation( pQuest );
12323 if( pQuest->GetRewSpellCast() > 0 )
12324 CastSpell( this, pQuest->GetRewSpellCast(), true);
12325 else if( pQuest->GetRewSpell() > 0)
12326 CastSpell( this, pQuest->GetRewSpell(), true);
12328 uint16 log_slot = FindQuestSlot( quest_id );
12329 if( log_slot < MAX_QUEST_LOG_SIZE)
12330 SetQuestSlot(log_slot,0);
12332 QuestStatusData& q_status = mQuestStatus[quest_id];
12334 // Not give XP in case already completed once repeatable quest
12335 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12337 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12338 GiveXP( XP , NULL );
12339 else
12341 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
12342 ModifyMoney( money );
12343 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
12346 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12347 if(pQuest->GetRewOrReqMoney())
12349 ModifyMoney( pQuest->GetRewOrReqMoney() );
12351 if(pQuest->GetRewOrReqMoney() > 0)
12352 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
12355 // honor reward
12356 if(pQuest->GetRewHonorableKills())
12357 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12359 // title reward
12360 if(pQuest->GetCharTitleId())
12362 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12363 SetTitle(titleEntry);
12366 if(pQuest->GetBonusTalents())
12368 m_questRewardTalentCount+=pQuest->GetBonusTalents();
12369 InitTalentForLevel();
12372 // Send reward mail
12373 if(pQuest->GetRewMailTemplateId())
12375 MailMessageType mailType;
12376 uint32 senderGuidOrEntry;
12377 switch(questGiver->GetTypeId())
12379 case TYPEID_UNIT:
12380 mailType = MAIL_CREATURE;
12381 senderGuidOrEntry = questGiver->GetEntry();
12382 break;
12383 case TYPEID_GAMEOBJECT:
12384 mailType = MAIL_GAMEOBJECT;
12385 senderGuidOrEntry = questGiver->GetEntry();
12386 break;
12387 case TYPEID_ITEM:
12388 mailType = MAIL_ITEM;
12389 senderGuidOrEntry = questGiver->GetEntry();
12390 break;
12391 case TYPEID_PLAYER:
12392 mailType = MAIL_NORMAL;
12393 senderGuidOrEntry = questGiver->GetGUIDLow();
12394 break;
12395 default:
12396 mailType = MAIL_NORMAL;
12397 senderGuidOrEntry = GetGUIDLow();
12398 break;
12401 Loot questMailLoot;
12403 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this,true);
12405 // fill mail
12406 MailItemsInfo mi; // item list preparing
12408 uint32 max_slot = questMailLoot.GetMaxSlotInLootFor(this);
12409 for(uint32 i = 0; mi.size() < MAX_MAIL_ITEMS && i < max_slot; ++i)
12411 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12413 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12415 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12416 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12421 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12424 if(pQuest->IsDaily())
12426 SetDailyQuestStatus(quest_id);
12427 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12430 if ( !pQuest->IsRepeatable() )
12431 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12432 else
12433 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12435 q_status.m_rewarded = true;
12437 if(announce)
12438 SendQuestReward( pQuest, XP, questGiver );
12440 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12441 if (pQuest->GetZoneOrSort() > 0)
12442 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
12443 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12444 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
12446 uint32 zone = 0;
12447 uint32 area = 0;
12449 // remove auras from spells with quest reward state limitations
12450 SpellAreaForQuestMapBounds saEndBounds = spellmgr.GetSpellAreaForQuestEndMapBounds(quest_id);
12451 if(saEndBounds.first != saEndBounds.second)
12453 GetZoneAndAreaId(zone,area);
12455 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
12456 if(!itr->second->IsFitToRequirements(this,zone,area))
12457 RemoveAurasDueToSpell(itr->second->spellId);
12460 // Some spells applied at quest reward
12461 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,false);
12462 if(saBounds.first != saBounds.second)
12464 if(!zone || !area)
12465 GetZoneAndAreaId(zone,area);
12467 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12468 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12469 if( !HasAura(itr->second->spellId,0) )
12470 CastSpell(this,itr->second->spellId,true);
12474 void Player::FailQuest( uint32 quest_id )
12476 if( quest_id )
12478 IncompleteQuest( quest_id );
12480 uint16 log_slot = FindQuestSlot( quest_id );
12481 if( log_slot < MAX_QUEST_LOG_SIZE)
12483 SetQuestSlotTimer(log_slot, 1 );
12484 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12486 SendQuestFailed( quest_id );
12490 void Player::FailTimedQuest( uint32 quest_id )
12492 if( quest_id )
12494 QuestStatusData& q_status = mQuestStatus[quest_id];
12496 q_status.m_timer = 0;
12497 if (q_status.uState != QUEST_NEW)
12498 q_status.uState = QUEST_CHANGED;
12500 IncompleteQuest( quest_id );
12502 uint16 log_slot = FindQuestSlot( quest_id );
12503 if( log_slot < MAX_QUEST_LOG_SIZE)
12505 SetQuestSlotTimer(log_slot, 1 );
12506 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12508 SendQuestTimerFailed( quest_id );
12512 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12514 int32 zoneOrSort = qInfo->GetZoneOrSort();
12515 int32 skillOrClass = qInfo->GetSkillOrClass();
12517 // skip zone zoneOrSort and 0 case skillOrClass
12518 if( zoneOrSort >= 0 && skillOrClass == 0 )
12519 return true;
12521 int32 questSort = -zoneOrSort;
12522 uint8 reqSortClass = ClassByQuestSort(questSort);
12524 // check class sort cases in zoneOrSort
12525 if( reqSortClass != 0 && getClass() != reqSortClass)
12527 if( msg )
12528 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12529 return false;
12532 // check class
12533 if( skillOrClass < 0 )
12535 uint8 reqClass = -int32(skillOrClass);
12536 if(getClass() != reqClass)
12538 if( msg )
12539 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12540 return false;
12543 // check skill
12544 else if( skillOrClass > 0 )
12546 uint32 reqSkill = skillOrClass;
12547 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12549 if( msg )
12550 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12551 return false;
12555 return true;
12558 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12560 if( getLevel() < qInfo->GetMinLevel() )
12562 if( msg )
12563 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12564 return false;
12566 return true;
12569 bool Player::SatisfyQuestLog( bool msg )
12571 // exist free slot
12572 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12573 return true;
12575 if( msg )
12577 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12578 GetSession()->SendPacket( &data );
12579 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12581 return false;
12584 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12586 // No previous quest (might be first quest in a series)
12587 if( qInfo->prevQuests.empty())
12588 return true;
12590 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12592 uint32 prevId = abs(*iter);
12594 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12595 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12597 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12599 // If any of the positive previous quests completed, return true
12600 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12602 // skip one-from-all exclusive group
12603 if(qPrevInfo->GetExclusiveGroup() >= 0)
12604 return true;
12606 // each-from-all exclusive group ( < 0)
12607 // can be start if only all quests in prev quest exclusive group completed and rewarded
12608 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12609 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12611 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12613 for(; iter2 != end; ++iter2)
12615 uint32 exclude_Id = iter2->second;
12617 // skip checked quest id, only state of other quests in group is interesting
12618 if(exclude_Id == prevId)
12619 continue;
12621 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12623 // alternative quest from group also must be completed and rewarded(reported)
12624 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12626 if( msg )
12627 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12628 return false;
12631 return true;
12633 // If any of the negative previous quests active, return true
12634 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12635 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12637 // skip one-from-all exclusive group
12638 if(qPrevInfo->GetExclusiveGroup() >= 0)
12639 return true;
12641 // each-from-all exclusive group ( < 0)
12642 // can be start if only all quests in prev quest exclusive group active
12643 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12644 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12646 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12648 for(; iter2 != end; ++iter2)
12650 uint32 exclude_Id = iter2->second;
12652 // skip checked quest id, only state of other quests in group is interesting
12653 if(exclude_Id == prevId)
12654 continue;
12656 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12658 // alternative quest from group also must be active
12659 if( i_exstatus == mQuestStatus.end() ||
12660 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12661 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12663 if( msg )
12664 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12665 return false;
12668 return true;
12673 // Has only positive prev. quests in non-rewarded state
12674 // and negative prev. quests in non-active state
12675 if( msg )
12676 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12678 return false;
12681 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12683 uint32 reqraces = qInfo->GetRequiredRaces();
12684 if ( reqraces == 0 )
12685 return true;
12686 if( (reqraces & getRaceMask()) == 0 )
12688 if( msg )
12689 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12690 return false;
12692 return true;
12695 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12697 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12698 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12700 if( msg )
12701 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12702 return false;
12705 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12706 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12708 if( msg )
12709 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12710 return false;
12713 return true;
12716 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12718 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12719 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12721 if( msg )
12722 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12723 return false;
12725 return true;
12728 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12730 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12732 if( msg )
12733 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12734 return false;
12736 return true;
12739 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12741 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12742 if(qInfo->GetExclusiveGroup() <= 0)
12743 return true;
12745 ObjectMgr::ExclusiveQuestGroups::const_iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12746 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12748 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12750 for(; iter != end; ++iter)
12752 uint32 exclude_Id = iter->second;
12754 // skip checked quest id, only state of other quests in group is interesting
12755 if(exclude_Id == qInfo->GetQuestId())
12756 continue;
12758 // not allow have daily quest if daily quest from exclusive group already recently completed
12759 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
12760 if( !SatisfyQuestDay(Nquest, false) )
12762 if( msg )
12763 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12764 return false;
12767 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12769 // alternative quest already started or completed
12770 if( i_exstatus != mQuestStatus.end()
12771 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12773 if( msg )
12774 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12775 return false;
12778 return true;
12781 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12783 if(!qInfo->GetNextQuestInChain())
12784 return true;
12786 // next quest in chain already started or completed
12787 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12788 if( itr != mQuestStatus.end()
12789 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12791 if( msg )
12792 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12793 return false;
12796 // check for all quests further up the chain
12797 // only necessary if there are quest chains with more than one quest that can be skipped
12798 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12799 return true;
12802 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12804 // No previous quest in chain
12805 if( qInfo->prevChainQuests.empty())
12806 return true;
12808 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12810 uint32 prevId = *iter;
12812 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12814 if( i_prevstatus != mQuestStatus.end() )
12816 // If any of the previous quests in chain active, return false
12817 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12818 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12820 if( msg )
12821 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12822 return false;
12826 // check for all quests further down the chain
12827 // only necessary if there are quest chains with more than one quest that can be skipped
12828 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12829 // return false;
12832 // No previous quest in chain active
12833 return true;
12836 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12838 if(!qInfo->IsDaily())
12839 return true;
12841 bool have_slot = false;
12842 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12844 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12845 if(qInfo->GetQuestId()==id)
12846 return false;
12848 if(!id)
12849 have_slot = true;
12852 if(!have_slot)
12854 if( msg )
12855 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
12856 return false;
12859 return true;
12862 bool Player::GiveQuestSourceItem( Quest const *pQuest )
12864 uint32 srcitem = pQuest->GetSrcItemId();
12865 if( srcitem > 0 )
12867 uint32 count = pQuest->GetSrcItemCount();
12868 if( count <= 0 )
12869 count = 1;
12871 ItemPosCountVec dest;
12872 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12873 if( msg == EQUIP_ERR_OK )
12875 Item * item = StoreNewItem(dest, srcitem, true);
12876 SendNewItem(item, count, true, false);
12877 return true;
12879 // player already have max amount required item, just report success
12880 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12881 return true;
12882 else
12883 SendEquipError( msg, NULL, NULL );
12884 return false;
12887 return true;
12890 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
12892 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12893 if( qInfo )
12895 uint32 srcitem = qInfo->GetSrcItemId();
12896 if( srcitem > 0 )
12898 uint32 count = qInfo->GetSrcItemCount();
12899 if( count <= 0 )
12900 count = 1;
12902 // exist one case when destroy source quest item not possible:
12903 // non un-equippable item (equipped non-empty bag, for example)
12904 uint8 res = CanUnequipItems(srcitem,count);
12905 if(res != EQUIP_ERR_OK)
12907 if(msg)
12908 SendEquipError( res, NULL, NULL );
12909 return false;
12912 DestroyItemCount(srcitem, count, true, true);
12915 return true;
12918 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
12920 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12921 if( qInfo )
12923 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12924 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12925 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
12926 && !qInfo->IsRepeatable() )
12927 return itr->second.m_rewarded;
12929 return false;
12931 return false;
12934 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
12936 if( quest_id )
12938 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12939 if( itr != mQuestStatus.end() )
12940 return itr->second.m_status;
12942 return QUEST_STATUS_NONE;
12945 bool Player::CanShareQuest(uint32 quest_id) const
12947 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12948 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
12950 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12951 if( itr != mQuestStatus.end() )
12952 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
12954 return false;
12957 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
12959 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12960 if( qInfo )
12962 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
12964 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12965 m_timedquests.erase(qInfo->GetQuestId());
12968 QuestStatusData& q_status = mQuestStatus[quest_id];
12970 q_status.m_status = status;
12971 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12974 UpdateForQuestsGO();
12977 // not used in MaNGOS, but used in scripting code
12978 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
12980 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12981 if( !qInfo )
12982 return 0;
12984 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
12985 if ( qInfo->ReqCreatureOrGOId[j] == entry )
12986 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
12988 return 0;
12991 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
12993 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12995 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12997 uint32 reqitemcount = pQuest->ReqItemCount[i];
12998 if( reqitemcount != 0 )
13000 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13002 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13003 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13009 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13011 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13012 if ( GetQuestSlotQuestId(i) == quest_id )
13013 return i;
13015 return MAX_QUEST_LOG_SIZE;
13018 void Player::AreaExploredOrEventHappens( uint32 questId )
13020 if( questId )
13022 uint16 log_slot = FindQuestSlot( questId );
13023 if( log_slot < MAX_QUEST_LOG_SIZE)
13025 QuestStatusData& q_status = mQuestStatus[questId];
13027 if(!q_status.m_explored)
13029 q_status.m_explored = true;
13030 if (q_status.uState != QUEST_NEW)
13031 q_status.uState = QUEST_CHANGED;
13034 if( CanCompleteQuest( questId ) )
13035 CompleteQuest( questId );
13039 //not used in mangosd, function for external script library
13040 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13042 if( Group *pGroup = GetGroup() )
13044 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13046 Player *pGroupGuy = itr->getSource();
13048 // for any leave or dead (with not released body) group member at appropriate distance
13049 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13050 pGroupGuy->AreaExploredOrEventHappens(questId);
13053 else
13054 AreaExploredOrEventHappens(questId);
13057 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13059 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13061 uint32 questid = GetQuestSlotQuestId(i);
13062 if ( questid == 0 )
13063 continue;
13065 QuestStatusData& q_status = mQuestStatus[questid];
13067 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13068 continue;
13070 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13071 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13072 continue;
13074 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13076 uint32 reqitem = qInfo->ReqItemId[j];
13077 if ( reqitem == entry )
13079 uint32 reqitemcount = qInfo->ReqItemCount[j];
13080 uint32 curitemcount = q_status.m_itemcount[j];
13081 if ( curitemcount < reqitemcount )
13083 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13084 q_status.m_itemcount[j] += additemcount;
13085 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13087 SendQuestUpdateAddItem( qInfo, j, additemcount );
13089 if ( CanCompleteQuest( questid ) )
13090 CompleteQuest( questid );
13091 return;
13095 UpdateForQuestsGO();
13098 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13100 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13102 uint32 questid = GetQuestSlotQuestId(i);
13103 if(!questid)
13104 continue;
13105 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13106 if ( !qInfo )
13107 continue;
13108 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13109 continue;
13111 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13113 uint32 reqitem = qInfo->ReqItemId[j];
13114 if ( reqitem == entry )
13116 QuestStatusData& q_status = mQuestStatus[questid];
13118 uint32 reqitemcount = qInfo->ReqItemCount[j];
13119 uint32 curitemcount;
13120 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13121 curitemcount = q_status.m_itemcount[j];
13122 else
13123 curitemcount = GetItemCount(entry,true);
13124 if ( curitemcount < reqitemcount + count )
13126 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13127 q_status.m_itemcount[j] = curitemcount - remitemcount;
13128 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13130 IncompleteQuest( questid );
13132 return;
13136 UpdateForQuestsGO();
13139 void Player::KilledMonster( uint32 entry, uint64 guid )
13141 uint32 addkillcount = 1;
13142 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13143 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13145 uint32 questid = GetQuestSlotQuestId(i);
13146 if(!questid)
13147 continue;
13149 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13150 if( !qInfo )
13151 continue;
13152 // just if !ingroup || !noraidgroup || raidgroup
13153 QuestStatusData& q_status = mQuestStatus[questid];
13154 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13156 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13158 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13160 // skip GO activate objective or none
13161 if(qInfo->ReqCreatureOrGOId[j] <=0)
13162 continue;
13164 // skip Cast at creature objective
13165 if(qInfo->ReqSpell[j] !=0 )
13166 continue;
13168 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13170 if ( reqkill == entry )
13172 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13173 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13174 if ( curkillcount < reqkillcount )
13176 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13177 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13179 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13181 if ( CanCompleteQuest( questid ) )
13182 CompleteQuest( questid );
13184 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13185 continue;
13193 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13195 bool isCreature = IS_CREATURE_GUID(guid);
13197 uint32 addCastCount = 1;
13198 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
13200 uint32 questid = GetQuestSlotQuestId(i);
13201 if(!questid)
13202 continue;
13204 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13205 if ( !qInfo )
13206 continue;
13208 QuestStatusData& q_status = mQuestStatus[questid];
13210 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13212 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13214 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13216 // skip kill creature objective (0) or wrong spell casts
13217 if(qInfo->ReqSpell[j] != spell_id )
13218 continue;
13220 uint32 reqTarget = 0;
13222 if(isCreature)
13224 // creature activate objectives
13225 if(qInfo->ReqCreatureOrGOId[j] > 0)
13226 // checked at quest_template loading
13227 reqTarget = qInfo->ReqCreatureOrGOId[j];
13229 else
13231 // GO activate objective
13232 if(qInfo->ReqCreatureOrGOId[j] < 0)
13233 // checked at quest_template loading
13234 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13237 // other not this creature/GO related objectives
13238 if( reqTarget != entry )
13239 continue;
13241 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13242 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13243 if ( curCastCount < reqCastCount )
13245 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13246 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13248 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13251 if ( CanCompleteQuest( questid ) )
13252 CompleteQuest( questid );
13254 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13255 break;
13262 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13264 uint32 addTalkCount = 1;
13265 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13267 uint32 questid = GetQuestSlotQuestId(i);
13268 if(!questid)
13269 continue;
13271 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13272 if ( !qInfo )
13273 continue;
13275 QuestStatusData& q_status = mQuestStatus[questid];
13277 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13279 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13281 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13283 // skip spell casts and Gameobject objectives
13284 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13285 continue;
13287 uint32 reqTarget = 0;
13289 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13290 // checked at quest_template loading
13291 reqTarget = qInfo->ReqCreatureOrGOId[j];
13292 else
13293 continue;
13295 if ( reqTarget == entry )
13297 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13298 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13299 if ( curTalkCount < reqTalkCount )
13301 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13302 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13304 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13306 if ( CanCompleteQuest( questid ) )
13307 CompleteQuest( questid );
13309 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13310 continue;
13318 void Player::MoneyChanged( uint32 count )
13320 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13322 uint32 questid = GetQuestSlotQuestId(i);
13323 if (!questid)
13324 continue;
13326 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13327 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13329 QuestStatusData& q_status = mQuestStatus[questid];
13331 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13333 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13335 if ( CanCompleteQuest( questid ) )
13336 CompleteQuest( questid );
13339 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13341 if(int32(count) < -qInfo->GetRewOrReqMoney())
13342 IncompleteQuest( questid );
13348 void Player::ReputationChanged(FactionEntry const* factionEntry )
13350 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13352 if(uint32 questid = GetQuestSlotQuestId(i))
13354 if(Quest const* qInfo = objmgr.GetQuestTemplate(questid))
13356 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
13358 QuestStatusData& q_status = mQuestStatus[questid];
13359 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13361 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
13362 if ( CanCompleteQuest( questid ) )
13363 CompleteQuest( questid );
13365 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13367 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
13368 IncompleteQuest( questid );
13376 bool Player::HasQuestForItem( uint32 itemid ) const
13378 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13380 uint32 questid = GetQuestSlotQuestId(i);
13381 if ( questid == 0 )
13382 continue;
13384 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
13385 if(qs_itr == mQuestStatus.end())
13386 continue;
13388 QuestStatusData const& q_status = qs_itr->second;
13390 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13392 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
13393 if(!qinfo)
13394 continue;
13396 // hide quest if player is in raid-group and quest is no raid quest
13397 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13398 continue;
13400 // There should be no mixed ReqItem/ReqSource drop
13401 // This part for ReqItem drop
13402 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13404 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13405 return true;
13407 // This part - for ReqSource
13408 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
13410 // examined item is a source item
13411 if (qinfo->ReqSourceId[j] == itemid)
13413 ItemPrototype const *pProto = objmgr.GetItemPrototype(itemid);
13415 // 'unique' item
13416 if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
13417 return true;
13419 // allows custom amount drop when not 0
13420 if (qinfo->ReqSourceCount[j])
13422 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13423 return true;
13424 } else if (GetItemCount(itemid,true) < pProto->Stackable)
13425 return true;
13430 return false;
13433 void Player::SendQuestComplete( uint32 quest_id )
13435 if( quest_id )
13437 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13438 data << uint32(quest_id);
13439 GetSession()->SendPacket( &data );
13440 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13444 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13446 uint32 questid = pQuest->GetQuestId();
13447 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13448 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13449 data << uint32(questid);
13451 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13453 data << uint32(XP);
13454 data << uint32(pQuest->GetRewOrReqMoney());
13456 else
13458 data << uint32(0);
13459 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13462 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13463 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13464 GetSession()->SendPacket( &data );
13466 if (pQuest->GetQuestCompleteScript() != 0)
13467 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13470 void Player::SendQuestFailed( uint32 quest_id )
13472 if( quest_id )
13474 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13475 data << quest_id;
13476 data << uint32(0); // failed reason (4 for inventory is full)
13477 GetSession()->SendPacket( &data );
13478 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13482 void Player::SendQuestTimerFailed( uint32 quest_id )
13484 if( quest_id )
13486 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13487 data << quest_id;
13488 GetSession()->SendPacket( &data );
13489 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13493 void Player::SendCanTakeQuestResponse( uint32 msg )
13495 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13496 data << uint32(msg);
13497 GetSession()->SendPacket( &data );
13498 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13501 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13503 if( pPlayer )
13505 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13506 data << uint64(pPlayer->GetGUID());
13507 data << uint8(msg); // valid values: 0-8
13508 GetSession()->SendPacket( &data );
13509 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13513 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13515 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13516 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13517 //data << pQuest->ReqItemId[item_idx];
13518 //data << count;
13519 GetSession()->SendPacket( &data );
13522 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13524 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13526 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13527 if (entry < 0)
13528 // client expected gameobject template id in form (id|0x80000000)
13529 entry = (-entry) | 0x80000000;
13531 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13532 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13533 data << uint32(pQuest->GetQuestId());
13534 data << uint32(entry);
13535 data << uint32(old_count + add_count);
13536 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13537 data << uint64(guid);
13538 GetSession()->SendPacket(&data);
13540 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13541 if( log_slot < MAX_QUEST_LOG_SIZE)
13542 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13545 /*********************************************************/
13546 /*** LOAD SYSTEM ***/
13547 /*********************************************************/
13549 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13551 bool delete_result = true;
13552 if(!result)
13554 // 0 1 2 3 4 5 6 7 8 9
13555 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13556 if(!result) return false;
13558 else delete_result = false;
13560 Field *fields = result->Fetch();
13562 if(!LoadValues( fields[1].GetString()))
13564 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
13565 if(delete_result) delete result;
13566 return false;
13569 // overwrite possible wrong/corrupted guid
13570 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13572 m_name = fields[2].GetCppString();
13574 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13575 SetMapId(fields[6].GetUInt32());
13576 // the instance id is not needed at character enum
13578 m_Played_time[0] = fields[7].GetUInt32();
13579 m_Played_time[1] = fields[8].GetUInt32();
13581 m_atLoginFlags = fields[9].GetUInt32();
13583 // I don't see these used anywhere ..
13584 /*_LoadGroup();
13586 _LoadBoundInstances();*/
13588 if (delete_result) delete result;
13590 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
13591 m_items[i] = NULL;
13593 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13594 m_deathState = DEAD;
13596 return true;
13599 void Player::_LoadDeclinedNames(QueryResult* result)
13601 if(!result)
13602 return;
13604 if(m_declinedname)
13605 delete m_declinedname;
13607 m_declinedname = new DeclinedName;
13608 Field *fields = result->Fetch();
13609 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13610 m_declinedname->name[i] = fields[i].GetCppString();
13612 delete result;
13615 void Player::_LoadArenaTeamInfo(QueryResult *result)
13617 // arenateamid, played_week, played_season, personal_rating
13618 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
13619 if (!result)
13620 return;
13624 Field *fields = result->Fetch();
13626 uint32 arenateamid = fields[0].GetUInt32();
13627 uint32 played_week = fields[1].GetUInt32();
13628 uint32 played_season = fields[2].GetUInt32();
13629 uint32 personal_rating = fields[3].GetUInt32();
13631 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
13632 if(!aTeam)
13634 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
13635 continue;
13637 uint8 arenaSlot = aTeam->GetSlot();
13639 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
13640 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
13641 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
13642 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
13643 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
13644 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
13646 }while (result->NextRow());
13647 delete result;
13650 void Player::_LoadEquipmentSets(QueryResult *result)
13652 // SetPQuery(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS, "SELECT setguid, setindex, name, iconname, item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18 FROM character_equipmentsets WHERE guid = '%u' ORDER BY setindex", GUID_LOPART(m_guid));
13653 if (!result)
13654 return;
13656 uint32 count = 0;
13659 Field *fields = result->Fetch();
13661 EquipmentSet eqSet;
13663 eqSet.Guid = fields[0].GetUInt64();
13664 uint32 index = fields[1].GetUInt32();
13665 eqSet.Name = fields[2].GetCppString();
13666 eqSet.IconName = fields[3].GetCppString();
13667 eqSet.state = EQUIPMENT_SET_UNCHANGED;
13669 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
13670 eqSet.Items[i] = fields[4+i].GetUInt32();
13672 m_EquipmentSets[index] = eqSet;
13674 ++count;
13676 if(count >= MAX_EQUIPMENT_SET_INDEX) // client limit
13677 break;
13678 } while (result->NextRow());
13679 delete result;
13682 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13684 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13685 if(!result)
13686 return false;
13688 Field *fields = result->Fetch();
13690 x = fields[0].GetFloat();
13691 y = fields[1].GetFloat();
13692 z = fields[2].GetFloat();
13693 o = fields[3].GetFloat();
13694 mapid = fields[4].GetUInt32();
13695 in_flight = !fields[5].GetCppString().empty();
13697 delete result;
13698 return true;
13701 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13703 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13704 if( !result )
13705 return false;
13707 Field *fields = result->Fetch();
13709 data = StrSplit(fields[0].GetCppString(), " ");
13711 delete result;
13713 return true;
13716 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13718 if(index >= data.size())
13719 return 0;
13721 return (uint32)atoi(data[index].c_str());
13724 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13726 float result;
13727 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13728 memcpy(&result, &temp, sizeof(result));
13730 return result;
13733 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13735 Tokens data;
13736 if(!LoadValuesArrayFromDB(data,guid))
13737 return 0;
13739 return GetUInt32ValueFromArray(data,index);
13742 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13744 float result;
13745 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13746 memcpy(&result, &temp, sizeof(result));
13748 return result;
13751 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
13753 //// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 [28] [29] 30 31 32 33 34 35 36 37 38 39 40
13754 //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty, arena_pending_points,bgid,bgteam,bgmap,bgx,bgy,bgz,bgo FROM characters WHERE guid = '%u'", guid);
13755 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
13757 if(!result)
13759 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
13760 return false;
13763 Field *fields = result->Fetch();
13765 uint32 dbAccountId = fields[1].GetUInt32();
13767 // check if the character's account in the db and the logged in account match.
13768 // player should be able to load/delete character only with correct account!
13769 if( dbAccountId != GetSession()->GetAccountId() )
13771 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
13772 delete result;
13773 return false;
13776 Object::_Create( guid, 0, HIGHGUID_PLAYER );
13778 m_name = fields[3].GetCppString();
13780 // check name limitations
13781 if(!ObjectMgr::IsValidName(m_name) || (GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name)))
13783 delete result;
13784 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
13785 return false;
13788 if(!LoadValues( fields[2].GetString()))
13790 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13791 delete result;
13792 return false;
13795 // overwrite possible wrong/corrupted guid
13796 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13798 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13799 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
13801 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), 0 );
13802 SetVisibleItemSlot(slot,NULL);
13804 if (m_items[slot])
13806 delete m_items[slot];
13807 m_items[slot] = NULL;
13811 // update money limits
13812 if(GetMoney() > MAX_MONEY_AMOUNT)
13813 SetMoney(MAX_MONEY_AMOUNT);
13815 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
13816 outDebugValues();
13818 m_race = fields[4].GetUInt8();
13819 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13820 //Other way is to saves m_team into characters table.
13821 setFactionForRace(m_race);
13822 SetCharm(NULL);
13824 m_class = fields[5].GetUInt8();
13826 // load home bind and check in same time class/race pair, it used later for restore broken positions
13827 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
13828 return false;
13830 InitPrimaryProffesions(); // to max set before any spell loaded
13832 // init saved position, and fix it later if problematic
13833 uint32 transGUID = fields[24].GetUInt32();
13834 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
13835 SetMapId(fields[9].GetUInt32());
13836 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
13838 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
13840 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
13842 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[33].GetUInt32();
13843 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
13844 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
13846 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
13848 // check arena teams integrity
13849 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
13851 uint32 arena_team_id = GetArenaTeamId(arena_slot);
13852 if(!arena_team_id)
13853 continue;
13855 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
13856 if(at->HaveMember(GetGUID()))
13857 continue;
13859 // arena team not exist or not member, cleanup fields
13860 for(int j =0; j < 6; ++j)
13861 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
13864 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
13866 if(!IsPositionValid())
13868 sLog.outError("Player (guidlow %d) have invalid coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",guid,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
13869 RelocateToHomebind();
13871 transGUID = 0;
13873 m_movementInfo.t_x = 0.0f;
13874 m_movementInfo.t_y = 0.0f;
13875 m_movementInfo.t_z = 0.0f;
13876 m_movementInfo.t_o = 0.0f;
13879 uint32 bgid = fields[34].GetUInt32();
13880 uint32 bgteam = fields[35].GetUInt32();
13882 if(bgid) //saved in BattleGround
13884 SetBattleGroundEntryPoint(fields[36].GetUInt32(),fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
13886 // check entry point and fix to homebind if need
13887 MapEntry const* mapEntry = sMapStore.LookupEntry(m_bgEntryPoint.mapid);
13888 if(!mapEntry || mapEntry->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint))
13889 SetBattleGroundEntryPoint(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ,0.0f);
13891 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(bgid, BATTLEGROUND_TYPE_NONE);
13893 if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID()))
13895 BattleGroundQueueTypeId bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
13896 AddBattleGroundQueueId(bgQueueTypeId);
13898 SetBattleGroundId(currentBg->GetInstanceID(), currentBg->GetTypeID());
13899 SetBGTeam(bgteam);
13901 //join player to battleground group
13902 currentBg->EventPlayerLoggedIn(this, GetGUID());
13903 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), bgteam);
13905 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
13907 else
13909 Relocate(GetBattleGroundEntryPoint());
13910 //RemoveArenaAuras(true);
13913 else
13915 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
13916 // if server restart after player save in BG or area
13917 // player can have current coordinates in to BG/Arean map, fix this
13918 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
13920 // return to BG master
13921 SetMapId(fields[36].GetUInt32());
13922 Relocate(fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
13924 // check entry point and fix to homebind if need
13925 mapEntry = sMapStore.LookupEntry(GetMapId());
13926 if(!mapEntry || mapEntry->IsBattleGroundOrArena() || !IsPositionValid())
13927 RelocateToHomebind();
13931 if (transGUID != 0)
13933 m_movementInfo.t_x = fields[20].GetFloat();
13934 m_movementInfo.t_y = fields[21].GetFloat();
13935 m_movementInfo.t_z = fields[22].GetFloat();
13936 m_movementInfo.t_o = fields[23].GetFloat();
13938 if( !MaNGOS::IsValidMapCoord(
13939 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13940 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
13941 // transport size limited
13942 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
13944 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13945 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13946 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
13948 RelocateToHomebind();
13950 m_movementInfo.t_x = 0.0f;
13951 m_movementInfo.t_y = 0.0f;
13952 m_movementInfo.t_z = 0.0f;
13953 m_movementInfo.t_o = 0.0f;
13955 transGUID = 0;
13959 if (transGUID != 0)
13961 for (MapManager::TransportSet::const_iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
13963 if( (*iter)->GetGUIDLow() == transGUID)
13965 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
13966 // client without expansion support
13967 if(GetSession()->Expansion() < transMapEntry->Expansion())
13969 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
13970 break;
13973 m_transport = *iter;
13974 m_transport->AddPassenger(this);
13975 SetMapId(m_transport->GetMapId());
13976 break;
13980 if(!m_transport)
13982 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
13983 guid,transGUID);
13985 RelocateToHomebind();
13987 m_movementInfo.t_x = 0.0f;
13988 m_movementInfo.t_y = 0.0f;
13989 m_movementInfo.t_z = 0.0f;
13990 m_movementInfo.t_o = 0.0f;
13992 transGUID = 0;
13995 else // not transport case
13997 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
13998 // client without expansion support
13999 if(GetSession()->Expansion() < mapEntry->Expansion())
14001 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14002 RelocateToHomebind();
14006 // NOW player must have valid map
14007 // load the player's map here if it's not already loaded
14008 Map *map = GetMap();
14010 // since the player may not be bound to the map yet, make sure subsequent
14011 // getmap calls won't create new maps
14012 SetInstanceId(map->GetInstanceId());
14014 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14015 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
14017 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
14018 if(at)
14019 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14020 else
14021 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());
14024 SaveRecallPosition();
14026 time_t now = time(NULL);
14027 time_t logoutTime = time_t(fields[16].GetUInt64());
14029 // since last logout (in seconds)
14030 uint64 time_diff = uint64(now - logoutTime);
14032 // set value, including drunk invisibility detection
14033 // calculate sobering. after 15 minutes logged out, the player will be sober again
14034 float soberFactor;
14035 if(time_diff > 15*MINUTE)
14036 soberFactor = 0;
14037 else
14038 soberFactor = 1-time_diff/(15.0f*MINUTE);
14039 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14040 SetDrunkValue(newDrunkenValue);
14042 m_rest_bonus = fields[15].GetFloat();
14043 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14044 float bubble0 = 0.031;
14045 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14046 float bubble1 = 0.125;
14048 if((int32)fields[16].GetUInt32() > 0)
14050 float bubble = fields[17].GetUInt32() > 0
14051 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14052 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14054 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14057 m_cinematic = fields[12].GetUInt32();
14058 m_Played_time[0]= fields[13].GetUInt32();
14059 m_Played_time[1]= fields[14].GetUInt32();
14061 m_resetTalentsCost = fields[18].GetUInt32();
14062 m_resetTalentsTime = time_t(fields[19].GetUInt64());
14064 // reserve some flags
14065 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14067 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14068 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14070 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
14072 uint32 extraflags = fields[25].GetUInt32();
14074 m_stableSlots = fields[26].GetUInt32();
14075 if(m_stableSlots > MAX_PET_STABLES)
14077 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
14078 m_stableSlots = MAX_PET_STABLES;
14081 m_atLoginFlags = fields[27].GetUInt32();
14083 // Honor system
14084 // Update Honor kills data
14085 m_lastHonorUpdateTime = logoutTime;
14086 UpdateHonorFields();
14088 m_deathExpireTime = (time_t)fields[30].GetUInt64();
14089 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14090 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14092 std::string taxi_nodes = fields[31].GetCppString();
14094 delete result;
14096 // clear channel spell data (if saved at channel spell casting)
14097 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14098 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14100 // clear charm/summon related fields
14101 SetCharm(NULL);
14102 SetPet(NULL);
14103 SetCharmerGUID(0);
14104 SetOwnerGUID(0);
14105 SetCreatorGUID(0);
14107 // reset some aura modifiers before aura apply
14108 SetFarSightGUID(0);
14109 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14110 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14112 _LoadSkills();
14114 // make sure the unit is considered out of combat for proper loading
14115 ClearInCombat();
14117 // make sure the unit is considered not in duel for proper loading
14118 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14119 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14121 // remember loaded power/health values to restore after stats initialization and modifier applying
14122 uint32 savedHealth = GetHealth();
14123 uint32 savedPower[MAX_POWERS];
14124 for(uint32 i = 0; i < MAX_POWERS; ++i)
14125 savedPower[i] = GetPower(Powers(i));
14127 // reset stats before loading any modifiers
14128 InitStatsForLevel();
14129 InitTaxiNodesForLevel();
14130 InitGlyphsForLevel();
14131 InitRunes();
14133 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14135 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14136 //_LoadMail();
14138 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14139 _LoadGlyphAuras();
14141 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14142 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14143 m_deathState = DEAD;
14145 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14147 // after spell load, learn rewarded spell if need also
14148 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14149 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14151 // after spell and quest load
14152 InitTalentForLevel();
14153 learnDefaultSpells();
14155 // must be before inventory (some items required reputation check)
14156 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14158 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14160 // update items with duration and realtime
14161 UpdateItemDuration(time_diff, true);
14163 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14165 // unread mails and next delivery time, actual mails not loaded
14166 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14168 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14170 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14171 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14172 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14174 if(!HasTitle(curTitle))
14175 SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
14178 // Not finish taxi flight path
14179 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14181 // problems with taxi path loading
14182 TaxiNodesEntry const* nodeEntry = NULL;
14183 if(uint32 node_id = m_taxi.GetTaxiSource())
14184 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14186 if(!nodeEntry) // don't know taxi start node, to homebind
14188 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14189 RelocateToHomebind();
14190 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14192 else // have start node, to it
14194 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14195 SetMapId(nodeEntry->map_id);
14196 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14197 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14199 m_taxi.ClearTaxiDestinations();
14201 else if(uint32 node_id = m_taxi.GetTaxiSource())
14203 // save source node as recall coord to prevent recall and fall from sky
14204 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14205 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14206 m_recallMap = nodeEntry->map_id;
14207 m_recallX = nodeEntry->x;
14208 m_recallY = nodeEntry->y;
14209 m_recallZ = nodeEntry->z;
14211 // flight will started later
14214 // has to be called after last Relocate() in Player::LoadFromDB
14215 SetFallInformation(0, GetPositionZ());
14217 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14219 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14220 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14221 if(!isAlive())
14222 RemoveAllAurasOnDeath();
14224 //apply all stat bonuses from items and auras
14225 SetCanModifyStats(true);
14226 UpdateAllStats();
14228 // restore remembered power/health values (but not more max values)
14229 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14230 for(uint32 i = 0; i < MAX_POWERS; ++i)
14231 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14233 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14234 outDebugValues();
14236 // GM state
14237 if(GetSession()->GetSecurity() > SEC_PLAYER)
14239 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14241 default:
14242 case 0: break; // disable
14243 case 1: SetGameMaster(true); break; // enable
14244 case 2: // save state
14245 if(extraflags & PLAYER_EXTRA_GM_ON)
14246 SetGameMaster(true);
14247 break;
14250 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
14252 default:
14253 case 0: SetGMVisible(false); break; // invisible
14254 case 1: break; // visible
14255 case 2: // save state
14256 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
14257 SetGMVisible(false);
14258 break;
14261 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14263 default:
14264 case 0: break; // disable
14265 case 1: SetAcceptTicket(true); break; // enable
14266 case 2: // save state
14267 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14268 SetAcceptTicket(true);
14269 break;
14272 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14274 default:
14275 case 0: break; // disable
14276 case 1: SetGMChat(true); break; // enable
14277 case 2: // save state
14278 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14279 SetGMChat(true);
14280 break;
14283 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14285 default:
14286 case 0: break; // disable
14287 case 1: SetAcceptWhispers(true); break; // enable
14288 case 2: // save state
14289 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14290 SetAcceptWhispers(true);
14291 break;
14295 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14297 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14298 m_achievementMgr.CheckAllAchievementCriteria();
14300 _LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
14302 return true;
14305 bool Player::isAllowedToLoot(Creature* creature)
14307 if(Player* recipient = creature->GetLootRecipient())
14309 if (recipient == this)
14310 return true;
14311 if( Group* otherGroup = recipient->GetGroup())
14313 Group* thisGroup = GetGroup();
14314 if(!thisGroup)
14315 return false;
14316 return thisGroup == otherGroup;
14318 return false;
14320 else
14321 // prevent other players from looting if the recipient got disconnected
14322 return !creature->hasLootRecipient();
14325 void Player::_LoadActions(QueryResult *result)
14327 m_actionButtons.clear();
14329 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14331 if(result)
14335 Field *fields = result->Fetch();
14337 uint8 button = fields[0].GetUInt8();
14339 if(addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8()))
14340 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14341 else
14343 sLog.outError( " ...at loading, and will deleted in DB also");
14345 // Will deleted in DB at next save (it can create data until save but marked as deleted)
14346 m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
14349 while( result->NextRow() );
14351 delete result;
14355 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14357 m_Auras.clear();
14358 for (int i = 0; i < TOTAL_AURAS; ++i)
14359 m_modAuras[i].clear();
14361 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14363 if(result)
14367 Field *fields = result->Fetch();
14368 uint64 caster_guid = fields[0].GetUInt64();
14369 uint32 spellid = fields[1].GetUInt32();
14370 uint32 effindex = fields[2].GetUInt32();
14371 uint32 stackcount = fields[3].GetUInt32();
14372 int32 damage = (int32)fields[4].GetUInt32();
14373 int32 maxduration = (int32)fields[5].GetUInt32();
14374 int32 remaintime = (int32)fields[6].GetUInt32();
14375 int32 remaincharges = (int32)fields[7].GetUInt32();
14377 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14378 if(!spellproto)
14380 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14381 continue;
14384 if(effindex >= 3)
14386 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14387 continue;
14390 // negative effects should continue counting down after logout
14391 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14393 if(remaintime <= int32(timediff))
14394 continue;
14396 remaintime -= timediff;
14399 // prevent wrong values of remaincharges
14400 if(spellproto->procCharges)
14402 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14403 remaincharges = spellproto->procCharges;
14405 else
14406 remaincharges = 0;
14409 for(uint32 i=0; i<stackcount; ++i)
14411 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14412 if(!damage)
14413 damage = aura->GetModifier()->m_amount;
14415 // reset stolen single target auras
14416 if (caster_guid != GetGUID() && aura->IsSingleTarget())
14417 aura->SetIsSingleTarget(false);
14419 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14420 AddAura(aura);
14421 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14424 while( result->NextRow() );
14426 delete result;
14429 if(m_class == CLASS_WARRIOR)
14430 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14433 void Player::_LoadGlyphAuras()
14435 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
14437 if (uint32 glyph = GetGlyph(i))
14439 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
14441 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
14443 if(gp->TypeFlags == gs->TypeFlags)
14445 CastSpell(this, gp->SpellId, true);
14446 continue;
14448 else
14449 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
14451 else
14452 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
14454 else
14455 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
14457 // On any error remove glyph
14458 SetGlyph(i, 0);
14463 void Player::LoadCorpse()
14465 if( isAlive() )
14467 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14469 else
14471 if(Corpse *corpse = GetCorpse())
14473 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14475 else
14477 //Prevent Dead Player login without corpse
14478 ResurrectPlayer(0.5f);
14483 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14485 //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());
14486 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14487 //NOTE: the "order by `bag`" is important because it makes sure
14488 //the bagMap is filled before items in the bags are loaded
14489 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14490 //expected to be equipped before offhand items (TODO: fixme)
14492 uint32 zone = GetZoneId();
14494 if (result)
14496 std::list<Item*> problematicItems;
14498 // prevent items from being added to the queue when stored
14499 m_itemUpdateQueueBlocked = true;
14502 Field *fields = result->Fetch();
14503 uint32 bag_guid = fields[1].GetUInt32();
14504 uint8 slot = fields[2].GetUInt8();
14505 uint32 item_guid = fields[3].GetUInt32();
14506 uint32 item_id = fields[4].GetUInt32();
14508 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14510 if(!proto)
14512 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14513 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14514 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14515 continue;
14518 Item *item = NewItemOrBag(proto);
14520 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14522 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14523 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14524 item->FSetState(ITEM_REMOVED);
14525 item->SaveToDB(); // it also deletes item object !
14526 continue;
14529 // not allow have in alive state item limited to another map/zone
14530 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14532 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14533 item->FSetState(ITEM_REMOVED);
14534 item->SaveToDB(); // it also deletes item object !
14535 continue;
14538 // "Conjured items disappear if you are logged out for more than 15 minutes"
14539 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14541 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14542 item->FSetState(ITEM_REMOVED);
14543 item->SaveToDB(); // it also deletes item object !
14544 continue;
14547 bool success = true;
14549 if (!bag_guid)
14551 // the item is not in a bag
14552 item->SetContainer( NULL );
14553 item->SetSlot(slot);
14555 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14557 ItemPosCountVec dest;
14558 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14559 item = StoreItem(dest, item, true);
14560 else
14561 success = false;
14563 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14565 uint16 dest;
14566 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14567 QuickEquipItem(dest, item);
14568 else
14569 success = false;
14571 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14573 ItemPosCountVec dest;
14574 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14575 item = BankItem(dest, item, true);
14576 else
14577 success = false;
14580 if(success)
14582 // store bags that may contain items in them
14583 if(item->IsBag() && IsBagPos(item->GetPos()))
14584 bagMap[item_guid] = (Bag*)item;
14587 else
14589 item->SetSlot(NULL_SLOT);
14590 // the item is in a bag, find the bag
14591 std::map<uint64, Bag*>::const_iterator itr = bagMap.find(bag_guid);
14592 if(itr != bagMap.end())
14593 itr->second->StoreItem(slot, item, true );
14594 else
14595 success = false;
14598 // item's state may have changed after stored
14599 if (success)
14600 item->SetState(ITEM_UNCHANGED, this);
14601 else
14603 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);
14604 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14605 problematicItems.push_back(item);
14607 } while (result->NextRow());
14609 delete result;
14610 m_itemUpdateQueueBlocked = false;
14612 // send by mail problematic items
14613 while(!problematicItems.empty())
14615 // fill mail
14616 MailItemsInfo mi; // item list preparing
14618 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14620 Item* item = problematicItems.front();
14621 problematicItems.pop_front();
14623 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14626 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14628 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14631 //if(isAlive())
14632 _ApplyAllItemMods();
14635 // load mailed item which should receive current player
14636 void Player::_LoadMailedItems(Mail *mail)
14638 // data needs to be at first place for Item::LoadFromDB
14639 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);
14640 if(!result)
14641 return;
14645 Field *fields = result->Fetch();
14646 uint32 item_guid_low = fields[1].GetUInt32();
14647 uint32 item_template = fields[2].GetUInt32();
14649 mail->AddItem(item_guid_low, item_template);
14651 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14653 if(!proto)
14655 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);
14656 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14657 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14658 continue;
14661 Item *item = NewItemOrBag(proto);
14663 if(!item->LoadFromDB(item_guid_low, 0, result))
14665 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14666 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14667 item->FSetState(ITEM_REMOVED);
14668 item->SaveToDB(); // it also deletes item object !
14669 continue;
14672 AddMItem(item);
14673 } while (result->NextRow());
14675 delete result;
14678 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14680 //set a count of unread mails
14681 //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);
14682 if (resultUnread)
14684 Field *fieldMail = resultUnread->Fetch();
14685 unReadMails = fieldMail[0].GetUInt8();
14686 delete resultUnread;
14689 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14690 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14691 if (resultDelivery)
14693 Field *fieldMail = resultDelivery->Fetch();
14694 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14695 delete resultDelivery;
14699 void Player::_LoadMail()
14701 m_mail.clear();
14702 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14703 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());
14704 if(result)
14708 Field *fields = result->Fetch();
14709 Mail *m = new Mail;
14710 m->messageID = fields[0].GetUInt32();
14711 m->messageType = fields[1].GetUInt8();
14712 m->sender = fields[2].GetUInt32();
14713 m->receiver = fields[3].GetUInt32();
14714 m->subject = fields[4].GetCppString();
14715 m->itemTextId = fields[5].GetUInt32();
14716 bool has_items = fields[6].GetBool();
14717 m->expire_time = (time_t)fields[7].GetUInt64();
14718 m->deliver_time = (time_t)fields[8].GetUInt64();
14719 m->money = fields[9].GetUInt32();
14720 m->COD = fields[10].GetUInt32();
14721 m->checked = fields[11].GetUInt32();
14722 m->stationery = fields[12].GetUInt8();
14723 m->mailTemplateId = fields[13].GetInt16();
14725 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14727 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14728 m->mailTemplateId = 0;
14731 m->state = MAIL_STATE_UNCHANGED;
14733 if (has_items)
14734 _LoadMailedItems(m);
14736 m_mail.push_back(m);
14737 } while( result->NextRow() );
14738 delete result;
14740 m_mailsLoaded = true;
14743 void Player::LoadPet()
14745 //fixme: the pet should still be loaded if the player is not in world
14746 // just not added to the map
14747 if(IsInWorld())
14749 Pet *pet = new Pet;
14750 if(!pet->LoadPetFromDB(this,0,0,true))
14751 delete pet;
14755 void Player::_LoadQuestStatus(QueryResult *result)
14757 mQuestStatus.clear();
14759 uint32 slot = 0;
14761 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14762 //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());
14764 if(result)
14768 Field *fields = result->Fetch();
14770 uint32 quest_id = fields[0].GetUInt32();
14771 // used to be new, no delete?
14772 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14773 if( pQuest )
14775 // find or create
14776 QuestStatusData& questStatusData = mQuestStatus[quest_id];
14778 uint32 qstatus = fields[1].GetUInt32();
14779 if(qstatus < MAX_QUEST_STATUS)
14780 questStatusData.m_status = QuestStatus(qstatus);
14781 else
14783 questStatusData.m_status = QUEST_STATUS_NONE;
14784 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
14787 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
14788 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
14790 time_t quest_time = time_t(fields[4].GetUInt64());
14792 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
14794 AddTimedQuest( quest_id );
14796 if (quest_time <= sWorld.GetGameTime())
14797 questStatusData.m_timer = 1;
14798 else
14799 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
14801 else
14802 quest_time = 0;
14804 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
14805 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
14806 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
14807 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
14808 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
14809 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
14810 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
14811 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
14813 questStatusData.uState = QUEST_UNCHANGED;
14815 // add to quest log
14816 if( slot < MAX_QUEST_LOG_SIZE &&
14817 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
14818 questStatusData.m_status==QUEST_STATUS_COMPLETE &&
14819 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
14821 SetQuestSlot(slot,quest_id,quest_time);
14823 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
14824 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
14826 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
14827 if(questStatusData.m_creatureOrGOcount[idx])
14828 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
14830 ++slot;
14833 if(questStatusData.m_rewarded)
14835 // learn rewarded spell if unknown
14836 learnQuestRewardedSpells(pQuest);
14838 // set rewarded title if any
14839 if(pQuest->GetCharTitleId())
14841 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
14842 SetTitle(titleEntry);
14845 if(pQuest->GetBonusTalents())
14846 m_questRewardTalentCount+=pQuest->GetBonusTalents();
14849 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
14852 while( result->NextRow() );
14854 delete result;
14857 // clear quest log tail
14858 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
14859 SetQuestSlot(i,0);
14862 void Player::_LoadDailyQuestStatus(QueryResult *result)
14864 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
14865 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
14867 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14869 if(result)
14871 uint32 quest_daily_idx = 0;
14875 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
14877 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14878 break;
14881 Field *fields = result->Fetch();
14883 uint32 quest_id = fields[0].GetUInt32();
14885 // save _any_ from daily quest times (it must be after last reset anyway)
14886 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
14888 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14889 if( !pQuest )
14890 continue;
14892 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
14893 ++quest_daily_idx;
14895 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
14897 while( result->NextRow() );
14899 delete result;
14902 m_DailyQuestChanged = false;
14905 void Player::_LoadSpells(QueryResult *result)
14907 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14909 if(result)
14913 Field *fields = result->Fetch();
14915 addSpell(fields[0].GetUInt16(), fields[1].GetBool(), false, false, fields[2].GetBool());
14917 while( result->NextRow() );
14919 delete result;
14923 void Player::_LoadGroup(QueryResult *result)
14925 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14926 if(result)
14928 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
14929 delete result;
14930 Group* group = objmgr.GetGroupByLeader(leaderGuid);
14931 if(group)
14933 uint8 subgroup = group->GetMemberGroup(GetGUID());
14934 SetGroup(group, subgroup);
14935 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
14937 // the group leader may change the instance difficulty while the player is offline
14938 SetDifficulty(group->GetDifficulty());
14944 void Player::_LoadBoundInstances(QueryResult *result)
14946 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
14947 m_boundInstances[i].clear();
14949 Group *group = GetGroup();
14951 //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));
14952 if(result)
14956 Field *fields = result->Fetch();
14957 bool perm = fields[1].GetBool();
14958 uint32 mapId = fields[2].GetUInt32();
14959 uint32 instanceId = fields[0].GetUInt32();
14960 uint8 difficulty = fields[3].GetUInt8();
14961 time_t resetTime = (time_t)fields[4].GetUInt64();
14962 // the resettime for normal instances is only saved when the InstanceSave is unloaded
14963 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
14964 // and in that case it is not used
14966 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
14967 if(!mapEntry || !mapEntry->IsDungeon())
14969 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
14970 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
14971 continue;
14974 if(!perm && group)
14976 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);
14977 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
14978 continue;
14981 // since non permanent binds are always solo bind, they can always be reset
14982 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
14983 if(save) BindToInstance(save, perm, true);
14984 } while(result->NextRow());
14985 delete result;
14989 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
14991 // some instances only have one difficulty
14992 const MapEntry* entry = sMapStore.LookupEntry(mapid);
14993 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
14995 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
14996 if(itr != m_boundInstances[difficulty].end())
14997 return &itr->second;
14998 else
14999 return NULL;
15002 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
15004 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15005 UnbindInstance(itr, difficulty, unload);
15008 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
15010 if(itr != m_boundInstances[difficulty].end())
15012 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15013 itr->second.save->RemovePlayer(this); // save can become invalid
15014 m_boundInstances[difficulty].erase(itr++);
15018 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15020 if(save)
15022 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15023 if(bind.save)
15025 // update the save when the group kills a boss
15026 if(permanent != bind.perm || save != bind.save)
15027 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());
15029 else
15030 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15032 if(bind.save != save)
15034 if(bind.save) bind.save->RemovePlayer(this);
15035 save->AddPlayer(this);
15038 if(permanent) save->SetCanReset(false);
15040 bind.save = save;
15041 bind.perm = permanent;
15042 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());
15043 return &bind;
15045 else
15046 return NULL;
15049 void Player::SendRaidInfo()
15051 uint32 counter = 0;
15053 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15055 size_t p_counter = data.wpos();
15056 data << uint32(counter); // placeholder
15058 for(int i = 0; i < TOTAL_DIFFICULTIES; ++i)
15060 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15062 if(itr->second.perm)
15064 InstanceSave *save = itr->second.save;
15065 data << uint32(save->GetMapId());
15066 data << uint32(save->GetResetTime() - time(NULL));
15067 data << uint32(save->GetInstanceId());
15068 data << uint32(save->GetDifficulty());
15069 ++counter;
15073 data.put<uint32>(p_counter,counter);
15074 GetSession()->SendPacket(&data);
15078 - called on every successful teleportation to a map
15080 void Player::SendSavedInstances()
15082 bool hasBeenSaved = false;
15083 WorldPacket data;
15085 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15087 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15089 if(itr->second.perm) // only permanent binds are sent
15091 hasBeenSaved = true;
15092 break;
15097 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15098 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15099 data << uint32(hasBeenSaved);
15100 GetSession()->SendPacket(&data);
15102 if(!hasBeenSaved)
15103 return;
15105 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15107 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15109 if(itr->second.perm)
15111 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15112 data << uint32(itr->second.save->GetMapId());
15113 GetSession()->SendPacket(&data);
15119 /// convert the player's binds to the group
15120 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15122 bool has_binds = false;
15123 bool has_solo = false;
15125 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15126 assert(player_guid);
15128 // copy all binds to the group, when changing leader it's assumed the character
15129 // will not have any solo binds
15131 if(player)
15133 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15135 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15137 has_binds = true;
15138 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15139 // permanent binds are not removed
15140 if(!itr->second.perm)
15142 player->UnbindInstance(itr, i, true); // increments itr
15143 has_solo = true;
15145 else
15146 ++itr;
15151 // if the player's not online we don't know what binds it has
15152 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));
15153 // the following should not get executed when changing leaders
15154 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15157 bool Player::_LoadHomeBind(QueryResult *result)
15159 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15160 if(!info)
15162 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
15163 return false;
15166 bool ok = false;
15167 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15168 if (result)
15170 Field *fields = result->Fetch();
15171 m_homebindMapId = fields[0].GetUInt32();
15172 m_homebindZoneId = fields[1].GetUInt16();
15173 m_homebindX = fields[2].GetFloat();
15174 m_homebindY = fields[3].GetFloat();
15175 m_homebindZ = fields[4].GetFloat();
15176 delete result;
15178 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
15180 // accept saved data only for valid position (and non instanceable), and accessable
15181 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15182 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
15184 ok = true;
15186 else
15187 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15190 if(!ok)
15192 m_homebindMapId = info->mapId;
15193 m_homebindZoneId = info->zoneId;
15194 m_homebindX = info->positionX;
15195 m_homebindY = info->positionY;
15196 m_homebindZ = info->positionZ;
15198 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);
15201 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
15202 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15204 return true;
15207 /*********************************************************/
15208 /*** SAVE SYSTEM ***/
15209 /*********************************************************/
15211 void Player::SaveToDB()
15213 // delay auto save at any saves (manual, in code, or autosave)
15214 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15216 // first save/honor gain after midnight will also update the player's honor fields
15217 UpdateHonorFields();
15219 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15220 //save, far from tavern/city
15221 //save, but in tavern/city
15222 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15223 outDebugValues();
15225 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15226 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15227 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15228 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15229 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15230 uint32 tmp_displayid = GetDisplayId();
15232 // Set player sit state to standing on save, also stealth and shifted form
15233 SetByteValue(UNIT_FIELD_BYTES_1, 0, UNIT_STAND_STATE_STAND);
15234 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15235 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15236 SetDisplayId(GetNativeDisplayId());
15238 bool inworld = IsInWorld();
15240 CharacterDatabase.BeginTransaction();
15242 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15244 std::string sql_name = m_name;
15245 CharacterDatabase.escape_string(sql_name);
15247 std::ostringstream ss;
15248 ss << "INSERT INTO characters (guid,account,name,race,class,"
15249 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15250 "taximask, online, cinematic, "
15251 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15252 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15253 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15254 << GetGUIDLow() << ", "
15255 << GetSession()->GetAccountId() << ", '"
15256 << sql_name << "', "
15257 << m_race << ", "
15258 << m_class << ", ";
15260 if(!IsBeingTeleported())
15262 ss << GetMapId() << ", "
15263 << (uint32)GetDifficulty() << ", "
15264 << finiteAlways(GetPositionX()) << ", "
15265 << finiteAlways(GetPositionY()) << ", "
15266 << finiteAlways(GetPositionZ()) << ", "
15267 << finiteAlways(GetOrientation()) << ", '";
15269 else
15271 ss << GetTeleportDest().mapid << ", "
15272 << (uint32)GetDifficulty() << ", "
15273 << finiteAlways(GetTeleportDest().x) << ", "
15274 << finiteAlways(GetTeleportDest().y) << ", "
15275 << finiteAlways(GetTeleportDest().z) << ", "
15276 << finiteAlways(GetTeleportDest().o) << ", '";
15279 uint16 i;
15280 for( i = 0; i < m_valuesCount; ++i )
15282 ss << GetUInt32Value(i) << " ";
15285 ss << "', ";
15287 ss << m_taxi; // string with TaxiMaskSize numbers
15289 ss << ", ";
15290 ss << (inworld ? 1 : 0);
15292 ss << ", ";
15293 ss << m_cinematic;
15295 ss << ", ";
15296 ss << m_Played_time[0];
15297 ss << ", ";
15298 ss << m_Played_time[1];
15300 ss << ", ";
15301 ss << finiteAlways(m_rest_bonus);
15302 ss << ", ";
15303 ss << (uint64)time(NULL);
15304 ss << ", ";
15305 ss << is_save_resting;
15306 ss << ", ";
15307 ss << m_resetTalentsCost;
15308 ss << ", ";
15309 ss << (uint64)m_resetTalentsTime;
15311 ss << ", ";
15312 ss << finiteAlways(m_movementInfo.t_x);
15313 ss << ", ";
15314 ss << finiteAlways(m_movementInfo.t_y);
15315 ss << ", ";
15316 ss << finiteAlways(m_movementInfo.t_z);
15317 ss << ", ";
15318 ss << finiteAlways(m_movementInfo.t_o);
15319 ss << ", ";
15320 if (m_transport)
15321 ss << m_transport->GetGUIDLow();
15322 else
15323 ss << "0";
15325 ss << ", ";
15326 ss << m_ExtraFlags;
15328 ss << ", ";
15329 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15331 ss << ", ";
15332 ss << uint32(m_atLoginFlags);
15334 ss << ", ";
15335 ss << GetZoneId();
15337 ss << ", ";
15338 ss << (uint64)m_deathExpireTime;
15340 ss << ", '";
15341 ss << m_taxi.SaveTaxiDestinationsToString();
15342 ss << "', '0', ";
15343 ss << GetBattleGroundId();
15344 ss << ", ";
15345 ss << GetBGTeam();
15346 ss << ", ";
15347 ss << m_bgEntryPoint.mapid << ", "
15348 << finiteAlways(m_bgEntryPoint.x) << ", "
15349 << finiteAlways(m_bgEntryPoint.y) << ", "
15350 << finiteAlways(m_bgEntryPoint.z) << ", "
15351 << finiteAlways(m_bgEntryPoint.o);
15352 ss << ")";
15354 CharacterDatabase.Execute( ss.str().c_str() );
15356 if(m_mailsUpdated) //save mails only when needed
15357 _SaveMail();
15359 _SaveInventory();
15360 _SaveQuestStatus();
15361 _SaveDailyQuestStatus();
15362 _SaveSpells();
15363 _SaveSpellCooldowns();
15364 _SaveActions();
15365 _SaveAuras();
15366 m_achievementMgr.SaveToDB();
15367 m_reputationMgr.SaveToDB();
15368 _SaveEquipmentSets();
15369 GetSession()->SaveTutorialsData(); // changed only while character in game
15371 CharacterDatabase.CommitTransaction();
15373 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15374 SetDisplayId(tmp_displayid);
15375 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15376 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15377 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15378 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15380 // save pet (hunter pet level and experience and all type pets health/mana).
15381 if(Pet* pet = GetPet())
15382 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15385 // fast save function for item/money cheating preventing - save only inventory and money state
15386 void Player::SaveInventoryAndGoldToDB()
15388 _SaveInventory();
15389 //money is in data field
15390 SaveDataFieldToDB();
15393 void Player::_SaveActions()
15395 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15397 switch (itr->second.uState)
15399 case ACTIONBUTTON_NEW:
15400 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15401 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15402 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15403 ++itr;
15404 break;
15405 case ACTIONBUTTON_CHANGED:
15406 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15407 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15408 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15409 ++itr;
15410 break;
15411 case ACTIONBUTTON_DELETED:
15412 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15413 m_actionButtons.erase(itr++);
15414 break;
15415 default:
15416 ++itr;
15417 break;
15422 void Player::_SaveAuras()
15424 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15426 AuraMap const& auras = GetAuras();
15428 if (auras.empty())
15429 return;
15431 spellEffectPair lastEffectPair = auras.begin()->first;
15432 uint32 stackCounter = 1;
15434 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15436 if(itr == auras.end() || lastEffectPair != itr->first)
15438 AuraMap::const_iterator itr2 = itr;
15439 // save previous spellEffectPair to db
15440 itr2--;
15442 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15444 //skip all auras from spells that are passive or need a shapeshift
15445 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15447 //do not save single target auras (unless they were cast by the player)
15448 if (!(itr2->second->GetCasterGUID() != GetGUID() && itr2->second->IsSingleTarget()))
15450 uint8 i;
15451 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15452 for (i = 0; i < 3; ++i)
15453 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15454 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15455 break;
15457 if (i == 3)
15459 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15460 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15461 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()));
15466 if(itr == auras.end())
15467 break;
15470 if (lastEffectPair == itr->first)
15471 stackCounter++;
15472 else
15474 lastEffectPair = itr->first;
15475 stackCounter = 1;
15480 void Player::_SaveInventory()
15482 // force items in buyback slots to new state
15483 // and remove those that aren't already
15484 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
15486 Item *item = m_items[i];
15487 if (!item || item->GetState() == ITEM_NEW) continue;
15488 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15489 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15490 m_items[i]->FSetState(ITEM_NEW);
15493 // update enchantment durations
15494 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15496 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15499 // if no changes
15500 if (m_itemUpdateQueue.empty()) return;
15502 // do not save if the update queue is corrupt
15503 bool error = false;
15504 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15506 Item *item = m_itemUpdateQueue[i];
15507 if(!item || item->GetState() == ITEM_REMOVED) continue;
15508 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15510 if (test == NULL)
15512 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());
15513 error = true;
15515 else if (test != item)
15517 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());
15518 error = true;
15522 if (error)
15524 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15525 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15526 return;
15529 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15531 Item *item = m_itemUpdateQueue[i];
15532 if(!item) continue;
15534 Bag *container = item->GetContainer();
15535 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15537 switch(item->GetState())
15539 case ITEM_NEW:
15540 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());
15541 break;
15542 case ITEM_CHANGED:
15543 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());
15544 break;
15545 case ITEM_REMOVED:
15546 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15547 break;
15548 case ITEM_UNCHANGED:
15549 break;
15552 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15554 m_itemUpdateQueue.clear();
15557 void Player::_SaveMail()
15559 if (!m_mailsLoaded)
15560 return;
15562 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15564 Mail *m = (*itr);
15565 if (m->state == MAIL_STATE_CHANGED)
15567 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'",
15568 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15569 if(m->removedItems.size())
15571 for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15572 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15573 m->removedItems.clear();
15575 m->state = MAIL_STATE_UNCHANGED;
15577 else if (m->state == MAIL_STATE_DELETED)
15579 if (m->HasItems())
15580 for(std::vector<MailItemInfo>::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15581 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15582 if (m->itemTextId)
15583 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15584 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15585 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15589 //deallocate deleted mails...
15590 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15592 if ((*itr)->state == MAIL_STATE_DELETED)
15594 Mail* m = *itr;
15595 m_mail.erase(itr);
15596 delete m;
15597 itr = m_mail.begin();
15599 else
15600 ++itr;
15603 m_mailsUpdated = false;
15606 void Player::_SaveQuestStatus()
15608 // we don't need transactions here.
15609 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15611 switch (i->second.uState)
15613 case QUEST_NEW :
15614 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15615 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15616 GetGUIDLow(), i->first, i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / IN_MILISECONDS+ sWorld.GetGameTime()), i->second.m_creatureOrGOcount[0], i->second.m_creatureOrGOcount[1], i->second.m_creatureOrGOcount[2], i->second.m_creatureOrGOcount[3], i->second.m_itemcount[0], i->second.m_itemcount[1], i->second.m_itemcount[2], i->second.m_itemcount[3]);
15617 break;
15618 case QUEST_CHANGED :
15619 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' ",
15620 i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / IN_MILISECONDS + sWorld.GetGameTime()), i->second.m_creatureOrGOcount[0], i->second.m_creatureOrGOcount[1], i->second.m_creatureOrGOcount[2], i->second.m_creatureOrGOcount[3], i->second.m_itemcount[0], i->second.m_itemcount[1], i->second.m_itemcount[2], i->second.m_itemcount[3], GetGUIDLow(), i->first );
15621 break;
15622 case QUEST_UNCHANGED:
15623 break;
15625 i->second.uState = QUEST_UNCHANGED;
15629 void Player::_SaveDailyQuestStatus()
15631 if(!m_DailyQuestChanged)
15632 return;
15634 m_DailyQuestChanged = false;
15636 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15638 // we don't need transactions here.
15639 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15640 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15641 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15642 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
15643 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15646 void Player::_SaveSpells()
15648 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
15650 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15651 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15653 // add only changed/new not dependent spells
15654 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
15655 CharacterDatabase.PExecute("INSERT INTO character_spell (guid,spell,active,disabled) VALUES ('%u', '%u', '%u', '%u')", GetGUIDLow(), itr->first, itr->second->active ? 1 : 0,itr->second->disabled ? 1 : 0);
15657 if (itr->second->state == PLAYERSPELL_REMOVED)
15659 delete itr->second;
15660 m_spells.erase(itr++);
15662 else
15664 itr->second->state = PLAYERSPELL_UNCHANGED;
15665 ++itr;
15671 void Player::outDebugValues() const
15673 if(!sLog.IsOutDebug()) // optimize disabled debug output
15674 return;
15676 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15677 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15678 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15679 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15680 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15681 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15682 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15683 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15684 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15685 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15686 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15687 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15690 /*********************************************************/
15691 /*** FLOOD FILTER SYSTEM ***/
15692 /*********************************************************/
15694 void Player::UpdateSpeakTime()
15696 // ignore chat spam protection for GMs in any mode
15697 if(GetSession()->GetSecurity() > SEC_PLAYER)
15698 return;
15700 time_t current = time (NULL);
15701 if(m_speakTime > current)
15703 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15704 if(!max_count)
15705 return;
15707 ++m_speakCount;
15708 if(m_speakCount >= max_count)
15710 // prevent overwrite mute time, if message send just before mutes set, for example.
15711 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15712 if(GetSession()->m_muteTime < new_mute)
15713 GetSession()->m_muteTime = new_mute;
15715 m_speakCount = 0;
15718 else
15719 m_speakCount = 0;
15721 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15724 bool Player::CanSpeak() const
15726 return GetSession()->m_muteTime <= time (NULL);
15729 /*********************************************************/
15730 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15731 /*********************************************************/
15733 void Player::SendAttackSwingNotInRange()
15735 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15736 GetSession()->SendPacket( &data );
15739 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15741 std::ostringstream ss;
15742 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15743 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15744 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15745 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15746 sLog.outDebug(ss.str().c_str());
15747 CharacterDatabase.Execute(ss.str().c_str());
15750 void Player::SaveDataFieldToDB()
15752 std::ostringstream ss;
15753 ss<<"UPDATE characters SET data='";
15755 for(uint16 i = 0; i < m_valuesCount; ++i )
15757 ss << GetUInt32Value(i) << " ";
15759 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
15761 CharacterDatabase.Execute(ss.str().c_str());
15764 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
15766 std::ostringstream ss2;
15767 ss2<<"UPDATE characters SET data='";
15768 int i=0;
15769 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
15771 ss2<<tokens[i]<<" ";
15773 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15775 return CharacterDatabase.Execute(ss2.str().c_str());
15778 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
15780 char buf[11];
15781 snprintf(buf,11,"%u",value);
15783 if(index >= tokens.size())
15784 return;
15786 tokens[index] = buf;
15789 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
15791 Tokens tokens;
15792 if(!LoadValuesArrayFromDB(tokens,guid))
15793 return;
15795 if(index >= tokens.size())
15796 return;
15798 char buf[11];
15799 snprintf(buf,11,"%u",value);
15800 tokens[index] = buf;
15802 SaveValuesArrayInDB(tokens,guid);
15805 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
15807 uint32 temp;
15808 memcpy(&temp, &value, sizeof(value));
15809 Player::SetUInt32ValueInDB(index, temp, guid);
15812 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
15814 Tokens tokens;
15815 if(!LoadValuesArrayFromDB(tokens, guid))
15816 return;
15818 uint32 unit_bytes0 = GetUInt32ValueFromArray(tokens, UNIT_FIELD_BYTES_0);
15819 uint8 race = unit_bytes0 & 0xFF;
15820 uint8 class_ = (unit_bytes0 >> 8) & 0xFF;
15822 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
15823 if(!info)
15824 return;
15826 unit_bytes0 &= ~(0xFF << 16);
15827 unit_bytes0 |= (gender << 16);
15828 SetUInt32ValueInArray(tokens, UNIT_FIELD_BYTES_0, unit_bytes0);
15830 SetUInt32ValueInArray(tokens, UNIT_FIELD_DISPLAYID, gender ? info->displayId_f : info->displayId_m);
15831 SetUInt32ValueInArray(tokens, UNIT_FIELD_NATIVEDISPLAYID, gender ? info->displayId_f : info->displayId_m);
15833 SetUInt32ValueInArray(tokens, PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
15835 uint32 player_bytes2 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_2);
15836 player_bytes2 &= ~0xFF;
15837 player_bytes2 |= facialHair;
15838 SetUInt32ValueInArray(tokens, PLAYER_BYTES_2, player_bytes2);
15840 uint32 player_bytes3 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_3);
15841 player_bytes3 &= ~0xFF;
15842 player_bytes3 |= gender;
15843 SetUInt32ValueInArray(tokens, PLAYER_BYTES_3, player_bytes3);
15845 SaveValuesArrayInDB(tokens, guid);
15848 void Player::SendAttackSwingNotStanding()
15850 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
15851 GetSession()->SendPacket( &data );
15854 void Player::SendAttackSwingDeadTarget()
15856 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
15857 GetSession()->SendPacket( &data );
15860 void Player::SendAttackSwingCantAttack()
15862 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
15863 GetSession()->SendPacket( &data );
15866 void Player::SendAttackSwingCancelAttack()
15868 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
15869 GetSession()->SendPacket( &data );
15872 void Player::SendAttackSwingBadFacingAttack()
15874 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
15875 GetSession()->SendPacket( &data );
15878 void Player::SendAutoRepeatCancel()
15880 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
15881 data.append(GetPackGUID()); // may be it's target guid
15882 GetSession()->SendPacket( &data );
15885 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
15887 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
15888 data << Area;
15889 data << Experience;
15890 GetSession()->SendPacket(&data);
15893 void Player::SendDungeonDifficulty(bool IsInGroup)
15895 uint8 val = 0x00000001;
15896 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
15897 data << (uint32)GetDifficulty();
15898 data << uint32(val);
15899 data << uint32(IsInGroup);
15900 GetSession()->SendPacket(&data);
15903 void Player::SendResetFailedNotify(uint32 mapid)
15905 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
15906 data << uint32(mapid);
15907 GetSession()->SendPacket(&data);
15910 /// Reset all solo instances and optionally send a message on success for each
15911 void Player::ResetInstances(uint8 method)
15913 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15915 // we assume that when the difficulty changes, all instances that can be reset will be
15916 uint8 dif = GetDifficulty();
15918 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
15920 InstanceSave *p = itr->second.save;
15921 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
15922 if(!entry || !p->CanReset())
15924 ++itr;
15925 continue;
15928 if(method == INSTANCE_RESET_ALL)
15930 // the "reset all instances" method can only reset normal maps
15931 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
15933 ++itr;
15934 continue;
15938 // if the map is loaded, reset it
15939 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
15940 if(map && map->IsDungeon())
15941 ((InstanceMap*)map)->Reset(method);
15943 // since this is a solo instance there should not be any players inside
15944 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
15945 SendResetInstanceSuccess(p->GetMapId());
15947 p->DeleteFromDB();
15948 m_boundInstances[dif].erase(itr++);
15950 // the following should remove the instance save from the manager and delete it as well
15951 p->RemovePlayer(this);
15955 void Player::SendResetInstanceSuccess(uint32 MapId)
15957 WorldPacket data(SMSG_INSTANCE_RESET, 4);
15958 data << MapId;
15959 GetSession()->SendPacket(&data);
15962 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
15964 // TODO: find what other fail reasons there are besides players in the instance
15965 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
15966 data << reason;
15967 data << MapId;
15968 GetSession()->SendPacket(&data);
15971 /*********************************************************/
15972 /*** Update timers ***/
15973 /*********************************************************/
15975 ///checks the 15 afk reports per 5 minutes limit
15976 void Player::UpdateAfkReport(time_t currTime)
15978 if(m_bgAfkReportedTimer <= currTime)
15980 m_bgAfkReportedCount = 0;
15981 m_bgAfkReportedTimer = currTime+5*MINUTE;
15985 void Player::UpdateContestedPvP(uint32 diff)
15987 if(!m_contestedPvPTimer||isInCombat())
15988 return;
15989 if(m_contestedPvPTimer <= diff)
15991 ResetContestedPvP();
15993 else
15994 m_contestedPvPTimer -= diff;
15997 void Player::UpdatePvPFlag(time_t currTime)
15999 if(!IsPvP())
16000 return;
16001 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16002 return;
16004 UpdatePvP(false);
16007 void Player::UpdateDuelFlag(time_t currTime)
16009 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16010 return;
16012 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16013 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16015 duel->startTimer = 0;
16016 duel->startTime = currTime;
16017 duel->opponent->duel->startTimer = 0;
16018 duel->opponent->duel->startTime = currTime;
16021 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16023 if(!pet)
16024 pet = GetPet();
16026 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16028 //returning of reagents only for players, so best done here
16029 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16030 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16032 if(spellInfo)
16034 for(uint32 i = 0; i < 7; ++i)
16036 if(spellInfo->Reagent[i] > 0)
16038 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16039 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16040 if( msg == EQUIP_ERR_OK )
16042 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16043 if(IsInWorld())
16044 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16049 m_temporaryUnsummonedPetNumber = 0;
16052 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16053 return;
16055 // only if current pet in slot
16056 switch(pet->getPetType())
16058 case MINI_PET:
16059 m_miniPet = 0;
16060 break;
16061 case GUARDIAN_PET:
16062 m_guardianPets.erase(pet->GetGUID());
16063 break;
16064 default:
16065 if(GetPetGUID() == pet->GetGUID())
16066 SetPet(NULL);
16067 break;
16070 pet->CombatStop();
16072 if(returnreagent)
16074 switch(pet->GetEntry())
16076 //warlock pets except imp are removed(?) when logging out
16077 case 1860:
16078 case 1863:
16079 case 417:
16080 case 17252:
16081 mode = PET_SAVE_NOT_IN_SLOT;
16082 break;
16086 pet->SavePetToDB(mode);
16088 pet->CleanupsBeforeDelete();
16089 pet->AddObjectToRemoveList();
16090 pet->m_removed = true;
16092 if(pet->isControlled())
16094 WorldPacket data(SMSG_PET_SPELLS, 8+4);
16095 data << uint64(0);
16096 data << uint32(0);
16097 GetSession()->SendPacket(&data);
16099 if(GetGroup())
16100 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16104 void Player::RemoveMiniPet()
16106 if(Pet* pet = GetMiniPet())
16108 pet->Remove(PET_SAVE_AS_DELETED);
16109 m_miniPet = 0;
16113 Pet* Player::GetMiniPet()
16115 if(!m_miniPet)
16116 return NULL;
16117 return ObjectAccessor::GetPet(m_miniPet);
16120 void Player::RemoveGuardians()
16122 while(!m_guardianPets.empty())
16124 uint64 guid = *m_guardianPets.begin();
16125 if(Pet* pet = ObjectAccessor::GetPet(guid))
16126 pet->Remove(PET_SAVE_AS_DELETED);
16128 m_guardianPets.erase(guid);
16132 bool Player::HasGuardianWithEntry(uint32 entry)
16134 // pet guid middle part is entry (and creature also)
16135 // and in guardian list must be guardians with same entry _always_
16136 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
16137 if(GUID_ENPART(*itr)==entry)
16138 return true;
16140 return false;
16143 void Player::Uncharm()
16145 Unit* charm = GetCharm();
16146 if(!charm)
16147 return;
16149 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16150 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16153 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16155 *data << (uint8)msgtype;
16156 *data << (uint32)language;
16157 *data << (uint64)GetGUID();
16158 *data << (uint32)language; //language 2.1.0 ?
16159 *data << (uint64)GetGUID();
16160 *data << (uint32)(text.length()+1);
16161 *data << text;
16162 *data << (uint8)chatTag();
16165 void Player::Say(const std::string& text, const uint32 language)
16167 WorldPacket data(SMSG_MESSAGECHAT, 200);
16168 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16169 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16172 void Player::Yell(const std::string& text, const uint32 language)
16174 WorldPacket data(SMSG_MESSAGECHAT, 200);
16175 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16176 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16179 void Player::TextEmote(const std::string& text)
16181 WorldPacket data(SMSG_MESSAGECHAT, 200);
16182 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16183 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16186 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16188 if (language != LANG_ADDON) // if not addon data
16189 language = LANG_UNIVERSAL; // whispers should always be readable
16191 Player *rPlayer = objmgr.GetPlayer(receiver);
16193 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16194 if(!rPlayer->isDND() || isGameMaster())
16196 WorldPacket data(SMSG_MESSAGECHAT, 200);
16197 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16198 rPlayer->GetSession()->SendPacket(&data);
16200 data.Initialize(SMSG_MESSAGECHAT, 200);
16201 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16202 GetSession()->SendPacket(&data);
16204 else
16206 // announce to player that player he is whispering to is dnd and cannot receive his message
16207 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16210 if(!isAcceptWhispers())
16212 SetAcceptWhispers(true);
16213 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16216 // announce to player that player he is whispering to is afk
16217 if(rPlayer->isAFK())
16218 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16220 // if player whisper someone, auto turn of dnd to be able to receive an answer
16221 if(isDND() && !rPlayer->isGameMaster())
16222 ToggleDND();
16225 void Player::PetSpellInitialize()
16227 Pet* pet = GetPet();
16229 if(!pet)
16230 return;
16232 sLog.outDebug("Pet Spells Groups");
16234 CharmInfo *charmInfo = pet->GetCharmInfo();
16236 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+10*4);
16237 data << uint64(pet->GetGUID());
16238 data << uint32(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16239 data << uint32(0);
16240 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16242 // action bar loop
16243 for(uint32 i = 0; i < 10; ++i)
16245 data << uint32(charmInfo->GetActionBarEntry(i)->Raw);
16248 size_t spellsCountPos = data.wpos();
16250 // spells count
16251 uint8 addlist = 0;
16252 data << uint8(addlist); // placeholder
16254 if(pet->isControlled() && ((pet->getPetType() == HUNTER_PET) || ((pet->GetCreatureInfo()->type == CREATURE_TYPE_DEMON) && (getClass() == CLASS_WARLOCK))))
16256 // spells loop
16257 for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16259 if(itr->second->state == PETSPELL_REMOVED)
16260 continue;
16262 data << uint16(itr->first);
16263 data << uint16(itr->second->active); // pet spell active state isn't boolean
16264 ++addlist;
16268 data.put<uint8>(spellsCountPos, addlist);
16270 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16271 data << uint8(cooldownsCount);
16273 time_t curTime = time(NULL);
16275 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16277 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16279 data << uint32(itr->first); // spellid
16280 data << uint16(0); // spell category?
16281 data << uint32(cooldown); // cooldown
16282 data << uint32(0); // category cooldown
16285 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16287 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16289 data << uint32(itr->first); // spellid
16290 data << uint16(0); // spell category?
16291 data << uint32(0); // cooldown
16292 data << uint32(cooldown); // category cooldown
16295 GetSession()->SendPacket(&data);
16298 void Player::PossessSpellInitialize()
16300 Unit* charm = GetCharm();
16302 if(!charm)
16303 return;
16305 CharmInfo *charmInfo = charm->GetCharmInfo();
16307 if(!charmInfo)
16309 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16310 return;
16313 uint8 addlist = 0;
16314 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16316 //16
16317 data << uint64(charm->GetGUID());
16318 data << uint32(0x00000000);
16319 data << uint32(0);
16320 data << uint32(0);
16322 for(uint32 i = 0; i < 10; ++i) //40
16324 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16327 data << uint8(addlist); //1
16329 uint8 count = 0;
16330 data << uint8(count); // cooldowns count
16332 GetSession()->SendPacket(&data);
16335 void Player::CharmSpellInitialize()
16337 Unit* charm = GetCharm();
16339 if(!charm)
16340 return;
16342 CharmInfo *charmInfo = charm->GetCharmInfo();
16343 if(!charmInfo)
16345 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16346 return;
16349 uint8 addlist = 0;
16351 if(charm->GetTypeId() != TYPEID_PLAYER)
16353 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16355 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16357 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16359 if(charmInfo->GetCharmSpell(i)->spellId)
16360 ++addlist;
16365 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16367 data << uint64(charm->GetGUID());
16368 data << uint32(0x00000000);
16369 data << uint32(0);
16370 if(charm->GetTypeId() != TYPEID_PLAYER)
16371 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
16372 else
16373 data << uint8(0) << uint8(0);
16374 data << uint16(0);
16376 for(uint32 i = 0; i < 10; ++i) //40
16378 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16381 data << uint8(addlist); //1
16383 if(addlist)
16385 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16387 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16388 if(cspell->spellId)
16390 data << uint16(cspell->spellId);
16391 data << uint16(cspell->active);
16396 uint8 count = 0;
16397 data << uint8(count); // cooldowns count
16399 GetSession()->SendPacket(&data);
16402 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16404 if (!mod || !spellInfo)
16405 return false;
16407 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16409 // prevent apply to any spell except spell that trigger expire
16410 if(spell)
16412 if(mod->lastAffected != spell)
16413 return false;
16415 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16416 return false;
16419 return spellmgr.IsAffectedByMod(spellInfo, mod);
16422 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16424 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16426 for(int eff=0;eff<96;++eff)
16428 uint64 _mask = 0;
16429 uint64 _mask2= 0;
16430 if (eff<64) _mask = uint64(1) << (eff- 0);
16431 else _mask2= uint64(1) << (eff-64);
16432 if ( mod->mask & _mask || mod->mask2 & _mask2)
16434 int32 val = 0;
16435 for (SpellModList::const_iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16437 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16438 val += (*itr)->value;
16440 val += apply ? mod->value : -(mod->value);
16441 WorldPacket data(Opcode, (1+1+4));
16442 data << uint8(eff);
16443 data << uint8(mod->op);
16444 data << int32(val);
16445 SendDirectMessage(&data);
16449 if (apply)
16450 m_spellMods[mod->op].push_back(mod);
16451 else
16453 if (mod->charges == -1)
16454 --m_SpellModRemoveCount;
16455 m_spellMods[mod->op].remove(mod);
16456 delete mod;
16460 void Player::RemoveSpellMods(Spell const* spell)
16462 if(!spell || (m_SpellModRemoveCount == 0))
16463 return;
16465 for(int i=0;i<MAX_SPELLMOD;++i)
16467 for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16469 SpellModifier *mod = *itr;
16470 ++itr;
16472 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16474 RemoveAurasDueToSpell(mod->spellId);
16475 if (m_spellMods[i].empty())
16476 break;
16477 else
16478 itr = m_spellMods[i].begin();
16484 // send Proficiency
16485 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16487 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16488 data << pr1 << pr2;
16489 GetSession()->SendPacket (&data);
16492 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16494 QueryResult *result = NULL;
16495 if(type==10)
16496 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16497 else
16498 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16499 if(result)
16501 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.
16502 { // and SendPetitionQueryOpcode reads data from the DB
16503 Field *fields = result->Fetch();
16504 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16505 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16507 // send update if charter owner in game
16508 Player* owner = objmgr.GetPlayer(ownerguid);
16509 if(owner)
16510 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16512 } while ( result->NextRow() );
16514 delete result;
16516 if(type==10)
16517 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16518 else
16519 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16522 CharacterDatabase.BeginTransaction();
16523 if(type == 10)
16525 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16526 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16528 else
16530 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16531 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16533 CharacterDatabase.CommitTransaction();
16536 void Player::LeaveAllArenaTeams(uint64 guid)
16538 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));
16539 if(!result)
16540 return;
16544 Field *fields = result->Fetch();
16545 uint32 at_id = fields[0].GetUInt32();
16546 if(at_id != 0)
16548 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
16549 if(at)
16550 at->DelMember(guid);
16552 } while (result->NextRow());
16554 delete result;
16557 void Player::SetRestBonus (float rest_bonus_new)
16559 // Prevent resting on max level
16560 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16561 rest_bonus_new = 0;
16563 if(rest_bonus_new < 0)
16564 rest_bonus_new = 0;
16566 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16568 if(rest_bonus_new > rest_bonus_max)
16569 m_rest_bonus = rest_bonus_max;
16570 else
16571 m_rest_bonus = rest_bonus_new;
16573 // update data for client
16574 if(m_rest_bonus>10)
16575 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16576 else if(m_rest_bonus<=1)
16577 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16579 //RestTickUpdate
16580 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16583 void Player::HandleStealthedUnitsDetection()
16585 std::list<Unit*> stealthedUnits;
16587 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16588 Cell cell(p);
16589 cell.data.Part.reserved = ALL_DISTRICT;
16590 cell.SetNoCreate();
16592 MaNGOS::AnyStealthedCheck u_check;
16593 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
16595 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16596 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16598 CellLock<GridReadGuard> cell_lock(cell, p);
16599 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
16600 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
16602 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16604 if((*i)==this)
16606 i = stealthedUnits.erase(i);
16607 continue;
16610 if ((*i)->isVisibleForOrDetect(this,true))
16613 (*i)->SendUpdateToPlayer(this);
16614 m_clientGUIDs.insert((*i)->GetGUID());
16616 #ifdef MANGOS_DEBUG
16617 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16618 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16619 #endif
16621 // target aura duration for caster show only if target exist at caster client
16622 // send data at target visibility change (adding to client)
16623 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16624 SendAurasForTarget(*i);
16626 i = stealthedUnits.erase(i);
16627 continue;
16630 ++i;
16634 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
16636 if(nodes.size() < 2)
16637 return false;
16639 // not let cheating with start flight mounted
16640 if(IsMounted())
16642 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16643 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16644 GetSession()->SendPacket(&data);
16645 return false;
16648 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16650 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16651 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16652 GetSession()->SendPacket(&data);
16653 return false;
16656 // 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
16657 if(GetSession()->isLogingOut() ||
16658 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
16659 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
16660 IsNonMeleeSpellCasted(false) ||
16661 isInCombat())
16663 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16664 data << uint32(ERR_TAXIPLAYERBUSY);
16665 GetSession()->SendPacket(&data);
16666 return false;
16669 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16670 return false;
16672 uint32 sourcenode = nodes[0];
16674 // starting node too far away (cheat?)
16675 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16676 if( !node || node->map_id != GetMapId() ||
16677 (node->x - GetPositionX())*(node->x - GetPositionX())+
16678 (node->y - GetPositionY())*(node->y - GetPositionY())+
16679 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16680 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
16682 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16683 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16684 GetSession()->SendPacket(&data);
16685 return false;
16688 // Prepare to flight start now
16690 // stop combat at start taxi flight if any
16691 CombatStop();
16693 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16694 TradeCancel(true);
16696 // clean not finished taxi path if any
16697 m_taxi.ClearTaxiDestinations();
16699 // 0 element current node
16700 m_taxi.AddTaxiDestination(sourcenode);
16702 // fill destinations path tail
16703 uint32 sourcepath = 0;
16704 uint32 totalcost = 0;
16706 uint32 prevnode = sourcenode;
16707 uint32 lastnode = 0;
16709 for(uint32 i = 1; i < nodes.size(); ++i)
16711 uint32 path, cost;
16713 lastnode = nodes[i];
16714 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16716 if(!path)
16718 m_taxi.ClearTaxiDestinations();
16719 return false;
16722 totalcost += cost;
16724 if(prevnode == sourcenode)
16725 sourcepath = path;
16727 m_taxi.AddTaxiDestination(lastnode);
16729 prevnode = lastnode;
16732 if(!mount_id) // if not provide then attempt use default.
16733 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
16735 if (mount_id == 0 || sourcepath == 0)
16737 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16738 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16739 GetSession()->SendPacket(&data);
16740 m_taxi.ClearTaxiDestinations();
16741 return false;
16744 uint32 money = GetMoney();
16746 if(npc)
16748 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16751 if(money < totalcost)
16753 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16754 data << uint32(ERR_TAXINOTENOUGHMONEY);
16755 GetSession()->SendPacket(&data);
16756 m_taxi.ClearTaxiDestinations();
16757 return false;
16760 //Checks and preparations done, DO FLIGHT
16761 ModifyMoney(-(int32)totalcost);
16762 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
16764 // prevent stealth flight
16765 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16767 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16768 data << uint32(ERR_TAXIOK);
16769 GetSession()->SendPacket(&data);
16771 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16773 GetSession()->SendDoFlight(mount_id, sourcepath);
16775 return true;
16778 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16780 // last check 2.0.10
16781 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16782 data << GetGUID();
16783 data << uint8(0x0); // flags (0x1, 0x2)
16784 time_t curTime = time(NULL);
16785 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
16787 if (itr->second->state == PLAYERSPELL_REMOVED)
16788 continue;
16789 uint32 unSpellId = itr->first;
16790 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
16791 if (!spellInfo)
16793 ASSERT(spellInfo);
16794 continue;
16797 // Not send cooldown for this spells
16798 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
16799 continue;
16801 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
16803 data << unSpellId;
16804 data << unTimeMs; // in m.secs
16805 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
16808 GetSession()->SendPacket(&data);
16811 void Player::InitDataForForm(bool reapplyMods)
16813 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
16814 if(ssEntry && ssEntry->attackSpeed)
16816 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
16817 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
16818 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
16820 else
16821 SetRegularAttackTime();
16823 switch(m_form)
16825 case FORM_CAT:
16827 if(getPowerType()!=POWER_ENERGY)
16828 setPowerType(POWER_ENERGY);
16829 break;
16831 case FORM_BEAR:
16832 case FORM_DIREBEAR:
16834 if(getPowerType()!=POWER_RAGE)
16835 setPowerType(POWER_RAGE);
16836 break;
16838 default: // 0, for example
16840 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
16841 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
16842 setPowerType(Powers(cEntry->powerType));
16843 break;
16847 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16848 if (!reapplyMods)
16849 UpdateEquipSpellsAtFormChange();
16851 UpdateAttackPowerAndDamage();
16852 UpdateAttackPowerAndDamage(true);
16855 // Return true is the bought item has a max count to force refresh of window by caller
16856 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
16858 // cheating attempt
16859 if(count < 1) count = 1;
16861 if(!isAlive())
16862 return false;
16864 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
16865 if( !pProto )
16867 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
16868 return false;
16871 Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
16872 if (!pCreature)
16874 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
16875 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
16876 return false;
16879 VendorItemData const* vItems = pCreature->GetVendorItems();
16880 if(!vItems || vItems->Empty())
16882 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16883 return false;
16886 size_t vendor_slot = vItems->FindItemSlot(item);
16887 if(vendor_slot >= vItems->GetItemCount())
16889 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16890 return false;
16893 VendorItem const* crItem = vItems->m_items[vendor_slot];
16895 // check current item amount if it limited
16896 if( crItem->maxcount != 0 )
16898 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
16900 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
16901 return false;
16905 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
16907 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
16908 return false;
16911 if(crItem->ExtendedCost)
16913 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16914 if(!iece)
16916 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
16917 return false;
16920 // honor points price
16921 if(GetHonorPoints() < (iece->reqhonorpoints * count))
16923 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
16924 return false;
16927 // arena points price
16928 if(GetArenaPoints() < (iece->reqarenapoints * count))
16930 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
16931 return false;
16934 // item base price
16935 for (uint8 i = 0; i < 5; ++i)
16937 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
16939 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
16940 return false;
16944 // check for personal arena rating requirement
16945 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
16947 // probably not the proper equip err
16948 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
16949 return false;
16953 uint32 price = pProto->BuyPrice * count;
16955 // reputation discount
16956 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
16958 if( GetMoney() < price )
16960 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
16961 return false;
16964 uint8 bag = 0; // init for case invalid bagGUID
16966 if (bagguid != NULL_BAG && slot != NULL_SLOT)
16968 Bag *pBag;
16969 if( bagguid == GetGUID() )
16971 bag = INVENTORY_SLOT_BAG_0;
16973 else
16975 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;++i)
16977 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
16978 if( pBag )
16980 if( bagguid == pBag->GetGUID() )
16982 bag = i;
16983 break;
16990 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
16992 ItemPosCountVec dest;
16993 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
16994 if( msg != EQUIP_ERR_OK )
16996 SendEquipError( msg, NULL, NULL );
16997 return false;
17000 ModifyMoney( -(int32)price );
17001 if(crItem->ExtendedCost) // case for new honor system
17003 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17004 if(iece->reqhonorpoints)
17005 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17006 if(iece->reqarenapoints)
17007 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17008 for (uint8 i = 0; i < 5; ++i)
17010 if(iece->reqitem[i])
17011 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17015 if(Item *it = StoreNewItem( dest, item, true ))
17017 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17019 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17020 data << pCreature->GetGUID();
17021 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17022 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17023 data << (uint32)count;
17024 GetSession()->SendPacket(&data);
17026 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17029 else if( IsEquipmentPos( bag, slot ) )
17031 if(pProto->BuyCount * count != 1)
17033 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17034 return false;
17037 uint16 dest;
17038 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17039 if( msg != EQUIP_ERR_OK )
17041 SendEquipError( msg, NULL, NULL );
17042 return false;
17045 ModifyMoney( -(int32)price );
17046 if(crItem->ExtendedCost) // case for new honor system
17048 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17049 if(iece->reqhonorpoints)
17050 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17051 if(iece->reqarenapoints)
17052 ModifyArenaPoints( - int32(iece->reqarenapoints));
17053 for (uint8 i = 0; i < 5; ++i)
17055 if(iece->reqitem[i])
17056 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17060 if(Item *it = EquipNewItem( dest, item, true ))
17062 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17064 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17065 data << pCreature->GetGUID();
17066 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17067 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17068 data << (uint32)count;
17069 GetSession()->SendPacket(&data);
17071 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17073 AutoUnequipOffhandIfNeed();
17076 else
17078 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17079 return false;
17082 return crItem->maxcount!=0;
17085 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17087 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17088 // the personal rating of the arena team must match the required limit as well
17089 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17090 uint32 max_personal_rating = 0;
17091 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17093 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17095 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17096 uint32 t_rating = at->GetRating();
17097 p_rating = p_rating<t_rating? p_rating : t_rating;
17098 if(max_personal_rating < p_rating)
17099 max_personal_rating = p_rating;
17102 return max_personal_rating;
17105 void Player::UpdateHomebindTime(uint32 time)
17107 // GMs never get homebind timer online
17108 if (m_InstanceValid || isGameMaster())
17110 if(m_HomebindTimer) // instance valid, but timer not reset
17112 // hide reminder
17113 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17114 data << uint32(0);
17115 data << uint32(0);
17116 GetSession()->SendPacket(&data);
17118 // instance is valid, reset homebind timer
17119 m_HomebindTimer = 0;
17121 else if (m_HomebindTimer > 0)
17123 if (time >= m_HomebindTimer)
17125 // teleport to nearest graveyard
17126 RepopAtGraveyard();
17128 else
17129 m_HomebindTimer -= time;
17131 else
17133 // instance is invalid, start homebind timer
17134 m_HomebindTimer = 60000;
17135 // send message to player
17136 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17137 data << m_HomebindTimer;
17138 data << uint32(1);
17139 GetSession()->SendPacket(&data);
17140 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17144 void Player::UpdatePvP(bool state, bool ovrride)
17146 if(!state || ovrride)
17148 SetPvP(state);
17149 if(Pet* pet = GetPet())
17150 pet->SetPvP(state);
17151 if(Unit* charmed = GetCharm())
17152 charmed->SetPvP(state);
17154 pvpInfo.endTimer = 0;
17156 else
17158 if(pvpInfo.endTimer != 0)
17159 pvpInfo.endTimer = time(NULL);
17160 else
17162 SetPvP(state);
17164 if(Pet* pet = GetPet())
17165 pet->SetPvP(state);
17166 if(Unit* charmed = GetCharm())
17167 charmed->SetPvP(state);
17172 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
17174 // init cooldown values
17175 uint32 cat = 0;
17176 int32 rec = -1;
17177 int32 catrec = -1;
17179 // some special item spells without correct cooldown in SpellInfo
17180 // cooldown information stored in item prototype
17181 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17183 if(itemId)
17185 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
17187 for(int idx = 0; idx < 5; ++idx)
17189 if(proto->Spells[idx].SpellId == spellInfo->Id)
17191 cat = proto->Spells[idx].SpellCategory;
17192 rec = proto->Spells[idx].SpellCooldown;
17193 catrec = proto->Spells[idx].SpellCategoryCooldown;
17194 break;
17200 // if no cooldown found above then base at DBC data
17201 if(rec < 0 && catrec < 0)
17203 cat = spellInfo->Category;
17204 rec = spellInfo->RecoveryTime;
17205 catrec = spellInfo->CategoryRecoveryTime;
17208 time_t curTime = time(NULL);
17210 time_t catrecTime;
17211 time_t recTime;
17213 // overwrite time for selected category
17214 if(infinityCooldown)
17216 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17217 // but not allow ignore until reset or re-login
17218 catrecTime = catrec > 0 ? curTime+MONTH : 0;
17219 recTime = rec > 0 ? curTime+MONTH : catrecTime;
17221 else
17223 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17224 // prevent 0 cooldowns set by another way
17225 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
17226 rec = GetAttackTime(RANGED_ATTACK);
17228 // Now we have cooldown data (if found any), time to apply mods
17229 if(rec > 0)
17230 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
17232 if(catrec > 0)
17233 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
17235 // replace negative cooldowns by 0
17236 if (rec < 0) rec = 0;
17237 if (catrec < 0) catrec = 0;
17239 // no cooldown after applying spell mods
17240 if( rec == 0 && catrec == 0)
17241 return;
17243 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
17244 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
17247 // self spell cooldown
17248 if(recTime > 0)
17249 AddSpellCooldown(spellInfo->Id, itemId, recTime);
17251 // category spells
17252 if (cat && catrec > 0)
17254 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
17255 if(i_scstore != sSpellCategoryStore.end())
17257 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
17259 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
17260 continue;
17262 AddSpellCooldown(*i_scset, itemId, catrecTime);
17268 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17270 SpellCooldown sc;
17271 sc.end = end_time;
17272 sc.itemid = itemid;
17273 m_spellCooldowns[spellid] = sc;
17276 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
17278 // start cooldowns at server side, if any
17279 AddSpellAndCategoryCooldowns(spellInfo,itemId,spell);
17281 // Send activate cooldown timer (possible 0) at client side
17282 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17283 data << spellInfo->Id;
17284 data << GetGUID();
17285 SendDirectMessage(&data);
17288 void Player::UpdatePotionCooldown(Spell* spell)
17290 // no potion used i combat or still in combat
17291 if(!m_lastPotionId || isInCombat())
17292 return;
17294 // Call not from spell cast, send cooldown event for item spells if no in combat
17295 if(!spell)
17297 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17298 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
17299 for(int idx = 0; idx < 5; ++idx)
17300 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
17301 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
17302 SendCooldownEvent(spellInfo,m_lastPotionId);
17304 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17305 else
17306 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
17308 m_lastPotionId = 0;
17311 //slot to be excluded while counting
17312 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17314 if(!enchantmentcondition)
17315 return true;
17317 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17319 if(!Condition)
17320 return true;
17322 uint8 curcount[4] = {0, 0, 0, 0};
17324 //counting current equipped gem colors
17325 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17327 if(i == slot)
17328 continue;
17329 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17330 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17332 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17334 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17335 if(!enchant_id)
17336 continue;
17338 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17339 if(!enchantEntry)
17340 continue;
17342 uint32 gemid = enchantEntry->GemID;
17343 if(!gemid)
17344 continue;
17346 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17347 if(!gemProto)
17348 continue;
17350 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17351 if(!gemProperty)
17352 continue;
17354 uint8 GemColor = gemProperty->color;
17356 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17358 if(tmpcolormask & GemColor)
17359 ++curcount[b];
17365 bool activate = true;
17367 for(int i = 0; i < 5; ++i)
17369 if(!Condition->Color[i])
17370 continue;
17372 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17374 // if have <CompareColor> use them as count, else use <value> from Condition
17375 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17377 switch(Condition->Comparator[i])
17379 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17380 activate &= (_cur_gem < _cmp_gem) ? true : false;
17381 break;
17382 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17383 activate &= (_cur_gem > _cmp_gem) ? true : false;
17384 break;
17385 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17386 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17387 break;
17391 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");
17393 return activate;
17396 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17398 //cycle all equipped items
17399 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17401 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17402 if(slot == exceptslot)
17403 continue;
17405 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17407 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17408 continue;
17410 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17412 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17413 if(!enchant_id)
17414 continue;
17416 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17417 if(!enchantEntry)
17418 continue;
17420 uint32 condition = enchantEntry->EnchantmentCondition;
17421 if(condition)
17423 //was enchant active with/without item?
17424 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17425 //should it now be?
17426 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17428 // ignore item gem conditions
17429 //if state changed, (dis)apply enchant
17430 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17437 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17438 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17440 //cycle all equipped items
17441 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17443 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17444 if(slot == exceptslot)
17445 continue;
17447 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17449 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17450 continue;
17452 //cycle all (gem)enchants
17453 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17455 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17456 if(!enchant_id) //if no enchant go to next enchant(slot)
17457 continue;
17459 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17460 if(!enchantEntry)
17461 continue;
17463 //only metagems to be (de)activated, so only enchants with condition
17464 uint32 condition = enchantEntry->EnchantmentCondition;
17465 if(condition)
17466 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17471 void Player::LeaveBattleground(bool teleportToEntryPoint)
17473 if(BattleGround *bg = GetBattleGround())
17475 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17477 // call after remove to be sure that player resurrected for correct cast
17478 if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) )
17480 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
17481 CastSpell(this, 26013, true); // Deserter
17486 bool Player::CanJoinToBattleground() const
17488 // check Deserter debuff
17489 if(GetDummyAura(26013))
17490 return false;
17492 return true;
17495 bool Player::CanReportAfkDueToLimit()
17497 // a player can complain about 15 people per 5 minutes
17498 if(m_bgAfkReportedCount >= 15)
17499 return false;
17500 ++m_bgAfkReportedCount;
17501 return true;
17504 ///This player has been blamed to be inactive in a battleground
17505 void Player::ReportedAfkBy(Player* reporter)
17507 BattleGround *bg = GetBattleGround();
17508 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17509 return;
17511 // check if player has 'Idle' or 'Inactive' debuff
17512 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17514 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17515 // 3 players have to complain to apply debuff
17516 if(m_bgAfkReporter.size() >= 3)
17518 // cast 'Idle' spell
17519 CastSpell(this, 43680, true);
17520 m_bgAfkReporter.clear();
17525 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17527 // gamemaster in GM mode see all, including ghosts
17528 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17529 return true;
17531 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17532 if (InBattleGround())
17534 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17535 return false;
17536 return true;
17539 // Live player see live player or dead player with not realized corpse
17540 if(pl->isAlive() || pl->m_deathTimer > 0)
17542 return isAlive() || m_deathTimer > 0;
17545 // Ghost see other friendly ghosts, that's for sure
17546 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17547 return true;
17549 // Dead player see live players near own corpse
17550 if(isAlive())
17552 Corpse *corpse = pl->GetCorpse();
17553 if(corpse)
17555 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17556 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17557 return true;
17561 // and not see any other
17562 return false;
17565 bool Player::IsVisibleGloballyFor( Player* u ) const
17567 if(!u)
17568 return false;
17570 // Always can see self
17571 if (u==this)
17572 return true;
17574 // Visible units, always are visible for all players
17575 if (GetVisibility() == VISIBILITY_ON)
17576 return true;
17578 // GMs are visible for higher gms (or players are visible for gms)
17579 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17580 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17582 // non faction visibility non-breakable for non-GMs
17583 if (GetVisibility() == VISIBILITY_OFF)
17584 return false;
17586 // non-gm stealth/invisibility not hide from global player lists
17587 return true;
17590 void Player::UpdateVisibilityOf(WorldObject* target)
17592 if(HaveAtClient(target))
17594 if(!target->isVisibleForInState(this,true))
17596 target->DestroyForPlayer(this);
17597 m_clientGUIDs.erase(target->GetGUID());
17599 #ifdef MANGOS_DEBUG
17600 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17601 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17602 #endif
17605 else
17607 if(target->isVisibleForInState(this,false))
17609 target->SendUpdateToPlayer(this);
17610 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17611 m_clientGUIDs.insert(target->GetGUID());
17613 #ifdef MANGOS_DEBUG
17614 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17615 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17616 #endif
17618 // target aura duration for caster show only if target exist at caster client
17619 // send data at target visibility change (adding to client)
17620 if(target!=this && target->isType(TYPEMASK_UNIT))
17621 SendAurasForTarget((Unit*)target);
17623 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17624 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17629 template<class T>
17630 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17632 s64.insert(target->GetGUID());
17635 template<>
17636 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17638 if(!target->IsTransport())
17639 s64.insert(target->GetGUID());
17642 template<class T>
17643 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17645 if(HaveAtClient(target))
17647 if(!target->isVisibleForInState(this,true))
17649 target->BuildOutOfRangeUpdateBlock(&data);
17650 m_clientGUIDs.erase(target->GetGUID());
17652 #ifdef MANGOS_DEBUG
17653 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17654 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));
17655 #endif
17658 else
17660 if(target->isVisibleForInState(this,false))
17662 visibleNow.insert(target);
17663 target->BuildUpdate(data_updates);
17664 target->BuildCreateUpdateBlockForPlayer(&data, this);
17665 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17667 #ifdef MANGOS_DEBUG
17668 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17669 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));
17670 #endif
17675 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17676 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17677 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17678 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17679 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17681 void Player::InitPrimaryProffesions()
17683 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17686 void Player::SendComboPoints()
17688 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17689 if (combotarget)
17691 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17692 data.append(combotarget->GetPackGUID());
17693 data << uint8(m_comboPoints);
17694 GetSession()->SendPacket(&data);
17698 void Player::AddComboPoints(Unit* target, int8 count)
17700 if(!count)
17701 return;
17703 // without combo points lost (duration checked in aura)
17704 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17706 if(target->GetGUID() == m_comboTarget)
17708 m_comboPoints += count;
17710 else
17712 if(m_comboTarget)
17713 if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget))
17714 target2->RemoveComboPointHolder(GetGUIDLow());
17716 m_comboTarget = target->GetGUID();
17717 m_comboPoints = count;
17719 target->AddComboPointHolder(GetGUIDLow());
17722 if (m_comboPoints > 5) m_comboPoints = 5;
17723 if (m_comboPoints < 0) m_comboPoints = 0;
17725 SendComboPoints();
17728 void Player::ClearComboPoints()
17730 if(!m_comboTarget)
17731 return;
17733 // without combopoints lost (duration checked in aura)
17734 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17736 m_comboPoints = 0;
17738 SendComboPoints();
17740 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17741 target->RemoveComboPointHolder(GetGUIDLow());
17743 m_comboTarget = 0;
17746 void Player::SetGroup(Group *group, int8 subgroup)
17748 if(group == NULL)
17749 m_group.unlink();
17750 else
17752 // never use SetGroup without a subgroup unless you specify NULL for group
17753 assert(subgroup >= 0);
17754 m_group.link(group, this);
17755 m_group.setSubGroup((uint8)subgroup);
17759 void Player::SendInitialPacketsBeforeAddToMap()
17761 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
17762 data << uint32(0); // unknown, may be rest state time or experience
17763 GetSession()->SendPacket(&data);
17765 GetSocial()->SendSocialList();
17767 // Homebind
17768 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17769 data << m_homebindX << m_homebindY << m_homebindZ;
17770 data << (uint32) m_homebindMapId;
17771 data << (uint32) m_homebindZoneId;
17772 GetSession()->SendPacket(&data);
17774 // SMSG_SET_PROFICIENCY
17775 // SMSG_UPDATE_AURA_DURATION
17777 SendTalentsInfoData(false);
17778 SendInitialSpells();
17780 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17781 data << uint32(0); // count, for(count) uint32;
17782 GetSession()->SendPacket(&data);
17784 SendInitialActionButtons();
17785 m_reputationMgr.SendInitialReputations();
17786 m_achievementMgr.SendAllAchievementData();
17788 // update zone
17789 uint32 newzone, newarea;
17790 GetZoneAndAreaId(newzone,newarea);
17791 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
17793 SendEquipmentSetList();
17795 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
17796 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
17797 data << (float)0.01666667f; // game speed
17798 data << uint32(0); // added in 3.1.2
17799 GetSession()->SendPacket( &data );
17801 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17802 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
17803 m_movementInfo.flags |= MOVEMENTFLAG_FLYING2;
17805 m_mover = this;
17808 void Player::SendInitialPacketsAfterAddToMap()
17810 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
17811 data << uint32(0x00000000); // on blizz it increments periodically
17812 GetSession()->SendPacket(&data);
17814 CastSpell(this, 836, true); // LOGINEFFECT
17816 // set some aura effects that send packet to player client after add player to map
17817 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17818 // same auras state lost at far teleport, send it one more time in this case also
17819 static const AuraType auratypes[] =
17821 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
17822 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
17823 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
17825 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
17827 Unit::AuraList const& auraList = GetAurasByType(*itr);
17828 if(!auraList.empty())
17829 auraList.front()->ApplyModifier(true,true);
17832 if(HasAuraType(SPELL_AURA_MOD_STUN))
17833 SetMovement(MOVE_ROOT);
17835 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17836 if(HasAuraType(SPELL_AURA_MOD_ROOT))
17838 WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
17839 data2.append(GetPackGUID());
17840 data2 << (uint32)2;
17841 SendMessageToSet(&data2,true);
17844 SendAurasForTarget(this);
17845 SendEnchantmentDurations(); // must be after add to map
17846 SendItemDurations(); // must be after add to map
17849 void Player::SendUpdateToOutOfRangeGroupMembers()
17851 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
17852 return;
17853 if(Group* group = GetGroup())
17854 group->UpdatePlayerOutOfRange(this);
17856 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
17857 m_auraUpdateMask = 0;
17858 if(Pet *pet = GetPet())
17859 pet->ResetAuraUpdateMask();
17862 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
17864 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
17865 data << uint32(mapid);
17866 data << uint8(reason); // transfer abort reason
17867 switch(reason)
17869 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
17870 case TRANSFER_ABORT_DIFFICULTY:
17871 case TRANSFER_ABORT_UNIQUE_MESSAGE:
17872 data << uint8(arg);
17873 break;
17875 GetSession()->SendPacket(&data);
17878 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
17880 // type of warning, based on the time remaining until reset
17881 uint32 type;
17882 if(time > 3600)
17883 type = RAID_INSTANCE_WELCOME;
17884 else if(time > 900 && time <= 3600)
17885 type = RAID_INSTANCE_WARNING_HOURS;
17886 else if(time > 300 && time <= 900)
17887 type = RAID_INSTANCE_WARNING_MIN;
17888 else
17889 type = RAID_INSTANCE_WARNING_MIN_SOON;
17890 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
17891 data << uint32(type);
17892 data << uint32(mapid);
17893 data << uint32(time);
17894 GetSession()->SendPacket(&data);
17897 void Player::ApplyEquipCooldown( Item * pItem )
17899 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
17901 _Spell const& spellData = pItem->GetProto()->Spells[i];
17903 // no spell
17904 if( !spellData.SpellId )
17905 continue;
17907 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17908 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
17909 continue;
17911 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
17913 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
17914 data << pItem->GetGUID();
17915 data << uint32(spellData.SpellId);
17916 GetSession()->SendPacket(&data);
17920 void Player::resetSpells()
17922 // not need after this call
17923 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
17925 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
17926 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
17929 // make full copy of map (spells removed and marked as deleted at another spell remove
17930 // and we can't use original map for safe iterative with visit each spell at loop end
17931 PlayerSpellMap smap = GetSpellMap();
17933 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
17934 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
17936 learnDefaultSpells();
17937 learnQuestRewardedSpells();
17940 void Player::learnDefaultSpells()
17942 // learn default race/class spells
17943 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
17944 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
17946 uint32 tspell = *itr;
17947 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
17948 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
17949 addSpell(tspell,true,true,true,false);
17950 else // but send in normal spell in game learn case
17951 learnSpell(tspell,true);
17955 void Player::learnQuestRewardedSpells(Quest const* quest)
17957 uint32 spell_id = quest->GetRewSpellCast();
17959 // skip quests without rewarded spell
17960 if( !spell_id )
17961 return;
17963 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
17964 if(!spellInfo)
17965 return;
17967 // check learned spells state
17968 bool found = false;
17969 for(int i=0; i < 3; ++i)
17971 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
17973 found = true;
17974 break;
17978 // skip quests with not teaching spell or already known spell
17979 if(!found)
17980 return;
17982 // prevent learn non first rank unknown profession and second specialization for same profession)
17983 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
17984 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
17986 // not have first rank learned (unlearned prof?)
17987 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
17988 if( !HasSpell(first_spell) )
17989 return;
17991 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
17992 if(!learnedInfo)
17993 return;
17995 // specialization
17996 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
17998 // search other specialization for same prof
17999 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
18001 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
18002 continue;
18004 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
18005 if(!itrInfo)
18006 return;
18008 // compare only specializations
18009 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18010 continue;
18012 // compare same chain spells
18013 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18014 continue;
18016 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18017 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18018 return;
18023 CastSpell( this, spell_id, true);
18026 void Player::learnQuestRewardedSpells()
18028 // learn spells received from quest completing
18029 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18031 // skip no rewarded quests
18032 if(!itr->second.m_rewarded)
18033 continue;
18035 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18036 if( !quest )
18037 continue;
18039 learnQuestRewardedSpells(quest);
18043 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
18045 uint32 raceMask = getRaceMask();
18046 uint32 classMask = getClassMask();
18047 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18049 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18050 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18051 continue;
18052 // Check race if set
18053 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18054 continue;
18055 // Check class if set
18056 if (pAbility->classmask && !(pAbility->classmask & classMask))
18057 continue;
18059 if (sSpellStore.LookupEntry(pAbility->spellId))
18061 // need unlearn spell
18062 if (skill_value < pAbility->req_skill_value)
18063 removeSpell(pAbility->spellId);
18064 // need learn
18065 else if (!IsInWorld())
18066 addSpell(pAbility->spellId,true,true,true,false);
18067 else
18068 learnSpell(pAbility->spellId,true);
18073 void Player::SendAurasForTarget(Unit *target)
18075 if(target->GetVisibleAuras()->empty()) // speedup things
18076 return;
18078 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18079 data.append(target->GetPackGUID());
18081 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18082 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18084 for(uint32 j = 0; j < 3; ++j)
18086 if(Aura *aura = target->GetAura(itr->second, j))
18088 data << uint8(aura->GetAuraSlot());
18089 data << uint32(aura->GetId());
18091 if(aura->GetId())
18093 uint8 auraFlags = aura->GetAuraFlags();
18094 // flags
18095 data << uint8(auraFlags);
18096 // level
18097 data << uint8(aura->GetAuraLevel());
18098 // charges
18099 data << uint8(aura->GetAuraCharges());
18101 if(!(auraFlags & AFLAG_NOT_CASTER))
18103 data << uint8(0); // packed GUID of someone (caster?)
18106 if(auraFlags & AFLAG_DURATION) // include aura duration
18108 data << uint32(aura->GetAuraMaxDuration());
18109 data << uint32(aura->GetAuraDuration());
18112 break;
18117 GetSession()->SendPacket(&data);
18120 void Player::SetDailyQuestStatus( uint32 quest_id )
18122 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18124 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18126 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18127 m_lastDailyQuestTime = time(NULL); // last daily quest time
18128 m_DailyQuestChanged = true;
18129 break;
18134 void Player::ResetDailyQuestStatus()
18136 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18137 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18139 // DB data deleted in caller
18140 m_DailyQuestChanged = false;
18141 m_lastDailyQuestTime = 0;
18144 BattleGround* Player::GetBattleGround() const
18146 if(GetBattleGroundId()==0)
18147 return NULL;
18149 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgTypeID);
18152 bool Player::InArena() const
18154 BattleGround *bg = GetBattleGround();
18155 if(!bg || !bg->isArena())
18156 return false;
18158 return true;
18161 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
18163 // get a template bg instead of running one
18164 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18165 if(!bg)
18166 return false;
18168 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18169 return false;
18171 return true;
18174 BGQueueIdBasedOnLevel Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId) const
18176 //returned to hardcoded version of this function, because there is no way to code it dynamic
18177 uint32 level = getLevel();
18178 if( bgTypeId == BATTLEGROUND_AV )
18179 level--;
18181 uint32 queue_id = (level / 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18182 if( queue_id >= MAX_BATTLEGROUND_QUEUES )
18184 sLog.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id);
18185 return QUEUE_ID_MAX_LEVEL_80;
18187 return BGQueueIdBasedOnLevel(queue_id);
18190 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18192 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18193 if(!vendor_faction || !vendor_faction->faction)
18194 return 1.0f;
18196 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18197 if(rank <= REP_NEUTRAL)
18198 return 1.0f;
18200 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18203 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18205 uint32 racemask = getRaceMask();
18206 uint32 classmask = getClassMask();
18208 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
18209 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
18210 if(lower==upper)
18211 return true;
18213 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
18215 // skip wrong race skills
18216 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18217 continue;
18219 // skip wrong class skills
18220 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18221 continue;
18223 return true;
18226 return false;
18229 bool Player::HasQuestForGO(int32 GOId) const
18231 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
18233 uint32 questid = GetQuestSlotQuestId(i);
18234 if ( questid == 0 )
18235 continue;
18237 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
18238 if(qs_itr == mQuestStatus.end())
18239 continue;
18241 QuestStatusData const& qs = qs_itr->second;
18243 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18245 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
18246 if(!qinfo)
18247 continue;
18249 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18250 continue;
18252 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
18254 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18255 continue;
18257 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18258 return true;
18262 return false;
18265 void Player::UpdateForQuestsGO()
18267 if(m_clientGUIDs.empty())
18268 return;
18270 UpdateData udata;
18271 WorldPacket packet;
18272 for(ClientGUIDs::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18274 if(IS_GAMEOBJECT_GUID(*itr))
18276 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18277 if(obj)
18278 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18281 udata.BuildPacket(&packet);
18282 GetSession()->SendPacket(&packet);
18285 void Player::SummonIfPossible(bool agree)
18287 if(!agree)
18289 m_summon_expire = 0;
18290 return;
18293 // expire and auto declined
18294 if(m_summon_expire < time(NULL))
18295 return;
18297 // stop taxi flight at summon
18298 if(isInFlight())
18300 GetMotionMaster()->MovementExpired();
18301 m_taxi.ClearTaxiDestinations();
18304 // drop flag at summon
18305 // this code can be reached only when GM is summoning player who carries flag, because player should be immune to summoning spells when he carries flag
18306 if(BattleGround *bg = GetBattleGround())
18307 bg->EventPlayerDroppedFlag(this);
18309 m_summon_expire = 0;
18311 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18314 void Player::RemoveItemDurations( Item *item )
18316 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18318 if(*itr==item)
18320 m_itemDuration.erase(itr);
18321 break;
18326 void Player::AddItemDurations( Item *item )
18328 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18330 m_itemDuration.push_back(item);
18331 item->SendTimeUpdate(this);
18335 void Player::AutoUnequipOffhandIfNeed()
18337 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18338 if(!offItem)
18339 return;
18341 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18342 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
18343 return;
18345 ItemPosCountVec off_dest;
18346 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18347 if( off_msg == EQUIP_ERR_OK )
18349 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18350 StoreItem( off_dest, offItem, true );
18352 else
18354 MailItemsInfo mi;
18355 mi.AddItem(offItem->GetGUIDLow(), offItem->GetEntry(), offItem);
18356 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18357 CharacterDatabase.BeginTransaction();
18358 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
18359 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18360 CharacterDatabase.CommitTransaction();
18362 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
18363 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
18367 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18369 if(spellInfo->EquippedItemClass < 0)
18370 return true;
18372 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18373 // for optimize check 2 used cases only
18374 switch(spellInfo->EquippedItemClass)
18376 case ITEM_CLASS_WEAPON:
18378 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18379 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18380 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18381 return true;
18382 break;
18384 case ITEM_CLASS_ARMOR:
18386 // tabard not have dependent spells
18387 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18388 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18389 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18390 return true;
18392 // shields can be equipped to offhand slot
18393 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18394 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18395 return true;
18397 // ranged slot can have some armor subclasses
18398 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18399 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18400 return true;
18402 break;
18404 default:
18405 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18406 break;
18409 return false;
18412 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18414 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18415 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18416 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18417 return true;
18419 // Check no reagent use mask
18420 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18421 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18422 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18423 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18424 return true;
18426 return false;
18429 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18431 AuraMap& auras = GetAuras();
18432 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); )
18434 Aura* aura = itr->second;
18436 // skip passive (passive item dependent spells work in another way) and not self applied auras
18437 SpellEntry const* spellInfo = aura->GetSpellProto();
18438 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18440 ++itr;
18441 continue;
18444 // skip if not item dependent or have alternative item
18445 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18447 ++itr;
18448 continue;
18451 // no alt item, remove aura, restart check
18452 RemoveAurasDueToSpell(aura->GetId());
18453 itr = auras.begin();
18456 // currently casted spells can be dependent from item
18457 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
18459 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18460 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18461 InterruptSpell(i);
18465 uint32 Player::GetResurrectionSpellId()
18467 // search priceless resurrection possibilities
18468 uint32 prio = 0;
18469 uint32 spell_id = 0;
18470 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18471 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18473 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18474 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18476 switch((*itr)->GetId())
18478 case 20707: spell_id = 3026; break; // rank 1
18479 case 20762: spell_id = 20758; break; // rank 2
18480 case 20763: spell_id = 20759; break; // rank 3
18481 case 20764: spell_id = 20760; break; // rank 4
18482 case 20765: spell_id = 20761; break; // rank 5
18483 case 27239: spell_id = 27240; break; // rank 6
18484 case 47883: spell_id = 47882; break; // rank 7
18485 default:
18486 sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
18487 continue;
18490 prio = 3;
18492 // Twisting Nether // prio: 2 (max)
18493 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18495 prio = 2;
18496 spell_id = 23700;
18500 // Reincarnation (passive spell) // prio: 1
18501 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18502 spell_id = 21169;
18504 return spell_id;
18507 // Used in triggers for check "Only to targets that grant experience or honor" req
18508 bool Player::isHonorOrXPTarget(Unit* pVictim)
18510 uint32 v_level = pVictim->getLevel();
18511 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
18513 // Victim level less gray level
18514 if(v_level<=k_grey)
18515 return false;
18517 if(pVictim->GetTypeId() == TYPEID_UNIT)
18519 if (((Creature*)pVictim)->isTotem() ||
18520 ((Creature*)pVictim)->isPet() ||
18521 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
18522 return false;
18524 return true;
18527 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18529 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18531 // prepare data for near group iteration (PvP and !PvP cases)
18532 uint32 xp = 0;
18533 bool honored_kill = false;
18535 if(Group *pGroup = GetGroup())
18537 uint32 count = 0;
18538 uint32 sum_level = 0;
18539 Player* member_with_max_level = NULL;
18540 Player* not_gray_member_with_max_level = NULL;
18542 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18544 if(member_with_max_level)
18546 /// not get Xp in PvP or no not gray players in group
18547 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18549 /// skip in check PvP case (for speed, not used)
18550 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18551 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18552 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18554 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18556 Player* pGroupGuy = itr->getSource();
18557 if(!pGroupGuy)
18558 continue;
18560 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18561 continue; // member (alive or dead) or his corpse at req. distance
18563 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18564 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18565 honored_kill = true;
18567 // xp and reputation only in !PvP case
18568 if(!PvP)
18570 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18572 // if is in dungeon then all receive full reputation at kill
18573 // rewarded any alive/dead/near_corpse group member
18574 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18576 // XP updated only for alive group member
18577 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18578 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18580 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18582 pGroupGuy->GiveXP(itr_xp, pVictim);
18583 if(Pet* pet = pGroupGuy->GetPet())
18584 pet->GivePetXP(itr_xp/2);
18587 // quest objectives updated only for alive group member or dead but with not released body
18588 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18590 // normal creature (not pet/etc) can be only in !PvP case
18591 if(pVictim->GetTypeId()==TYPEID_UNIT)
18592 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18598 else // if (!pGroup)
18600 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18602 // honor can be in PvP and !PvP (racial leader) cases
18603 if(RewardHonor(pVictim,1))
18604 honored_kill = true;
18606 // xp and reputation only in !PvP case
18607 if(!PvP)
18609 RewardReputation(pVictim,1);
18610 GiveXP(xp, pVictim);
18612 if(Pet* pet = GetPet())
18613 pet->GivePetXP(xp);
18615 // normal creature (not pet/etc) can be only in !PvP case
18616 if(pVictim->GetTypeId()==TYPEID_UNIT)
18617 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18620 return xp || honored_kill;
18623 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
18625 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
18627 // prepare data for near group iteration
18628 if(Group *pGroup = GetGroup())
18630 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18632 Player* pGroupGuy = itr->getSource();
18633 if(!pGroupGuy)
18634 continue;
18636 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
18637 continue; // member (alive or dead) or his corpse at req. distance
18639 // quest objectives updated only for alive group member or dead but with not released body
18640 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18641 pGroupGuy->KilledMonster(creature_id, creature_guid);
18644 else // if (!pGroup)
18645 KilledMonster(creature_id, creature_guid);
18648 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18650 if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE)))
18651 return true;
18653 if (isAlive())
18654 return false;
18656 Corpse* corpse = GetCorpse();
18657 if (!corpse)
18658 return false;
18660 return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE));
18663 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18665 Item* item = GetWeaponForAttack(attType,true);
18667 // unarmed only with base attack
18668 if(attType != BASE_ATTACK && !item)
18669 return 0;
18671 // weapon skill or (unarmed for base attack)
18672 uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
18673 return GetBaseSkillValue(skill);
18676 void Player::ResurectUsingRequestData()
18678 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
18679 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18681 ResurrectPlayer(0.0f,false);
18683 if(GetMaxHealth() > m_resurrectHealth)
18684 SetHealth( m_resurrectHealth );
18685 else
18686 SetHealth( GetMaxHealth() );
18688 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18689 SetPower(POWER_MANA, m_resurrectMana );
18690 else
18691 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18693 SetPower(POWER_RAGE, 0 );
18695 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18697 SpawnCorpseBones();
18700 void Player::SetClientControl(Unit* target, uint8 allowMove)
18702 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18703 data.append(target->GetPackGUID());
18704 data << uint8(allowMove);
18705 GetSession()->SendPacket(&data);
18708 void Player::UpdateZoneDependentAuras( uint32 newZone )
18710 // remove new continent flight forms
18711 if( !IsAllowUseFlyMountsHere() )
18713 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18714 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18717 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
18718 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newZone);
18719 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
18720 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
18721 if( !HasAura(itr->second->spellId,0) )
18722 CastSpell(this,itr->second->spellId,true);
18725 void Player::UpdateAreaDependentAuras( uint32 newArea )
18727 // remove auras from spells with area limitations
18728 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
18730 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18731 if(spellmgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
18732 RemoveAura(iter);
18733 else
18734 ++iter;
18737 // some auras applied at subzone enter
18738 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newArea);
18739 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
18740 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
18741 if( !HasAura(itr->second->spellId,0) )
18742 CastSpell(this,itr->second->spellId,true);
18745 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18747 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18748 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18750 return copseReclaimDelay[0];
18753 time_t now = time(NULL);
18754 // 0..2 full period
18755 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18756 return copseReclaimDelay[count];
18759 void Player::UpdateCorpseReclaimDelay()
18761 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18763 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18764 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18765 return;
18767 time_t now = time(NULL);
18768 if(now < m_deathExpireTime)
18770 // full and partly periods 1..3
18771 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18772 if(count < MAX_DEATH_COUNT)
18773 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
18774 else
18775 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
18777 else
18778 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
18781 void Player::SendCorpseReclaimDelay(bool load)
18783 Corpse* corpse = GetCorpse();
18784 if(!corpse)
18785 return;
18787 uint32 delay;
18788 if(load)
18790 if(corpse->GetGhostTime() > m_deathExpireTime)
18791 return;
18793 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
18795 uint32 count;
18796 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18797 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18799 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
18800 if(count>=MAX_DEATH_COUNT)
18801 count = MAX_DEATH_COUNT-1;
18803 else
18804 count=0;
18806 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
18808 time_t now = time(NULL);
18809 if(now >= expected_time)
18810 return;
18812 delay = expected_time-now;
18814 else
18815 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
18817 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18818 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
18819 data << uint32(delay*IN_MILISECONDS);
18820 GetSession()->SendPacket( &data );
18823 Player* Player::GetNextRandomRaidMember(float radius)
18825 Group *pGroup = GetGroup();
18826 if(!pGroup)
18827 return NULL;
18829 std::vector<Player*> nearMembers;
18830 nearMembers.reserve(pGroup->GetMembersCount());
18832 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18834 Player* Target = itr->getSource();
18836 // IsHostileTo check duel and controlled by enemy
18837 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
18838 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
18839 nearMembers.push_back(Target);
18842 if (nearMembers.empty())
18843 return NULL;
18845 uint32 randTarget = urand(0,nearMembers.size()-1);
18846 return nearMembers[randTarget];
18849 PartyResult Player::CanUninviteFromGroup() const
18851 const Group* grp = GetGroup();
18852 if(!grp)
18853 return PARTY_RESULT_YOU_NOT_IN_GROUP;
18855 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
18856 return PARTY_RESULT_YOU_NOT_LEADER;
18858 if(InBattleGround())
18859 return PARTY_RESULT_INVITE_RESTRICTED;
18861 return PARTY_RESULT_OK;
18864 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
18866 //we must move references from m_group to m_originalGroup
18867 SetOriginalGroup(GetGroup(), GetSubGroup());
18869 m_group.unlink();
18870 m_group.link(group, this);
18871 m_group.setSubGroup((uint8)subgroup);
18874 void Player::RemoveFromBattleGroundRaid()
18876 //remove existing reference
18877 m_group.unlink();
18878 if( Group* group = GetOriginalGroup() )
18880 m_group.link(group, this);
18881 m_group.setSubGroup(GetOriginalSubGroup());
18883 SetOriginalGroup(NULL);
18886 void Player::SetOriginalGroup(Group *group, int8 subgroup)
18888 if( group == NULL )
18889 m_originalGroup.unlink();
18890 else
18892 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
18893 assert(subgroup >= 0);
18894 m_originalGroup.link(group, this);
18895 m_originalGroup.setSubGroup((uint8)subgroup);
18899 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
18901 LiquidData liquid_status;
18902 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
18903 if (!res)
18905 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
18906 // Small hack for enable breath in WMO
18907 if (IsInWater())
18908 m_MirrorTimerFlags|=UNDERWATER_INWATER;
18909 return;
18912 // All liquids type - check under water position
18913 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
18915 if ( res & LIQUID_MAP_UNDER_WATER)
18916 m_MirrorTimerFlags |= UNDERWATER_INWATER;
18917 else
18918 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
18921 // Allow travel in dark water on taxi or transport
18922 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
18923 m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
18924 else
18925 m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
18927 // in lava check, anywhere in lava level
18928 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
18930 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
18931 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
18932 else
18933 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
18935 // in slime check, anywhere in slime level
18936 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
18938 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
18939 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
18940 else
18941 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
18945 void Player::SetCanParry( bool value )
18947 if(m_canParry==value)
18948 return;
18950 m_canParry = value;
18951 UpdateParryPercentage();
18954 void Player::SetCanBlock( bool value )
18956 if(m_canBlock==value)
18957 return;
18959 m_canBlock = value;
18960 UpdateBlockPercentage();
18963 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
18965 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
18966 if(itr->pos == pos)
18967 return true;
18969 return false;
18972 bool Player::CanUseBattleGroundObject()
18974 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
18975 // maybe gameobject code should handle that ForceReaction usage
18976 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
18977 return ( //InBattleGround() && // in battleground - not need, check in other cases
18978 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
18979 //player cannot use object when he is invulnerable (immune)
18980 !isTotalImmune() && // not totally immune
18981 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
18982 !HasStealthAura() && // not stealthed
18983 !HasInvisibilityAura() && // not invisible
18984 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
18985 isAlive() // live player
18989 bool Player::CanCaptureTowerPoint()
18991 return ( !HasStealthAura() && // not stealthed
18992 !HasInvisibilityAura() && // not invisible
18993 isAlive() // live player
18997 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
18999 uint32 level = getLevel();
19001 if(level > GT_MAX_LEVEL)
19002 level = GT_MAX_LEVEL; // max level in this dbc
19004 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
19005 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
19006 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
19008 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
19009 return 0;
19011 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
19013 if(!bsc) // shouldn't happen
19014 return 0xFFFFFFFF;
19016 float cost = 0;
19018 if(hairstyle != newhairstyle)
19019 cost += bsc->cost; // full price
19021 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
19022 cost += bsc->cost * 0.5f; // +1/2 of price
19024 if(facialhair != newfacialhair)
19025 cost += bsc->cost * 0.75f; // +3/4 of price
19027 return uint32(cost);
19030 void Player::InitGlyphsForLevel()
19032 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
19033 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
19034 if(gs->Order)
19035 SetGlyphSlot(gs->Order - 1, gs->Id);
19037 uint32 level = getLevel();
19038 uint32 value = 0;
19040 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19041 if(level >= 15)
19042 value |= (0x01 | 0x02);
19043 if(level >= 30)
19044 value |= 0x08;
19045 if(level >= 50)
19046 value |= 0x04;
19047 if(level >= 70)
19048 value |= 0x10;
19049 if(level >= 80)
19050 value |= 0x20;
19052 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
19055 void Player::EnterVehicle(Vehicle *vehicle)
19057 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
19058 if(!ve)
19059 return;
19061 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
19062 if(!veSeat)
19063 return;
19065 vehicle->SetCharmerGUID(GetGUID());
19066 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19067 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19068 vehicle->setFaction(getFaction());
19070 SetCharm(vehicle); // charm
19071 SetFarSightGUID(vehicle->GetGUID()); // set view
19073 SetClientControl(vehicle, 1); // redirect controls to vehicle
19075 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
19076 GetSession()->SendPacket(&data);
19078 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
19079 data.append(GetPackGUID());
19080 data << uint32(0); // counter?
19081 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
19082 data << uint16(0); // special flags
19083 data << uint32(getMSTime()); // time
19084 data << vehicle->GetPositionX(); // x
19085 data << vehicle->GetPositionY(); // y
19086 data << vehicle->GetPositionZ(); // z
19087 data << vehicle->GetOrientation(); // o
19088 // transport part, TODO: load/calculate seat offsets
19089 data << uint64(vehicle->GetGUID()); // transport guid
19090 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19091 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19092 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19093 data << float(0); // transport orientation
19094 data << uint32(getMSTime()); // transport time
19095 data << uint8(0); // seat
19096 // end of transport part
19097 data << uint32(0); // fall time
19098 GetSession()->SendPacket(&data);
19100 data.Initialize(SMSG_PET_SPELLS, 8+4+4+4+4*10+1+1);
19101 data << uint64(vehicle->GetGUID());
19102 data << uint32(0x00000000);
19103 data << uint32(0x00000000);
19104 data << uint32(0x00000101);
19106 for(uint32 i = 0; i < 10; ++i)
19107 data << uint16(0) << uint8(0) << uint8(i+8);
19109 data << uint8(0);
19110 data << uint8(0);
19111 GetSession()->SendPacket(&data);
19114 void Player::ExitVehicle(Vehicle *vehicle)
19116 vehicle->SetCharmerGUID(0);
19117 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19118 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19119 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19121 SetCharm(NULL);
19122 SetFarSightGUID(0);
19124 SetClientControl(vehicle, 0);
19126 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19127 data.append(GetPackGUID());
19128 data << uint32(0); // counter?
19129 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19130 data << uint16(0x40); // special flags
19131 data << uint32(getMSTime()); // time
19132 data << vehicle->GetPositionX(); // x
19133 data << vehicle->GetPositionY(); // y
19134 data << vehicle->GetPositionZ(); // z
19135 data << vehicle->GetOrientation(); // o
19136 data << uint32(0); // fall time
19137 GetSession()->SendPacket(&data);
19139 data.Initialize(SMSG_PET_SPELLS, 8+4);
19140 data << uint64(0);
19141 data << uint32(0);
19142 GetSession()->SendPacket(&data);
19144 // only for flyable vehicles?
19145 CastSpell(this, 45472, true); // Parachute
19148 bool Player::isTotalImmune()
19150 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
19152 uint32 immuneMask = 0;
19153 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
19155 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
19156 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
19157 return true;
19159 return false;
19162 bool Player::HasTitle(uint32 bitIndex)
19164 if (bitIndex > 128)
19165 return false;
19167 uint32 fieldIndexOffset = bitIndex/32;
19168 uint32 flag = 1 << (bitIndex%32);
19169 return HasFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19172 void Player::SetTitle(CharTitlesEntry const* title)
19174 uint32 fieldIndexOffset = title->bit_index/32;
19175 uint32 flag = 1 << (title->bit_index%32);
19176 SetFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19179 void Player::ConvertRune(uint8 index, uint8 newType)
19181 SetCurrentRune(index, newType);
19183 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19184 data << uint8(index);
19185 data << uint8(newType);
19186 GetSession()->SendPacket(&data);
19189 void Player::ResyncRunes(uint8 count)
19191 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19192 for(uint32 i = 0; i < count; ++i)
19194 data << uint8(GetCurrentRune(i)); // rune type
19195 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
19197 GetSession()->SendPacket(&data);
19200 void Player::AddRunePower(uint8 index)
19202 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19203 data << uint32(1 << index); // mask (0x00-0x3F probably)
19204 GetSession()->SendPacket(&data);
19207 void Player::InitRunes()
19209 if(getClass() != CLASS_DEATH_KNIGHT)
19210 return;
19212 m_runes = new Runes;
19214 m_runes->runeState = 0;
19216 for(uint32 i = 0; i < MAX_RUNES; ++i)
19218 SetBaseRune(i, i / 2); // init base types
19219 SetCurrentRune(i, i / 2); // init current types
19220 SetRuneCooldown(i, 0); // reset cooldowns
19221 m_runes->SetRuneState(i);
19224 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19225 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
19228 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
19230 Loot loot;
19231 loot.FillLoot (loot_id,store,this,true);
19233 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
19234 for(uint32 i = 0; i < max_slot; ++i)
19236 LootItem* lootItem = loot.LootItemInSlot(i,this);
19238 ItemPosCountVec dest;
19239 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
19240 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
19241 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19242 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
19243 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19244 if(msg != EQUIP_ERR_OK)
19246 SendEquipError( msg, NULL, NULL );
19247 continue;
19250 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
19251 SendNewItem(pItem, lootItem->count, false, false, broadcast);
19255 uint32 Player::CalculateTalentsPoints() const
19257 uint32 base_talent = getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld.getRate(RATE_TALENT));
19259 if(getClass() != CLASS_DEATH_KNIGHT)
19260 return base_talent;
19262 uint32 talentPointsForLevel =
19263 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld.getRate(RATE_TALENT)))
19264 + m_questRewardTalentCount;
19266 if(talentPointsForLevel > base_talent)
19267 talentPointsForLevel = base_talent;
19269 return talentPointsForLevel;
19272 bool Player::IsAllowUseFlyMountsHere() const
19274 if (isGameMaster())
19275 return true;
19277 uint32 v_map = GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19278 return v_map == 530 || v_map == 571 && HasSpell(54197);
19281 void Player::learnSpellHighRank(uint32 spellid)
19283 learnSpell(spellid,false);
19285 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
19286 for(SpellChainMapNext::const_iterator itr = nextMap.lower_bound(spellid); itr != nextMap.upper_bound(spellid); ++itr)
19287 learnSpellHighRank(itr->second);
19290 void Player::_LoadSkills()
19292 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19294 // reset skill modifiers and set correct unlearn flags
19295 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; ++i)
19297 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
19299 // set correct unlearn bit
19300 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
19301 if(!id) continue;
19303 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
19304 if(!pSkill) continue;
19306 // enable unlearn button for primary professions only
19307 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
19308 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
19309 else
19310 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
19312 // set fixed skill ranges
19313 switch(GetSkillRangeType(pSkill,false))
19315 case SKILL_RANGE_LANGUAGE: // 300..300
19316 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(300,300));
19317 break;
19318 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
19319 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(1,1));
19320 break;
19321 default:
19322 break;
19325 uint32 vskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
19326 learnSkillRewardedSpells(id, vskill);
19329 // special settings
19330 if(getClass()==CLASS_DEATH_KNIGHT)
19332 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
19333 if(base_level < 1)
19334 base_level = 1;
19335 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
19336 if(base_skill < 1)
19337 base_skill = 1; // skill mast be known and then > 0 in any case
19339 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
19340 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
19341 if(GetPureSkillValue (SKILL_AXES) < base_skill)
19342 SetSkill(SKILL_AXES, base_skill,base_skill);
19343 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
19344 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
19345 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
19346 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
19347 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
19348 SetSkill(SKILL_SWORDS, base_skill,base_skill);
19349 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
19350 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
19351 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
19352 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
19353 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
19354 SetSkill(SKILL_UNARMED, base_skill,base_skill);
19358 uint32 Player::GetPhaseMaskForSpawn() const
19360 uint32 phase = PHASEMASK_NORMAL;
19361 if(!isGameMaster())
19362 phase = GetPhaseMask();
19363 else
19365 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
19366 if(!phases.empty())
19367 phase = phases.front()->GetMiscValue();
19370 // some aura phases include 1 normal map in addition to phase itself
19371 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
19372 return n_phase;
19374 return PHASEMASK_NORMAL;
19377 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
19379 ItemPrototype const* pProto = pItem->GetProto();
19381 // proto based limitations
19382 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
19383 return res;
19385 // check unique-equipped on gems
19386 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
19388 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
19389 if(!enchant_id)
19390 continue;
19391 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
19392 if(!enchantEntry)
19393 continue;
19395 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
19396 if(!pGem)
19397 continue;
19399 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19400 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
19401 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
19403 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
19404 return res;
19407 return EQUIP_ERR_OK;
19410 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
19412 // check unique-equipped on item
19413 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
19415 // there is an equip limit on this item
19416 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
19417 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19420 // check unique-equipped limit
19421 if (itemProto->ItemLimitCategory)
19423 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
19424 if(!limitEntry)
19425 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19427 if(limit_count > limitEntry->maxCount)
19428 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
19430 // there is an equip limit on this item
19431 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
19432 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19435 return EQUIP_ERR_OK;
19438 void Player::HandleFall(MovementInfo const& movementInfo)
19440 // calculate total z distance of the fall
19441 float z_diff = m_lastFallZ - movementInfo.z;
19442 sLog.outDebug("zDiff = %f", z_diff);
19444 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19445 // 14.57 can be calculated by resolving damageperc formula below to 0
19446 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
19447 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
19448 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
19450 //Safe fall, fall height reduction
19451 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
19453 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
19455 if(damageperc >0 )
19457 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
19459 float height = movementInfo.z;
19460 UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
19462 if (damage > 0)
19464 //Prevent fall damage from being more than the player maximum health
19465 if (damage > GetMaxHealth())
19466 damage = GetMaxHealth();
19468 // Gust of Wind
19469 if (GetDummyAura(43621))
19470 damage = GetMaxHealth()/2;
19472 EnvironmentalDamage(DAMAGE_FALL, damage);
19474 // recheck alive, might have died of EnvironmentalDamage
19475 if (isAlive())
19476 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
19479 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
19480 DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo.z, height, GetPositionZ(), movementInfo.fallTime, height, damage, safe_fall);
19485 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
19487 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
19490 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
19492 uint32 CurTalentPoints = GetFreeTalentPoints();
19494 if(CurTalentPoints == 0)
19495 return;
19497 if (talentRank >= MAX_TALENT_RANK)
19498 return;
19500 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
19502 if(!talentInfo)
19503 return;
19505 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
19507 if(!talentTabInfo)
19508 return;
19510 // prevent learn talent for different class (cheating)
19511 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
19512 return;
19514 // find current max talent rank
19515 int32 curtalent_maxrank = 0;
19516 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19518 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
19520 curtalent_maxrank = k + 1;
19521 break;
19525 // we already have same or higher talent rank learned
19526 if(curtalent_maxrank >= (talentRank + 1))
19527 return;
19529 // check if we have enough talent points
19530 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19531 return;
19533 // Check if it requires another talent
19534 if (talentInfo->DependsOn > 0)
19536 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19538 bool hasEnoughRank = false;
19539 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19541 if (depTalentInfo->RankID[i] != 0)
19542 if (HasSpell(depTalentInfo->RankID[i]))
19543 hasEnoughRank = true;
19545 if (!hasEnoughRank)
19546 return;
19550 // Find out how many points we have in this field
19551 uint32 spentPoints = 0;
19553 uint32 tTab = talentInfo->TalentTab;
19554 if (talentInfo->Row > 0)
19556 unsigned int numRows = sTalentStore.GetNumRows();
19557 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19559 // Someday, someone needs to revamp
19560 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19561 if (tmpTalent) // the way talents are tracked
19563 if (tmpTalent->TalentTab == tTab)
19565 for (int j = 0; j < MAX_TALENT_RANK; ++j)
19567 if (tmpTalent->RankID[j] != 0)
19569 if (HasSpell(tmpTalent->RankID[j]))
19571 spentPoints += j + 1;
19580 // not have required min points spent in talent tree
19581 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
19582 return;
19584 // spell not set in talent.dbc
19585 uint32 spellid = talentInfo->RankID[talentRank];
19586 if( spellid == 0 )
19588 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19589 return;
19592 // already known
19593 if(HasSpell(spellid))
19594 return;
19596 // learn! (other talent ranks will unlearned at learning)
19597 learnSpell(spellid, false);
19598 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19600 // update free talent points
19601 SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19604 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
19606 Pet *pet = GetPet();
19608 if(!pet)
19609 return;
19611 if(petGuid != pet->GetGUID())
19612 return;
19614 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
19616 if(CurTalentPoints == 0)
19617 return;
19619 if (talentRank >= MAX_PET_TALENT_RANK)
19620 return;
19622 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
19624 if(!talentInfo)
19625 return;
19627 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
19629 if(!talentTabInfo)
19630 return;
19632 CreatureInfo const *ci = pet->GetCreatureInfo();
19634 if(!ci)
19635 return;
19637 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
19639 if(!pet_family)
19640 return;
19642 if(pet_family->petTalentType < 0) // not hunter pet
19643 return;
19645 // prevent learn talent for different family (cheating)
19646 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
19647 return;
19649 // find current max talent rank
19650 int32 curtalent_maxrank = 0;
19651 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19653 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
19655 curtalent_maxrank = k + 1;
19656 break;
19660 // we already have same or higher talent rank learned
19661 if(curtalent_maxrank >= (talentRank + 1))
19662 return;
19664 // check if we have enough talent points
19665 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19666 return;
19668 // Check if it requires another talent
19669 if (talentInfo->DependsOn > 0)
19671 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19673 bool hasEnoughRank = false;
19674 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19676 if (depTalentInfo->RankID[i] != 0)
19677 if (pet->HasSpell(depTalentInfo->RankID[i]))
19678 hasEnoughRank = true;
19680 if (!hasEnoughRank)
19681 return;
19685 // Find out how many points we have in this field
19686 uint32 spentPoints = 0;
19688 uint32 tTab = talentInfo->TalentTab;
19689 if (talentInfo->Row > 0)
19691 unsigned int numRows = sTalentStore.GetNumRows();
19692 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19694 // Someday, someone needs to revamp
19695 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19696 if (tmpTalent) // the way talents are tracked
19698 if (tmpTalent->TalentTab == tTab)
19700 for (int j = 0; j < MAX_TALENT_RANK; ++j)
19702 if (tmpTalent->RankID[j] != 0)
19704 if (pet->HasSpell(tmpTalent->RankID[j]))
19706 spentPoints += j + 1;
19715 // not have required min points spent in talent tree
19716 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
19717 return;
19719 // spell not set in talent.dbc
19720 uint32 spellid = talentInfo->RankID[talentRank];
19721 if( spellid == 0 )
19723 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19724 return;
19727 // already known
19728 if(pet->HasSpell(spellid))
19729 return;
19731 // learn! (other talent ranks will unlearned at learning)
19732 pet->learnSpell(spellid);
19733 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19735 // update free talent points
19736 pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19739 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
19741 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
19743 if(apply)
19744 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(1LL << (ctEntry->BitIndex-1)));
19745 else
19746 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(1LL << (ctEntry->BitIndex-1)));
19750 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
19752 if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <=minfo.z || opcode == MSG_MOVE_FALL_LAND)
19753 SetFallInformation(minfo.fallTime, minfo.z);
19756 void Player::UnsummonPetTemporaryIfAny()
19758 Pet* pet = GetPet();
19759 if(!pet)
19760 return;
19762 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
19764 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
19765 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
19768 RemovePet(pet, PET_SAVE_AS_CURRENT);
19771 void Player::ResummonPetTemporaryUnSummonedIfAny()
19773 if(!m_temporaryUnsummonedPetNumber)
19774 return;
19776 // not resummon in not appropriate state
19777 if(IsPetNeedBeTemporaryUnsummoned())
19778 return;
19780 if(GetPetGUID())
19781 return;
19783 Pet* NewPet = new Pet;
19784 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
19785 delete NewPet;
19787 m_temporaryUnsummonedPetNumber = 0;
19790 void Player::BuildPlayerTalentsInfoData(WorldPacket *data)
19792 *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
19793 uint8 talentGroupCount = 1;
19794 *data << uint8(talentGroupCount); // talent group count (1 or 2)
19795 *data << uint8(0); // talent group index (0 or 1)
19797 if(talentGroupCount)
19799 uint8 talentIdCount = 0;
19800 size_t pos = data->wpos();
19801 *data << uint8(talentIdCount); // [PH], talentIdCount
19803 // find class talent tabs (all players have 3 talent tabs)
19804 uint32 const* talentTabIds = GetTalentTabPages(getClass());
19806 for(uint32 i = 0; i < 3; ++i)
19808 uint32 talentTabId = talentTabIds[i];
19810 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
19812 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
19813 if(!talentInfo)
19814 continue;
19816 // skip another tab talents
19817 if(talentInfo->TalentTab != talentTabId)
19818 continue;
19820 // find max talent rank
19821 int32 curtalent_maxrank = -1;
19822 for(int32 k = 4; k > -1; --k)
19824 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
19826 curtalent_maxrank = k;
19827 break;
19831 // not learned talent
19832 if(curtalent_maxrank < 0)
19833 continue;
19835 *data << uint32(talentInfo->TalentID); // Talent.dbc
19836 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
19838 ++talentIdCount;
19842 data->put<uint8>(pos, talentIdCount); // put real count
19844 *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
19846 for(uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
19847 *data << uint16(GetGlyph(i)); // GlyphProperties.dbc
19851 void Player::BuildPetTalentsInfoData(WorldPacket *data)
19853 uint32 unspentTalentPoints = 0;
19854 size_t pointsPos = data->wpos();
19855 *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
19857 uint8 talentIdCount = 0;
19858 size_t countPos = data->wpos();
19859 *data << uint8(talentIdCount); // [PH], talentIdCount
19861 Pet *pet = GetPet();
19862 if(!pet)
19863 return;
19865 unspentTalentPoints = pet->GetFreeTalentPoints();
19867 data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
19869 CreatureInfo const *ci = pet->GetCreatureInfo();
19870 if(!ci)
19871 return;
19873 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
19874 if(!pet_family || pet_family->petTalentType < 0)
19875 return;
19877 for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
19879 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
19880 if(!talentTabInfo)
19881 continue;
19883 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
19884 continue;
19886 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
19888 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
19889 if(!talentInfo)
19890 continue;
19892 // skip another tab talents
19893 if(talentInfo->TalentTab != talentTabId)
19894 continue;
19896 // find max talent rank
19897 int32 curtalent_maxrank = -1;
19898 for(int32 k = 4; k > -1; --k)
19900 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
19902 curtalent_maxrank = k;
19903 break;
19907 // not learned talent
19908 if(curtalent_maxrank < 0)
19909 continue;
19911 *data << uint32(talentInfo->TalentID); // Talent.dbc
19912 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
19914 ++talentIdCount;
19917 data->put<uint8>(countPos, talentIdCount); // put real count
19919 break;
19923 void Player::SendTalentsInfoData(bool pet)
19925 if(GetSession()->PlayerLoading())
19926 return;
19928 WorldPacket data(SMSG_TALENTS_INFO, 50);
19929 data << uint8(pet ? 1 : 0);
19930 if(pet)
19931 BuildPetTalentsInfoData(&data);
19932 else
19933 BuildPlayerTalentsInfoData(&data);
19934 GetSession()->SendPacket(&data);
19937 void Player::BuildEnchantmentsInfoData(WorldPacket *data)
19939 uint32 slotUsedMask = 0;
19940 size_t slotUsedMaskPos = data->wpos();
19941 *data << uint32(slotUsedMask); // slotUsedMask < 0x80000
19943 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
19945 Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
19947 if(!item)
19948 continue;
19950 slotUsedMask |= (1 << i);
19952 *data << uint32(item->GetEntry()); // item entry
19954 uint16 enchantmentMask = 0;
19955 size_t enchantmentMaskPos = data->wpos();
19956 *data << uint16(enchantmentMask); // enchantmentMask < 0x1000
19958 for(uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
19960 uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
19962 if(!enchId)
19963 continue;
19965 enchantmentMask |= (1 << j);
19967 *data << uint16(enchId); // enchantmentId?
19970 data->put<uint16>(enchantmentMaskPos, enchantmentMask);
19972 *data << uint16(0); // ?
19973 *data << uint8(0); // PGUID!
19974 *data << uint32(0); // seed?
19977 data->put<uint32>(slotUsedMaskPos, slotUsedMask);
19980 void Player::SendEquipmentSetList()
19982 uint32 count = 0;
19983 WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4);
19984 size_t count_pos = data.wpos();
19985 data << uint32(count); // count placeholder
19986 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
19988 if(itr->second.state==EQUIPMENT_SET_DELETED)
19989 continue;
19990 data.appendPackGUID(itr->second.Guid);
19991 data << uint32(itr->first);
19992 data << itr->second.Name;
19993 data << itr->second.IconName;
19994 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
19995 data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM));
19997 ++count; // client have limit but it checked at loading and set
19999 data.put<uint32>(count_pos,count);
20000 GetSession()->SendPacket(&data);
20003 void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
20005 if(eqset.Guid != 0)
20007 bool found = false;
20009 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20011 if((itr->second.Guid == eqset.Guid) && (itr->first == index))
20013 found = true;
20014 break;
20018 if(!found) // something wrong...
20020 sLog.outError("Player %s tried to save equipment set "I64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
20021 return;
20025 EquipmentSet& eqslot = m_EquipmentSets[index];
20027 EquipmentSetUpdateState old_state = eqslot.state;
20029 eqslot = eqset;
20031 if(eqset.Guid == 0)
20033 eqslot.Guid = objmgr.GenerateEquipmentSetGuid();
20035 WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4+1);
20036 data << uint32(index);
20037 data.appendPackGUID(eqslot.Guid);
20038 GetSession()->SendPacket(&data);
20041 eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
20044 void Player::_SaveEquipmentSets()
20046 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
20048 uint32 index = itr->first;
20049 EquipmentSet& eqset = itr->second;
20050 switch(eqset.state)
20052 case EQUIPMENT_SET_UNCHANGED:
20053 ++itr;
20054 break; // nothing do
20055 case EQUIPMENT_SET_CHANGED:
20056 CharacterDatabase.PExecute("UPDATE character_equipmentsets SET name='%s', iconname='%s', item0='%u', item1='%u', item2='%u', item3='%u', item4='%u', item5='%u', item6='%u', item7='%u', item8='%u', item9='%u', item10='%u', item11='%u', item12='%u', item13='%u', item14='%u', item15='%u', item16='%u', item17='%u', item18='%u' WHERE guid='%u' AND setguid='"I64FMTD"' AND setindex='%u'",
20057 eqset.Name.c_str(), eqset.IconName.c_str(), eqset.Items[0], eqset.Items[1], eqset.Items[2], eqset.Items[3], eqset.Items[4], eqset.Items[5], eqset.Items[6], eqset.Items[7],
20058 eqset.Items[8], eqset.Items[9], eqset.Items[10], eqset.Items[11], eqset.Items[12], eqset.Items[13], eqset.Items[14], eqset.Items[15], eqset.Items[16], eqset.Items[17], eqset.Items[18], GetGUIDLow(), eqset.Guid, index);
20059 eqset.state = EQUIPMENT_SET_UNCHANGED;
20060 ++itr;
20061 break;
20062 case EQUIPMENT_SET_NEW:
20063 CharacterDatabase.PExecute("INSERT INTO character_equipmentsets VALUES ('%u', '"I64FMTD"', '%u', '%s', '%s', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
20064 GetGUIDLow(), eqset.Guid, index, eqset.Name.c_str(), eqset.IconName.c_str(), eqset.Items[0], eqset.Items[1], eqset.Items[2], eqset.Items[3], eqset.Items[4], eqset.Items[5], eqset.Items[6], eqset.Items[7],
20065 eqset.Items[8], eqset.Items[9], eqset.Items[10], eqset.Items[11], eqset.Items[12], eqset.Items[13], eqset.Items[14], eqset.Items[15], eqset.Items[16], eqset.Items[17], eqset.Items[18]);
20066 eqset.state = EQUIPMENT_SET_UNCHANGED;
20067 ++itr;
20068 break;
20069 case EQUIPMENT_SET_DELETED:
20070 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE setguid="I64FMTD, eqset.Guid);
20071 m_EquipmentSets.erase(itr++);
20072 break;
20077 void Player::DeleteEquipmentSet(uint64 setGuid)
20079 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20081 if(itr->second.Guid == setGuid)
20083 itr->second.state = EQUIPMENT_SET_DELETED;
20084 break;