[9033] Fixed percent mana regneration from spell 53228 and ranks buff.
[getmangos.git] / src / game / Player.cpp
blob2d09f4f3bb4d01d6c1646532485eb8250698e688
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 "ObjectDefines.h"
46 #include "CreatureAI.h"
47 #include "Formulas.h"
48 #include "Group.h"
49 #include "Guild.h"
50 #include "Pet.h"
51 #include "Util.h"
52 #include "Transports.h"
53 #include "Weather.h"
54 #include "BattleGround.h"
55 #include "BattleGroundAV.h"
56 #include "BattleGroundMgr.h"
57 #include "ArenaTeam.h"
58 #include "Chat.h"
59 #include "Database/DatabaseImpl.h"
60 #include "Spell.h"
61 #include "SocialMgr.h"
62 #include "AchievementMgr.h"
64 #include <cmath>
66 #define ZONE_UPDATE_INTERVAL (1*IN_MILISECONDS)
68 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
69 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
70 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
72 #define SKILL_VALUE(x) PAIR32_LOPART(x)
73 #define SKILL_MAX(x) PAIR32_HIPART(x)
74 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
76 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
77 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
78 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
80 enum CharacterFlags
82 CHARACTER_FLAG_NONE = 0x00000000,
83 CHARACTER_FLAG_UNK1 = 0x00000001,
84 CHARACTER_FLAG_UNK2 = 0x00000002,
85 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
86 CHARACTER_FLAG_UNK4 = 0x00000008,
87 CHARACTER_FLAG_UNK5 = 0x00000010,
88 CHARACTER_FLAG_UNK6 = 0x00000020,
89 CHARACTER_FLAG_UNK7 = 0x00000040,
90 CHARACTER_FLAG_UNK8 = 0x00000080,
91 CHARACTER_FLAG_UNK9 = 0x00000100,
92 CHARACTER_FLAG_UNK10 = 0x00000200,
93 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
94 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
95 CHARACTER_FLAG_UNK13 = 0x00001000,
96 CHARACTER_FLAG_GHOST = 0x00002000,
97 CHARACTER_FLAG_RENAME = 0x00004000,
98 CHARACTER_FLAG_UNK16 = 0x00008000,
99 CHARACTER_FLAG_UNK17 = 0x00010000,
100 CHARACTER_FLAG_UNK18 = 0x00020000,
101 CHARACTER_FLAG_UNK19 = 0x00040000,
102 CHARACTER_FLAG_UNK20 = 0x00080000,
103 CHARACTER_FLAG_UNK21 = 0x00100000,
104 CHARACTER_FLAG_UNK22 = 0x00200000,
105 CHARACTER_FLAG_UNK23 = 0x00400000,
106 CHARACTER_FLAG_UNK24 = 0x00800000,
107 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
108 CHARACTER_FLAG_DECLINED = 0x02000000,
109 CHARACTER_FLAG_UNK27 = 0x04000000,
110 CHARACTER_FLAG_UNK28 = 0x08000000,
111 CHARACTER_FLAG_UNK29 = 0x10000000,
112 CHARACTER_FLAG_UNK30 = 0x20000000,
113 CHARACTER_FLAG_UNK31 = 0x40000000,
114 CHARACTER_FLAG_UNK32 = 0x80000000
117 enum CharacterCustomizeFlags
119 CHAR_CUSTOMIZE_FLAG_NONE = 0x00000000,
120 CHAR_CUSTOMIZE_FLAG_CUSTOMIZE = 0x00000001, // name, gender, etc...
121 CHAR_CUSTOMIZE_FLAG_FACTION = 0x00010000, // name, gender, faction, etc...
122 CHAR_CUSTOMIZE_FLAG_RACE = 0x00100000 // name, gender, race, etc...
125 // corpse reclaim times
126 #define DEATH_EXPIRE_STEP (5*MINUTE)
127 #define MAX_DEATH_COUNT 3
129 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
131 //== PlayerTaxi ================================================
133 PlayerTaxi::PlayerTaxi()
135 // Taxi nodes
136 memset(m_taximask, 0, sizeof(m_taximask));
139 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
141 // class specific initial known nodes
142 switch(chrClass)
144 case CLASS_DEATH_KNIGHT:
146 for(int i = 0; i < TaxiMaskSize; ++i)
147 m_taximask[i] |= sOldContinentsNodesMask[i];
148 break;
152 // race specific initial known nodes: capital and taxi hub masks
153 switch(race)
155 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
156 case RACE_ORC: SetTaximaskNode(23); break; // Orc
157 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
158 case RACE_NIGHTELF: SetTaximaskNode(26);
159 SetTaximaskNode(27); break; // Night Elf
160 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
161 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
162 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
163 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
164 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
165 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
168 // new continent starting masks (It will be accessible only at new map)
169 switch(Player::TeamForRace(race))
171 case ALLIANCE: SetTaximaskNode(100); break;
172 case HORDE: SetTaximaskNode(99); break;
174 // level dependent taxi hubs
175 if(level>=68)
176 SetTaximaskNode(213); //Shattered Sun Staging Area
179 void PlayerTaxi::LoadTaxiMask(const char* data)
181 Tokens tokens = StrSplit(data, " ");
183 int index;
184 Tokens::iterator iter;
185 for (iter = tokens.begin(), index = 0;
186 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
188 // load and set bits only for existed taxi nodes
189 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
193 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
195 if(all)
197 for (uint8 i=0; i<TaxiMaskSize; ++i)
198 data << uint32(sTaxiNodesMask[i]); // all existed nodes
200 else
202 for (uint8 i=0; i<TaxiMaskSize; ++i)
203 data << uint32(m_taximask[i]); // known nodes
207 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team )
209 ClearTaxiDestinations();
211 Tokens tokens = StrSplit(values," ");
213 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
215 uint32 node = uint32(atol(iter->c_str()));
216 AddTaxiDestination(node);
219 if(m_TaxiDestinations.empty())
220 return true;
222 // Check integrity
223 if(m_TaxiDestinations.size() < 2)
224 return false;
226 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
228 uint32 cost;
229 uint32 path;
230 sObjectMgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
231 if(!path)
232 return false;
235 // can't load taxi path without mount set (quest taxi path?)
236 if(!sObjectMgr.GetTaxiMountDisplayId(GetTaxiSource(),team,true))
237 return false;
239 return true;
242 std::string PlayerTaxi::SaveTaxiDestinationsToString()
244 if(m_TaxiDestinations.empty())
245 return "";
247 std::ostringstream ss;
249 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
250 ss << m_TaxiDestinations[i] << " ";
252 return ss.str();
255 uint32 PlayerTaxi::GetCurrentTaxiPath() const
257 if(m_TaxiDestinations.size() < 2)
258 return 0;
260 uint32 path;
261 uint32 cost;
263 sObjectMgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
265 return path;
268 std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
270 ss << "'";
271 for(int i = 0; i < TaxiMaskSize; ++i)
272 ss << taxi.m_taximask[i] << " ";
273 ss << "'";
274 return ss;
277 //== Player ====================================================
279 UpdateMask Player::updateVisualBits;
281 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this), m_reputationMgr(this)
283 m_transport = 0;
285 m_speakTime = 0;
286 m_speakCount = 0;
288 m_objectType |= TYPEMASK_PLAYER;
289 m_objectTypeId = TYPEID_PLAYER;
291 m_valuesCount = PLAYER_END;
293 m_session = session;
295 m_divider = 0;
297 m_ExtraFlags = 0;
298 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
299 SetAcceptTicket(true);
301 // players always accept
302 if(GetSession()->GetSecurity() == SEC_PLAYER)
303 SetAcceptWhispers(true);
305 m_curSelection = 0;
306 m_lootGuid = 0;
308 m_comboTarget = 0;
309 m_comboPoints = 0;
311 m_usedTalentCount = 0;
312 m_questRewardTalentCount = 0;
314 m_regenTimer = 0;
315 m_weaponChangeTimer = 0;
317 m_zoneUpdateId = 0;
318 m_zoneUpdateTimer = 0;
320 m_areaUpdateId = 0;
322 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
324 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
325 // this must help in case next save after mass player load after server startup
326 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
328 clearResurrectRequestData();
330 m_SpellModRemoveCount = 0;
332 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
334 m_social = NULL;
336 // group is initialized in the reference constructor
337 SetGroupInvite(NULL);
338 m_groupUpdateMask = 0;
339 m_auraUpdateMask = 0;
341 duel = NULL;
343 m_GuildIdInvited = 0;
344 m_ArenaTeamIdInvited = 0;
346 m_atLoginFlags = AT_LOGIN_NONE;
348 mSemaphoreTeleport_Near = false;
349 mSemaphoreTeleport_Far = false;
351 m_DelayedOperations = 0;
352 m_bCanDelayTeleport = false;
353 m_bHasDelayedTeleport = false;
354 m_teleport_options = 0;
356 pTrader = 0;
357 ClearTrade();
359 m_cinematic = 0;
361 PlayerTalkClass = new PlayerMenu( GetSession() );
362 m_currentBuybackSlot = BUYBACK_SLOT_START;
364 m_DailyQuestChanged = false;
365 m_lastDailyQuestTime = 0;
367 for (int i=0; i<MAX_TIMERS; ++i)
368 m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
370 m_MirrorTimerFlags = UNDERWATER_NONE;
371 m_MirrorTimerFlagsLast = UNDERWATER_NONE;
372 m_isInWater = false;
373 m_drunkTimer = 0;
374 m_drunk = 0;
375 m_restTime = 0;
376 m_deathTimer = 0;
377 m_deathExpireTime = 0;
379 m_swingErrorMsg = 0;
381 m_DetectInvTimer = 1*IN_MILISECONDS;
383 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
385 m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
386 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
389 m_logintime = time(NULL);
390 m_Last_tick = m_logintime;
391 m_WeaponProficiency = 0;
392 m_ArmorProficiency = 0;
393 m_canParry = false;
394 m_canBlock = false;
395 m_canDualWield = false;
396 m_canTitanGrip = false;
397 m_ammoDPS = 0.0f;
399 m_temporaryUnsummonedPetNumber = 0;
400 //cache for UNIT_CREATED_BY_SPELL to allow
401 //returning reagents for temporarily removed pets
402 //when dying/logging out
403 m_oldpetspell = 0;
405 ////////////////////Rest System/////////////////////
406 time_inn_enter=0;
407 inn_pos_mapid=0;
408 inn_pos_x=0;
409 inn_pos_y=0;
410 inn_pos_z=0;
411 m_rest_bonus=0;
412 rest_type=REST_TYPE_NO;
413 ////////////////////Rest System/////////////////////
415 m_mailsLoaded = false;
416 m_mailsUpdated = false;
417 unReadMails = 0;
418 m_nextMailDelivereTime = 0;
420 m_resetTalentsCost = 0;
421 m_resetTalentsTime = 0;
422 m_itemUpdateQueueBlocked = false;
424 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
425 m_forced_speed_changes[i] = 0;
427 m_stableSlots = 0;
429 /////////////////// Instance System /////////////////////
431 m_HomebindTimer = 0;
432 m_InstanceValid = true;
433 m_dungeonDifficulty = DUNGEON_DIFFICULTY_NORMAL;
434 m_raidDifficulty = RAID_DIFFICULTY_10MAN_NORMAL;
436 m_lastPotionId = 0;
438 m_activeSpec = 0;
439 m_specsCount = 1;
441 for (int i = 0; i < BASEMOD_END; ++i)
443 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
444 m_auraBaseMod[i][PCT_MOD] = 1.0f;
447 for (int i = 0; i < MAX_COMBAT_RATING; ++i)
448 m_baseRatingValue[i] = 0;
450 m_baseSpellPower = 0;
451 m_baseFeralAP = 0;
452 m_baseManaRegen = 0;
453 m_armorPenetrationPct = 0.0f;
455 // Honor System
456 m_lastHonorUpdateTime = time(NULL);
458 // Player summoning
459 m_summon_expire = 0;
460 m_summon_mapid = 0;
461 m_summon_x = 0.0f;
462 m_summon_y = 0.0f;
463 m_summon_z = 0.0f;
465 m_mover = this;
467 m_miniPet = 0;
468 m_contestedPvPTimer = 0;
470 m_declinedname = NULL;
471 m_runes = NULL;
473 m_lastFallTime = 0;
474 m_lastFallZ = 0;
477 Player::~Player ()
479 CleanupsBeforeDelete();
481 // it must be unloaded already in PlayerLogout and accessed only for loggined player
482 //m_social = NULL;
484 // Note: buy back item already deleted from DB when player was saved
485 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
487 if(m_items[i])
488 delete m_items[i];
490 CleanupChannels();
492 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
493 delete itr->second;
495 //all mailed items should be deleted, also all mail should be deallocated
496 for (PlayerMails::const_iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
497 delete *itr;
499 for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
500 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
502 delete PlayerTalkClass;
504 if (m_transport)
506 m_transport->RemovePassenger(this);
509 for(size_t x = 0; x < ItemSetEff.size(); x++)
510 if(ItemSetEff[x])
511 delete ItemSetEff[x];
513 // clean up player-instance binds, may unload some instance saves
514 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
515 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
516 itr->second.save->RemovePlayer(this);
518 delete m_declinedname;
519 delete m_runes;
522 void Player::CleanupsBeforeDelete()
524 if(m_uint32Values) // only for fully created Object
526 TradeCancel(false);
527 DuelComplete(DUEL_INTERUPTED);
529 Unit::CleanupsBeforeDelete();
532 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 )
534 //FIXME: outfitId not used in player creating
536 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
538 m_name = name;
540 PlayerInfo const* info = sObjectMgr.GetPlayerInfo(race, class_);
541 if(!info)
543 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
544 return false;
547 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
548 m_items[i] = NULL;
550 SetLocationMapId(info->mapId);
551 Relocate(info->positionX,info->positionY,info->positionZ);
553 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
554 if(!cEntry)
556 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
557 return false;
560 SetMap(sMapMgr.CreateMap(info->mapId, this));
562 uint8 powertype = cEntry->powerType;
564 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
565 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
567 setFactionForRace(race);
569 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
571 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
572 InitDisplayIds();
573 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
574 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
575 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
576 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
577 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
579 // -1 is default value
580 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
582 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
583 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
584 SetByteValue(PLAYER_BYTES_3, 0, gender);
586 SetUInt32Value( PLAYER_GUILDID, 0 );
587 SetUInt32Value( PLAYER_GUILDRANK, 0 );
588 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
590 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
591 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
592 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES2, 0 ); // 0=disabled
593 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
594 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
595 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
596 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
597 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
599 // set starting level
600 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
601 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
602 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
604 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
606 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
607 if(gm_level > start_level)
608 start_level = gm_level;
611 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
613 InitRunes();
615 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
616 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
617 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
619 // Played time
620 m_Last_tick = time(NULL);
621 m_Played_time[PLAYED_TIME_TOTAL] = 0;
622 m_Played_time[PLAYED_TIME_LEVEL] = 0;
624 // base stats and related field values
625 InitStatsForLevel();
626 InitTaxiNodesForLevel();
627 InitGlyphsForLevel();
628 InitTalentForLevel();
629 InitPrimaryProfessions(); // to max set before any spell added
631 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
632 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
633 SetHealth(GetMaxHealth());
634 if (getPowerType()==POWER_MANA)
636 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
637 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
640 if(getPowerType() == POWER_RUNIC_POWER)
642 SetPower(POWER_RUNE, 8);
643 SetMaxPower(POWER_RUNE, 8);
644 SetPower(POWER_RUNIC_POWER, 0);
645 SetMaxPower(POWER_RUNIC_POWER, 1000);
648 // original spells
649 learnDefaultSpells();
651 // original action bar
652 for (PlayerCreateInfoActions::const_iterator action_itr = info->action.begin(); action_itr != info->action.end(); ++action_itr)
653 addActionButton(action_itr->button,action_itr->action,action_itr->type);
655 // original items
656 CharStartOutfitEntry const* oEntry = NULL;
657 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
659 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
661 if(entry->RaceClassGender == RaceClassGender)
663 oEntry = entry;
664 break;
669 if(oEntry)
671 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
673 if(oEntry->ItemId[j] <= 0)
674 continue;
676 uint32 item_id = oEntry->ItemId[j];
678 // Hack for not existed item id in dbc 3.0.3
679 if(item_id==40582)
680 continue;
682 ItemPrototype const* iProto = ObjectMgr::GetItemPrototype(item_id);
683 if(!iProto)
685 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
686 continue;
689 // BuyCount by default
690 uint32 count = iProto->BuyCount;
692 // special amount for foor/drink
693 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
695 switch(iProto->Spells[0].SpellCategory)
697 case 11: // food
698 count = getClass()==CLASS_DEATH_KNIGHT ? 10 : 4;
699 break;
700 case 59: // drink
701 count = 2;
702 break;
704 if(iProto->Stackable < count)
705 count = iProto->Stackable;
708 StoreNewItemInBestSlots(item_id, count);
712 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
713 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
715 // bags and main-hand weapon must equipped at this moment
716 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
717 // or ammo not equipped in special bag
718 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
720 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
722 uint16 eDest;
723 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
724 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
725 if( msg == EQUIP_ERR_OK )
727 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
728 EquipItem( eDest, pItem, true);
730 // move other items to more appropriate slots (ammo not equipped in special bag)
731 else
733 ItemPosCountVec sDest;
734 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
735 if( msg == EQUIP_ERR_OK )
737 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
738 pItem = StoreItem( sDest, pItem, true);
741 // if this is ammo then use it
742 msg = CanUseAmmo( pItem->GetEntry() );
743 if( msg == EQUIP_ERR_OK )
744 SetAmmo( pItem->GetEntry() );
748 // all item positions resolved
750 return true;
753 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
755 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
757 // attempt equip by one
758 while(titem_amount > 0)
760 uint16 eDest;
761 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
762 if( msg != EQUIP_ERR_OK )
763 break;
765 EquipNewItem( eDest, titem_id, true);
766 AutoUnequipOffhandIfNeed();
767 --titem_amount;
770 if(titem_amount == 0)
771 return true; // equipped
773 // attempt store
774 ItemPosCountVec sDest;
775 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
776 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
777 if( msg == EQUIP_ERR_OK )
779 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
780 return true; // stored
783 // item can't be added
784 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
785 return false;
788 void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
790 if (int(MaxValue) == DISABLED_MIRROR_TIMER)
792 if (int(CurrentValue) != DISABLED_MIRROR_TIMER)
793 StopMirrorTimer(Type);
794 return;
796 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
797 data << (uint32)Type;
798 data << CurrentValue;
799 data << MaxValue;
800 data << Regen;
801 data << (uint8)0;
802 data << (uint32)0; // spell id
803 GetSession()->SendPacket( &data );
806 void Player::StopMirrorTimer(MirrorTimerType Type)
808 m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
809 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
810 data << (uint32)Type;
811 GetSession()->SendPacket( &data );
814 uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
816 if(!isAlive() || isGameMaster())
817 return 0;
819 // Absorb, resist some environmental damage type
820 uint32 absorb = 0;
821 uint32 resist = 0;
822 if (type == DAMAGE_LAVA)
823 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
824 else if (type == DAMAGE_SLIME)
825 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
827 damage-=absorb+resist;
829 DealDamageMods(this,damage,&absorb);
831 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
832 data << uint64(GetGUID());
833 data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
834 data << uint32(damage);
835 data << uint32(absorb);
836 data << uint32(resist);
837 SendMessageToSet(&data, true);
839 uint32 final_damage = DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
841 if(!isAlive())
843 if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
845 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
846 DurabilityLossAll(0.10f,false);
847 // durability lost message
848 WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
849 GetSession()->SendPacket(&data2);
852 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
855 return final_damage;
858 int32 Player::getMaxTimer(MirrorTimerType timer)
860 switch (timer)
862 case FATIGUE_TIMER:
863 if (GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_TIMERBAR_FATIGUE_GMLEVEL))
864 return DISABLED_MIRROR_TIMER;
865 return sWorld.getConfig(CONFIG_TIMERBAR_FATIGUE_MAX)*IN_MILISECONDS;
866 case BREATH_TIMER:
868 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) ||
869 GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_TIMERBAR_BREATH_GMLEVEL))
870 return DISABLED_MIRROR_TIMER;
871 int32 UnderWaterTime = sWorld.getConfig(CONFIG_TIMERBAR_BREATH_MAX)*IN_MILISECONDS;
872 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
873 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
874 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
875 return UnderWaterTime;
877 case FIRE_TIMER:
879 if (!isAlive() || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_TIMERBAR_FIRE_GMLEVEL))
880 return DISABLED_MIRROR_TIMER;
881 return sWorld.getConfig(CONFIG_TIMERBAR_FIRE_MAX)*IN_MILISECONDS;
883 default:
884 return 0;
886 return 0;
889 void Player::UpdateMirrorTimers()
891 // Desync flags for update on next HandleDrowning
892 if (m_MirrorTimerFlags)
893 m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
896 void Player::HandleDrowning(uint32 time_diff)
898 if (!m_MirrorTimerFlags)
899 return;
901 // In water
902 if (m_MirrorTimerFlags & UNDERWATER_INWATER)
904 // Breath timer not activated - activate it
905 if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
907 m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
908 SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
910 else // If activated - do tick
912 m_MirrorTimer[BREATH_TIMER]-=time_diff;
913 // Timer limit - need deal damage
914 if (m_MirrorTimer[BREATH_TIMER] < 0)
916 m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILISECONDS;
917 // Calculate and deal damage
918 // TODO: Check this formula
919 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
920 EnvironmentalDamage(DAMAGE_DROWNING, damage);
922 else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
923 SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
926 else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
928 int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
929 // Need breath regen
930 m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
931 if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
932 StopMirrorTimer(BREATH_TIMER);
933 else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
934 SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
937 // In dark water
938 if (m_MirrorTimerFlags & UNDERWARER_INDARKWATER)
940 // Fatigue timer not activated - activate it
941 if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
943 m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
944 SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
946 else
948 m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
949 // Timer limit - need deal damage or teleport ghost to graveyard
950 if (m_MirrorTimer[FATIGUE_TIMER] < 0)
952 m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILISECONDS;
953 if (isAlive()) // Calculate and deal damage
955 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
956 EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
958 else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
959 RepopAtGraveyard();
961 else if (!(m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER))
962 SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
965 else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
967 int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
968 m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
969 if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
970 StopMirrorTimer(FATIGUE_TIMER);
971 else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER)
972 SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
975 if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
977 // Breath timer not activated - activate it
978 if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
979 m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
980 else
982 m_MirrorTimer[FIRE_TIMER]-=time_diff;
983 if (m_MirrorTimer[FIRE_TIMER] < 0)
985 m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILISECONDS;
986 // Calculate and deal damage
987 // TODO: Check this formula
988 uint32 damage = urand(600, 700);
989 if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
990 EnvironmentalDamage(DAMAGE_LAVA, damage);
991 else
992 EnvironmentalDamage(DAMAGE_SLIME, damage);
996 else
997 m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
999 // Recheck timers flag
1000 m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
1001 for (int i = 0; i< MAX_TIMERS; ++i)
1002 if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
1004 m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
1005 break;
1007 m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
1010 ///The player sobers by 256 every 10 seconds
1011 void Player::HandleSobering()
1013 m_drunkTimer = 0;
1015 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
1016 SetDrunkValue(drunk);
1019 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
1021 if(value >= 23000)
1022 return DRUNKEN_SMASHED;
1023 if(value >= 12800)
1024 return DRUNKEN_DRUNK;
1025 if(value & 0xFFFE)
1026 return DRUNKEN_TIPSY;
1027 return DRUNKEN_SOBER;
1030 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
1032 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1034 m_drunk = newDrunkenValue;
1035 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
1037 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1039 // special drunk invisibility detection
1040 if(newDrunkenState >= DRUNKEN_DRUNK)
1041 m_detectInvisibilityMask |= (1<<6);
1042 else
1043 m_detectInvisibilityMask &= ~(1<<6);
1045 if(newDrunkenState == oldDrunkenState)
1046 return;
1048 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1049 data << uint64(GetGUID());
1050 data << uint32(newDrunkenState);
1051 data << uint32(itemId);
1053 SendMessageToSet(&data, true);
1056 void Player::Update( uint32 p_time )
1058 if(!IsInWorld())
1059 return;
1061 // undelivered mail
1062 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1064 SendNewMail();
1065 ++unReadMails;
1067 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1068 m_nextMailDelivereTime = 0;
1071 //used to implement delayed far teleports
1072 SetCanDelayTeleport(true);
1073 Unit::Update( p_time );
1074 SetCanDelayTeleport(false);
1076 // update player only attacks
1077 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1079 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1082 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1084 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1087 time_t now = time (NULL);
1089 UpdatePvPFlag(now);
1091 UpdateContestedPvP(p_time);
1093 UpdateDuelFlag(now);
1095 CheckDuelDistance(now);
1097 UpdateAfkReport(now);
1099 // Update items that have just a limited lifetime
1100 if (now>m_Last_tick)
1101 UpdateItemDuration(uint32(now- m_Last_tick));
1103 if (!m_timedquests.empty())
1105 std::set<uint32>::iterator iter = m_timedquests.begin();
1106 while (iter != m_timedquests.end())
1108 QuestStatusData& q_status = mQuestStatus[*iter];
1109 if( q_status.m_timer <= p_time )
1111 uint32 quest_id = *iter;
1112 ++iter; // current iter will be removed in FailQuest
1113 FailQuest(quest_id);
1115 else
1117 q_status.m_timer -= p_time;
1118 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1119 ++iter;
1124 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1126 Unit *pVictim = getVictim();
1127 if (pVictim && !IsNonMeleeSpellCasted(false))
1129 // default combat reach 10
1130 // TODO add weapon,skill check
1132 float pldistance = ATTACK_DISTANCE;
1134 if (isAttackReady(BASE_ATTACK))
1136 if(!IsWithinDistInMap(pVictim, pldistance))
1138 setAttackTimer(BASE_ATTACK,100);
1139 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1141 SendAttackSwingNotInRange();
1142 m_swingErrorMsg = 1;
1145 //120 degrees of radiant range
1146 else if( !HasInArc( 2*M_PI/3, pVictim ))
1148 setAttackTimer(BASE_ATTACK,100);
1149 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1151 SendAttackSwingBadFacingAttack();
1152 m_swingErrorMsg = 2;
1155 else
1157 m_swingErrorMsg = 0; // reset swing error state
1159 // prevent base and off attack in same time, delay attack at 0.2 sec
1160 if(haveOffhandWeapon())
1162 uint32 off_att = getAttackTimer(OFF_ATTACK);
1163 if(off_att < ATTACK_DISPLAY_DELAY)
1164 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1166 AttackerStateUpdate(pVictim, BASE_ATTACK);
1167 resetAttackTimer(BASE_ATTACK);
1171 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1173 if(!IsWithinDistInMap(pVictim, pldistance))
1175 setAttackTimer(OFF_ATTACK,100);
1177 else if( !HasInArc( 2*M_PI/3, pVictim ))
1179 setAttackTimer(OFF_ATTACK,100);
1181 else
1183 // prevent base and off attack in same time, delay attack at 0.2 sec
1184 uint32 base_att = getAttackTimer(BASE_ATTACK);
1185 if(base_att < ATTACK_DISPLAY_DELAY)
1186 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1187 // do attack
1188 AttackerStateUpdate(pVictim, OFF_ATTACK);
1189 resetAttackTimer(OFF_ATTACK);
1193 Unit *owner = pVictim->GetOwner();
1194 Unit *u = owner ? owner : pVictim;
1195 if(u->IsPvP() && (!duel || duel->opponent != u))
1197 UpdatePvP(true);
1198 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1203 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1205 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1207 int time_inn = time(NULL)-GetTimeInnEnter();
1208 if (time_inn >= 10) //freeze update
1210 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1211 //speed collect rest bonus (section/in hour)
1212 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1213 UpdateInnerTime(time(NULL));
1218 if (m_regenTimer)
1220 if(p_time >= m_regenTimer)
1221 m_regenTimer = 0;
1222 else
1223 m_regenTimer -= p_time;
1226 if (m_weaponChangeTimer > 0)
1228 if(p_time >= m_weaponChangeTimer)
1229 m_weaponChangeTimer = 0;
1230 else
1231 m_weaponChangeTimer -= p_time;
1234 if (m_zoneUpdateTimer > 0)
1236 if(p_time >= m_zoneUpdateTimer)
1238 uint32 newzone, newarea;
1239 GetZoneAndAreaId(newzone,newarea);
1241 if( m_zoneUpdateId != newzone )
1242 UpdateZone(newzone,newarea); // also update area
1243 else
1245 // use area updates as well
1246 // needed for free far all arenas for example
1247 if( m_areaUpdateId != newarea )
1248 UpdateArea(newarea);
1250 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1253 else
1254 m_zoneUpdateTimer -= p_time;
1257 if (isAlive())
1259 // if no longer casting, set regen power as soon as it is up.
1260 if (!IsUnderLastManaUseEffect())
1261 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
1263 if (!m_regenTimer)
1264 RegenerateAll();
1267 if (m_deathState == JUST_DIED)
1269 KillPlayer();
1272 if(m_nextSave > 0)
1274 if(p_time >= m_nextSave)
1276 // m_nextSave reseted in SaveToDB call
1277 SaveToDB();
1278 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1280 else
1282 m_nextSave -= p_time;
1286 //Handle Water/drowning
1287 HandleDrowning(p_time);
1289 //Handle detect stealth players
1290 if (m_DetectInvTimer > 0)
1292 if (p_time >= m_DetectInvTimer)
1294 HandleStealthedUnitsDetection();
1295 m_DetectInvTimer = 3000;
1297 else
1298 m_DetectInvTimer -= p_time;
1301 // Played time
1302 if (now > m_Last_tick)
1304 uint32 elapsed = uint32(now - m_Last_tick);
1305 m_Played_time[PLAYED_TIME_TOTAL] += elapsed; // Total played time
1306 m_Played_time[PLAYED_TIME_LEVEL] += elapsed; // Level played time
1307 m_Last_tick = now;
1310 if (m_drunk)
1312 m_drunkTimer += p_time;
1314 if (m_drunkTimer > 10*IN_MILISECONDS)
1315 HandleSobering();
1318 // not auto-free ghost from body in instances
1319 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1321 if(p_time >= m_deathTimer)
1323 m_deathTimer = 0;
1324 BuildPlayerRepop();
1325 RepopAtGraveyard();
1327 else
1328 m_deathTimer -= p_time;
1331 UpdateEnchantTime(p_time);
1332 UpdateHomebindTime(p_time);
1334 // group update
1335 SendUpdateToOutOfRangeGroupMembers();
1337 Pet* pet = GetPet();
1338 if(pet && !pet->IsWithinDistInMap(this, GetMap()->GetVisibilityDistance()) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1340 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1343 //we should execute delayed teleports only for alive(!) players
1344 //because we don't want player's ghost teleported from graveyard
1345 if(IsHasDelayedTeleport() && isAlive())
1346 TeleportTo(m_teleport_dest, m_teleport_options);
1349 void Player::setDeathState(DeathState s)
1351 uint32 ressSpellId = 0;
1353 bool cur = isAlive();
1355 if(s == JUST_DIED && cur)
1357 // drunken state is cleared on death
1358 SetDrunkValue(0);
1359 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1360 ClearComboPoints();
1362 clearResurrectRequestData();
1364 // remove form before other mods to prevent incorrect stats calculation
1365 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1367 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1368 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1370 // remove uncontrolled pets
1371 RemoveMiniPet();
1373 // save value before aura remove in Unit::setDeathState
1374 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1376 // passive spell
1377 if(!ressSpellId)
1378 ressSpellId = GetResurrectionSpellId();
1379 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1380 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
1381 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
1383 Unit::setDeathState(s);
1385 // restore resurrection spell id for player after aura remove
1386 if(s == JUST_DIED && cur && ressSpellId)
1387 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1389 if(isAlive() && !cur)
1391 //clear aura case after resurrection by another way (spells will be applied before next death)
1392 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1394 // restore default warrior stance
1395 if(getClass()== CLASS_WARRIOR)
1396 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1400 bool Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1402 // 0 1 2 3 4 5 6 7
1403 // "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.playerBytes, characters.playerBytes2, characters.level, "
1404 // 8 9 10 11 12 13 14
1405 // "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, "
1406 // 15 16 17 18 19 20
1407 // "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.data, character_declinedname.genitive "
1409 Field *fields = result->Fetch();
1411 uint32 guid = fields[0].GetUInt32();
1412 uint8 pRace = fields[2].GetUInt8();
1413 uint8 pClass = fields[3].GetUInt8();
1415 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(pRace, pClass);
1416 if(!info)
1418 sLog.outError("Player %u has incorrect race/class pair. Don't build enum.", guid);
1419 return false;
1422 *p_data << uint64(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
1423 *p_data << fields[1].GetString(); // name
1424 *p_data << uint8(pRace); // race
1425 *p_data << uint8(pClass); // class
1426 *p_data << uint8(fields[4].GetUInt8()); // gender
1428 uint32 playerBytes = fields[5].GetUInt32();
1429 *p_data << uint8(playerBytes); // skin
1430 *p_data << uint8(playerBytes >> 8); // face
1431 *p_data << uint8(playerBytes >> 16); // hair style
1432 *p_data << uint8(playerBytes >> 24); // hair color
1434 uint32 playerBytes2 = fields[6].GetUInt32();
1435 *p_data << uint8(playerBytes2 & 0xFF); // facial hair
1437 *p_data << uint8(fields[7].GetUInt8()); // level
1438 *p_data << uint32(fields[8].GetUInt32()); // zone
1439 *p_data << uint32(fields[9].GetUInt32()); // map
1441 *p_data << fields[10].GetFloat(); // x
1442 *p_data << fields[11].GetFloat(); // y
1443 *p_data << fields[12].GetFloat(); // z
1445 *p_data << uint32(fields[13].GetUInt32()); // guild id
1447 uint32 char_flags = 0;
1448 uint32 playerFlags = fields[14].GetUInt32();
1449 uint32 atLoginFlags = fields[15].GetUInt32();
1450 if(playerFlags & PLAYER_FLAGS_HIDE_HELM)
1451 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1452 if(playerFlags & PLAYER_FLAGS_HIDE_CLOAK)
1453 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1454 if(playerFlags & PLAYER_FLAGS_GHOST)
1455 char_flags |= CHARACTER_FLAG_GHOST;
1456 if(atLoginFlags & AT_LOGIN_RENAME)
1457 char_flags |= CHARACTER_FLAG_RENAME;
1458 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED))
1460 if(!fields[20].GetCppString().empty())
1461 char_flags |= CHARACTER_FLAG_DECLINED;
1463 else
1464 char_flags |= CHARACTER_FLAG_DECLINED;
1466 *p_data << uint32(char_flags); // character flags
1467 // character customize flags
1468 *p_data << uint32(atLoginFlags & AT_LOGIN_CUSTOMIZE ? CHAR_CUSTOMIZE_FLAG_CUSTOMIZE : CHAR_CUSTOMIZE_FLAG_NONE);
1469 *p_data << uint8(1); // unknown
1471 // Pets info
1473 uint32 petDisplayId = 0;
1474 uint32 petLevel = 0;
1475 uint32 petFamily = 0;
1477 // show pet at selection character in character list only for non-ghost character
1478 if (result && !(playerFlags & PLAYER_FLAGS_GHOST) && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER || pClass == CLASS_DEATH_KNIGHT))
1480 uint32 entry = fields[16].GetUInt32();
1481 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1482 if(cInfo)
1484 petDisplayId = fields[17].GetUInt32();
1485 petLevel = fields[18].GetUInt32();
1486 petFamily = cInfo->family;
1490 *p_data << uint32(petDisplayId);
1491 *p_data << uint32(petLevel);
1492 *p_data << uint32(petFamily);
1495 // TODO: do not access data field here
1496 Tokens data = StrSplit(fields[19].GetCppString(), " ");
1498 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1500 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2);
1501 uint32 item_id = GetUInt32ValueFromArray(data, visualbase);
1502 const ItemPrototype * proto = ObjectMgr::GetItemPrototype(item_id);
1503 if(!proto)
1505 *p_data << uint32(0);
1506 *p_data << uint8(0);
1507 *p_data << uint32(0);
1508 continue;
1511 SpellItemEnchantmentEntry const *enchant = NULL;
1513 uint32 enchants = GetUInt32ValueFromArray(data, visualbase + 1);
1514 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot)
1516 // values stored in 2 uint16
1517 uint32 enchantId = 0x0000FFFF & (enchants >> enchantSlot*16);
1518 if(!enchantId)
1519 continue;
1521 if ((enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId)))
1522 break;
1525 *p_data << uint32(proto->DisplayInfoID);
1526 *p_data << uint8(proto->InventoryType);
1527 *p_data << uint32(enchant ? enchant->aura_id : 0);
1529 *p_data << uint32(0); // first bag display id
1530 *p_data << uint8(0); // first bag inventory type
1531 *p_data << uint32(0); // enchant?
1533 return true;
1536 bool Player::ToggleAFK()
1538 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1540 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1542 // afk player not allowed in battleground
1543 if(state && InBattleGround())
1544 LeaveBattleground();
1546 return state;
1549 bool Player::ToggleDND()
1551 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1553 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1556 uint8 Player::chatTag() const
1558 // it's bitmask
1559 // 0x8 - ??
1560 // 0x4 - gm
1561 // 0x2 - dnd
1562 // 0x1 - afk
1563 if(isGMChat())
1564 return 4;
1565 else if(isDND())
1566 return 3;
1567 if(isAFK())
1568 return 1;
1569 else
1570 return 0;
1573 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1575 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1577 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1578 return false;
1581 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1582 Pet* pet = GetPet();
1584 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1586 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1587 // don't let gm level > 1 either
1588 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1589 return false;
1591 // client without expansion support
1592 if(GetSession()->Expansion() < mEntry->Expansion())
1594 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1596 if(GetTransport())
1597 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1599 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1601 return false; // normal client can't teleport to this map...
1603 else
1605 sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
1608 // if we were on a transport, leave
1609 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1611 m_transport->RemovePassenger(this);
1612 m_transport = NULL;
1613 m_movementInfo.t_x = 0.0f;
1614 m_movementInfo.t_y = 0.0f;
1615 m_movementInfo.t_z = 0.0f;
1616 m_movementInfo.t_o = 0.0f;
1617 m_movementInfo.t_seat = -1;
1618 m_movementInfo.t_time = 0;
1621 // The player was ported to another map and looses the duel immediately.
1622 // We have to perform this check before the teleport, otherwise the
1623 // ObjectAccessor won't find the flag.
1624 if (duel && GetMapId()!=mapid)
1626 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
1627 if (obj)
1628 DuelComplete(DUEL_FLED);
1631 // reset movement flags at teleport, because player will continue move with these flags after teleport
1632 m_movementInfo.SetMovementFlags(MOVEMENTFLAG_NONE);
1634 if ((GetMapId() == mapid) && (!m_transport))
1636 //lets reset far teleport flag if it wasn't reset during chained teleports
1637 SetSemaphoreTeleportFar(false);
1638 //setup delayed teleport flag
1639 SetDelayedTeleportFlag(IsCanDelayTeleport());
1640 //if teleport spell is casted in Unit::Update() func
1641 //then we need to delay it until update process will be finished
1642 if(IsHasDelayedTeleport())
1644 SetSemaphoreTeleportNear(true);
1645 //lets save teleport destination for player
1646 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1647 m_teleport_options = options;
1648 return true;
1651 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1653 //same map, only remove pet if out of range for new position
1654 if(pet && !pet->IsWithinDist3d(x,y,z,GetMap()->GetVisibilityDistance()))
1655 UnsummonPetTemporaryIfAny();
1658 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1659 CombatStop();
1661 // this will be used instead of the current location in SaveToDB
1662 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1663 SetFallInformation(0, z);
1665 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1666 // at client packet MSG_MOVE_TELEPORT_ACK
1667 SetSemaphoreTeleportNear(true);
1668 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1669 if(!GetSession()->PlayerLogout())
1671 WorldPacket data;
1672 BuildTeleportAckMsg(&data, x, y, z, orientation);
1673 GetSession()->SendPacket(&data);
1676 else
1678 // far teleport to another map
1679 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1680 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1682 // Check enter rights before map getting to avoid creating instance copy for player
1683 // this check not dependent from map instance copy and same for all instance copies of selected map
1684 if (!sMapMgr.CanPlayerEnter(mapid, this))
1685 return false;
1687 // If the map is not created, assume it is possible to enter it.
1688 // It will be created in the WorldPortAck.
1689 Map *map = sMapMgr.FindMap(mapid);
1690 if (!map || map->CanEnter(this))
1692 //lets reset near teleport flag if it wasn't reset during chained teleports
1693 SetSemaphoreTeleportNear(false);
1694 //setup delayed teleport flag
1695 SetDelayedTeleportFlag(IsCanDelayTeleport());
1696 //if teleport spell is casted in Unit::Update() func
1697 //then we need to delay it until update process will be finished
1698 if(IsHasDelayedTeleport())
1700 SetSemaphoreTeleportFar(true);
1701 //lets save teleport destination for player
1702 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1703 m_teleport_options = options;
1704 return true;
1707 SetSelection(0);
1709 CombatStop();
1711 ResetContestedPvP();
1713 // remove player from battleground on far teleport (when changing maps)
1714 if(BattleGround const* bg = GetBattleGround())
1716 // Note: at battleground join battleground id set before teleport
1717 // and we already will found "current" battleground
1718 // just need check that this is targeted map or leave
1719 if(bg->GetMapId() != mapid)
1720 LeaveBattleground(false); // don't teleport to entry point
1723 // remove pet on map change
1724 if (pet)
1725 UnsummonPetTemporaryIfAny();
1727 // remove all dyn objects
1728 RemoveAllDynObjects();
1730 // stop spellcasting
1731 // not attempt interrupt teleportation spell at caster teleport
1732 if(!(options & TELE_TO_SPELL))
1733 if(IsNonMeleeSpellCasted(true))
1734 InterruptNonMeleeSpells(true);
1736 //remove auras before removing from map...
1737 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
1739 if(!GetSession()->PlayerLogout())
1741 // send transfer packets
1742 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1743 data << uint32(mapid);
1744 if (m_transport)
1746 data << m_transport->GetEntry() << GetMapId();
1748 GetSession()->SendPacket(&data);
1750 data.Initialize(SMSG_NEW_WORLD, (20));
1751 if (m_transport)
1753 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1755 else
1757 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1759 GetSession()->SendPacket( &data );
1760 SendSavedInstances();
1763 // remove from old map now
1764 if(oldmap)
1765 oldmap->Remove(this, false);
1767 // new final coordinates
1768 float final_x = x;
1769 float final_y = y;
1770 float final_z = z;
1771 float final_o = orientation;
1773 if(m_transport)
1775 final_x += m_movementInfo.t_x;
1776 final_y += m_movementInfo.t_y;
1777 final_z += m_movementInfo.t_z;
1778 final_o += m_movementInfo.t_o;
1781 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1782 SetFallInformation(0, final_z);
1783 // if the player is saved before worldportack (at logout for example)
1784 // this will be used instead of the current location in SaveToDB
1786 // move packet sent by client always after far teleport
1787 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1788 SetSemaphoreTeleportFar(true);
1790 else
1791 return false;
1793 return true;
1796 bool Player::TeleportToBGEntryPoint()
1798 ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE);
1799 ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE);
1800 return TeleportTo(m_bgData.joinPos);
1803 void Player::ProcessDelayedOperations()
1805 if(m_DelayedOperations == 0)
1806 return;
1808 if(m_DelayedOperations & DELAYED_RESURRECT_PLAYER)
1810 ResurrectPlayer(0.0f, false);
1812 if(GetMaxHealth() > m_resurrectHealth)
1813 SetHealth( m_resurrectHealth );
1814 else
1815 SetHealth( GetMaxHealth() );
1817 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
1818 SetPower(POWER_MANA, m_resurrectMana );
1819 else
1820 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
1822 SetPower(POWER_RAGE, 0 );
1823 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
1825 SpawnCorpseBones();
1828 if(m_DelayedOperations & DELAYED_SAVE_PLAYER)
1830 SaveToDB();
1833 if(m_DelayedOperations & DELAYED_SPELL_CAST_DESERTER)
1835 CastSpell(this, 26013, true); // Deserter
1838 if (m_DelayedOperations & DELAYED_BG_MOUNT_RESTORE)
1840 if (m_bgData.mountSpell)
1842 CastSpell(this, m_bgData.mountSpell, true);
1843 m_bgData.mountSpell = 0;
1847 if (m_DelayedOperations & DELAYED_BG_TAXI_RESTORE)
1849 if (m_bgData.HasTaxiPath())
1851 m_taxi.AddTaxiDestination(m_bgData.taxiPath[0]);
1852 m_taxi.AddTaxiDestination(m_bgData.taxiPath[1]);
1853 m_bgData.ClearTaxiPath();
1855 ContinueTaxiFlight();
1859 //we have executed ALL delayed ops, so clear the flag
1860 m_DelayedOperations = 0;
1863 void Player::AddToWorld()
1865 ///- Do not add/remove the player from the object storage
1866 ///- It will crash when updating the ObjectAccessor
1867 ///- The player should only be added when logging in
1868 Unit::AddToWorld();
1870 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1872 if(m_items[i])
1873 m_items[i]->AddToWorld();
1877 void Player::RemoveFromWorld()
1879 // cleanup
1880 if(IsInWorld())
1882 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1883 UnsummonAllTotems();
1884 RemoveMiniPet();
1887 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1889 if(m_items[i])
1890 m_items[i]->RemoveFromWorld();
1893 ///- Do not add/remove the player from the object storage
1894 ///- It will crash when updating the ObjectAccessor
1895 ///- The player should only be removed when logging out
1896 Unit::RemoveFromWorld();
1899 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1901 float addRage;
1903 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1905 if(attacker)
1907 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1909 // talent who gave more rage on attack
1910 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1912 else
1914 addRage = damage/rageconversion*2.5;
1916 // Berserker Rage effect
1917 if(HasAura(18499,0))
1918 addRage *= 1.3;
1921 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1923 ModifyPower(POWER_RAGE, uint32(addRage*10));
1926 void Player::RegenerateAll(uint32 diff)
1928 // Not in combat or they have regeneration
1929 if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1930 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1932 RegenerateHealth(diff);
1933 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1935 Regenerate(POWER_RAGE, diff);
1936 if(getClass() == CLASS_DEATH_KNIGHT)
1937 Regenerate(POWER_RUNIC_POWER, diff);
1941 Regenerate(POWER_ENERGY, diff);
1943 Regenerate(POWER_MANA, diff);
1945 if (getClass() == CLASS_DEATH_KNIGHT)
1946 Regenerate(POWER_RUNE, diff);
1948 m_regenTimer = REGEN_TIME_FULL;
1951 // diff contains the time in milliseconds since last regen.
1952 void Player::Regenerate(Powers power, uint32 diff)
1954 uint32 curValue = GetPower(power);
1955 uint32 maxValue = GetMaxPower(power);
1957 float addvalue = 0.0f;
1959 switch (power)
1961 case POWER_MANA:
1963 bool recentCast = IsUnderLastManaUseEffect();
1964 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1965 if (recentCast)
1967 // Mangos Updates Mana in intervals of 2s, which is correct
1968 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1970 else
1972 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1974 } break;
1975 case POWER_RAGE: // Regenerate rage
1977 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1978 addvalue = 20 * RageDecreaseRate; // 2 rage by tick (= 2 seconds => 1 rage/sec)
1979 } break;
1980 case POWER_ENERGY: // Regenerate energy (rogue)
1981 addvalue = 20;
1982 break;
1983 case POWER_RUNIC_POWER:
1985 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1986 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1987 } break;
1988 case POWER_RUNE:
1990 if (getClass() != CLASS_DEATH_KNIGHT)
1991 break;
1993 for(uint32 i = 0; i < MAX_RUNES; ++i)
1995 if(uint16 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1996 SetRuneCooldown(i, (cd < diff) ? 0 : cd - diff);
1998 } break;
1999 case POWER_FOCUS:
2000 case POWER_HAPPINESS:
2001 case POWER_HEALTH:
2002 break;
2005 // Mana regen calculated in Player::UpdateManaRegen()
2006 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
2007 if(power != POWER_MANA)
2009 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
2010 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
2011 if ((*i)->GetModifier()->m_miscvalue == power)
2012 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
2015 // addvalue computed on a 2sec basis. => update to diff time
2016 addvalue *= float(diff) / REGEN_TIME_FULL;
2018 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
2020 curValue += uint32(addvalue);
2021 if (curValue > maxValue)
2022 curValue = maxValue;
2024 else
2026 if(curValue <= uint32(addvalue))
2027 curValue = 0;
2028 else
2029 curValue -= uint32(addvalue);
2031 SetPower(power, curValue);
2034 void Player::RegenerateHealth(uint32 diff)
2036 uint32 curValue = GetHealth();
2037 uint32 maxValue = GetMaxHealth();
2039 if (curValue >= maxValue) return;
2041 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
2043 float addvalue = 0.0f;
2045 // polymorphed case
2046 if ( IsPolymorphed() )
2047 addvalue = GetMaxHealth()/3;
2048 // normal regen case (maybe partly in combat case)
2049 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
2051 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
2052 if (!isInCombat())
2054 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
2055 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
2056 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
2058 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
2059 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
2061 if(!IsStandState())
2062 addvalue *= 1.5;
2065 // always regeneration bonus (including combat)
2066 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
2068 if(addvalue < 0)
2069 addvalue = 0;
2071 addvalue *= (float)diff / REGEN_TIME_FULL;
2073 ModifyHealth(int32(addvalue));
2076 Creature* Player::GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask)
2078 // unit checks
2079 if (!guid || !IsInWorld() || isInFlight())
2080 return NULL;
2082 // exist (we need look pets also for some interaction (quest/etc)
2083 Creature *unit = GetMap()->GetCreatureOrPetOrVehicle(guid);
2084 if (!unit)
2085 return NULL;
2087 // appropriate npc type
2088 if (npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
2089 return NULL;
2091 if (npcflagmask == UNIT_NPC_FLAG_STABLEMASTER)
2093 if (getClass() != CLASS_HUNTER)
2094 return NULL;
2097 // if a dead unit should be able to talk - the creature must be alive and have special flags
2098 if (!unit->isAlive())
2099 return NULL;
2101 if (isAlive() && unit->isInvisibleForAlive())
2102 return NULL;
2104 // not allow interaction under control, but allow with own pets
2105 if (unit->GetCharmerGUID())
2106 return NULL;
2108 // not enemy
2109 if (unit->IsHostileTo(this))
2110 return NULL;
2112 // not unfriendly
2113 if(FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction()))
2114 if(factionTemplate->faction)
2115 if(FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
2116 if(faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
2117 return NULL;
2119 // not too far
2120 if(!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE))
2121 return NULL;
2123 return unit;
2126 GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, uint32 gameobject_type) const
2128 if (GameObject *go = GetMap()->GetGameObject(guid))
2130 if (uint32(go->GetGoType()) == gameobject_type || gameobject_type == MAX_GAMEOBJECT_TYPE)
2132 float maxdist;
2133 switch(go->GetGoType())
2135 // TODO: find out how the client calculates the maximal usage distance to spellless working
2136 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2137 case GAMEOBJECT_TYPE_GUILD_BANK:
2138 case GAMEOBJECT_TYPE_MAILBOX:
2139 maxdist = 10.0f;
2140 break;
2141 case GAMEOBJECT_TYPE_FISHINGHOLE:
2142 maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
2143 break;
2144 default:
2145 maxdist = INTERACTION_DISTANCE;
2146 break;
2149 if (go->IsWithinDistInMap(this, maxdist) && go->isSpawned())
2150 return go;
2152 sLog.outError("GetGameObjectIfCanInteractWith: 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,
2153 go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
2156 return NULL;
2159 bool Player::IsUnderWater() const
2161 return IsInWater() &&
2162 GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2165 void Player::SetInWater(bool apply)
2167 if(m_isInWater==apply)
2168 return;
2170 //define player in water by opcodes
2171 //move player's guid into HateOfflineList of those mobs
2172 //which can't swim and move guid back into ThreatList when
2173 //on surface.
2174 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2175 m_isInWater = apply;
2177 // remove auras that need water/land
2178 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
2180 getHostileRefManager().updateThreatTables();
2183 void Player::SetGameMaster(bool on)
2185 if(on)
2187 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
2188 setFaction(35);
2189 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2191 if (Pet* pet = GetPet())
2193 pet->setFaction(35);
2194 pet->getHostileRefManager().setOnlineOfflineState(false);
2197 for (int8 i = 0; i < MAX_TOTEM; ++i)
2198 if(m_TotemSlot[i])
2199 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
2200 totem->setFaction(35);
2202 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2203 ResetContestedPvP();
2205 getHostileRefManager().setOnlineOfflineState(false);
2206 CombatStopWithPets();
2208 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
2210 else
2212 // restore phase
2213 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
2214 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2216 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2217 setFactionForRace(getRace());
2218 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2220 if (Pet* pet = GetPet())
2222 pet->setFaction(getFaction());
2223 pet->getHostileRefManager().setOnlineOfflineState(true);
2226 for (int8 i = 0; i < MAX_TOTEM; ++i)
2227 if(m_TotemSlot[i])
2228 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
2229 totem->setFaction(getFaction());
2231 // restore FFA PvP Server state
2232 if(sWorld.IsFFAPvPRealm())
2233 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2235 // restore FFA PvP area state, remove not allowed for GM mounts
2236 UpdateArea(m_areaUpdateId);
2238 getHostileRefManager().setOnlineOfflineState(true);
2241 UpdateVisibilityForPlayer();
2244 void Player::SetGMVisible(bool on)
2246 if(on)
2248 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2250 // Reapply stealth/invisibility if active or show if not any
2251 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2252 SetVisibility(VISIBILITY_GROUP_STEALTH);
2253 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2254 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2255 else
2256 SetVisibility(VISIBILITY_ON);
2258 else
2260 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2262 SetAcceptWhispers(false);
2263 SetGameMaster(true);
2265 SetVisibility(VISIBILITY_OFF);
2269 bool Player::IsGroupVisibleFor(Player* p) const
2271 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2273 default: return IsInSameGroupWith(p);
2274 case 1: return IsInSameRaidWith(p);
2275 case 2: return GetTeam()==p->GetTeam();
2279 bool Player::IsInSameGroupWith(Player const* p) const
2281 return (p==this || (GetGroup() != NULL &&
2282 GetGroup()->SameSubGroup((Player*)this, (Player*)p)));
2285 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2286 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2287 void Player::UninviteFromGroup()
2289 Group* group = GetGroupInvite();
2290 if(!group)
2291 return;
2293 group->RemoveInvite(this);
2295 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2297 if(group->IsCreated())
2299 group->Disband(true);
2300 sObjectMgr.RemoveGroup(group);
2302 else
2303 group->RemoveAllInvites();
2305 delete group;
2309 void Player::RemoveFromGroup(Group* group, uint64 guid)
2311 if(group)
2313 if (group->RemoveMember(guid, 0) <= 1)
2315 // group->Disband(); already disbanded in RemoveMember
2316 sObjectMgr.RemoveGroup(group);
2317 delete group;
2318 // removemember sets the player's group pointer to NULL
2323 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2325 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2326 data << uint64(victim ? victim->GetGUID() : 0); // guid
2327 data << uint32(GivenXP+RestXP); // given experience
2328 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2329 if(victim)
2331 data << uint32(GivenXP); // experience without rested bonus
2332 data << float(1); // 1 - none 0 - 100% group bonus output
2334 data << uint8(0); // new 2.4.0
2335 GetSession()->SendPacket(&data);
2338 void Player::GiveXP(uint32 xp, Unit* victim)
2340 if ( xp < 1 )
2341 return;
2343 if(!isAlive())
2344 return;
2346 uint32 level = getLevel();
2348 // XP to money conversion processed in Player::RewardQuest
2349 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2350 return;
2352 if(victim)
2354 // handle SPELL_AURA_MOD_KILL_XP_PCT auras
2355 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_KILL_XP_PCT);
2356 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2357 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2359 else
2361 // handle SPELL_AURA_MOD_QUEST_XP_PCT auras
2362 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_QUEST_XP_PCT);
2363 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2364 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2368 // XP resting bonus for kill
2369 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2371 SendLogXPGain(xp,victim,rested_bonus_xp);
2373 uint32 curXP = GetUInt32Value(PLAYER_XP);
2374 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2375 uint32 newXP = curXP + xp + rested_bonus_xp;
2377 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2379 newXP -= nextLvlXP;
2381 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2382 GiveLevel(level + 1);
2384 level = getLevel();
2385 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2388 SetUInt32Value(PLAYER_XP, newXP);
2391 // Update player to next level
2392 // Current player experience not update (must be update by caller)
2393 void Player::GiveLevel(uint32 level)
2395 if ( level == getLevel() )
2396 return;
2398 PlayerLevelInfo info;
2399 sObjectMgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2401 PlayerClassLevelInfo classInfo;
2402 sObjectMgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2404 // send levelup info to client
2405 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2406 data << uint32(level);
2407 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2408 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2409 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2410 data << uint32(0);
2411 data << uint32(0);
2412 data << uint32(0);
2413 data << uint32(0);
2414 data << uint32(0);
2415 data << uint32(0);
2416 // end for
2417 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2418 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2420 GetSession()->SendPacket(&data);
2422 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr.GetXPForLevel(level));
2424 //update level, max level of skills
2425 m_Played_time[PLAYED_TIME_LEVEL] = 0; // Level Played Time reset
2427 _ApplyAllLevelScaleItemMods(false);
2429 SetLevel(level);
2431 UpdateSkillsForLevel ();
2433 // save base values (bonuses already included in stored stats
2434 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2435 SetCreateStat(Stats(i), info.stats[i]);
2437 SetCreateHealth(classInfo.basehealth);
2438 SetCreateMana(classInfo.basemana);
2440 InitTalentForLevel();
2441 InitTaxiNodesForLevel();
2442 InitGlyphsForLevel();
2444 UpdateAllStats();
2446 // set current level health and mana/energy to maximum after applying all mods.
2447 SetHealth(GetMaxHealth());
2448 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2449 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2450 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2451 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2452 SetPower(POWER_FOCUS, 0);
2453 SetPower(POWER_HAPPINESS, 0);
2455 _ApplyAllLevelScaleItemMods(true);
2457 // update level to hunter/summon pet
2458 if (Pet* pet = GetPet())
2459 pet->SynchronizeLevelWithOwner();
2461 if (MailLevelReward const* mailReward = sObjectMgr.GetMailLevelReward(level,getRaceMask()))
2462 MailDraft(mailReward->mailTemplateId).SendMailTo(this,MailSender(MAIL_CREATURE,mailReward->senderEntry));
2464 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2467 void Player::InitTalentForLevel()
2469 uint32 level = getLevel();
2470 // talents base at level diff ( talents = level - 9 but some can be used already)
2471 if(level < 10)
2473 // Remove all talent points
2474 if(m_usedTalentCount > 0) // Free any used talents
2476 resetTalents(true);
2477 SetFreeTalentPoints(0);
2480 else
2482 uint32 talentPointsForLevel = CalculateTalentsPoints();
2484 // if used more that have then reset
2485 if(m_usedTalentCount > talentPointsForLevel)
2487 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2488 resetTalents(true);
2489 else
2490 SetFreeTalentPoints(0);
2492 // else update amount of free points
2493 else
2494 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2497 if(!GetSession()->PlayerLoading())
2498 SendTalentsInfoData(false); // update at client
2501 void Player::InitStatsForLevel(bool reapplyMods)
2503 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2504 _RemoveAllStatBonuses();
2506 PlayerClassLevelInfo classInfo;
2507 sObjectMgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2509 PlayerLevelInfo info;
2510 sObjectMgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2512 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2513 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr.GetXPForLevel(getLevel()));
2515 // reset before any aura state sources (health set/aura apply)
2516 SetUInt32Value(UNIT_FIELD_AURASTATE, 0);
2518 UpdateSkillsForLevel ();
2520 // set default cast time multiplier
2521 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2523 // reset size before reapply auras
2524 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2526 // save base values (bonuses already included in stored stats
2527 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2528 SetCreateStat(Stats(i), info.stats[i]);
2530 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2531 SetStat(Stats(i), info.stats[i]);
2533 SetCreateHealth(classInfo.basehealth);
2535 //set create powers
2536 SetCreateMana(classInfo.basemana);
2538 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2540 InitStatBuffMods();
2542 //reset rating fields values
2543 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2544 SetUInt32Value(index, 0);
2546 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2547 for (int i = 0; i < 7; ++i)
2549 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2550 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2551 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2554 //reset attack power, damage and attack speed fields
2555 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2556 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2557 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2559 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2560 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2561 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2562 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2563 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2564 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2566 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2567 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2568 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2569 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2570 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2571 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2573 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2574 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2575 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2576 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2578 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2579 for (uint8 i = 0; i < 7; ++i)
2580 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2582 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2583 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2584 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2586 // Dodge percentage
2587 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2589 // set armor (resistance 0) to original value (create_agility*2)
2590 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2591 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2592 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2593 // set other resistance to original value (0)
2594 for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
2596 SetResistance(SpellSchools(i), 0);
2597 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2598 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2601 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2602 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2603 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2605 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
2606 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2608 // Reset no reagent cost field
2609 for(int i = 0; i < 3; ++i)
2610 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2611 // Init data for form but skip reapply item mods for form
2612 InitDataForForm(reapplyMods);
2614 // save new stats
2615 for (int i = POWER_MANA; i < MAX_POWERS; ++i)
2616 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2618 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2620 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2621 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2623 // cleanup unit flags (will be re-applied if need at aura load).
2624 RemoveFlag( UNIT_FIELD_FLAGS,
2625 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2626 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2627 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2628 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2629 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2630 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2632 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2634 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2635 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2637 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2638 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2640 // restore if need some important flags
2641 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2643 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2644 _ApplyAllStatBonuses();
2646 // set current level health and mana/energy to maximum after applying all mods.
2647 SetHealth(GetMaxHealth());
2648 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2649 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2650 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2651 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2652 SetPower(POWER_FOCUS, 0);
2653 SetPower(POWER_HAPPINESS, 0);
2654 SetPower(POWER_RUNIC_POWER, 0);
2656 // update level to hunter/summon pet
2657 if (Pet* pet = GetPet())
2658 pet->SynchronizeLevelWithOwner();
2661 void Player::SendInitialSpells()
2663 time_t curTime = time(NULL);
2664 time_t infTime = curTime + infinityCooldownDelayCheck;
2666 uint16 spellCount = 0;
2668 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2669 data << uint8(0);
2671 size_t countPos = data.wpos();
2672 data << uint16(spellCount); // spell count placeholder
2674 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2676 if(itr->second->state == PLAYERSPELL_REMOVED)
2677 continue;
2679 if(!itr->second->active || itr->second->disabled)
2680 continue;
2682 data << uint32(itr->first);
2683 data << uint16(0); // it's not slot id
2685 spellCount +=1;
2688 data.put<uint16>(countPos,spellCount); // write real count value
2690 uint16 spellCooldowns = m_spellCooldowns.size();
2691 data << uint16(spellCooldowns);
2692 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2694 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2695 if(!sEntry)
2696 continue;
2698 data << uint32(itr->first);
2700 data << uint16(itr->second.itemid); // cast item id
2701 data << uint16(sEntry->Category); // spell category
2703 // send infinity cooldown in special format
2704 if(itr->second.end >= infTime)
2706 data << uint32(1); // cooldown
2707 data << uint32(0x80000000); // category cooldown
2708 continue;
2711 time_t cooldown = itr->second.end > curTime ? (itr->second.end-curTime)*IN_MILISECONDS : 0;
2713 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2715 data << uint32(0); // cooldown
2716 data << uint32(cooldown); // category cooldown
2718 else
2720 data << uint32(cooldown); // cooldown
2721 data << uint32(0); // category cooldown
2725 GetSession()->SendPacket(&data);
2727 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2730 void Player::RemoveMail(uint32 id)
2732 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2734 if ((*itr)->messageID == id)
2736 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2737 m_mail.erase(itr);
2738 return;
2743 void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2745 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2746 data << (uint32) mailId;
2747 data << (uint32) mailAction;
2748 data << (uint32) mailError;
2749 if ( mailError == MAIL_ERR_EQUIP_ERROR )
2750 data << (uint32) equipError;
2751 else if( mailAction == MAIL_ITEM_TAKEN )
2753 data << (uint32) item_guid; // item guid low?
2754 data << (uint32) item_count; // item count?
2756 GetSession()->SendPacket(&data);
2759 void Player::SendNewMail()
2761 // deliver undelivered mail
2762 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2763 data << (uint32) 0;
2764 GetSession()->SendPacket(&data);
2767 void Player::UpdateNextMailTimeAndUnreads()
2769 // calculate next delivery time (min. from non-delivered mails
2770 // and recalculate unReadMail
2771 time_t cTime = time(NULL);
2772 m_nextMailDelivereTime = 0;
2773 unReadMails = 0;
2774 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2776 if((*itr)->deliver_time > cTime)
2778 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2779 m_nextMailDelivereTime = (*itr)->deliver_time;
2781 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2782 ++unReadMails;
2786 void Player::AddNewMailDeliverTime(time_t deliver_time)
2788 if(deliver_time <= time(NULL)) // ready now
2790 ++unReadMails;
2791 SendNewMail();
2793 else // not ready and no have ready mails
2795 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2796 m_nextMailDelivereTime = deliver_time;
2800 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2802 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2803 if (!spellInfo)
2805 // do character spell book cleanup (all characters)
2806 if(!IsInWorld() && !learning) // spell load case
2808 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2809 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2811 else
2812 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2814 return false;
2817 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2819 // do character spell book cleanup (all characters)
2820 if(!IsInWorld() && !learning) // spell load case
2822 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2823 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2825 else
2826 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2828 return false;
2831 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2833 bool dependent_set = false;
2834 bool disabled_case = false;
2835 bool superceded_old = false;
2837 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2838 if (itr != m_spells.end())
2840 uint32 next_active_spell_id = 0;
2841 // fix activate state for non-stackable low rank (and find next spell for !active case)
2842 if(!SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
2844 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
2845 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2847 if(HasSpell(next_itr->second))
2849 // high rank already known so this must !active
2850 active = false;
2851 next_active_spell_id = next_itr->second;
2852 break;
2857 // not do anything if already known in expected state
2858 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2859 itr->second->dependent == dependent && itr->second->disabled == disabled)
2861 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2862 itr->second->state = PLAYERSPELL_UNCHANGED;
2864 return false;
2867 // dependent spell known as not dependent, overwrite state
2868 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2870 itr->second->dependent = dependent;
2871 if (itr->second->state != PLAYERSPELL_NEW)
2872 itr->second->state = PLAYERSPELL_CHANGED;
2873 dependent_set = true;
2876 // update active state for known spell
2877 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2879 itr->second->active = active;
2881 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2882 itr->second->state = PLAYERSPELL_UNCHANGED;
2883 else if(itr->second->state != PLAYERSPELL_NEW)
2884 itr->second->state = PLAYERSPELL_CHANGED;
2886 if(active)
2888 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2889 CastSpell (this,spell_id,true);
2891 else if(IsInWorld())
2893 if(next_active_spell_id)
2895 // update spell ranks in spellbook and action bar
2896 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2897 data << uint32(spell_id);
2898 data << uint32(next_active_spell_id);
2899 GetSession()->SendPacket( &data );
2901 else
2903 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2904 data << uint32(spell_id);
2905 GetSession()->SendPacket(&data);
2909 return active; // learn (show in spell book if active now)
2912 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2914 if(itr->second->state != PLAYERSPELL_NEW)
2915 itr->second->state = PLAYERSPELL_CHANGED;
2916 itr->second->disabled = disabled;
2918 if(disabled)
2919 return false;
2921 disabled_case = true;
2923 else switch(itr->second->state)
2925 case PLAYERSPELL_UNCHANGED: // known saved spell
2926 return false;
2927 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2929 delete itr->second;
2930 m_spells.erase(itr);
2931 state = PLAYERSPELL_CHANGED;
2932 break; // need re-add
2934 default: // known not saved yet spell (new or modified)
2936 // can be in case spell loading but learned at some previous spell loading
2937 if(!IsInWorld() && !learning && !dependent_set)
2938 itr->second->state = PLAYERSPELL_UNCHANGED;
2940 return false;
2945 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2947 // talent: unlearn all other talent ranks (high and low)
2948 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2950 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2952 for(int i=0; i < MAX_TALENT_RANK; ++i)
2954 // skip learning spell and no rank spell case
2955 uint32 rankSpellId = talentInfo->RankID[i];
2956 if(!rankSpellId || rankSpellId==spell_id)
2957 continue;
2959 removeSpell(rankSpellId,false,false);
2963 // non talent spell: learn low ranks (recursive call)
2964 else if(uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id))
2966 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
2967 addSpell(prev_spell,active,true,true,disabled);
2968 else // at normal learning
2969 learnSpell(prev_spell,true);
2972 PlayerSpell *newspell = new PlayerSpell;
2973 newspell->state = state;
2974 newspell->active = active;
2975 newspell->dependent = dependent;
2976 newspell->disabled = disabled;
2978 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2979 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
2981 for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
2983 if(itr2->second->state == PLAYERSPELL_REMOVED) continue;
2984 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
2985 if(!i_spellInfo) continue;
2987 if( sSpellMgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
2989 if(itr2->second->active)
2991 if(sSpellMgr.IsHighRankOfSpell(spell_id,itr2->first))
2993 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2995 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2996 data << uint32(itr2->first);
2997 data << uint32(spell_id);
2998 GetSession()->SendPacket( &data );
3001 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
3002 itr2->second->active = false;
3003 if(itr2->second->state != PLAYERSPELL_NEW)
3004 itr2->second->state = PLAYERSPELL_CHANGED;
3005 superceded_old = true; // new spell replace old in action bars and spell book.
3007 else if(sSpellMgr.IsHighRankOfSpell(itr2->first,spell_id))
3009 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
3011 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3012 data << uint32(spell_id);
3013 data << uint32(itr2->first);
3014 GetSession()->SendPacket( &data );
3017 // mark new spell as disable (not learned yet for client and will not learned)
3018 newspell->active = false;
3019 if(newspell->state != PLAYERSPELL_NEW)
3020 newspell->state = PLAYERSPELL_CHANGED;
3027 m_spells[spell_id] = newspell;
3029 // return false if spell disabled
3030 if (newspell->disabled)
3031 return false;
3034 uint32 talentCost = GetTalentSpellCost(spell_id);
3036 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
3037 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
3038 if (talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL))
3040 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
3041 CastSpell(this, spell_id, true);
3043 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
3044 else if (IsPassiveSpell(spell_id))
3046 if (IsNeedCastPassiveSpellAtLearn(spellInfo))
3047 CastSpell(this, spell_id, true);
3049 else if (IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP))
3051 CastSpell(this, spell_id, true);
3052 return false;
3055 // update used talent points count
3056 m_usedTalentCount += talentCost;
3058 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
3059 if (uint32 freeProfs = GetFreePrimaryProfessionPoints())
3061 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3062 SetFreePrimaryProfessions(freeProfs-1);
3065 // add dependent skills
3066 uint16 maxskill = GetMaxSkillValueForLevel();
3068 SpellLearnSkillNode const* spellLearnSkill = sSpellMgr.GetSpellLearnSkill(spell_id);
3070 SkillLineAbilityMapBounds skill_bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
3072 if (spellLearnSkill)
3074 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
3075 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
3077 if (skill_value < spellLearnSkill->value)
3078 skill_value = spellLearnSkill->value;
3080 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
3082 if (skill_max_value < new_skill_max_value)
3083 skill_max_value = new_skill_max_value;
3085 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
3087 else
3089 // not ranked skills
3090 for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
3092 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3093 if (!pSkill)
3094 continue;
3096 if (HasSkill(pSkill->id))
3097 continue;
3099 if (_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3100 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3101 ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
3103 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
3105 case SKILL_RANGE_LANGUAGE:
3106 SetSkill(pSkill->id, 300, 300 );
3107 break;
3108 case SKILL_RANGE_LEVEL:
3109 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
3110 break;
3111 case SKILL_RANGE_MONO:
3112 SetSkill(pSkill->id, 1, 1 );
3113 break;
3114 default:
3115 break;
3121 // learn dependent spells
3122 SpellLearnSpellMapBounds spell_bounds = sSpellMgr.GetSpellLearnSpellMapBounds(spell_id);
3124 for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
3126 if (!itr2->second.autoLearned)
3128 if (!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
3129 addSpell(itr2->second.spell,itr2->second.active,true,true,false);
3130 else // at normal learning
3131 learnSpell(itr2->second.spell,true);
3135 if (!GetSession()->PlayerLoading())
3137 // not ranked skills
3138 for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
3140 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
3141 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
3144 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
3147 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
3148 return active && !disabled && !superceded_old;
3151 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
3153 // note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell
3154 // talent dependent passives activated at form apply have proper stance data
3155 bool need_cast = (!spellInfo->Stances || (m_form != 0 && (spellInfo->Stances & (1<<(m_form-1)))));
3157 //Check CasterAuraStates
3158 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
3161 void Player::learnSpell(uint32 spell_id, bool dependent)
3163 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3165 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
3166 bool active = disabled ? itr->second->active : true;
3168 bool learning = addSpell(spell_id,active,true,dependent,false);
3170 // learn all disabled higher ranks (recursive)
3171 if(disabled)
3173 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
3174 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
3176 PlayerSpellMap::iterator iter = m_spells.find(i->second);
3177 if (iter != m_spells.end() && iter->second->disabled)
3178 learnSpell(i->second,false);
3182 // prevent duplicated entires in spell book, also not send if not in world (loading)
3183 if(!learning || !IsInWorld ())
3184 return;
3186 WorldPacket data(SMSG_LEARNED_SPELL, 4);
3187 data << uint32(spell_id);
3188 GetSession()->SendPacket(&data);
3191 void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bool sendUpdate)
3193 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3194 if (itr == m_spells.end())
3195 return;
3197 if (itr->second->state == PLAYERSPELL_REMOVED || (disabled && itr->second->disabled))
3198 return;
3200 // unlearn non talent higher ranks (recursive)
3201 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
3202 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
3203 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
3204 removeSpell(itr2->second,disabled,false);
3206 // re-search, it can be corrupted in prev loop
3207 itr = m_spells.find(spell_id);
3208 if (itr == m_spells.end())
3209 return; // already unleared
3211 bool cur_active = itr->second->active;
3212 bool cur_dependent = itr->second->dependent;
3214 if (disabled)
3216 itr->second->disabled = disabled;
3217 if(itr->second->state != PLAYERSPELL_NEW)
3218 itr->second->state = PLAYERSPELL_CHANGED;
3220 else
3222 if(itr->second->state == PLAYERSPELL_NEW)
3224 delete itr->second;
3225 m_spells.erase(itr);
3227 else
3228 itr->second->state = PLAYERSPELL_REMOVED;
3231 RemoveAurasDueToSpell(spell_id);
3233 // remove pet auras
3234 for(int i = 0; i < 3; ++i)
3235 if(PetAura const* petSpell = sSpellMgr.GetPetAura(spell_id, i))
3236 RemovePetAura(petSpell);
3238 // free talent points
3239 uint32 talentCosts = GetTalentSpellCost(spell_id);
3240 if(talentCosts > 0)
3242 if(talentCosts < m_usedTalentCount)
3243 m_usedTalentCount -= talentCosts;
3244 else
3245 m_usedTalentCount = 0;
3248 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3249 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3251 uint32 freeProfs = GetFreePrimaryProfessionPoints()+1;
3252 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
3253 SetFreePrimaryProfessions(freeProfs);
3256 // remove dependent skill
3257 SpellLearnSkillNode const* spellLearnSkill = sSpellMgr.GetSpellLearnSkill(spell_id);
3258 if(spellLearnSkill)
3260 uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id);
3261 if(!prev_spell) // first rank, remove skill
3262 SetSkill(spellLearnSkill->skill,0,0);
3263 else
3265 // search prev. skill setting by spell ranks chain
3266 SpellLearnSkillNode const* prevSkill = sSpellMgr.GetSpellLearnSkill(prev_spell);
3267 while(!prevSkill && prev_spell)
3269 prev_spell = sSpellMgr.GetPrevSpellInChain(prev_spell);
3270 prevSkill = sSpellMgr.GetSpellLearnSkill(sSpellMgr.GetFirstSpellInChain(prev_spell));
3273 if (!prevSkill) // not found prev skill setting, remove skill
3274 SetSkill(spellLearnSkill->skill,0,0);
3275 else // set to prev. skill setting values
3277 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3278 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3280 if (skill_value > prevSkill->value)
3281 skill_value = prevSkill->value;
3283 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3285 if (skill_max_value > new_skill_max_value)
3286 skill_max_value = new_skill_max_value;
3288 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3293 else
3295 // not ranked skills
3296 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
3298 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
3300 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3301 if (!pSkill)
3302 continue;
3304 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL &&
3305 pSkill->categoryId != SKILL_CATEGORY_CLASS ||// not unlearn class skills (spellbook/talent pages)
3306 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3307 ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
3309 // not reset skills for professions and racial abilities
3310 if ((pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3311 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0))
3312 continue;
3314 SetSkill(pSkill->id, 0, 0 );
3319 // remove dependent spells
3320 SpellLearnSpellMapBounds spell_bounds = sSpellMgr.GetSpellLearnSpellMapBounds(spell_id);
3322 for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
3323 removeSpell(itr2->second.spell, disabled);
3325 // activate lesser rank in spellbook/action bar, and cast it if need
3326 bool prev_activate = false;
3328 if (uint32 prev_id = sSpellMgr.GetPrevSpellInChain (spell_id))
3330 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3332 // if talent then lesser rank also talent and need learn
3333 if (talentCosts)
3335 if(learn_low_rank)
3336 learnSpell (prev_id,false);
3338 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3339 else if (cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
3341 // need manually update dependence state (learn spell ignore like attempts)
3342 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3343 if (prev_itr != m_spells.end())
3345 if (prev_itr->second->dependent != cur_dependent)
3347 prev_itr->second->dependent = cur_dependent;
3348 if (prev_itr->second->state != PLAYERSPELL_NEW)
3349 prev_itr->second->state = PLAYERSPELL_CHANGED;
3352 // now re-learn if need re-activate
3353 if (cur_active && !prev_itr->second->active && learn_low_rank)
3355 if (addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3357 // downgrade spell ranks in spellbook and action bar
3358 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3359 data << uint32(spell_id);
3360 data << uint32(prev_id);
3361 GetSession()->SendPacket( &data );
3362 prev_activate = true;
3369 // remove from spell book if not replaced by lesser rank
3370 if (!prev_activate && sendUpdate)
3372 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3373 data << uint32(spell_id);
3374 GetSession()->SendPacket(&data);
3378 void Player::RemoveSpellCooldown( uint32 spell_id, bool update /* = false */ )
3380 m_spellCooldowns.erase(spell_id);
3382 if(update)
3383 SendClearCooldown(spell_id, this);
3386 void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */)
3388 SpellCategoryStore::const_iterator ct = sSpellCategoryStore.find(cat);
3389 if (ct == sSpellCategoryStore.end())
3390 return;
3392 const SpellCategorySet& ct_set = ct->second;
3393 for (SpellCooldowns::const_iterator i = m_spellCooldowns.begin(); i != m_spellCooldowns.end();)
3395 if (ct_set.find(i->first) != ct_set.end())
3396 RemoveSpellCooldown((i++)->first, update);
3397 else
3398 ++i;
3402 void Player::RemoveArenaSpellCooldowns()
3404 // remove cooldowns on spells that has < 15 min CD
3405 SpellCooldowns::iterator itr, next;
3406 // iterate spell cooldowns
3407 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3409 next = itr;
3410 ++next;
3411 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3412 // check if spellentry is present and if the cooldown is less than 15 mins
3413 if( entry &&
3414 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3415 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3417 // remove & notify
3418 RemoveSpellCooldown(itr->first, true);
3423 void Player::RemoveAllSpellCooldown()
3425 if(!m_spellCooldowns.empty())
3427 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3428 SendClearCooldown(itr->first, this);
3430 m_spellCooldowns.clear();
3434 void Player::_LoadSpellCooldowns(QueryResult *result)
3436 // some cooldowns can be already set at aura loading...
3438 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3440 if(result)
3442 time_t curTime = time(NULL);
3446 Field *fields = result->Fetch();
3448 uint32 spell_id = fields[0].GetUInt32();
3449 uint32 item_id = fields[1].GetUInt32();
3450 time_t db_time = (time_t)fields[2].GetUInt64();
3452 if(!sSpellStore.LookupEntry(spell_id))
3454 sLog.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3455 continue;
3458 // skip outdated cooldown
3459 if(db_time <= curTime)
3460 continue;
3462 AddSpellCooldown(spell_id, item_id, db_time);
3464 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3466 while( result->NextRow() );
3468 delete result;
3472 void Player::_SaveSpellCooldowns()
3474 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3476 time_t curTime = time(NULL);
3477 time_t infTime = curTime + infinityCooldownDelayCheck;
3479 /* copied following sql-code partly from achievementmgr */
3480 bool first_round = true;
3481 std::ostringstream ss;
3483 // remove outdated and save active
3484 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3486 if(itr->second.end <= curTime)
3487 m_spellCooldowns.erase(itr++);
3488 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3490 if (first_round)
3492 ss << "INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ";
3493 first_round = false;
3495 // next new/changed record prefix
3496 else
3497 ss << ", ";
3498 ss << "(" << GetGUIDLow() << "," << itr->first << "," << itr->second.itemid << "," << uint64(itr->second.end) << ")";
3499 ++itr;
3501 else
3502 ++itr;
3505 // if something changed execute
3506 if (!first_round)
3507 CharacterDatabase.Execute( ss.str().c_str() );
3510 uint32 Player::resetTalentsCost() const
3512 // The first time reset costs 1 gold
3513 if(m_resetTalentsCost < 1*GOLD)
3514 return 1*GOLD;
3515 // then 5 gold
3516 else if(m_resetTalentsCost < 5*GOLD)
3517 return 5*GOLD;
3518 // After that it increases in increments of 5 gold
3519 else if(m_resetTalentsCost < 10*GOLD)
3520 return 10*GOLD;
3521 else
3523 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3524 if(months > 0)
3526 // This cost will be reduced by a rate of 5 gold per month
3527 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3528 // to a minimum of 10 gold.
3529 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3531 else
3533 // After that it increases in increments of 5 gold
3534 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3535 // until it hits a cap of 50 gold.
3536 if(new_cost > 50*GOLD)
3537 new_cost = 50*GOLD;
3538 return new_cost;
3543 bool Player::resetTalents(bool no_cost)
3545 // not need after this call
3546 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3547 RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS,true);
3549 uint32 talentPointsForLevel = CalculateTalentsPoints();
3551 if (m_usedTalentCount == 0)
3553 SetFreeTalentPoints(talentPointsForLevel);
3554 return false;
3557 uint32 cost = 0;
3559 if(!no_cost)
3561 cost = resetTalentsCost();
3563 if (GetMoney() < cost)
3565 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3566 return false;
3570 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
3572 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3574 if (!talentInfo) continue;
3576 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3578 if(!talentTabInfo)
3579 continue;
3581 // unlearn only talents for character class
3582 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3583 // to prevent unexpected lost normal learned spell skip another class talents
3584 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3585 continue;
3587 for (int j = 0; j < MAX_TALENT_RANK; ++j)
3589 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3591 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3593 ++itr;
3594 continue;
3597 // remove learned spells (all ranks)
3598 uint32 itrFirstId = sSpellMgr.GetFirstSpellInChain(itr->first);
3600 // unlearn if first rank is talent or learned by talent
3601 if (itrFirstId == talentInfo->RankID[j])
3603 removeSpell(itr->first,!IsPassiveSpell(itr->first),false);
3604 itr = GetSpellMap().begin();
3605 continue;
3607 else if (sSpellMgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3609 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3610 itr = GetSpellMap().begin();
3611 continue;
3613 else
3614 ++itr;
3619 SetFreeTalentPoints(talentPointsForLevel);
3621 if(!no_cost)
3623 ModifyMoney(-(int32)cost);
3624 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3625 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
3627 m_resetTalentsCost = cost;
3628 m_resetTalentsTime = time(NULL);
3631 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3632 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3633 /* when prev line will dropped use next line
3634 if(Pet* pet = GetPet())
3636 if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
3637 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3642 if(m_canTitanGrip)
3644 m_canTitanGrip = false;
3645 if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET))
3646 AutoUnequipOffhandIfNeed();
3649 return true;
3652 Mail* Player::GetMail(uint32 id)
3654 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3656 if ((*itr)->messageID == id)
3658 return (*itr);
3661 return NULL;
3664 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3666 if(target == this)
3668 Object::_SetCreateBits(updateMask, target);
3670 else
3672 for(uint16 index = 0; index < m_valuesCount; index++)
3674 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3675 updateMask->SetBit(index);
3680 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3682 if(target == this)
3684 Object::_SetUpdateBits(updateMask, target);
3686 else
3688 Object::_SetUpdateBits(updateMask, target);
3689 *updateMask &= updateVisualBits;
3693 void Player::InitVisibleBits()
3695 updateVisualBits.SetCount(PLAYER_END);
3697 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3698 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3699 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3700 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3701 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3702 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3703 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3704 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3705 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3706 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3707 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3708 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3709 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3710 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3711 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3712 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3713 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3714 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3715 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3716 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3717 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3718 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3719 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3720 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3721 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3722 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3723 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3724 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3725 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3726 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3727 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3728 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3729 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3730 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3731 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3732 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3733 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3734 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3735 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3736 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3737 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3738 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3739 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3740 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3741 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3742 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3743 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3744 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3745 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3746 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3747 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3748 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3749 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3750 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3751 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3753 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3754 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3755 updateVisualBits.SetBit(PLAYER_FLAGS);
3756 updateVisualBits.SetBit(PLAYER_GUILDID);
3757 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3758 updateVisualBits.SetBit(PLAYER_BYTES);
3759 updateVisualBits.SetBit(PLAYER_BYTES_2);
3760 updateVisualBits.SetBit(PLAYER_BYTES_3);
3761 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3762 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3764 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3765 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3766 updateVisualBits.SetBit(i);
3768 // Players visible items are not inventory stuff
3769 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3771 uint32 offset = i * 2;
3773 // item entry
3774 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset);
3775 // enchant
3776 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset);
3779 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3782 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3784 for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
3786 if(m_items[i] == NULL)
3787 continue;
3789 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3792 if(target == this)
3794 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3796 if(m_items[i] == NULL)
3797 continue;
3799 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3801 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3803 if(m_items[i] == NULL)
3804 continue;
3806 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3810 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3813 void Player::DestroyForPlayer( Player *target, bool anim ) const
3815 Unit::DestroyForPlayer( target, anim );
3817 for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
3819 if(m_items[i] == NULL)
3820 continue;
3822 m_items[i]->DestroyForPlayer( target );
3825 if(target == this)
3827 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3829 if(m_items[i] == NULL)
3830 continue;
3832 m_items[i]->DestroyForPlayer( target );
3834 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3836 if(m_items[i] == NULL)
3837 continue;
3839 m_items[i]->DestroyForPlayer( target );
3844 bool Player::HasSpell(uint32 spell) const
3846 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3847 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3848 !itr->second->disabled);
3851 bool Player::HasActiveSpell(uint32 spell) const
3853 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3854 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3855 itr->second->active && !itr->second->disabled);
3858 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3860 if (!trainer_spell)
3861 return TRAINER_SPELL_RED;
3863 if (!trainer_spell->learnedSpell)
3864 return TRAINER_SPELL_RED;
3866 // known spell
3867 if(HasSpell(trainer_spell->learnedSpell))
3868 return TRAINER_SPELL_GRAY;
3870 // check race/class requirement
3871 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3872 return TRAINER_SPELL_RED;
3874 // check level requirement
3875 if(getLevel() < trainer_spell->reqLevel)
3876 return TRAINER_SPELL_RED;
3878 if(SpellChainNode const* spell_chain = sSpellMgr.GetSpellChainNode(trainer_spell->learnedSpell))
3880 // check prev.rank requirement
3881 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3882 return TRAINER_SPELL_RED;
3884 // check additional spell requirement
3885 if(spell_chain->req && !HasSpell(spell_chain->req))
3886 return TRAINER_SPELL_RED;
3889 // check skill requirement
3890 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3891 return TRAINER_SPELL_RED;
3893 // exist, already checked at loading
3894 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3896 // secondary prof. or not prof. spell
3897 uint32 skill = spell->EffectMiscValue[1];
3899 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3900 return TRAINER_SPELL_GREEN;
3902 // check primary prof. limit
3903 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProfessionPoints() == 0)
3904 return TRAINER_SPELL_GREEN_DISABLED;
3906 return TRAINER_SPELL_GREEN;
3909 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3911 uint32 guid = GUID_LOPART(playerguid);
3913 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3914 // bones will be deleted by corpse/bones deleting thread shortly
3915 sObjectAccessor.ConvertCorpseForPlayer(playerguid);
3917 // remove from guild
3918 uint32 guildId = GetGuildIdFromDB(playerguid);
3919 if(guildId != 0)
3921 Guild* guild = sObjectMgr.GetGuildById(guildId);
3922 if(guild)
3923 guild->DelMember(guid);
3926 // remove from arena teams
3927 LeaveAllArenaTeams(playerguid);
3929 // the player was uninvited already on logout so just remove from group
3930 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3931 if(resultGroup)
3933 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3934 delete resultGroup;
3935 Group* group = sObjectMgr.GetGroupByLeader(leaderGuid);
3936 if(group)
3938 RemoveFromGroup(group, playerguid);
3942 // remove signs from petitions (also remove petitions if owner);
3943 RemovePetitionsAndSigns(playerguid, 10);
3945 // return back all mails with COD and Item 0 1 2 3 4 5 6 7
3946 QueryResult *resultMail = CharacterDatabase.PQuery("SELECT id,messageType,mailTemplateId,sender,subject,itemTextId,money,has_items FROM mail WHERE receiver='%u' AND has_items<>0 AND cod<>0", guid);
3947 if(resultMail)
3951 Field *fields = resultMail->Fetch();
3953 uint32 mail_id = fields[0].GetUInt32();
3954 uint16 mailType = fields[1].GetUInt16();
3955 uint16 mailTemplateId= fields[2].GetUInt16();
3956 uint32 sender = fields[3].GetUInt32();
3957 std::string subject = fields[4].GetCppString();
3958 uint32 itemTextId = fields[5].GetUInt32();
3959 uint32 money = fields[6].GetUInt32();
3960 bool has_items = fields[7].GetBool();
3962 //we can return mail now
3963 //so firstly delete the old one
3964 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3966 // mail not from player
3967 if (mailType != MAIL_NORMAL)
3969 if(has_items)
3970 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3971 continue;
3974 MailDraft draft(subject, itemTextId);
3975 if (mailTemplateId)
3976 draft = MailDraft(mailTemplateId,false); // itesm already included
3978 if(has_items)
3980 // data needs to be at first place for Item::LoadFromDB
3981 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);
3982 if(resultItems)
3986 Field *fields2 = resultItems->Fetch();
3988 uint32 item_guidlow = fields2[1].GetUInt32();
3989 uint32 item_template = fields2[2].GetUInt32();
3991 ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(item_template);
3992 if(!itemProto)
3994 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3995 continue;
3998 Item *pItem = NewItemOrBag(itemProto);
3999 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
4001 pItem->FSetState(ITEM_REMOVED);
4002 pItem->SaveToDB(); // it also deletes item object !
4003 continue;
4006 draft.AddItem(pItem);
4008 while (resultItems->NextRow());
4010 delete resultItems;
4014 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
4016 uint32 pl_account = sObjectMgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
4018 draft.AddMoney(money).SendReturnToSender(pl_account, guid, sender);
4020 while (resultMail->NextRow());
4022 delete resultMail;
4025 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
4026 // Get guids of character's pets, will deleted in transaction
4027 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
4029 // NOW we can finally clear other DB data related to character
4030 CharacterDatabase.BeginTransaction();
4031 if (resultPets)
4035 Field *fields3 = resultPets->Fetch();
4036 uint32 petguidlow = fields3[0].GetUInt32();
4037 Pet::DeleteFromDB(petguidlow);
4038 } while (resultPets->NextRow());
4039 delete resultPets;
4042 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
4043 CharacterDatabase.PExecute("DELETE FROM character_account_data WHERE guid = '%u'",guid);
4044 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
4045 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
4046 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
4047 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
4048 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
4049 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
4050 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
4051 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
4052 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
4053 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
4054 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u'",guid);
4055 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
4056 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
4057 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
4058 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
4059 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
4060 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
4061 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
4062 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
4063 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
4064 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
4065 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
4066 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid);
4067 CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid1 = '%u'",guid);
4068 CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid2 = '%u'",guid);
4069 CharacterDatabase.PExecute("DELETE FROM guild_bank_eventlog WHERE PlayerGuid = '%u'",guid);
4070 CharacterDatabase.CommitTransaction();
4072 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
4073 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
4076 void Player::SetMovement(PlayerMovementType pType)
4078 WorldPacket data;
4079 switch(pType)
4081 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
4082 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
4083 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
4084 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
4085 default:
4086 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
4087 return;
4089 data.append(GetPackGUID());
4090 data << uint32(0);
4091 GetSession()->SendPacket( &data );
4094 /* Preconditions:
4095 - a resurrectable corpse must not be loaded for the player (only bones)
4096 - the player must be in world
4098 void Player::BuildPlayerRepop()
4100 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
4101 data.append(GetPackGUID());
4102 GetSession()->SendPacket(&data);
4104 if(getRace() == RACE_NIGHTELF)
4105 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)
4106 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
4108 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
4109 // there must be SMSG.STOP_MIRROR_TIMER
4110 // there we must send 888 opcode
4112 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
4113 if(GetCorpse())
4115 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
4116 assert(false);
4119 // create a corpse and place it at the player's location
4120 CreateCorpse();
4121 Corpse *corpse = GetCorpse();
4122 if(!corpse)
4124 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
4125 return;
4127 GetMap()->Add(corpse);
4129 // convert player body to ghost
4130 SetHealth( 1 );
4132 SetMovement(MOVE_WATER_WALK);
4133 if(!GetSession()->isLogingOut())
4134 SetMovement(MOVE_UNROOT);
4136 // BG - remove insignia related
4137 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
4139 SendCorpseReclaimDelay();
4141 // to prevent cheating
4142 corpse->ResetGhostTime();
4144 StopMirrorTimers(); //disable timers(bars)
4146 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
4148 // set and clear other
4149 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
4152 void Player::SendDelayResponse(const uint32 ml_seconds)
4154 //FIXME: is this delay time arg really need? 50msec by default in code
4155 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
4156 data << (uint32)time(NULL);
4157 data << (uint32)0;
4158 GetSession()->SendPacket( &data );
4161 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
4163 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
4164 data << uint32(-1);
4165 data << float(0);
4166 data << float(0);
4167 data << float(0);
4168 GetSession()->SendPacket(&data);
4170 // speed change, land walk
4172 // remove death flag + set aura
4173 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
4174 if(getRace() == RACE_NIGHTELF)
4175 RemoveAurasDueToSpell(20584); // speed bonuses
4176 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
4178 setDeathState(ALIVE);
4180 SetMovement(MOVE_LAND_WALK);
4181 SetMovement(MOVE_UNROOT);
4183 m_deathTimer = 0;
4185 // set health/powers (0- will be set in caller)
4186 if(restore_percent>0.0f)
4188 SetHealth(uint32(GetMaxHealth()*restore_percent));
4189 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
4190 SetPower(POWER_RAGE, 0);
4191 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
4194 // trigger update zone for alive state zone updates
4195 uint32 newzone, newarea;
4196 GetZoneAndAreaId(newzone,newarea);
4197 UpdateZone(newzone,newarea);
4199 // update visibility
4200 UpdateVisibilityForPlayer();
4202 if(!applySickness)
4203 return;
4205 //Characters from level 1-10 are not affected by resurrection sickness.
4206 //Characters from level 11-19 will suffer from one minute of sickness
4207 //for each level they are above 10.
4208 //Characters level 20 and up suffer from ten minutes of sickness.
4209 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
4211 if(int32(getLevel()) >= startLevel)
4213 // set resurrection sickness
4214 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
4216 // not full duration
4217 if(int32(getLevel()) < startLevel+9)
4219 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
4221 for(int i =0; i < 3; ++i)
4223 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
4225 Aur->SetAuraDuration(delta*IN_MILISECONDS);
4226 Aur->SendAuraUpdate(false);
4233 void Player::KillPlayer()
4235 SetMovement(MOVE_ROOT);
4237 StopMirrorTimers(); //disable timers(bars)
4239 setDeathState(CORPSE);
4240 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4242 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
4243 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
4245 // 6 minutes until repop at graveyard
4246 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
4248 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4250 // don't create corpse at this moment, player might be falling
4252 // update visibility
4253 UpdateObjectVisibility();
4256 void Player::CreateCorpse()
4258 // prevent existence 2 corpse for player
4259 SpawnCorpseBones();
4261 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
4263 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
4264 SetPvPDeath(false);
4266 if(!corpse->Create(sObjectMgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
4268 delete corpse;
4269 return;
4272 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
4273 _pb = GetUInt32Value(PLAYER_BYTES);
4274 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
4276 uint8 race = (uint8)(_uf);
4277 uint8 skin = (uint8)(_pb);
4278 uint8 face = (uint8)(_pb >> 8);
4279 uint8 hairstyle = (uint8)(_pb >> 16);
4280 uint8 haircolor = (uint8)(_pb >> 24);
4281 uint8 facialhair = (uint8)(_pb2);
4283 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
4284 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
4286 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
4287 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
4289 uint32 flags = CORPSE_FLAG_UNK2;
4290 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
4291 flags |= CORPSE_FLAG_HIDE_HELM;
4292 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
4293 flags |= CORPSE_FLAG_HIDE_CLOAK;
4294 if(InBattleGround() && !InArena())
4295 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
4296 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4298 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4300 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4302 uint32 iDisplayID;
4303 uint32 iIventoryType;
4304 uint32 _cfi;
4305 for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
4307 if(m_items[i])
4309 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4310 iIventoryType = m_items[i]->GetProto()->InventoryType;
4312 _cfi = iDisplayID | (iIventoryType << 24);
4313 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i, _cfi);
4317 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4318 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4319 assert(entry);
4320 if(entry->map_type != MAP_BATTLEGROUND)
4321 corpse->SaveToDB();
4323 // register for player, but not show
4324 sObjectAccessor.AddCorpse(corpse);
4327 void Player::SpawnCorpseBones()
4329 if(sObjectAccessor.ConvertCorpseForPlayer(GetGUID()))
4330 if (!GetSession()->PlayerLogoutWithSave()) // at logout we will already store the player
4331 SaveToDB(); // prevent loading as ghost without corpse
4334 Corpse* Player::GetCorpse() const
4336 return sObjectAccessor.GetCorpseForPlayerGUID(GetGUID());
4339 void Player::DurabilityLossAll(double percent, bool inventory)
4341 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4342 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4343 DurabilityLoss(pItem,percent);
4345 if(inventory)
4347 // bags not have durability
4348 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4350 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4351 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4352 DurabilityLoss(pItem,percent);
4354 // keys not have durability
4355 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4357 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4358 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4359 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4360 if(Item* pItem = GetItemByPos( i, j ))
4361 DurabilityLoss(pItem,percent);
4365 void Player::DurabilityLoss(Item* item, double percent)
4367 if(!item )
4368 return;
4370 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4372 if(!pMaxDurability)
4373 return;
4375 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4377 if(pDurabilityLoss < 1 )
4378 pDurabilityLoss = 1;
4380 DurabilityPointsLoss(item,pDurabilityLoss);
4383 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4385 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4386 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4387 DurabilityPointsLoss(pItem,points);
4389 if(inventory)
4391 // bags not have durability
4392 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4394 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4395 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4396 DurabilityPointsLoss(pItem,points);
4398 // keys not have durability
4399 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4401 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4402 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4403 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4404 if(Item* pItem = GetItemByPos( i, j ))
4405 DurabilityPointsLoss(pItem,points);
4409 void Player::DurabilityPointsLoss(Item* item, int32 points)
4411 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4412 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4413 int32 pNewDurability = pOldDurability - points;
4415 if (pNewDurability < 0)
4416 pNewDurability = 0;
4417 else if (pNewDurability > pMaxDurability)
4418 pNewDurability = pMaxDurability;
4420 if (pOldDurability != pNewDurability)
4422 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4423 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4424 _ApplyItemMods(item,item->GetSlot(), false);
4426 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4428 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4429 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4430 _ApplyItemMods(item,item->GetSlot(), true);
4432 item->SetState(ITEM_CHANGED, this);
4436 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4438 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4439 DurabilityPointsLoss(pItem,1);
4442 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4444 uint32 TotalCost = 0;
4445 // equipped, backpack, bags itself
4446 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4447 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4449 // bank, buyback and keys not repaired
4451 // items in inventory bags
4452 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
4453 for(int i = 0; i < MAX_BAG_SIZE; ++i)
4454 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4455 return TotalCost;
4458 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4460 Item* item = GetItemByPos(pos);
4462 uint32 TotalCost = 0;
4463 if(!item)
4464 return TotalCost;
4466 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4467 if(!maxDurability)
4468 return TotalCost;
4470 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4472 if(cost)
4474 uint32 LostDurability = maxDurability - curDurability;
4475 if(LostDurability>0)
4477 ItemPrototype const *ditemProto = item->GetProto();
4479 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4480 if(!dcost)
4482 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4483 return TotalCost;
4486 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4487 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4488 if(!dQualitymodEntry)
4490 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4491 return TotalCost;
4494 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4495 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4497 costs = uint32(costs * discountMod);
4499 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4500 costs = 1;
4502 if (guildBank)
4504 if (GetGuildId()==0)
4506 DEBUG_LOG("You are not member of a guild");
4507 return TotalCost;
4510 Guild *pGuild = sObjectMgr.GetGuildById(GetGuildId());
4511 if (!pGuild)
4512 return TotalCost;
4514 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4516 DEBUG_LOG("You do not have rights to withdraw for repairs");
4517 return TotalCost;
4520 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4522 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4523 return TotalCost;
4526 if (pGuild->GetGuildBankMoney() < costs)
4528 DEBUG_LOG("There is not enough money in bank");
4529 return TotalCost;
4532 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4533 TotalCost = costs;
4535 else if (GetMoney() < costs)
4537 DEBUG_LOG("You do not have enough money");
4538 return TotalCost;
4540 else
4541 ModifyMoney( -int32(costs) );
4545 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4546 item->SetState(ITEM_CHANGED, this);
4548 // reapply mods for total broken and repaired item if equipped
4549 if(IsEquipmentPos(pos) && !curDurability)
4550 _ApplyItemMods(item,pos & 255, true);
4551 return TotalCost;
4554 void Player::RepopAtGraveyard()
4556 // note: this can be called also when the player is alive
4557 // for example from WorldSession::HandleMovementOpcodes
4559 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4561 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4562 if ((!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY) || GetTransport())
4564 ResurrectPlayer(0.5f);
4565 SpawnCorpseBones();
4568 WorldSafeLocsEntry const *ClosestGrave = NULL;
4570 // Special handle for battleground maps
4571 if( BattleGround *bg = GetBattleGround() )
4572 ClosestGrave = bg->GetClosestGraveYard(this);
4573 else
4574 ClosestGrave = sObjectMgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4576 // stop countdown until repop
4577 m_deathTimer = 0;
4579 // if no grave found, stay at the current location
4580 // and don't show spirit healer location
4581 if(ClosestGrave)
4583 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4584 if(isDead()) // not send if alive, because it used in TeleportTo()
4586 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4587 data << ClosestGrave->map_id;
4588 data << ClosestGrave->x;
4589 data << ClosestGrave->y;
4590 data << ClosestGrave->z;
4591 GetSession()->SendPacket(&data);
4596 void Player::JoinedChannel(Channel *c)
4598 m_channels.push_back(c);
4601 void Player::LeftChannel(Channel *c)
4603 m_channels.remove(c);
4606 void Player::CleanupChannels()
4608 while(!m_channels.empty())
4610 Channel* ch = *m_channels.begin();
4611 m_channels.erase(m_channels.begin()); // remove from player's channel list
4612 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4613 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4614 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4617 sLog.outDebug("Player: channels cleaned up!");
4620 void Player::UpdateLocalChannels(uint32 newZone )
4622 if(m_channels.empty())
4623 return;
4625 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4626 if(!current_zone)
4627 return;
4629 ChannelMgr* cMgr = channelMgr(GetTeam());
4630 if(!cMgr)
4631 return;
4633 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4635 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4637 next = i; ++next;
4639 // skip non built-in channels
4640 if(!(*i)->IsConstant())
4641 continue;
4643 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4644 if(!ch)
4645 continue;
4647 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4648 continue;
4650 // new channel
4651 char new_channel_name_buf[100];
4652 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4653 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4655 if((*i)!=new_channel)
4657 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4659 // leave old channel
4660 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4661 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4662 LeftChannel(*i); // remove from player's channel list
4663 cMgr->LeftChannel(name); // delete if empty
4666 sLog.outDebug("Player: channels cleaned up!");
4669 void Player::LeaveLFGChannel()
4671 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4673 if((*i)->IsLFG())
4675 (*i)->Leave(GetGUID());
4676 break;
4681 void Player::UpdateDefense()
4683 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4685 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4687 // update dependent from defense skill part
4688 UpdateDefenseBonusesMod();
4692 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4694 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4696 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4697 return;
4700 float val = 1.0f;
4702 switch(modType)
4704 case FLAT_MOD:
4705 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4706 break;
4707 case PCT_MOD:
4708 if(amount <= -100.0f)
4709 amount = -200.0f;
4711 val = (100.0f + amount) / 100.0f;
4712 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4713 break;
4716 if(!CanModifyStats())
4717 return;
4719 switch(modGroup)
4721 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4722 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4723 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4724 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4725 default: break;
4729 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4731 if(modGroup >= BASEMOD_END || modType > MOD_END)
4733 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4734 return 0.0f;
4737 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4738 return 0.0f;
4740 return m_auraBaseMod[modGroup][modType];
4743 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4745 if(modGroup >= BASEMOD_END)
4747 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4748 return 0.0f;
4751 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4752 return 0.0f;
4754 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4757 uint32 Player::GetShieldBlockValue() const
4759 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4761 value = (value < 0) ? 0 : value;
4763 return uint32(value);
4766 float Player::GetMeleeCritFromAgility()
4768 uint32 level = getLevel();
4769 uint32 pclass = getClass();
4771 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4773 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4774 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4775 if (critBase==NULL || critRatio==NULL)
4776 return 0.0f;
4778 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4779 return crit*100.0f;
4782 float Player::GetDodgeFromAgility()
4784 // Table for base dodge values
4785 float dodge_base[MAX_CLASSES] = {
4786 0.0075f, // Warrior
4787 0.00652f, // Paladin
4788 -0.0545f, // Hunter
4789 -0.0059f, // Rogue
4790 0.03183f, // Priest
4791 0.0114f, // DK
4792 0.0167f, // Shaman
4793 0.034575f, // Mage
4794 0.02011f, // Warlock
4795 0.0f, // ??
4796 -0.0187f // Druid
4798 // Crit/agility to dodge/agility coefficient multipliers
4799 float crit_to_dodge[MAX_CLASSES] = {
4800 1.1f, // Warrior
4801 1.0f, // Paladin
4802 1.6f, // Hunter
4803 2.0f, // Rogue
4804 1.0f, // Priest
4805 1.0f, // DK?
4806 1.0f, // Shaman
4807 1.0f, // Mage
4808 1.0f, // Warlock
4809 0.0f, // ??
4810 1.7f // Druid
4813 uint32 level = getLevel();
4814 uint32 pclass = getClass();
4816 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4818 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4819 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4820 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4821 return 0.0f;
4823 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4824 return dodge*100.0f;
4827 float Player::GetSpellCritFromIntellect()
4829 uint32 level = getLevel();
4830 uint32 pclass = getClass();
4832 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4834 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4835 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4836 if (critBase==NULL || critRatio==NULL)
4837 return 0.0f;
4839 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4840 return crit*100.0f;
4843 float Player::GetRatingCoefficient(CombatRating cr) const
4845 uint32 level = getLevel();
4847 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4849 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4850 if (Rating == NULL)
4851 return 1.0f; // By default use minimum coefficient (not must be called)
4853 return Rating->ratio;
4856 float Player::GetRatingBonusValue(CombatRating cr) const
4858 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4861 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4863 switch (attType)
4865 case BASE_ATTACK:
4866 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4867 case OFF_ATTACK:
4868 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4869 default:
4870 break;
4872 return 0.0f;
4875 float Player::OCTRegenHPPerSpirit()
4877 uint32 level = getLevel();
4878 uint32 pclass = getClass();
4880 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4882 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4883 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4884 if (baseRatio==NULL || moreRatio==NULL)
4885 return 0.0f;
4887 // Formula from PaperDollFrame script
4888 float spirit = GetStat(STAT_SPIRIT);
4889 float baseSpirit = spirit;
4890 if (baseSpirit>50) baseSpirit = 50;
4891 float moreSpirit = spirit - baseSpirit;
4892 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4893 return regen;
4896 float Player::OCTRegenMPPerSpirit()
4898 uint32 level = getLevel();
4899 uint32 pclass = getClass();
4901 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4903 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4904 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4905 if (moreRatio==NULL)
4906 return 0.0f;
4908 // Formula get from PaperDollFrame script
4909 float spirit = GetStat(STAT_SPIRIT);
4910 float regen = spirit * moreRatio->ratio;
4911 return regen;
4914 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4916 m_baseRatingValue[cr]+=(apply ? value : -value);
4918 int32 amount = uint32(m_baseRatingValue[cr]);
4919 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4920 // stat used stored in miscValueB for this aura
4921 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4922 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4923 if ((*i)->GetMiscValue() & (1<<cr))
4924 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4925 if (amount < 0)
4926 amount = 0;
4927 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4929 float RatingCoeffecient = GetRatingCoefficient(cr);
4930 float RatingChange = 0.0f;
4932 bool affectStats = CanModifyStats();
4934 switch (cr)
4936 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4937 case CR_DEFENSE_SKILL:
4938 UpdateDefenseBonusesMod();
4939 break;
4940 case CR_DODGE:
4941 UpdateDodgePercentage();
4942 break;
4943 case CR_PARRY:
4944 UpdateParryPercentage();
4945 break;
4946 case CR_BLOCK:
4947 UpdateBlockPercentage();
4948 break;
4949 case CR_HIT_MELEE:
4950 UpdateMeleeHitChances();
4951 break;
4952 case CR_HIT_RANGED:
4953 UpdateRangedHitChances();
4954 break;
4955 case CR_HIT_SPELL:
4956 UpdateSpellHitChances();
4957 break;
4958 case CR_CRIT_MELEE:
4959 if(affectStats)
4961 UpdateCritPercentage(BASE_ATTACK);
4962 UpdateCritPercentage(OFF_ATTACK);
4964 break;
4965 case CR_CRIT_RANGED:
4966 if(affectStats)
4967 UpdateCritPercentage(RANGED_ATTACK);
4968 break;
4969 case CR_CRIT_SPELL:
4970 if(affectStats)
4971 UpdateAllSpellCritChances();
4972 break;
4973 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4974 case CR_HIT_TAKEN_RANGED:
4975 break;
4976 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4977 break;
4978 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4979 case CR_CRIT_TAKEN_RANGED:
4980 break;
4981 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4982 break;
4983 case CR_HASTE_MELEE:
4984 RatingChange = value / RatingCoeffecient;
4985 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4986 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4987 break;
4988 case CR_HASTE_RANGED:
4989 RatingChange = value / RatingCoeffecient;
4990 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4991 break;
4992 case CR_HASTE_SPELL:
4993 RatingChange = value / RatingCoeffecient;
4994 ApplyCastTimePercentMod(RatingChange,apply);
4995 break;
4996 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4997 case CR_WEAPON_SKILL_OFFHAND:
4998 case CR_WEAPON_SKILL_RANGED:
4999 break;
5000 case CR_EXPERTISE:
5001 if(affectStats)
5003 UpdateExpertise(BASE_ATTACK);
5004 UpdateExpertise(OFF_ATTACK);
5006 break;
5007 case CR_ARMOR_PENETRATION:
5008 if(affectStats)
5009 UpdateArmorPenetration();
5010 break;
5014 void Player::SetRegularAttackTime()
5016 for(int i = 0; i < MAX_ATTACK; ++i)
5018 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i),true,false);
5019 if (tmpitem)
5021 ItemPrototype const *proto = tmpitem->GetProto();
5022 if(proto->Delay)
5023 SetAttackTime(WeaponAttackType(i), proto->Delay);
5024 else
5025 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
5030 //skill+step, checking for max value
5031 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
5033 if(!skill_id)
5034 return false;
5036 SkillStatusMap::iterator itr = mSkillStatus.find(skill_id);
5037 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5038 return false;
5040 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5041 uint32 data = GetUInt32Value(valueIndex);
5042 uint32 value = SKILL_VALUE(data);
5043 uint32 max = SKILL_MAX(data);
5045 if ((!max) || (!value) || (value >= max))
5046 return false;
5048 if (value*512 < max*urand(0,512))
5050 uint32 new_value = value+step;
5051 if(new_value > max)
5052 new_value = max;
5054 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,max));
5055 if(itr->second.uState != SKILL_NEW)
5056 itr->second.uState = SKILL_CHANGED;
5057 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
5058 return true;
5061 return false;
5064 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
5066 if ( SkillValue >= GrayLevel )
5067 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
5068 if ( SkillValue >= GreenLevel )
5069 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
5070 if ( SkillValue >= YellowLevel )
5071 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
5072 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
5075 bool Player::UpdateCraftSkill(uint32 spellid)
5077 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
5079 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spellid);
5081 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
5083 if (_spell_idx->second->skillId)
5085 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
5087 // Alchemy Discoveries here
5088 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
5089 if (spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
5091 if (uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
5092 learnSpell(discoveredSpell,false);
5095 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
5097 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
5098 _spell_idx->second->max_value,
5099 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
5100 _spell_idx->second->min_value),
5101 craft_skill_gain);
5104 return false;
5107 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
5109 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
5111 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
5113 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
5114 switch (SkillId)
5116 case SKILL_HERBALISM:
5117 case SKILL_LOCKPICKING:
5118 case SKILL_JEWELCRAFTING:
5119 case SKILL_INSCRIPTION:
5120 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5121 case SKILL_SKINNING:
5122 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
5123 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5124 else
5125 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
5126 case SKILL_MINING:
5127 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
5128 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5129 else
5130 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
5132 return false;
5135 bool Player::UpdateFishingSkill()
5137 sLog.outDebug("UpdateFishingSkill");
5139 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
5141 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
5143 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
5145 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
5148 // levels sync. with spell requirement for skill levels to learn
5149 // bonus abilities in sSkillLineAbilityStore
5150 // Used only to avoid scan DBC at each skill grow
5151 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
5153 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
5155 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
5156 if ( !SkillId )
5157 return false;
5159 if(Chance <= 0) // speedup in 0 chance case
5161 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5162 return false;
5165 SkillStatusMap::iterator itr = mSkillStatus.find(SkillId);
5166 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5167 return false;
5169 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5171 uint32 data = GetUInt32Value(valueIndex);
5172 uint16 SkillValue = SKILL_VALUE(data);
5173 uint16 MaxValue = SKILL_MAX(data);
5175 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
5176 return false;
5178 int32 Roll = irand(1,1000);
5180 if ( Roll <= Chance )
5182 uint32 new_value = SkillValue+step;
5183 if(new_value > MaxValue)
5184 new_value = MaxValue;
5186 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,MaxValue));
5187 if(itr->second.uState != SKILL_NEW)
5188 itr->second.uState = SKILL_CHANGED;
5189 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
5191 if((SkillValue < *bsl && new_value >= *bsl))
5193 learnSkillRewardedSpells( SkillId, new_value);
5194 break;
5197 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
5198 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
5199 return true;
5202 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5203 return false;
5206 void Player::UpdateWeaponSkill (WeaponAttackType attType)
5208 // no skill gain in pvp
5209 Unit *pVictim = getVictim();
5210 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
5211 return;
5213 if(IsInFeralForm())
5214 return; // always maximized SKILL_FERAL_COMBAT in fact
5216 if(m_form == FORM_TREE)
5217 return; // use weapon but not skill up
5219 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
5221 switch(attType)
5223 case BASE_ATTACK:
5225 Item *tmpitem = GetWeaponForAttack(attType,true,true);
5227 if (!tmpitem)
5228 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
5229 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
5230 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5231 break;
5233 case OFF_ATTACK:
5234 case RANGED_ATTACK:
5236 Item *tmpitem = GetWeaponForAttack(attType,true,true);
5237 if (tmpitem)
5238 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5239 break;
5242 UpdateAllCritPercentages();
5245 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
5247 uint32 plevel = getLevel(); // if defense than pVictim == attacker
5248 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
5249 uint32 moblevel = pVictim->getLevelForTarget(this);
5250 if(moblevel < greylevel)
5251 return;
5253 if (moblevel > plevel + 5)
5254 moblevel = plevel + 5;
5256 uint32 lvldif = moblevel - greylevel;
5257 if(lvldif < 3)
5258 lvldif = 3;
5260 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
5261 if(skilldif <= 0)
5262 return;
5264 float chance = float(3 * lvldif * skilldif) / plevel;
5265 if(!defence)
5267 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5268 chance *= 0.1f * GetStat(STAT_INTELLECT);
5271 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5273 if(roll_chance_f(chance))
5275 if(defence)
5276 UpdateDefense();
5277 else
5278 UpdateWeaponSkill(attType);
5280 else
5281 return;
5284 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5286 SkillStatusMap::const_iterator itr = mSkillStatus.find(skillid);
5287 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5288 return;
5290 uint32 bonusIndex = PLAYER_SKILL_BONUS_INDEX(itr->second.pos);
5292 uint32 bonus_val = GetUInt32Value(bonusIndex);
5293 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5294 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5296 if(talent) // permanent bonus stored in high part
5297 SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5298 else // temporary/item bonus stored in low part
5299 SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5302 void Player::UpdateSkillsForLevel()
5304 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5305 uint32 maxSkill = GetMaxSkillValueForLevel();
5307 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5309 for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
5311 if(itr->second.uState == SKILL_DELETED)
5312 continue;
5314 uint32 pskill = itr->first;
5316 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5317 if(!pSkill)
5318 continue;
5320 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5321 continue;
5323 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5324 uint32 data = GetUInt32Value(valueIndex);
5325 uint32 max = SKILL_MAX(data);
5326 uint32 val = SKILL_VALUE(data);
5328 /// update only level dependent max skill values
5329 if(max!=1)
5331 /// maximize skill always
5332 if(alwaysMaxSkill)
5334 SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(maxSkill,maxSkill));
5335 if(itr->second.uState != SKILL_NEW)
5336 itr->second.uState = SKILL_CHANGED;
5338 else if(max != maxconfskill) /// update max skill value if current max skill not maximized
5340 SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(val,maxSkill));
5341 if(itr->second.uState != SKILL_NEW)
5342 itr->second.uState = SKILL_CHANGED;
5348 void Player::UpdateSkillsToMaxSkillsForLevel()
5350 for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
5352 if(itr->second.uState == SKILL_DELETED)
5353 continue;
5355 uint32 pskill = itr->first;
5356 if( IsProfessionOrRidingSkill(pskill))
5357 continue;
5358 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5359 uint32 data = GetUInt32Value(valueIndex);
5361 uint32 max = SKILL_MAX(data);
5363 if(max > 1)
5365 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(max,max));
5366 if(itr->second.uState != SKILL_NEW)
5367 itr->second.uState = SKILL_CHANGED;
5370 if(pskill == SKILL_DEFENSE)
5371 UpdateDefenseBonusesMod();
5375 // This functions sets a skill line value (and adds if doesn't exist yet)
5376 // To "remove" a skill line, set it's values to zero
5377 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5379 if(!id)
5380 return;
5382 SkillStatusMap::iterator itr = mSkillStatus.find(id);
5384 //has skill
5385 if(itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED)
5387 if(currVal)
5389 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos),MAKE_SKILL_VALUE(currVal,maxVal));
5390 if(itr->second.uState != SKILL_NEW)
5391 itr->second.uState = SKILL_CHANGED;
5392 learnSkillRewardedSpells(id, currVal);
5393 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5394 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5396 else //remove
5398 // clear skill fields
5399 SetUInt32Value(PLAYER_SKILL_INDEX(itr->second.pos),0);
5400 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos),0);
5401 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos),0);
5403 // mark as deleted or simply remove from map if not saved yet
5404 if(itr->second.uState != SKILL_NEW)
5405 itr->second.uState = SKILL_DELETED;
5406 else
5407 mSkillStatus.erase(itr);
5409 // remove all spells that related to this skill
5410 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5411 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5412 if (pAbility->skillId==id)
5413 removeSpell(sSpellMgr.GetFirstSpellInChain(pAbility->spellId));
5416 else if(currVal) //add
5418 for (int i=0; i < PLAYER_MAX_SKILLS; ++i)
5419 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5421 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5422 if(!pSkill)
5424 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5425 return;
5427 // enable unlearn button for primary professions only
5428 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5429 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5430 else
5431 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5432 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5433 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5434 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5436 // insert new entry or update if not deleted old entry yet
5437 if(itr != mSkillStatus.end())
5439 itr->second.pos = i;
5440 itr->second.uState = SKILL_CHANGED;
5442 else
5443 mSkillStatus.insert(SkillStatusMap::value_type(id, SkillStatusData(i, SKILL_NEW)));
5445 // apply skill bonuses
5446 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5448 // temporary bonuses
5449 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5450 for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
5451 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5452 (*j)->ApplyModifier(true);
5454 // permanent bonuses
5455 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5456 for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
5457 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5458 (*j)->ApplyModifier(true);
5460 // Learn all spells for skill
5461 learnSkillRewardedSpells(id, currVal);
5462 return;
5467 bool Player::HasSkill(uint32 skill) const
5469 if(!skill)
5470 return false;
5472 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5473 return (itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED);
5476 uint16 Player::GetSkillValue(uint32 skill) const
5478 if(!skill)
5479 return 0;
5481 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5482 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5483 return 0;
5485 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
5487 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5488 result += SKILL_TEMP_BONUS(bonus);
5489 result += SKILL_PERM_BONUS(bonus);
5490 return result < 0 ? 0 : result;
5493 uint16 Player::GetMaxSkillValue(uint32 skill) const
5495 if(!skill)
5496 return 0;
5498 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5499 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5500 return 0;
5502 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
5504 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5505 result += SKILL_TEMP_BONUS(bonus);
5506 result += SKILL_PERM_BONUS(bonus);
5507 return result < 0 ? 0 : result;
5510 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5512 if(!skill)
5513 return 0;
5515 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5516 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5517 return 0;
5519 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
5522 uint16 Player::GetBaseSkillValue(uint32 skill) const
5524 if(!skill)
5525 return 0;
5527 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5528 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5529 return 0;
5531 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5532 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5533 return result < 0 ? 0 : result;
5536 uint16 Player::GetPureSkillValue(uint32 skill) const
5538 if(!skill)
5539 return 0;
5541 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5542 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5543 return 0;
5545 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
5548 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5550 if(!skill)
5551 return 0;
5553 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5554 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5555 return 0;
5557 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5560 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5562 if(!skill)
5563 return 0;
5565 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5566 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5567 return 0;
5569 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5572 void Player::SendInitialActionButtons() const
5574 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5576 WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
5577 data << uint8(0); // can be 0, 1, 2 (talent spec)
5578 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5580 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5581 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5582 data << uint32(itr->second.packedData);
5583 else
5584 data << uint32(0);
5587 GetSession()->SendPacket( &data );
5588 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5591 bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type, Player* player)
5593 if(button >= MAX_ACTION_BUTTONS)
5595 if (player)
5596 sLog.outError( "Action %u not added into button %u for player %s: button must be < %u", action, button, player->GetName(), MAX_ACTION_BUTTONS );
5597 else
5598 sLog.outError( "Table `playercreateinfo_action` have action %u into button %u : button must be < %u", action, button, MAX_ACTION_BUTTONS );
5599 return false;
5602 if(action >= MAX_ACTION_BUTTON_ACTION_VALUE)
5604 if (player)
5605 sLog.outError( "Action %u not added into button %u for player %s: action must be < %u", action, button, player->GetName(), MAX_ACTION_BUTTON_ACTION_VALUE );
5606 else
5607 sLog.outError( "Table `playercreateinfo_action` have action %u into button %u : action must be < %u", action, button, MAX_ACTION_BUTTON_ACTION_VALUE );
5608 return false;
5611 switch(type)
5613 case ACTION_BUTTON_SPELL:
5614 if(!sSpellStore.LookupEntry(action))
5616 if (player)
5617 sLog.outError( "Spell action %u not added into button %u for player %s: spell not exist", action, button, player->GetName() );
5618 else
5619 sLog.outError( "Table `playercreateinfo_action` have spell action %u into button %u: spell not exist", action, button );
5620 return false;
5623 if(player && !player->HasSpell(action))
5625 sLog.outError( "Spell action %u not added into button %u for player %s: player don't known this spell", action, button, player->GetName() );
5626 return false;
5628 break;
5629 case ACTION_BUTTON_ITEM:
5630 if(!ObjectMgr::GetItemPrototype(action))
5632 if (player)
5633 sLog.outError( "Item action %u not added into button %u for player %s: item not exist", action, button, player->GetName() );
5634 else
5635 sLog.outError( "Table `playercreateinfo_action` have item action %u into button %u: item not exist", action, button );
5636 return false;
5638 break;
5639 default:
5640 break; // other cases not checked at this moment
5643 return true;
5646 ActionButton* Player::addActionButton(uint8 button, uint32 action, uint8 type)
5649 if (!IsActionButtonDataValid(button,action,type,this))
5650 return NULL;
5652 // it create new button (NEW state) if need or return existed
5653 ActionButton& ab = m_actionButtons[button];
5655 // set data and update to CHANGED if not NEW
5656 ab.SetActionAndType(action,ActionButtonType(type));
5658 sLog.outDetail( "Player '%u' Added Action '%u' (type %u) to Button '%u'", GetGUIDLow(), action, uint32(type), button );
5659 return &ab;
5662 void Player::removeActionButton(uint8 button)
5664 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5665 if (buttonItr==m_actionButtons.end())
5666 return;
5668 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5669 m_actionButtons.erase(buttonItr); // new and not saved
5670 else
5671 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5673 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5676 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5678 // prevent crash when a bad coord is sent by the client
5679 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5681 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5682 return false;
5685 Map *m = GetMap();
5687 const float old_x = GetPositionX();
5688 const float old_y = GetPositionY();
5689 const float old_z = GetPositionZ();
5690 const float old_r = GetOrientation();
5692 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5694 if (teleport || old_x != x || old_y != y || old_z != z)
5695 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5696 else
5697 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5699 // move and update visible state if need
5700 m->PlayerRelocation(this, x, y, z, orientation);
5702 // reread after Map::Relocation
5703 m = GetMap();
5704 x = GetPositionX();
5705 y = GetPositionY();
5706 z = GetPositionZ();
5708 // group update
5709 if(GetGroup() && (old_x != x || old_y != y))
5710 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5713 // code block for underwater state update
5714 UpdateUnderwaterState(m, x, y, z);
5716 CheckExploreSystem();
5718 return true;
5721 void Player::SaveRecallPosition()
5723 m_recallMap = GetMapId();
5724 m_recallX = GetPositionX();
5725 m_recallY = GetPositionY();
5726 m_recallZ = GetPositionZ();
5727 m_recallO = GetOrientation();
5730 void Player::SendMessageToSet(WorldPacket *data, bool self)
5732 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5733 if(_map)
5735 _map->MessageBroadcast(this, data, self);
5736 return;
5739 //if player is not in world and map in not created/already destroyed
5740 //no need to create one, just send packet for itself!
5741 if(self)
5742 GetSession()->SendPacket(data);
5745 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5747 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5748 if(_map)
5750 _map->MessageDistBroadcast(this, data, dist, self);
5751 return;
5754 if(self)
5755 GetSession()->SendPacket(data);
5758 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5760 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5761 if(_map)
5763 _map->MessageDistBroadcast(this, data, dist, self, own_team_only);
5764 return;
5767 if(self)
5768 GetSession()->SendPacket(data);
5771 void Player::SendDirectMessage(WorldPacket *data)
5773 GetSession()->SendPacket(data);
5776 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5778 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5779 data << uint32(CinematicSequenceId);
5780 SendDirectMessage(&data);
5783 void Player::SendMovieStart(uint32 MovieId)
5785 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5786 data << uint32(MovieId);
5787 SendDirectMessage(&data);
5790 void Player::CheckExploreSystem()
5792 if (!isAlive())
5793 return;
5795 if (isInFlight())
5796 return;
5798 uint16 areaFlag = GetBaseMap()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5799 if(areaFlag==0xffff)
5800 return;
5801 int offset = areaFlag / 32;
5803 if(offset >= 128)
5805 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);
5806 return;
5809 uint32 val = (uint32)(1 << (areaFlag % 32));
5810 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5812 if( !(currFields & val) )
5814 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5816 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5818 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5819 if(!p)
5821 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5823 else if(p->area_level > 0)
5825 uint32 area = p->ID;
5826 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5828 SendExplorationExperience(area,0);
5830 else
5832 int32 diff = int32(getLevel()) - p->area_level;
5833 uint32 XP = 0;
5834 if (diff < -5)
5836 XP = uint32(sObjectMgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5838 else if (diff > 5)
5840 int32 exploration_percent = (100-((diff-5)*5));
5841 if (exploration_percent > 100)
5842 exploration_percent = 100;
5843 else if (exploration_percent < 0)
5844 exploration_percent = 0;
5846 XP = uint32(sObjectMgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5848 else
5850 XP = uint32(sObjectMgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5853 GiveXP( XP, NULL );
5854 SendExplorationExperience(area,XP);
5856 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5861 uint32 Player::TeamForRace(uint8 race)
5863 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5864 if(!rEntry)
5866 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5867 return ALLIANCE;
5870 switch(rEntry->TeamID)
5872 case 7: return ALLIANCE;
5873 case 1: return HORDE;
5876 sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5877 return ALLIANCE;
5880 uint32 Player::getFactionForRace(uint8 race)
5882 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5883 if(!rEntry)
5885 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5886 return 0;
5889 return rEntry->FactionID;
5892 void Player::setFactionForRace(uint8 race)
5894 m_team = TeamForRace(race);
5895 setFaction( getFactionForRace(race) );
5898 ReputationRank Player::GetReputationRank(uint32 faction) const
5900 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
5901 return GetReputationMgr().GetRank(factionEntry);
5904 //Calculate total reputation percent player gain with quest/creature level
5905 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest)
5907 float percent = 100.0f;
5909 float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL);
5911 if (rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
5912 percent *= rate;
5914 float repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5916 if (!for_quest)
5917 repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);
5919 percent += rep > 0 ? repMod : -repMod;
5921 if (percent <= 0.0f)
5922 return 0;
5924 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100.0f);
5927 //Calculates how many reputation points player gains in victim's enemy factions
5928 void Player::RewardReputation(Unit *pVictim, float rate)
5930 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5931 return;
5933 ReputationOnKillEntry const* Rep = sObjectMgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5935 if(!Rep)
5936 return;
5938 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5940 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue1, Rep->repfaction1, false);
5941 donerep1 = int32(donerep1*rate);
5942 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5943 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
5944 if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5945 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
5947 // Wiki: Team factions value divided by 2
5948 if (factionEntry1 && Rep->is_teamaward1)
5950 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5951 if(team1_factionEntry)
5952 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
5956 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5958 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue2, Rep->repfaction2, false);
5959 donerep2 = int32(donerep2*rate);
5960 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5961 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
5962 if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5963 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
5965 // Wiki: Team factions value divided by 2
5966 if (factionEntry2 && Rep->is_teamaward2)
5968 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5969 if(team2_factionEntry)
5970 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
5975 //Calculate how many reputation points player gain with the quest
5976 void Player::RewardReputation(Quest const *pQuest)
5978 // quest reputation reward/loss
5979 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5981 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5983 int32 rep = CalculateReputationGain(GetQuestLevelForPlayer(pQuest), pQuest->RewRepValue[i], pQuest->RewRepFaction[i], true);
5984 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5985 if(factionEntry)
5986 GetReputationMgr().ModifyReputation(factionEntry, rep);
5990 // TODO: implement reputation spillover
5993 void Player::UpdateArenaFields(void)
5995 /* arena calcs go here */
5998 void Player::UpdateHonorFields()
6000 /// called when rewarding honor and at each save
6001 uint64 now = time(NULL);
6002 uint64 today = uint64(time(NULL) / DAY) * DAY;
6004 if(m_lastHonorUpdateTime < today)
6006 uint64 yesterday = today - DAY;
6008 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
6010 // update yesterday's contribution
6011 if(m_lastHonorUpdateTime >= yesterday )
6013 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
6015 // this is the first update today, reset today's contribution
6016 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
6017 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
6019 else
6021 // no honor/kills yesterday or today, reset
6022 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
6023 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
6027 m_lastHonorUpdateTime = now;
6030 ///Calculate the amount of honor gained based on the victim
6031 ///and the size of the group for which the honor is divided
6032 ///An exact honor value can also be given (overriding the calcs)
6033 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
6035 // do not reward honor in arenas, but enable onkill spellproc
6036 if(InArena())
6038 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
6039 return false;
6041 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
6042 return false;
6044 return true;
6047 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
6048 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
6049 return false;
6051 uint64 victim_guid = 0;
6052 uint32 victim_rank = 0;
6054 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6055 UpdateHonorFields();
6057 if(honor <= 0)
6059 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
6060 return false;
6062 victim_guid = uVictim->GetGUID();
6064 if( uVictim->GetTypeId() == TYPEID_PLAYER )
6066 Player *pVictim = (Player *)uVictim;
6068 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
6069 return false;
6071 float f = 1; //need for total kills (?? need more info)
6072 uint32 k_grey = 0;
6073 uint32 k_level = getLevel();
6074 uint32 v_level = pVictim->getLevel();
6077 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6078 // [0] Just name
6079 // [1..14] Alliance honor titles and player name
6080 // [15..28] Horde honor titles and player name
6081 // [29..38] Other title and player name
6082 // [39+] Nothing
6083 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
6084 // Get Killer titles, CharTitlesEntry::bit_index
6085 // Ranks:
6086 // title[1..14] -> rank[5..18]
6087 // title[15..28] -> rank[5..18]
6088 // title[other] -> 0
6089 if (victim_title == 0)
6090 victim_guid = 0; // Don't show HK: <rank> message, only log.
6091 else if (victim_title < 15)
6092 victim_rank = victim_title + 4;
6093 else if (victim_title < 29)
6094 victim_rank = victim_title - 14 + 4;
6095 else
6096 victim_guid = 0; // Don't show HK: <rank> message, only log.
6099 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
6101 if(v_level<=k_grey)
6102 return false;
6104 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
6106 int32 v_rank =1; //need more info
6108 honor = ((f * diff_level * (190 + v_rank*10))/6);
6109 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
6111 // count the number of playerkills in one day
6112 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
6113 // and those in a lifetime
6114 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
6115 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
6116 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
6117 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
6119 else
6121 Creature *cVictim = (Creature *)uVictim;
6123 if (!cVictim->isRacialLeader())
6124 return false;
6126 honor = 100; // ??? need more info
6127 victim_rank = 19; // HK: Leader
6131 if (uVictim != NULL)
6133 honor *= sWorld.getRate(RATE_HONOR);
6134 honor *= (GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN) + 100.0f)/100.0f;
6136 if(groupsize > 1)
6137 honor /= groupsize;
6139 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6142 // honor - for show honor points in log
6143 // victim_guid - for show victim name in log
6144 // victim_rank [1..4] HK: <dishonored rank>
6145 // victim_rank [5..19] HK: <alliance\horde rank>
6146 // victim_rank [0,20+] HK: <>
6147 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
6148 data << (uint32) honor;
6149 data << (uint64) victim_guid;
6150 data << (uint32) victim_rank;
6152 GetSession()->SendPacket(&data);
6154 // add honor points
6155 ModifyHonorPoints(int32(honor));
6157 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
6158 return true;
6161 void Player::ModifyHonorPoints( int32 value )
6163 if(value < 0)
6165 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
6166 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
6167 else
6168 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6170 else
6171 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6174 void Player::ModifyArenaPoints( int32 value )
6176 if(value < 0)
6178 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6179 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6180 else
6181 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6183 else
6184 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6187 uint32 Player::GetGuildIdFromDB(uint64 guid)
6189 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
6190 if(!result)
6191 return 0;
6193 uint32 id = result->Fetch()[0].GetUInt32();
6194 delete result;
6195 return id;
6198 uint32 Player::GetRankFromDB(uint64 guid)
6200 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6201 if( result )
6203 uint32 v = result->Fetch()[0].GetUInt32();
6204 delete result;
6205 return v;
6207 else
6208 return 0;
6211 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6213 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);
6214 if(!result)
6215 return 0;
6217 uint32 id = (*result)[0].GetUInt32();
6218 delete result;
6219 return id;
6222 uint32 Player::GetZoneIdFromDB(uint64 guid)
6224 uint32 guidLow = GUID_LOPART(guid);
6225 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6226 if (!result)
6227 return 0;
6228 Field* fields = result->Fetch();
6229 uint32 zone = fields[0].GetUInt32();
6230 delete result;
6232 if (!zone)
6234 // stored zone is zero, use generic and slow zone detection
6235 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6236 if( !result )
6237 return 0;
6238 fields = result->Fetch();
6239 uint32 map = fields[0].GetUInt32();
6240 float posx = fields[1].GetFloat();
6241 float posy = fields[2].GetFloat();
6242 float posz = fields[3].GetFloat();
6243 delete result;
6245 zone = sMapMgr.GetZoneId(map,posx,posy,posz);
6247 if (zone > 0)
6248 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6251 return zone;
6254 uint32 Player::GetLevelFromDB(uint64 guid)
6256 QueryResult *result = CharacterDatabase.PQuery( "SELECT level FROM characters WHERE guid='%u'", GUID_LOPART(guid) );
6257 if (!result)
6258 return 0;
6260 Field* fields = result->Fetch();
6261 uint32 level = fields[0].GetUInt32();
6262 delete result;
6264 return level;
6267 void Player::UpdateArea(uint32 newArea)
6269 // FFA_PVP flags are area and not zone id dependent
6270 // so apply them accordingly
6271 m_areaUpdateId = newArea;
6273 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6275 if(area && (area->flags & AREA_FLAG_ARENA))
6277 if(!isGameMaster())
6278 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6280 else
6282 // remove ffa flag only if not ffapvp realm
6283 // removal in sanctuaries and capitals is handled in zone update
6284 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6285 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6288 UpdateAreaDependentAuras(newArea);
6291 void Player::UpdateZone(uint32 newZone, uint32 newArea)
6293 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6294 if(!zone)
6295 return;
6297 if(m_zoneUpdateId != newZone)
6299 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
6301 if (sWorld.getConfig(CONFIG_WEATHER))
6303 if(Weather *wth = sWorld.FindWeather(zone->ID))
6304 wth->SendWeatherUpdateToPlayer(this);
6305 else if(!sWorld.AddWeather(zone->ID))
6307 // send fine weather packet to remove old zone's weather
6308 Weather::SendFineWeatherUpdateToPlayer(this);
6313 m_zoneUpdateId = newZone;
6314 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6316 // zone changed, so area changed as well, update it
6317 UpdateArea(newArea);
6319 // in PvP, any not controlled zone (except zone->team == 6, default case)
6320 // in PvE, only opposition team capital
6321 switch(zone->team)
6323 case AREATEAM_ALLY:
6324 pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6325 break;
6326 case AREATEAM_HORDE:
6327 pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6328 break;
6329 case AREATEAM_NONE:
6330 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6331 pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround();
6332 break;
6333 default: // 6 in fact
6334 pvpInfo.inHostileArea = false;
6335 break;
6338 if(pvpInfo.inHostileArea) // in hostile area
6340 if(!IsPvP() || pvpInfo.endTimer != 0)
6341 UpdatePvP(true, true);
6343 else // in friendly area
6345 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6346 pvpInfo.endTimer = time(0); // start toggle-off
6349 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6351 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6352 if(sWorld.IsFFAPvPRealm())
6353 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6355 else
6357 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6360 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6362 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6363 SetRestType(REST_TYPE_IN_CITY);
6364 InnEnter(time(0),GetMapId(),0,0,0);
6366 if(sWorld.IsFFAPvPRealm())
6367 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6369 else // anywhere else
6371 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6373 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6375 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6377 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6378 SetRestType(REST_TYPE_NO);
6380 if(sWorld.IsFFAPvPRealm())
6381 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6384 else // not in tavern (leave city then)
6386 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6387 SetRestType(REST_TYPE_NO);
6389 // Set player to FFA PVP when not in rested environment.
6390 if(sWorld.IsFFAPvPRealm())
6391 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6396 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6397 // if player resurrected at teleport this will be applied in resurrect code
6398 if(isAlive())
6399 DestroyZoneLimitedItem( true, newZone );
6401 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6402 AutoUnequipOffhandIfNeed();
6404 // recent client version not send leave/join channel packets for built-in local channels
6405 UpdateLocalChannels( newZone );
6407 // group update
6408 if(GetGroup())
6409 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6411 UpdateZoneDependentAuras(newZone);
6414 //If players are too far way of duel flag... then player loose the duel
6415 void Player::CheckDuelDistance(time_t currTime)
6417 if(!duel)
6418 return;
6420 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6421 GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
6422 if(!obj)
6423 return;
6425 if(duel->outOfBound == 0)
6427 if(!IsWithinDistInMap(obj, 50))
6429 duel->outOfBound = currTime;
6431 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6432 GetSession()->SendPacket(&data);
6435 else
6437 if(IsWithinDistInMap(obj, 40))
6439 duel->outOfBound = 0;
6441 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6442 GetSession()->SendPacket(&data);
6444 else if(currTime >= (duel->outOfBound+10))
6446 DuelComplete(DUEL_FLED);
6451 void Player::DuelComplete(DuelCompleteType type)
6453 // duel not requested
6454 if(!duel)
6455 return;
6457 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6458 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6459 GetSession()->SendPacket(&data);
6460 duel->opponent->GetSession()->SendPacket(&data);
6462 if(type != DUEL_INTERUPTED)
6464 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6465 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6466 data << duel->opponent->GetName();
6467 data << GetName();
6468 SendMessageToSet(&data,true);
6471 if (type == DUEL_WON)
6473 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
6474 if (duel->opponent)
6475 duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
6478 //Remove Duel Flag object
6479 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
6480 if(obj)
6481 duel->initiator->RemoveGameObject(obj,true);
6483 /* remove auras */
6484 std::vector<uint32> auras2remove;
6485 AuraMap const& vAuras = duel->opponent->GetAuras();
6486 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6488 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6489 auras2remove.push_back(i->second->GetId());
6492 for(size_t i=0; i<auras2remove.size(); ++i)
6493 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6495 auras2remove.clear();
6496 AuraMap const& auras = GetAuras();
6497 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6499 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6500 auras2remove.push_back(i->second->GetId());
6502 for(size_t i=0; i<auras2remove.size(); ++i)
6503 RemoveAurasDueToSpell(auras2remove[i]);
6505 // cleanup combo points
6506 if(GetComboTarget()==duel->opponent->GetGUID())
6507 ClearComboPoints();
6508 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6509 ClearComboPoints();
6511 if(duel->opponent->GetComboTarget()==GetGUID())
6512 duel->opponent->ClearComboPoints();
6513 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6514 duel->opponent->ClearComboPoints();
6516 //cleanups
6517 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6518 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6519 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6520 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6522 delete duel->opponent->duel;
6523 duel->opponent->duel = NULL;
6524 delete duel;
6525 duel = NULL;
6528 //---------------------------------------------------------//
6530 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6532 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6533 return;
6535 // not apply/remove mods for broken item
6536 if(item->IsBroken())
6537 return;
6539 ItemPrototype const *proto = item->GetProto();
6541 if(!proto)
6542 return;
6544 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6546 uint32 attacktype = Player::GetAttackBySlot(slot);
6547 if(attacktype < MAX_ATTACK)
6548 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6550 _ApplyItemBonuses(proto,slot,apply);
6552 if( slot==EQUIPMENT_SLOT_RANGED )
6553 _ApplyAmmoBonuses();
6555 ApplyItemEquipSpell(item,apply);
6556 ApplyEnchantment(item, apply);
6558 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6559 CorrectMetaGemEnchants(slot, apply);
6561 sLog.outDebug("_ApplyItemMods complete.");
6564 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply, bool only_level_scale /*= false*/)
6566 if (slot >= INVENTORY_SLOT_BAG_END || !proto)
6567 return;
6569 ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : NULL;
6570 if (only_level_scale && !ssd)
6571 return;
6573 // req. check at equip, but allow use for extended range if range limit max level, set proper level
6574 uint32 ssd_level = getLevel();
6575 if (ssd && ssd_level > ssd->MaxLevel)
6576 ssd_level = ssd->MaxLevel;
6578 ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(ssd_level) : NULL;
6579 if (only_level_scale && !ssv)
6580 return;
6582 for (int i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6584 uint32 statType = 0;
6585 int32 val = 0;
6586 // If set ScalingStatDistribution need get stats and values from it
6587 if (ssd && ssv)
6589 if (ssd->StatMod[i] < 0)
6590 continue;
6591 statType = ssd->StatMod[i];
6592 val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[i]) / 10000;
6594 else
6596 if (i >= proto->StatsCount)
6597 continue;
6598 statType = proto->ItemStat[i].ItemStatType;
6599 val = proto->ItemStat[i].ItemStatValue;
6602 if(val == 0)
6603 continue;
6605 switch (statType)
6607 case ITEM_MOD_MANA:
6608 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6609 break;
6610 case ITEM_MOD_HEALTH: // modify HP
6611 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6612 break;
6613 case ITEM_MOD_AGILITY: // modify agility
6614 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6615 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6616 break;
6617 case ITEM_MOD_STRENGTH: //modify strength
6618 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6619 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6620 break;
6621 case ITEM_MOD_INTELLECT: //modify intellect
6622 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6623 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6624 break;
6625 case ITEM_MOD_SPIRIT: //modify spirit
6626 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6627 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6628 break;
6629 case ITEM_MOD_STAMINA: //modify stamina
6630 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6631 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6632 break;
6633 case ITEM_MOD_DEFENSE_SKILL_RATING:
6634 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6635 break;
6636 case ITEM_MOD_DODGE_RATING:
6637 ApplyRatingMod(CR_DODGE, int32(val), apply);
6638 break;
6639 case ITEM_MOD_PARRY_RATING:
6640 ApplyRatingMod(CR_PARRY, int32(val), apply);
6641 break;
6642 case ITEM_MOD_BLOCK_RATING:
6643 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6644 break;
6645 case ITEM_MOD_HIT_MELEE_RATING:
6646 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6647 break;
6648 case ITEM_MOD_HIT_RANGED_RATING:
6649 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6650 break;
6651 case ITEM_MOD_HIT_SPELL_RATING:
6652 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6653 break;
6654 case ITEM_MOD_CRIT_MELEE_RATING:
6655 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6656 break;
6657 case ITEM_MOD_CRIT_RANGED_RATING:
6658 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6659 break;
6660 case ITEM_MOD_CRIT_SPELL_RATING:
6661 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6662 break;
6663 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6664 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6665 break;
6666 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6667 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6668 break;
6669 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6670 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6671 break;
6672 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6673 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6674 break;
6675 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6676 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6677 break;
6678 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6679 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6680 break;
6681 case ITEM_MOD_HASTE_MELEE_RATING:
6682 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6683 break;
6684 case ITEM_MOD_HASTE_RANGED_RATING:
6685 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6686 break;
6687 case ITEM_MOD_HASTE_SPELL_RATING:
6688 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6689 break;
6690 case ITEM_MOD_HIT_RATING:
6691 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6692 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6693 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6694 break;
6695 case ITEM_MOD_CRIT_RATING:
6696 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6697 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6698 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6699 break;
6700 case ITEM_MOD_HIT_TAKEN_RATING:
6701 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6702 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6703 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6704 break;
6705 case ITEM_MOD_CRIT_TAKEN_RATING:
6706 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6707 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6708 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6709 break;
6710 case ITEM_MOD_RESILIENCE_RATING:
6711 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6712 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6713 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6714 break;
6715 case ITEM_MOD_HASTE_RATING:
6716 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6717 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6718 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6719 break;
6720 case ITEM_MOD_EXPERTISE_RATING:
6721 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6722 break;
6723 case ITEM_MOD_ATTACK_POWER:
6724 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6725 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6726 break;
6727 case ITEM_MOD_RANGED_ATTACK_POWER:
6728 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6729 break;
6730 case ITEM_MOD_FERAL_ATTACK_POWER:
6731 ApplyFeralAPBonus(int32(val), apply);
6732 break;
6733 case ITEM_MOD_MANA_REGENERATION:
6734 ApplyManaRegenBonus(int32(val), apply);
6735 break;
6736 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6737 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6738 break;
6739 case ITEM_MOD_SPELL_POWER:
6740 ApplySpellPowerBonus(int32(val), apply);
6741 break;
6742 // depricated item mods
6743 case ITEM_MOD_SPELL_HEALING_DONE:
6744 case ITEM_MOD_SPELL_DAMAGE_DONE:
6745 break;
6749 // Apply Spell Power from ScalingStatValue if set
6750 if(ssv)
6752 if (int32 spellbonus = ssv->getSpellBonus(proto->ScalingStatValue))
6753 ApplySpellPowerBonus(spellbonus, apply);
6756 // If set ScalingStatValue armor get it or use item armor
6757 uint32 armor = proto->Armor;
6758 if (ssv)
6760 if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue))
6761 armor = ssvarmor;
6763 // Add armor bonus from ArmorDamageModifier if > 0
6764 if (proto->ArmorDamageModifier > 0)
6765 armor += uint32(proto->ArmorDamageModifier);
6767 if (armor)
6768 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(armor), apply);
6770 if (proto->Block)
6771 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6773 if (proto->HolyRes)
6774 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6776 if (proto->FireRes)
6777 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6779 if (proto->NatureRes)
6780 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6782 if (proto->FrostRes)
6783 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6785 if (proto->ShadowRes)
6786 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6788 if (proto->ArcaneRes)
6789 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6791 WeaponAttackType attType = BASE_ATTACK;
6792 float damage = 0.0f;
6794 if( slot == EQUIPMENT_SLOT_RANGED && (
6795 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6796 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6798 attType = RANGED_ATTACK;
6800 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6802 attType = OFF_ATTACK;
6805 float minDamage = proto->Damage[0].DamageMin;
6806 float maxDamage = proto->Damage[0].DamageMax;
6807 int32 extraDPS = 0;
6808 // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
6809 if (ssv)
6811 if ((extraDPS = ssv->getDPSMod(proto->ScalingStatValue)))
6813 float average = extraDPS * proto->Delay / 1000.0f;
6814 minDamage = 0.7f * average;
6815 maxDamage = 1.3f * average;
6818 if (minDamage > 0 )
6820 damage = apply ? minDamage : BASE_MINDAMAGE;
6821 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6822 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6825 if (maxDamage > 0 )
6827 damage = apply ? maxDamage : BASE_MAXDAMAGE;
6828 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6831 // Apply feral bonus from ScalingStatValue if set
6832 if (ssv)
6834 if (int32 feral_bonus = ssv->getFeralBonus(proto->ScalingStatValue))
6835 ApplyFeralAPBonus(feral_bonus, apply);
6837 // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
6838 if(getClass() == CLASS_DRUID)
6840 int32 feral_bonus = proto->getFeralBonus(extraDPS);
6841 if (feral_bonus > 0)
6842 ApplyFeralAPBonus(feral_bonus, apply);
6845 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6846 return;
6848 if (proto->Delay)
6850 if(slot == EQUIPMENT_SLOT_RANGED)
6851 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6852 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6853 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6854 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6855 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6858 if(CanModifyStats() && (damage || proto->Delay))
6859 UpdateDamagePhysical(attType);
6862 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6864 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6865 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6866 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6868 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6869 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6870 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6872 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6873 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6874 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6877 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6879 // generic not weapon specific case processes in aura code
6880 if(aura->GetSpellProto()->EquippedItemClass == -1)
6881 return;
6883 BaseModGroup mod = BASEMOD_END;
6884 switch(attackType)
6886 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6887 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6888 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6889 default: return;
6892 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6894 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6898 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6900 // ignore spell mods for not wands
6901 Modifier const* modifier = aura->GetModifier();
6902 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6903 return;
6905 // generic not weapon specific case processes in aura code
6906 if(aura->GetSpellProto()->EquippedItemClass == -1)
6907 return;
6909 UnitMods unitMod = UNIT_MOD_END;
6910 switch(attackType)
6912 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6913 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6914 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6915 default: return;
6918 UnitModifierType unitModType = TOTAL_VALUE;
6919 switch(modifier->m_auraname)
6921 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6922 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6923 default: return;
6926 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6928 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6932 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6934 if(!item)
6935 return;
6937 ItemPrototype const *proto = item->GetProto();
6938 if(!proto)
6939 return;
6941 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6943 _Spell const& spellData = proto->Spells[i];
6945 // no spell
6946 if(!spellData.SpellId )
6947 continue;
6949 // wrong triggering type
6950 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6951 continue;
6953 // check if it is valid spell
6954 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6955 if(!spellproto)
6956 continue;
6958 ApplyEquipSpell(spellproto,item,apply,form_change);
6962 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6964 if(apply)
6966 // Cannot be used in this stance/form
6967 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
6968 return;
6970 if(form_change) // check aura active state from other form
6972 bool found = false;
6973 for (int k=0; k < 3; ++k)
6975 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6976 for (AuraMap::const_iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6978 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6980 found = true;
6981 break;
6984 if(found)
6985 break;
6988 if(found) // and skip re-cast already active aura at form change
6989 return;
6992 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6994 CastSpell(this,spellInfo,true,item);
6996 else
6998 if(form_change) // check aura compatibility
7000 // Cannot be used in this stance/form
7001 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
7002 return; // and remove only not compatible at form change
7005 if(item)
7006 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
7007 else
7008 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
7012 void Player::UpdateEquipSpellsAtFormChange()
7014 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7016 if(m_items[i] && !m_items[i]->IsBroken())
7018 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
7019 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
7023 // item set bonuses not dependent from item broken state
7024 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
7026 ItemSetEffect* eff = ItemSetEff[setindex];
7027 if(!eff)
7028 continue;
7030 for(uint32 y=0;y<8; ++y)
7032 SpellEntry const* spellInfo = eff->spells[y];
7033 if(!spellInfo)
7034 continue;
7036 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
7037 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
7042 void Player::CastItemCombatSpell(Unit* Target, WeaponAttackType attType)
7044 Item *item = GetWeaponForAttack(attType, true, false);
7045 if(!item)
7046 return;
7048 ItemPrototype const *proto = item->GetProto();
7049 if(!proto)
7050 return;
7052 if (!Target || Target == this )
7053 return;
7055 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7057 _Spell const& spellData = proto->Spells[i];
7059 // no spell
7060 if(!spellData.SpellId )
7061 continue;
7063 // wrong triggering type
7064 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
7065 continue;
7067 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7068 if(!spellInfo)
7070 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
7071 continue;
7074 // not allow proc extra attack spell at extra attack
7075 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
7076 return;
7078 float chance = spellInfo->procChance;
7080 if(spellData.SpellPPMRate)
7082 uint32 WeaponSpeed = proto->Delay;
7083 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
7085 else if(chance > 100.0f)
7087 chance = GetWeaponProcChance();
7090 if (roll_chance_f(chance))
7091 CastSpell(Target, spellInfo->Id, true, item);
7094 // item combat enchantments
7095 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7097 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7098 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7099 if(!pEnchant) continue;
7100 for (int s=0;s<3;s++)
7102 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
7103 continue;
7105 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7106 if (!spellInfo)
7108 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7109 continue;
7112 // Use first rank to access spell item enchant procs
7113 float ppmRate = sSpellMgr.GetItemEnchantProcChance(spellInfo->Id);
7115 float chance = ppmRate
7116 ? GetPPMProcChance(proto->Delay, ppmRate)
7117 : pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
7120 ApplySpellMod(spellInfo->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
7121 ApplySpellMod(spellInfo->Id,SPELLMOD_FREQUENCY_OF_SUCCESS,chance);
7123 if (roll_chance_f(chance))
7125 if(IsPositiveSpell(pEnchant->spellid[s]))
7126 CastSpell(this, pEnchant->spellid[s], true, item);
7127 else
7128 CastSpell(Target, pEnchant->spellid[s], true, item);
7134 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
7136 ItemPrototype const* proto = item->GetProto();
7137 // special learning case
7138 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
7140 uint32 learn_spell_id = proto->Spells[0].SpellId;
7141 uint32 learning_spell_id = proto->Spells[1].SpellId;
7143 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
7144 if(!spellInfo)
7146 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
7147 SendEquipError(EQUIP_ERR_NONE,item,NULL);
7148 return;
7151 Spell *spell = new Spell(this, spellInfo, false);
7152 spell->m_CastItem = item;
7153 spell->m_cast_count = cast_count; //set count of casts
7154 spell->m_currentBasePoints[0] = learning_spell_id;
7155 spell->prepare(&targets);
7156 return;
7159 // use triggered flag only for items with many spell casts and for not first cast
7160 int count = 0;
7162 // item spells casted at use
7163 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7165 _Spell const& spellData = proto->Spells[i];
7167 // no spell
7168 if(!spellData.SpellId)
7169 continue;
7171 // wrong triggering type
7172 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
7173 continue;
7175 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7176 if(!spellInfo)
7178 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
7179 continue;
7182 Spell *spell = new Spell(this, spellInfo, (count > 0));
7183 spell->m_CastItem = item;
7184 spell->m_cast_count = cast_count; // set count of casts
7185 spell->m_glyphIndex = glyphIndex; // glyph index
7186 spell->prepare(&targets);
7188 ++count;
7191 // Item enchantments spells casted at use
7192 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7194 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7195 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7196 if(!pEnchant) continue;
7197 for (int s=0;s<3;s++)
7199 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
7200 continue;
7202 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7203 if (!spellInfo)
7205 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7206 continue;
7209 Spell *spell = new Spell(this, spellInfo, (count > 0));
7210 spell->m_CastItem = item;
7211 spell->m_cast_count = cast_count; // set count of casts
7212 spell->m_glyphIndex = glyphIndex; // glyph index
7213 spell->prepare(&targets);
7215 ++count;
7220 void Player::_RemoveAllItemMods()
7222 sLog.outDebug("_RemoveAllItemMods start.");
7224 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7226 if(m_items[i])
7228 ItemPrototype const *proto = m_items[i]->GetProto();
7229 if(!proto)
7230 continue;
7232 // item set bonuses not dependent from item broken state
7233 if(proto->ItemSet)
7234 RemoveItemsSetItem(this,proto);
7236 if(m_items[i]->IsBroken())
7237 continue;
7239 ApplyItemEquipSpell(m_items[i],false);
7240 ApplyEnchantment(m_items[i], false);
7244 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7246 if(m_items[i])
7248 if(m_items[i]->IsBroken())
7249 continue;
7250 ItemPrototype const *proto = m_items[i]->GetProto();
7251 if(!proto)
7252 continue;
7254 uint32 attacktype = Player::GetAttackBySlot(i);
7255 if(attacktype < MAX_ATTACK)
7256 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7258 _ApplyItemBonuses(proto,i, false);
7260 if( i == EQUIPMENT_SLOT_RANGED )
7261 _ApplyAmmoBonuses();
7265 sLog.outDebug("_RemoveAllItemMods complete.");
7268 void Player::_ApplyAllItemMods()
7270 sLog.outDebug("_ApplyAllItemMods start.");
7272 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7274 if(m_items[i])
7276 if(m_items[i]->IsBroken())
7277 continue;
7279 ItemPrototype const *proto = m_items[i]->GetProto();
7280 if(!proto)
7281 continue;
7283 uint32 attacktype = Player::GetAttackBySlot(i);
7284 if(attacktype < MAX_ATTACK)
7285 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7287 _ApplyItemBonuses(proto,i, true);
7289 if( i == EQUIPMENT_SLOT_RANGED )
7290 _ApplyAmmoBonuses();
7294 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7296 if(m_items[i])
7298 ItemPrototype const *proto = m_items[i]->GetProto();
7299 if(!proto)
7300 continue;
7302 // item set bonuses not dependent from item broken state
7303 if(proto->ItemSet)
7304 AddItemsSetItem(this,m_items[i]);
7306 if(m_items[i]->IsBroken())
7307 continue;
7309 ApplyItemEquipSpell(m_items[i],true);
7310 ApplyEnchantment(m_items[i], true);
7314 sLog.outDebug("_ApplyAllItemMods complete.");
7317 void Player::_ApplyAllLevelScaleItemMods(bool apply)
7319 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7321 if(m_items[i])
7323 if(m_items[i]->IsBroken())
7324 continue;
7326 ItemPrototype const *proto = m_items[i]->GetProto();
7327 if(!proto)
7328 continue;
7330 _ApplyItemBonuses(proto,i, apply, true);
7335 void Player::_ApplyAmmoBonuses()
7337 // check ammo
7338 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7339 if(!ammo_id)
7340 return;
7342 float currentAmmoDPS;
7344 ItemPrototype const *ammo_proto = ObjectMgr::GetItemPrototype( ammo_id );
7345 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7346 currentAmmoDPS = 0.0f;
7347 else
7348 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7350 if(currentAmmoDPS == GetAmmoDPS())
7351 return;
7353 m_ammoDPS = currentAmmoDPS;
7355 if(CanModifyStats())
7356 UpdateDamagePhysical(RANGED_ATTACK);
7359 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7361 if(!ammo_proto)
7362 return false;
7364 // check ranged weapon
7365 Item *weapon = GetWeaponForAttack( RANGED_ATTACK, true, false );
7366 if (!weapon)
7367 return false;
7369 ItemPrototype const* weapon_proto = weapon->GetProto();
7370 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7371 return false;
7373 // check ammo ws. weapon compatibility
7374 switch(weapon_proto->SubClass)
7376 case ITEM_SUBCLASS_WEAPON_BOW:
7377 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7378 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7379 return false;
7380 break;
7381 case ITEM_SUBCLASS_WEAPON_GUN:
7382 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7383 return false;
7384 break;
7385 default:
7386 return false;
7389 return true;
7392 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7393 Called by remove insignia spell effect */
7394 void Player::RemovedInsignia(Player* looterPlr)
7396 if (!GetBattleGroundId())
7397 return;
7399 // If not released spirit, do it !
7400 if(m_deathTimer > 0)
7402 m_deathTimer = 0;
7403 BuildPlayerRepop();
7404 RepopAtGraveyard();
7407 Corpse *corpse = GetCorpse();
7408 if (!corpse)
7409 return;
7411 // We have to convert player corpse to bones, not to be able to resurrect there
7412 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7413 Corpse *bones = sObjectAccessor.ConvertCorpseForPlayer(GetGUID(),true);
7414 if (!bones)
7415 return;
7417 // Now we must make bones lootable, and send player loot
7418 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7420 // We store the level of our player in the gold field
7421 // We retrieve this information at Player::SendLoot()
7422 bones->loot.gold = getLevel();
7423 bones->lootRecipient = looterPlr;
7424 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7427 void Player::SendLootRelease( uint64 guid )
7429 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7430 data << uint64(guid) << uint8(1);
7431 SendDirectMessage( &data );
7434 void Player::SendLoot(uint64 guid, LootType loot_type)
7436 if (uint64 lguid = GetLootGUID())
7437 m_session->DoLootRelease(lguid);
7439 Loot *loot = 0;
7440 PermissionTypes permission = ALL_PERMISSION;
7442 sLog.outDebug("Player::SendLoot");
7443 if (IS_GAMEOBJECT_GUID(guid))
7445 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7446 GameObject *go = GetMap()->GetGameObject(guid);
7448 // not check distance for GO in case owned GO (fishing bobber case, for example)
7449 // And permit out of range GO with no owner in case fishing hole
7450 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7452 SendLootRelease(guid);
7453 return;
7456 loot = &go->loot;
7458 if (go->getLootState() == GO_READY)
7460 uint32 lootid = go->GetGOInfo()->GetLootId();
7461 if ((go->GetEntry() == BG_AV_OBJECTID_MINE_N || go->GetEntry() == BG_AV_OBJECTID_MINE_S))
7462 if (BattleGround *bg = GetBattleGround())
7463 if (bg->GetTypeID() == BATTLEGROUND_AV)
7464 if (!(((BattleGroundAV*)bg)->PlayerCanDoMineQuest(go->GetEntry(), GetTeam())))
7466 SendLootRelease(guid);
7467 return;
7470 if (lootid)
7472 sLog.outDebug(" if(lootid)");
7473 loot->clear();
7474 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7477 if (loot_type == LOOT_FISHING)
7478 go->getFishLoot(loot,this);
7480 go->SetLootState(GO_ACTIVATED);
7483 else if (IS_ITEM_GUID(guid))
7485 Item *item = GetItemByGuid( guid );
7487 if (!item)
7489 SendLootRelease(guid);
7490 return;
7493 loot = &item->loot;
7495 if (!item->m_lootGenerated)
7497 item->m_lootGenerated = true;
7498 loot->clear();
7500 switch(loot_type)
7502 case LOOT_DISENCHANTING:
7503 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7504 break;
7505 case LOOT_PROSPECTING:
7506 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7507 break;
7508 case LOOT_MILLING:
7509 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7510 break;
7511 default:
7512 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7513 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7514 break;
7518 else if (IS_CORPSE_GUID(guid)) // remove insignia
7520 Corpse *bones = GetMap()->GetCorpse(guid);
7522 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7524 SendLootRelease(guid);
7525 return;
7528 loot = &bones->loot;
7530 if (!bones->lootForBody)
7532 bones->lootForBody = true;
7533 uint32 pLevel = bones->loot.gold;
7534 bones->loot.clear();
7535 if (GetBattleGround()->GetTypeID() == BATTLEGROUND_AV)
7536 loot->FillLoot(0, LootTemplates_Creature, this, false);
7537 // It may need a better formula
7538 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7539 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7542 if (bones->lootRecipient != this)
7543 permission = NONE_PERMISSION;
7545 else
7547 Creature *creature = GetMap()->GetCreature(guid);
7549 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7550 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7552 SendLootRelease(guid);
7553 return;
7556 if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7558 SendLootRelease(guid);
7559 return;
7562 loot = &creature->loot;
7564 if (loot_type == LOOT_PICKPOCKETING)
7566 if (!creature->lootForPickPocketed)
7568 creature->lootForPickPocketed = true;
7569 loot->clear();
7571 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7572 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7574 // Generate extra money for pick pocket loot
7575 const uint32 a = urand(0, creature->getLevel()/2);
7576 const uint32 b = urand(0, getLevel()/2);
7577 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7580 else
7582 // the player whose group may loot the corpse
7583 Player *recipient = creature->GetLootRecipient();
7584 if (!recipient)
7586 creature->SetLootRecipient(this);
7587 recipient = this;
7590 if (creature->lootForPickPocketed)
7592 creature->lootForPickPocketed = false;
7593 loot->clear();
7596 if (!creature->lootForBody)
7598 creature->lootForBody = true;
7599 loot->clear();
7601 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7602 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7604 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7606 if (Group* group = recipient->GetGroup())
7608 group->UpdateLooterGuid(creature,true);
7610 switch (group->GetLootMethod())
7612 case GROUP_LOOT:
7613 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7614 group->GroupLoot(recipient->GetGUID(), loot, creature);
7615 break;
7616 case NEED_BEFORE_GREED:
7617 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7618 break;
7619 case MASTER_LOOT:
7620 group->MasterLoot(recipient->GetGUID(), loot, creature);
7621 break;
7622 default:
7623 break;
7628 // possible only if creature->lootForBody && loot->empty() at spell cast check
7629 if (loot_type == LOOT_SKINNING)
7631 loot->clear();
7632 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7634 // set group rights only for loot_type != LOOT_SKINNING
7635 else
7637 if(Group* group = GetGroup())
7639 if (group == recipient->GetGroup())
7641 if (group->GetLootMethod() == FREE_FOR_ALL)
7642 permission = ALL_PERMISSION;
7643 else if (group->GetLooterGuid() == GetGUID())
7645 if (group->GetLootMethod() == MASTER_LOOT)
7646 permission = MASTER_PERMISSION;
7647 else
7648 permission = ALL_PERMISSION;
7650 else
7651 permission = GROUP_PERMISSION;
7653 else
7654 permission = NONE_PERMISSION;
7656 else if (recipient == this)
7657 permission = ALL_PERMISSION;
7658 else
7659 permission = NONE_PERMISSION;
7664 SetLootGUID(guid);
7666 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7667 switch(loot_type)
7669 case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
7670 case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
7671 default: break;
7674 // need know merged fishing/corpse loot type for achievements
7675 loot->loot_type = loot_type;
7677 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7679 data << uint64(guid);
7680 data << uint8(loot_type);
7681 data << LootView(*loot, this, permission);
7683 SendDirectMessage(&data);
7685 // add 'this' player as one of the players that are looting 'loot'
7686 if (permission != NONE_PERMISSION)
7687 loot->AddLooter(GetGUID());
7689 if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
7690 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7693 void Player::SendNotifyLootMoneyRemoved()
7695 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7696 GetSession()->SendPacket( &data );
7699 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7701 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7702 data << uint8(lootSlot);
7703 GetSession()->SendPacket( &data );
7706 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7708 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7709 data << Field;
7710 data << Value;
7711 GetSession()->SendPacket(&data);
7714 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7716 // data depends on zoneid/mapid...
7717 BattleGround* bg = GetBattleGround();
7718 uint16 NumberOfFields = 0;
7719 uint32 mapid = GetMapId();
7721 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7723 // may be exist better way to do this...
7724 switch(zoneid)
7726 case 0:
7727 case 1:
7728 case 4:
7729 case 8:
7730 case 10:
7731 case 11:
7732 case 12:
7733 case 36:
7734 case 38:
7735 case 40:
7736 case 41:
7737 case 51:
7738 case 267:
7739 case 1519:
7740 case 1537:
7741 case 2257:
7742 case 2918:
7743 NumberOfFields = 8;
7744 break;
7745 case 139:
7746 NumberOfFields = 41;
7747 break;
7748 case 1377:
7749 NumberOfFields = 15;
7750 break;
7751 case 2597:
7752 NumberOfFields = 83;
7753 break;
7754 case 3277:
7755 NumberOfFields = 16;
7756 break;
7757 case 3358:
7758 case 3820:
7759 NumberOfFields = 40;
7760 break;
7761 case 3483:
7762 NumberOfFields = 27;
7763 break;
7764 case 3518:
7765 NumberOfFields = 39;
7766 break;
7767 case 3519:
7768 NumberOfFields = 38;
7769 break;
7770 case 3521:
7771 NumberOfFields = 37;
7772 break;
7773 case 3698:
7774 case 3702:
7775 case 3968:
7776 NumberOfFields = 11;
7777 break;
7778 case 3703:
7779 NumberOfFields = 11;
7780 break;
7781 default:
7782 NumberOfFields = 12;
7783 break;
7786 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7787 data << uint32(mapid); // mapid
7788 data << uint32(zoneid); // zone id
7789 data << uint32(areaid); // area id, new 2.1.0
7790 data << uint16(NumberOfFields); // count of uint64 blocks
7791 data << uint32(0x8d8) << uint32(0x0); // 1
7792 data << uint32(0x8d7) << uint32(0x0); // 2
7793 data << uint32(0x8d6) << uint32(0x0); // 3
7794 data << uint32(0x8d5) << uint32(0x0); // 4
7795 data << uint32(0x8d4) << uint32(0x0); // 5
7796 data << uint32(0x8d3) << uint32(0x0); // 6
7797 // 7 1 - Arena season in progress, 0 - end of season
7798 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7799 // 8 Arena season id
7800 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7801 if(mapid == 530) // Outland
7803 data << uint32(0x9bf) << uint32(0x0); // 7
7804 data << uint32(0x9bd) << uint32(0xF); // 8
7805 data << uint32(0x9bb) << uint32(0xF); // 9
7807 switch(zoneid)
7809 case 1:
7810 case 11:
7811 case 12:
7812 case 38:
7813 case 40:
7814 case 51:
7815 case 1519:
7816 case 1537:
7817 case 2257:
7818 break;
7819 case 2597: // AV
7820 if (bg && bg->GetTypeID() == BATTLEGROUND_AV)
7821 bg->FillInitialWorldStates(data);
7822 else
7824 data << uint32(0x7ae) << uint32(0x1); // 7 snowfall n
7825 data << uint32(0x532) << uint32(0x1); // 8 frostwolfhut hc
7826 data << uint32(0x531) << uint32(0x0); // 9 frostwolfhut ac
7827 data << uint32(0x52e) << uint32(0x0); // 10 stormpike firstaid a_a
7828 data << uint32(0x571) << uint32(0x0); // 11 east frostwolf tower horde assaulted -unused
7829 data << uint32(0x570) << uint32(0x0); // 12 west frostwolf tower horde assaulted - unused
7830 data << uint32(0x567) << uint32(0x1); // 13 frostwolfe c
7831 data << uint32(0x566) << uint32(0x1); // 14 frostwolfw c
7832 data << uint32(0x550) << uint32(0x1); // 15 irondeep (N) ally
7833 data << uint32(0x544) << uint32(0x0); // 16 ice grave a_a
7834 data << uint32(0x536) << uint32(0x0); // 17 stormpike grave h_c
7835 data << uint32(0x535) << uint32(0x1); // 18 stormpike grave a_c
7836 data << uint32(0x518) << uint32(0x0); // 19 stoneheart grave a_a
7837 data << uint32(0x517) << uint32(0x0); // 20 stoneheart grave h_a
7838 data << uint32(0x574) << uint32(0x0); // 21 1396 unk
7839 data << uint32(0x573) << uint32(0x0); // 22 iceblood tower horde assaulted -unused
7840 data << uint32(0x572) << uint32(0x0); // 23 towerpoint horde assaulted - unused
7841 data << uint32(0x56f) << uint32(0x0); // 24 1391 unk
7842 data << uint32(0x56e) << uint32(0x0); // 25 iceblood a
7843 data << uint32(0x56d) << uint32(0x0); // 26 towerp a
7844 data << uint32(0x56c) << uint32(0x0); // 27 frostwolfe a
7845 data << uint32(0x56b) << uint32(0x0); // 28 froswolfw a
7846 data << uint32(0x56a) << uint32(0x1); // 29 1386 unk
7847 data << uint32(0x569) << uint32(0x1); // 30 iceblood c
7848 data << uint32(0x568) << uint32(0x1); // 31 towerp c
7849 data << uint32(0x565) << uint32(0x0); // 32 stoneh tower a
7850 data << uint32(0x564) << uint32(0x0); // 33 icewing tower a
7851 data << uint32(0x563) << uint32(0x0); // 34 dunn a
7852 data << uint32(0x562) << uint32(0x0); // 35 duns a
7853 data << uint32(0x561) << uint32(0x0); // 36 stoneheart bunker alliance assaulted - unused
7854 data << uint32(0x560) << uint32(0x0); // 37 icewing bunker alliance assaulted - unused
7855 data << uint32(0x55f) << uint32(0x0); // 38 dunbaldar south alliance assaulted - unused
7856 data << uint32(0x55e) << uint32(0x0); // 39 dunbaldar north alliance assaulted - unused
7857 data << uint32(0x55d) << uint32(0x0); // 40 stone tower d
7858 data << uint32(0x3c6) << uint32(0x0); // 41 966 unk
7859 data << uint32(0x3c4) << uint32(0x0); // 42 964 unk
7860 data << uint32(0x3c2) << uint32(0x0); // 43 962 unk
7861 data << uint32(0x516) << uint32(0x1); // 44 stoneheart grave a_c
7862 data << uint32(0x515) << uint32(0x0); // 45 stonheart grave h_c
7863 data << uint32(0x3b6) << uint32(0x0); // 46 950 unk
7864 data << uint32(0x55c) << uint32(0x0); // 47 icewing tower d
7865 data << uint32(0x55b) << uint32(0x0); // 48 dunn d
7866 data << uint32(0x55a) << uint32(0x0); // 49 duns d
7867 data << uint32(0x559) << uint32(0x0); // 50 1369 unk
7868 data << uint32(0x558) << uint32(0x0); // 51 iceblood d
7869 data << uint32(0x557) << uint32(0x0); // 52 towerp d
7870 data << uint32(0x556) << uint32(0x0); // 53 frostwolfe d
7871 data << uint32(0x555) << uint32(0x0); // 54 frostwolfw d
7872 data << uint32(0x554) << uint32(0x1); // 55 stoneh tower c
7873 data << uint32(0x553) << uint32(0x1); // 56 icewing tower c
7874 data << uint32(0x552) << uint32(0x1); // 57 dunn c
7875 data << uint32(0x551) << uint32(0x1); // 58 duns c
7876 data << uint32(0x54f) << uint32(0x0); // 59 irondeep (N) horde
7877 data << uint32(0x54e) << uint32(0x0); // 60 irondeep (N) ally
7878 data << uint32(0x54d) << uint32(0x1); // 61 mine (S) neutral
7879 data << uint32(0x54c) << uint32(0x0); // 62 mine (S) horde
7880 data << uint32(0x54b) << uint32(0x0); // 63 mine (S) ally
7881 data << uint32(0x545) << uint32(0x0); // 64 iceblood h_a
7882 data << uint32(0x543) << uint32(0x1); // 65 iceblod h_c
7883 data << uint32(0x542) << uint32(0x0); // 66 iceblood a_c
7884 data << uint32(0x540) << uint32(0x0); // 67 snowfall h_a
7885 data << uint32(0x53f) << uint32(0x0); // 68 snowfall a_a
7886 data << uint32(0x53e) << uint32(0x0); // 69 snowfall h_c
7887 data << uint32(0x53d) << uint32(0x0); // 70 snowfall a_c
7888 data << uint32(0x53c) << uint32(0x0); // 71 frostwolf g h_a
7889 data << uint32(0x53b) << uint32(0x0); // 72 frostwolf g a_a
7890 data << uint32(0x53a) << uint32(0x1); // 73 frostwolf g h_c
7891 data << uint32(0x539) << uint32(0x0); // 74 frostwolf g a_c
7892 data << uint32(0x538) << uint32(0x0); // 75 stormpike grave h_a
7893 data << uint32(0x537) << uint32(0x0); // 76 stormpike grave a_a
7894 data << uint32(0x534) << uint32(0x0); // 77 frostwolf hut h_a
7895 data << uint32(0x533) << uint32(0x0); // 78 frostwolf hut a_a
7896 data << uint32(0x530) << uint32(0x0); // 79 stormpike first aid h_a
7897 data << uint32(0x52f) << uint32(0x0); // 80 stormpike first aid h_c
7898 data << uint32(0x52d) << uint32(0x1); // 81 stormpike first aid a_c
7900 break;
7901 case 3277: // WS
7902 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7903 bg->FillInitialWorldStates(data);
7904 else
7906 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7907 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7908 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7909 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7910 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7911 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7912 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7913 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7915 break;
7916 case 3358: // AB
7917 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7918 bg->FillInitialWorldStates(data);
7919 else
7921 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7922 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7923 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7924 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7925 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7926 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7927 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7928 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7929 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7930 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7931 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7932 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7933 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7934 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7935 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7936 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7937 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7938 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7939 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7940 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7941 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7942 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7943 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7944 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7945 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7946 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7947 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7948 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7949 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7950 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7951 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7952 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7954 break;
7955 case 3820: // EY
7956 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7957 bg->FillInitialWorldStates(data);
7958 else
7960 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7961 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7962 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7963 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7964 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7965 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7966 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7967 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7968 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7969 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7970 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7971 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7972 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7973 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7974 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7975 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7976 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7977 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7978 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7979 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7980 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7981 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7982 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7983 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7984 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7985 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7986 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7987 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7988 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7989 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7990 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7991 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7992 // and some more ... unknown
7994 break;
7995 case 3483: // Hellfire Peninsula
7996 data << uint32(0x9ba) << uint32(0x1); // 10
7997 data << uint32(0x9b9) << uint32(0x1); // 11
7998 data << uint32(0x9b5) << uint32(0x0); // 12
7999 data << uint32(0x9b4) << uint32(0x1); // 13
8000 data << uint32(0x9b3) << uint32(0x0); // 14
8001 data << uint32(0x9b2) << uint32(0x0); // 15
8002 data << uint32(0x9b1) << uint32(0x1); // 16
8003 data << uint32(0x9b0) << uint32(0x0); // 17
8004 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
8005 data << uint32(0x9ac) << uint32(0x0); // 19
8006 data << uint32(0x9a8) << uint32(0x0); // 20
8007 data << uint32(0x9a7) << uint32(0x0); // 21
8008 data << uint32(0x9a6) << uint32(0x1); // 22
8009 break;
8010 case 3519: // Terokkar Forest
8011 data << uint32(0xa41) << uint32(0x0); // 10
8012 data << uint32(0xa40) << uint32(0x14); // 11
8013 data << uint32(0xa3f) << uint32(0x0); // 12
8014 data << uint32(0xa3e) << uint32(0x0); // 13
8015 data << uint32(0xa3d) << uint32(0x5); // 14
8016 data << uint32(0xa3c) << uint32(0x0); // 15
8017 data << uint32(0xa87) << uint32(0x0); // 16
8018 data << uint32(0xa86) << uint32(0x0); // 17
8019 data << uint32(0xa85) << uint32(0x0); // 18
8020 data << uint32(0xa84) << uint32(0x0); // 19
8021 data << uint32(0xa83) << uint32(0x0); // 20
8022 data << uint32(0xa82) << uint32(0x0); // 21
8023 data << uint32(0xa81) << uint32(0x0); // 22
8024 data << uint32(0xa80) << uint32(0x0); // 23
8025 data << uint32(0xa7e) << uint32(0x0); // 24
8026 data << uint32(0xa7d) << uint32(0x0); // 25
8027 data << uint32(0xa7c) << uint32(0x0); // 26
8028 data << uint32(0xa7b) << uint32(0x0); // 27
8029 data << uint32(0xa7a) << uint32(0x0); // 28
8030 data << uint32(0xa79) << uint32(0x0); // 29
8031 data << uint32(0x9d0) << uint32(0x5); // 30
8032 data << uint32(0x9ce) << uint32(0x0); // 31
8033 data << uint32(0x9cd) << uint32(0x0); // 32
8034 data << uint32(0x9cc) << uint32(0x0); // 33
8035 data << uint32(0xa88) << uint32(0x0); // 34
8036 data << uint32(0xad0) << uint32(0x0); // 35
8037 data << uint32(0xacf) << uint32(0x1); // 36
8038 break;
8039 case 3521: // Zangarmarsh
8040 data << uint32(0x9e1) << uint32(0x0); // 10
8041 data << uint32(0x9e0) << uint32(0x0); // 11
8042 data << uint32(0x9df) << uint32(0x0); // 12
8043 data << uint32(0xa5d) << uint32(0x1); // 13
8044 data << uint32(0xa5c) << uint32(0x0); // 14
8045 data << uint32(0xa5b) << uint32(0x1); // 15
8046 data << uint32(0xa5a) << uint32(0x0); // 16
8047 data << uint32(0xa59) << uint32(0x1); // 17
8048 data << uint32(0xa58) << uint32(0x0); // 18
8049 data << uint32(0xa57) << uint32(0x0); // 19
8050 data << uint32(0xa56) << uint32(0x0); // 20
8051 data << uint32(0xa55) << uint32(0x1); // 21
8052 data << uint32(0xa54) << uint32(0x0); // 22
8053 data << uint32(0x9e7) << uint32(0x0); // 23
8054 data << uint32(0x9e6) << uint32(0x0); // 24
8055 data << uint32(0x9e5) << uint32(0x0); // 25
8056 data << uint32(0xa00) << uint32(0x0); // 26
8057 data << uint32(0x9ff) << uint32(0x1); // 27
8058 data << uint32(0x9fe) << uint32(0x0); // 28
8059 data << uint32(0x9fd) << uint32(0x0); // 29
8060 data << uint32(0x9fc) << uint32(0x1); // 30
8061 data << uint32(0x9fb) << uint32(0x0); // 31
8062 data << uint32(0xa62) << uint32(0x0); // 32
8063 data << uint32(0xa61) << uint32(0x1); // 33
8064 data << uint32(0xa60) << uint32(0x1); // 34
8065 data << uint32(0xa5f) << uint32(0x0); // 35
8066 break;
8067 case 3698: // Nagrand Arena
8068 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
8069 bg->FillInitialWorldStates(data);
8070 else
8072 data << uint32(0xa0f) << uint32(0x0); // 7
8073 data << uint32(0xa10) << uint32(0x0); // 8
8074 data << uint32(0xa11) << uint32(0x0); // 9 show
8076 break;
8077 case 3702: // Blade's Edge Arena
8078 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
8079 bg->FillInitialWorldStates(data);
8080 else
8082 data << uint32(0x9f0) << uint32(0x0); // 7 gold
8083 data << uint32(0x9f1) << uint32(0x0); // 8 green
8084 data << uint32(0x9f3) << uint32(0x0); // 9 show
8086 break;
8087 case 3968: // Ruins of Lordaeron
8088 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
8089 bg->FillInitialWorldStates(data);
8090 else
8092 data << uint32(0xbb8) << uint32(0x0); // 7 gold
8093 data << uint32(0xbb9) << uint32(0x0); // 8 green
8094 data << uint32(0xbba) << uint32(0x0); // 9 show
8096 break;
8097 case 3703: // Shattrath City
8098 break;
8099 default:
8100 data << uint32(0x914) << uint32(0x0); // 7
8101 data << uint32(0x913) << uint32(0x0); // 8
8102 data << uint32(0x912) << uint32(0x0); // 9
8103 data << uint32(0x915) << uint32(0x0); // 10
8104 break;
8106 GetSession()->SendPacket(&data);
8109 uint32 Player::GetXPRestBonus(uint32 xp)
8111 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
8113 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
8114 rested_bonus = xp;
8116 SetRestBonus( GetRestBonus() - rested_bonus);
8118 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
8119 return rested_bonus;
8122 void Player::SetBindPoint(uint64 guid)
8124 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
8125 data << uint64(guid);
8126 GetSession()->SendPacket( &data );
8129 void Player::SendTalentWipeConfirm(uint64 guid)
8131 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
8132 data << uint64(guid);
8133 data << uint32(resetTalentsCost());
8134 GetSession()->SendPacket( &data );
8137 void Player::SendPetSkillWipeConfirm()
8139 Pet* pet = GetPet();
8140 if(!pet)
8141 return;
8142 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
8143 data << pet->GetGUID();
8144 data << uint32(pet->resetTalentsCost());
8145 GetSession()->SendPacket( &data );
8148 /*********************************************************/
8149 /*** STORAGE SYSTEM ***/
8150 /*********************************************************/
8152 void Player::SetVirtualItemSlot( uint8 i, Item* item)
8154 assert(i < 3);
8155 if(i < 2 && item)
8157 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
8158 return;
8159 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
8160 if(charges == 0)
8161 return;
8162 if(charges > 1)
8163 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
8164 else if(charges <= 1)
8166 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
8167 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
8172 void Player::SetSheath( SheathState sheathed )
8174 switch (sheathed)
8176 case SHEATH_STATE_UNARMED: // no prepared weapon
8177 SetVirtualItemSlot(0,NULL);
8178 SetVirtualItemSlot(1,NULL);
8179 SetVirtualItemSlot(2,NULL);
8180 break;
8181 case SHEATH_STATE_MELEE: // prepared melee weapon
8183 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true,true));
8184 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true,true));
8185 SetVirtualItemSlot(2,NULL);
8186 }; break;
8187 case SHEATH_STATE_RANGED: // prepared ranged weapon
8188 SetVirtualItemSlot(0,NULL);
8189 SetVirtualItemSlot(1,NULL);
8190 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true,true));
8191 break;
8192 default:
8193 SetVirtualItemSlot(0,NULL);
8194 SetVirtualItemSlot(1,NULL);
8195 SetVirtualItemSlot(2,NULL);
8196 break;
8198 Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
8201 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
8203 uint8 pClass = getClass();
8205 uint8 slots[4];
8206 slots[0] = NULL_SLOT;
8207 slots[1] = NULL_SLOT;
8208 slots[2] = NULL_SLOT;
8209 slots[3] = NULL_SLOT;
8210 switch( proto->InventoryType )
8212 case INVTYPE_HEAD:
8213 slots[0] = EQUIPMENT_SLOT_HEAD;
8214 break;
8215 case INVTYPE_NECK:
8216 slots[0] = EQUIPMENT_SLOT_NECK;
8217 break;
8218 case INVTYPE_SHOULDERS:
8219 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
8220 break;
8221 case INVTYPE_BODY:
8222 slots[0] = EQUIPMENT_SLOT_BODY;
8223 break;
8224 case INVTYPE_CHEST:
8225 slots[0] = EQUIPMENT_SLOT_CHEST;
8226 break;
8227 case INVTYPE_ROBE:
8228 slots[0] = EQUIPMENT_SLOT_CHEST;
8229 break;
8230 case INVTYPE_WAIST:
8231 slots[0] = EQUIPMENT_SLOT_WAIST;
8232 break;
8233 case INVTYPE_LEGS:
8234 slots[0] = EQUIPMENT_SLOT_LEGS;
8235 break;
8236 case INVTYPE_FEET:
8237 slots[0] = EQUIPMENT_SLOT_FEET;
8238 break;
8239 case INVTYPE_WRISTS:
8240 slots[0] = EQUIPMENT_SLOT_WRISTS;
8241 break;
8242 case INVTYPE_HANDS:
8243 slots[0] = EQUIPMENT_SLOT_HANDS;
8244 break;
8245 case INVTYPE_FINGER:
8246 slots[0] = EQUIPMENT_SLOT_FINGER1;
8247 slots[1] = EQUIPMENT_SLOT_FINGER2;
8248 break;
8249 case INVTYPE_TRINKET:
8250 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8251 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8252 break;
8253 case INVTYPE_CLOAK:
8254 slots[0] = EQUIPMENT_SLOT_BACK;
8255 break;
8256 case INVTYPE_WEAPON:
8258 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8260 // suggest offhand slot only if know dual wielding
8261 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8262 if(CanDualWield())
8263 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8264 break;
8266 case INVTYPE_SHIELD:
8267 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8268 break;
8269 case INVTYPE_RANGED:
8270 slots[0] = EQUIPMENT_SLOT_RANGED;
8271 break;
8272 case INVTYPE_2HWEAPON:
8273 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8274 if (CanDualWield() && CanTitanGrip())
8275 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8276 break;
8277 case INVTYPE_TABARD:
8278 slots[0] = EQUIPMENT_SLOT_TABARD;
8279 break;
8280 case INVTYPE_WEAPONMAINHAND:
8281 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8282 break;
8283 case INVTYPE_WEAPONOFFHAND:
8284 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8285 break;
8286 case INVTYPE_HOLDABLE:
8287 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8288 break;
8289 case INVTYPE_THROWN:
8290 slots[0] = EQUIPMENT_SLOT_RANGED;
8291 break;
8292 case INVTYPE_RANGEDRIGHT:
8293 slots[0] = EQUIPMENT_SLOT_RANGED;
8294 break;
8295 case INVTYPE_BAG:
8296 slots[0] = INVENTORY_SLOT_BAG_START + 0;
8297 slots[1] = INVENTORY_SLOT_BAG_START + 1;
8298 slots[2] = INVENTORY_SLOT_BAG_START + 2;
8299 slots[3] = INVENTORY_SLOT_BAG_START + 3;
8300 break;
8301 case INVTYPE_RELIC:
8303 switch(proto->SubClass)
8305 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8306 if (pClass == CLASS_PALADIN)
8307 slots[0] = EQUIPMENT_SLOT_RANGED;
8308 break;
8309 case ITEM_SUBCLASS_ARMOR_IDOL:
8310 if (pClass == CLASS_DRUID)
8311 slots[0] = EQUIPMENT_SLOT_RANGED;
8312 break;
8313 case ITEM_SUBCLASS_ARMOR_TOTEM:
8314 if (pClass == CLASS_SHAMAN)
8315 slots[0] = EQUIPMENT_SLOT_RANGED;
8316 break;
8317 case ITEM_SUBCLASS_ARMOR_MISC:
8318 if (pClass == CLASS_WARLOCK)
8319 slots[0] = EQUIPMENT_SLOT_RANGED;
8320 break;
8321 case ITEM_SUBCLASS_ARMOR_SIGIL:
8322 if (pClass == CLASS_DEATH_KNIGHT)
8323 slots[0] = EQUIPMENT_SLOT_RANGED;
8324 break;
8326 break;
8328 default :
8329 return NULL_SLOT;
8332 if( slot != NULL_SLOT )
8334 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8336 for (int i = 0; i < 4; ++i)
8338 if ( slots[i] == slot )
8339 return slot;
8343 else
8345 // search free slot at first
8346 for (int i = 0; i < 4; ++i)
8348 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8350 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8351 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8352 return slots[i];
8356 // if not found free and can swap return first appropriate from used
8357 for (int i = 0; i < 4; ++i)
8359 if ( slots[i] != NULL_SLOT && swap )
8360 return slots[i];
8364 // no free position
8365 return NULL_SLOT;
8368 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8370 Item *pItem;
8371 uint32 tempcount = 0;
8373 uint8 res = EQUIP_ERR_OK;
8375 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
8377 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8378 if( pItem && pItem->GetEntry() == item )
8380 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8381 if(ires==EQUIP_ERR_OK)
8383 tempcount += pItem->GetCount();
8384 if( tempcount >= count )
8385 return EQUIP_ERR_OK;
8387 else
8388 res = ires;
8391 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8393 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8394 if( pItem && pItem->GetEntry() == item )
8396 tempcount += pItem->GetCount();
8397 if( tempcount >= count )
8398 return EQUIP_ERR_OK;
8401 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8403 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8404 if( pItem && pItem->GetEntry() == item )
8406 tempcount += pItem->GetCount();
8407 if( tempcount >= count )
8408 return EQUIP_ERR_OK;
8411 Bag *pBag;
8412 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8414 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8415 if( pBag )
8417 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8419 pItem = GetItemByPos( i, j );
8420 if( pItem && pItem->GetEntry() == item )
8422 tempcount += pItem->GetCount();
8423 if( tempcount >= count )
8424 return EQUIP_ERR_OK;
8430 // not found req. item count and have unequippable items
8431 return res;
8434 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8436 uint32 count = 0;
8437 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8439 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8440 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8441 count += pItem->GetCount();
8443 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8445 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8446 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8447 count += pItem->GetCount();
8449 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8451 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8452 if( pBag )
8453 count += pBag->GetItemCount(item,skipItem);
8456 if(skipItem && skipItem->GetProto()->GemProperties)
8458 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8460 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8461 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8462 count += pItem->GetGemCountWithID(item);
8466 if(inBankAlso)
8468 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8470 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8471 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8472 count += pItem->GetCount();
8474 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8476 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8477 if( pBag )
8478 count += pBag->GetItemCount(item,skipItem);
8481 if(skipItem && skipItem->GetProto()->GemProperties)
8483 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8485 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8486 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8487 count += pItem->GetGemCountWithID(item);
8492 return count;
8495 Item* Player::GetItemByGuid( uint64 guid ) const
8497 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8499 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8500 if( pItem && pItem->GetGUID() == guid )
8501 return pItem;
8503 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8505 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8506 if( pItem && pItem->GetGUID() == guid )
8507 return pItem;
8510 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8512 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8513 if( pBag )
8515 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8517 Item* pItem = pBag->GetItemByPos( j );
8518 if( pItem && pItem->GetGUID() == guid )
8519 return pItem;
8523 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8525 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8526 if( pBag )
8528 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8530 Item* pItem = pBag->GetItemByPos( j );
8531 if( pItem && pItem->GetGUID() == guid )
8532 return pItem;
8537 return NULL;
8540 Item* Player::GetItemByPos( uint16 pos ) const
8542 uint8 bag = pos >> 8;
8543 uint8 slot = pos & 255;
8544 return GetItemByPos( bag, slot );
8547 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8549 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || (slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END )) )
8550 return m_items[slot];
8551 else if ((bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8552 || (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END) )
8554 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8555 if ( pBag )
8556 return pBag->GetItemByPos(slot);
8558 return NULL;
8561 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool nonbroken, bool useable) const
8563 uint16 slot;
8564 switch (attackType)
8566 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8567 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8568 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8569 default: return NULL;
8572 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8573 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8574 return NULL;
8576 if (useable && !IsUseEquipedWeapon(attackType==BASE_ATTACK))
8577 return NULL;
8579 if (nonbroken && item->IsBroken())
8580 return NULL;
8582 return item;
8585 Item* Player::GetShield(bool useable) const
8587 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8588 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8589 return NULL;
8591 if(!useable)
8592 return item;
8594 if( item->IsBroken())
8595 return NULL;
8597 return item;
8600 uint32 Player::GetAttackBySlot( uint8 slot )
8602 switch(slot)
8604 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8605 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8606 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8607 default: return MAX_ATTACK;
8611 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8613 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8614 return true;
8615 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8616 return true;
8617 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8618 return true;
8619 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8620 return true;
8621 return false;
8624 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8626 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8627 return true;
8628 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8629 return true;
8630 return false;
8633 bool Player::IsBankPos( uint8 bag, uint8 slot )
8635 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8636 return true;
8637 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8638 return true;
8639 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8640 return true;
8641 return false;
8644 bool Player::IsBagPos( uint16 pos )
8646 uint8 bag = pos >> 8;
8647 uint8 slot = pos & 255;
8648 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8649 return true;
8650 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8651 return true;
8652 return false;
8655 bool Player::IsValidPos( uint8 bag, uint8 slot, bool explicit_pos )
8657 // post selected
8658 if(bag == NULL_BAG && !explicit_pos)
8659 return true;
8661 if (bag == INVENTORY_SLOT_BAG_0)
8663 // any post selected
8664 if (slot == NULL_SLOT && !explicit_pos)
8665 return true;
8667 // equipment
8668 if (slot < EQUIPMENT_SLOT_END)
8669 return true;
8671 // bag equip slots
8672 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8673 return true;
8675 // backpack slots
8676 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8677 return true;
8679 // keyring slots
8680 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8681 return true;
8683 // bank main slots
8684 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8685 return true;
8687 // bank bag slots
8688 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8689 return true;
8691 return false;
8694 // bag content slots
8695 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8697 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8698 if(!pBag)
8699 return false;
8701 // any post selected
8702 if (slot == NULL_SLOT && !explicit_pos)
8703 return true;
8705 return slot < pBag->GetBagSize();
8708 // bank bag content slots
8709 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8711 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8712 if(!pBag)
8713 return false;
8715 // any post selected
8716 if (slot == NULL_SLOT && !explicit_pos)
8717 return true;
8719 return slot < pBag->GetBagSize();
8722 // where this?
8723 return false;
8727 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8729 uint32 tempcount = 0;
8730 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8732 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8733 if( pItem && pItem->GetEntry() == item )
8735 tempcount += pItem->GetCount();
8736 if( tempcount >= count )
8737 return true;
8740 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8742 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8743 if( pItem && pItem->GetEntry() == item )
8745 tempcount += pItem->GetCount();
8746 if( tempcount >= count )
8747 return true;
8750 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8752 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8754 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8756 Item* pItem = GetItemByPos( i, j );
8757 if( pItem && pItem->GetEntry() == item )
8759 tempcount += pItem->GetCount();
8760 if( tempcount >= count )
8761 return true;
8767 if(inBankAlso)
8769 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8771 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8772 if( pItem && pItem->GetEntry() == item )
8774 tempcount += pItem->GetCount();
8775 if( tempcount >= count )
8776 return true;
8779 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8781 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8783 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8785 Item* pItem = GetItemByPos( i, j );
8786 if( pItem && pItem->GetEntry() == item )
8788 tempcount += pItem->GetCount();
8789 if( tempcount >= count )
8790 return true;
8797 return false;
8800 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8802 uint32 tempcount = 0;
8803 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8805 if(i==int(except_slot))
8806 continue;
8808 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8809 if( pItem && pItem->GetEntry() == item)
8811 tempcount += pItem->GetCount();
8812 if( tempcount >= count )
8813 return true;
8817 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(item);
8818 if (pProto && pProto->GemProperties)
8820 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8822 if(i==int(except_slot))
8823 continue;
8825 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8826 if( pItem && pItem->GetProto()->Socket[0].Color)
8828 tempcount += pItem->GetGemCountWithID(item);
8829 if( tempcount >= count )
8830 return true;
8835 return false;
8838 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8840 uint32 tempcount = 0;
8841 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8843 if(i==int(except_slot))
8844 continue;
8846 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8847 if (!pItem)
8848 continue;
8850 ItemPrototype const *pProto = pItem->GetProto();
8851 if (!pProto)
8852 continue;
8854 if (pProto->ItemLimitCategory == limitCategory)
8856 tempcount += pItem->GetCount();
8857 if( tempcount >= count )
8858 return true;
8861 if( pProto->Socket[0].Color)
8863 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8864 if( tempcount >= count )
8865 return true;
8869 return false;
8872 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8874 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry);
8875 if( !pProto )
8877 if(no_space_count)
8878 *no_space_count = count;
8879 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8882 // no maximum
8883 if(pProto->MaxCount <= 0)
8884 return EQUIP_ERR_OK;
8886 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8888 if (curcount + count > uint32(pProto->MaxCount))
8890 if(no_space_count)
8891 *no_space_count = count +curcount - pProto->MaxCount;
8892 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8895 return EQUIP_ERR_OK;
8898 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8900 Item *pItem;
8901 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8903 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8904 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8905 return true;
8907 for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8909 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8910 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8911 return true;
8913 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8915 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8917 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8919 pItem = GetItemByPos( i, j );
8920 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8921 return true;
8925 return false;
8928 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8930 Item* pItem2 = GetItemByPos( bag, slot );
8932 // ignore move item (this slot will be empty at move)
8933 if (pItem2==pSrcItem)
8934 pItem2 = NULL;
8936 uint32 need_space;
8938 // empty specific slot - check item fit to slot
8939 if (!pItem2 || swap)
8941 if (bag == INVENTORY_SLOT_BAG_0)
8943 // keyring case
8944 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8945 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8947 // currencytoken case
8948 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8949 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8951 // prevent cheating
8952 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8953 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8955 else
8957 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8958 if (!pBag)
8959 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8961 ItemPrototype const* pBagProto = pBag->GetProto();
8962 if (!pBagProto)
8963 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8965 if (slot >= pBagProto->ContainerSlots)
8966 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8968 if (!ItemCanGoIntoBag(pProto,pBagProto))
8969 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8972 // non empty stack with space
8973 need_space = pProto->GetMaxStackSize();
8975 // non empty slot, check item type
8976 else
8978 // check item type
8979 if (pItem2->GetEntry() != pProto->ItemId)
8980 return EQUIP_ERR_ITEM_CANT_STACK;
8982 // check free space
8983 if (pItem2->GetCount() >= pProto->GetMaxStackSize())
8984 return EQUIP_ERR_ITEM_CANT_STACK;
8986 // free stack space or infinity
8987 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8990 if (need_space > count)
8991 need_space = count;
8993 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8994 if (!newPosition.isContainedIn(dest))
8996 dest.push_back(newPosition);
8997 count -= need_space;
8999 return EQUIP_ERR_OK;
9002 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
9004 // skip specific bag already processed in first called _CanStoreItem_InBag
9005 if (bag==skip_bag)
9006 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9008 // skip not existed bag or self targeted bag
9009 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
9010 if (!pBag || pBag==pSrcItem)
9011 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9013 ItemPrototype const* pBagProto = pBag->GetProto();
9014 if (!pBagProto)
9015 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9017 // specialized bag mode or non-specilized
9018 if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER))
9019 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9021 if (!ItemCanGoIntoBag(pProto,pBagProto))
9022 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9024 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9026 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9027 if (j==skip_slot)
9028 continue;
9030 Item* pItem2 = GetItemByPos( bag, j );
9032 // ignore move item (this slot will be empty at move)
9033 if (pItem2 == pSrcItem)
9034 pItem2 = NULL;
9036 // if merge skip empty, if !merge skip non-empty
9037 if ((pItem2 != NULL) != merge)
9038 continue;
9040 if (pItem2)
9042 if (pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
9044 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9045 if(need_space > count)
9046 need_space = count;
9048 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
9049 if (!newPosition.isContainedIn(dest))
9051 dest.push_back(newPosition);
9052 count -= need_space;
9054 if (count==0)
9055 return EQUIP_ERR_OK;
9059 else
9061 uint32 need_space = pProto->GetMaxStackSize();
9062 if (need_space > count)
9063 need_space = count;
9065 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
9066 if (!newPosition.isContainedIn(dest))
9068 dest.push_back(newPosition);
9069 count -= need_space;
9071 if (count==0)
9072 return EQUIP_ERR_OK;
9076 return EQUIP_ERR_OK;
9079 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
9081 for(uint32 j = slot_begin; j < slot_end; ++j)
9083 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9084 if (INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
9085 continue;
9087 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
9089 // ignore move item (this slot will be empty at move)
9090 if (pItem2==pSrcItem)
9091 pItem2 = NULL;
9093 // if merge skip empty, if !merge skip non-empty
9094 if ((pItem2 != NULL) != merge)
9095 continue;
9097 if (pItem2)
9099 if (pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
9101 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9102 if (need_space > count)
9103 need_space = count;
9104 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9105 if (!newPosition.isContainedIn(dest))
9107 dest.push_back(newPosition);
9108 count -= need_space;
9110 if (count==0)
9111 return EQUIP_ERR_OK;
9115 else
9117 uint32 need_space = pProto->GetMaxStackSize();
9118 if (need_space > count)
9119 need_space = count;
9121 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9122 if (!newPosition.isContainedIn(dest))
9124 dest.push_back(newPosition);
9125 count -= need_space;
9127 if (count==0)
9128 return EQUIP_ERR_OK;
9132 return EQUIP_ERR_OK;
9135 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
9137 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
9139 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry);
9140 if (!pProto)
9142 if (no_space_count)
9143 *no_space_count = count;
9144 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
9147 if (pItem && pItem->IsBindedNotWith(this))
9149 if (no_space_count)
9150 *no_space_count = count;
9151 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9154 // check count of items (skip for auto move for same player from bank)
9155 uint32 no_similar_count = 0; // can't store this amount similar items
9156 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
9157 if (res!=EQUIP_ERR_OK)
9159 if (count==no_similar_count)
9161 if (no_space_count)
9162 *no_space_count = no_similar_count;
9163 return res;
9165 count -= no_similar_count;
9168 // in specific slot
9169 if (bag != NULL_BAG && slot != NULL_SLOT)
9171 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9172 if (res!=EQUIP_ERR_OK)
9174 if (no_space_count)
9175 *no_space_count = count + no_similar_count;
9176 return res;
9179 if (count==0)
9181 if (no_similar_count==0)
9182 return EQUIP_ERR_OK;
9184 if (no_space_count)
9185 *no_space_count = count + no_similar_count;
9186 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9190 // not specific slot or have space for partly store only in specific slot
9192 // in specific bag
9193 if (bag != NULL_BAG)
9195 // search stack in bag for merge to
9196 if (pProto->Stackable != 1)
9198 if (bag == INVENTORY_SLOT_BAG_0) // inventory
9200 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9201 if (res!=EQUIP_ERR_OK)
9203 if (no_space_count)
9204 *no_space_count = count + no_similar_count;
9205 return res;
9208 if (count==0)
9210 if (no_similar_count==0)
9211 return EQUIP_ERR_OK;
9213 if (no_space_count)
9214 *no_space_count = count + no_similar_count;
9215 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9218 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9219 if (res!=EQUIP_ERR_OK)
9221 if (no_space_count)
9222 *no_space_count = count + no_similar_count;
9223 return res;
9226 if (count==0)
9228 if (no_similar_count==0)
9229 return EQUIP_ERR_OK;
9231 if (no_space_count)
9232 *no_space_count = count + no_similar_count;
9233 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9236 else // equipped bag
9238 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9239 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9240 if (res!=EQUIP_ERR_OK)
9241 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9243 if (res!=EQUIP_ERR_OK)
9245 if (no_space_count)
9246 *no_space_count = count + no_similar_count;
9247 return res;
9250 if (count==0)
9252 if (no_similar_count==0)
9253 return EQUIP_ERR_OK;
9255 if (no_space_count)
9256 *no_space_count = count + no_similar_count;
9257 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9262 // search free slot in bag for place to
9263 if(bag == INVENTORY_SLOT_BAG_0) // inventory
9265 // search free slot - keyring case
9266 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9268 uint32 keyringSize = GetMaxKeyringSize();
9269 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9270 if (res!=EQUIP_ERR_OK)
9272 if (no_space_count)
9273 *no_space_count = count + no_similar_count;
9274 return res;
9277 if (count==0)
9279 if (no_similar_count==0)
9280 return EQUIP_ERR_OK;
9282 if (no_space_count)
9283 *no_space_count = count + no_similar_count;
9284 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9287 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9288 if (res!=EQUIP_ERR_OK)
9290 if (no_space_count)
9291 *no_space_count = count + no_similar_count;
9292 return res;
9295 if (count==0)
9297 if (no_similar_count==0)
9298 return EQUIP_ERR_OK;
9300 if (no_space_count)
9301 *no_space_count = count + no_similar_count;
9302 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9305 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9307 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9308 if (res!=EQUIP_ERR_OK)
9310 if (no_space_count)
9311 *no_space_count = count + no_similar_count;
9312 return res;
9315 if (count==0)
9317 if (no_similar_count==0)
9318 return EQUIP_ERR_OK;
9320 if (no_space_count)
9321 *no_space_count = count + no_similar_count;
9322 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9326 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9327 if (res!=EQUIP_ERR_OK)
9329 if (no_space_count)
9330 *no_space_count = count + no_similar_count;
9331 return res;
9334 if (count==0)
9336 if (no_similar_count==0)
9337 return EQUIP_ERR_OK;
9339 if (no_space_count)
9340 *no_space_count = count + no_similar_count;
9341 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9344 else // equipped bag
9346 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9347 if (res!=EQUIP_ERR_OK)
9348 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9350 if (res!=EQUIP_ERR_OK)
9352 if (no_space_count)
9353 *no_space_count = count + no_similar_count;
9354 return res;
9357 if (count==0)
9359 if (no_similar_count==0)
9360 return EQUIP_ERR_OK;
9362 if (no_space_count)
9363 *no_space_count = count + no_similar_count;
9364 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9369 // not specific bag or have space for partly store only in specific bag
9371 // search stack for merge to
9372 if (pProto->Stackable != 1)
9374 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9375 if (res!=EQUIP_ERR_OK)
9377 if (no_space_count)
9378 *no_space_count = count + no_similar_count;
9379 return res;
9382 if (count==0)
9384 if (no_similar_count==0)
9385 return EQUIP_ERR_OK;
9387 if (no_space_count)
9388 *no_space_count = count + no_similar_count;
9389 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9392 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9393 if (res!=EQUIP_ERR_OK)
9395 if (no_space_count)
9396 *no_space_count = count + no_similar_count;
9397 return res;
9400 if (count==0)
9402 if (no_similar_count==0)
9403 return EQUIP_ERR_OK;
9405 if (no_space_count)
9406 *no_space_count = count + no_similar_count;
9407 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9410 if (pProto->BagFamily)
9412 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9414 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9415 if (res!=EQUIP_ERR_OK)
9416 continue;
9418 if (count==0)
9420 if (no_similar_count==0)
9421 return EQUIP_ERR_OK;
9423 if (no_space_count)
9424 *no_space_count = count + no_similar_count;
9425 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9430 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9432 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9433 if (res!=EQUIP_ERR_OK)
9434 continue;
9436 if (count==0)
9438 if (no_similar_count==0)
9439 return EQUIP_ERR_OK;
9441 if (no_space_count)
9442 *no_space_count = count + no_similar_count;
9443 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9448 // search free slot - special bag case
9449 if (pProto->BagFamily)
9451 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9453 uint32 keyringSize = GetMaxKeyringSize();
9454 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9455 if (res!=EQUIP_ERR_OK)
9457 if (no_space_count)
9458 *no_space_count = count + no_similar_count;
9459 return res;
9462 if (count==0)
9464 if (no_similar_count==0)
9465 return EQUIP_ERR_OK;
9467 if (no_space_count)
9468 *no_space_count = count + no_similar_count;
9469 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9472 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9474 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9475 if (res!=EQUIP_ERR_OK)
9477 if (no_space_count)
9478 *no_space_count = count + no_similar_count;
9479 return res;
9482 if (count==0)
9484 if (no_similar_count==0)
9485 return EQUIP_ERR_OK;
9487 if (no_space_count)
9488 *no_space_count = count + no_similar_count;
9489 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9493 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9495 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9496 if (res!=EQUIP_ERR_OK)
9497 continue;
9499 if (count==0)
9501 if (no_similar_count==0)
9502 return EQUIP_ERR_OK;
9504 if (no_space_count)
9505 *no_space_count = count + no_similar_count;
9506 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9511 // search free slot
9512 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9513 if (res!=EQUIP_ERR_OK)
9515 if (no_space_count)
9516 *no_space_count = count + no_similar_count;
9517 return res;
9520 if (count==0)
9522 if (no_similar_count==0)
9523 return EQUIP_ERR_OK;
9525 if (no_space_count)
9526 *no_space_count = count + no_similar_count;
9527 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9530 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9532 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9533 if (res!=EQUIP_ERR_OK)
9534 continue;
9536 if (count==0)
9538 if (no_similar_count==0)
9539 return EQUIP_ERR_OK;
9541 if (no_space_count)
9542 *no_space_count = count + no_similar_count;
9543 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9547 if (no_space_count)
9548 *no_space_count = count + no_similar_count;
9550 return EQUIP_ERR_INVENTORY_FULL;
9553 //////////////////////////////////////////////////////////////////////////
9554 uint8 Player::CanStoreItems( Item **pItems,int count) const
9556 Item *pItem2;
9558 // fill space table
9559 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9560 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9561 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9562 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9564 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9565 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9566 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9567 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9569 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9571 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9573 if (pItem2 && !pItem2->IsInTrade())
9575 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9579 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
9581 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9583 if (pItem2 && !pItem2->IsInTrade())
9585 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9589 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9591 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9593 if (pItem2 && !pItem2->IsInTrade())
9595 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9599 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9601 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9603 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9605 pItem2 = GetItemByPos( i, j );
9606 if (pItem2 && !pItem2->IsInTrade())
9608 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9614 // check free space for all items
9615 for (int k = 0; k < count; ++k)
9617 Item *pItem = pItems[k];
9619 // no item
9620 if (!pItem) continue;
9622 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9623 ItemPrototype const *pProto = pItem->GetProto();
9625 // strange item
9626 if( !pProto )
9627 return EQUIP_ERR_ITEM_NOT_FOUND;
9629 // item it 'bind'
9630 if(pItem->IsBindedNotWith(this))
9631 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9633 Bag *pBag;
9634 ItemPrototype const *pBagProto;
9636 // item is 'one item only'
9637 uint8 res = CanTakeMoreSimilarItems(pItem);
9638 if(res != EQUIP_ERR_OK)
9639 return res;
9641 // search stack for merge to
9642 if( pProto->Stackable != 1 )
9644 bool b_found = false;
9646 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
9648 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9649 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9651 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9652 b_found = true;
9653 break;
9656 if (b_found) continue;
9658 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9660 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9661 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9663 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9664 b_found = true;
9665 break;
9668 if (b_found) continue;
9670 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9672 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9673 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9675 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9676 b_found = true;
9677 break;
9680 if (b_found) continue;
9682 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9684 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9685 if( pBag )
9687 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9689 pItem2 = GetItemByPos( t, j );
9690 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9692 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9693 b_found = true;
9694 break;
9699 if (b_found) continue;
9702 // special bag case
9703 if( pProto->BagFamily )
9705 bool b_found = false;
9706 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9708 uint32 keyringSize = GetMaxKeyringSize();
9709 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9711 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9713 inv_keys[t-KEYRING_SLOT_START] = 1;
9714 b_found = true;
9715 break;
9720 if (b_found) continue;
9722 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9724 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9726 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9728 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9729 b_found = true;
9730 break;
9735 if (b_found) continue;
9737 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9739 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9740 if( pBag )
9742 pBagProto = pBag->GetProto();
9744 // not plain container check
9745 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9746 ItemCanGoIntoBag(pProto,pBagProto) )
9748 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9750 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9752 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9753 b_found = true;
9754 break;
9760 if (b_found) continue;
9763 // search free slot
9764 bool b_found = false;
9765 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9767 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9769 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9770 b_found = true;
9771 break;
9774 if (b_found) continue;
9776 // search free slot in bags
9777 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9779 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9780 if( pBag )
9782 pBagProto = pBag->GetProto();
9784 // special bag already checked
9785 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9786 continue;
9788 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9790 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9792 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9793 b_found = true;
9794 break;
9800 // no free slot found?
9801 if (!b_found)
9802 return EQUIP_ERR_INVENTORY_FULL;
9805 return EQUIP_ERR_OK;
9808 //////////////////////////////////////////////////////////////////////////
9809 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9811 dest = 0;
9812 Item *pItem = Item::CreateItem( item, 1, this );
9813 if( pItem )
9815 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9816 delete pItem;
9817 return result;
9820 return EQUIP_ERR_ITEM_NOT_FOUND;
9823 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9825 dest = 0;
9826 if( pItem )
9828 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9829 ItemPrototype const *pProto = pItem->GetProto();
9830 if( pProto )
9832 if(pItem->IsBindedNotWith(this))
9833 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9835 // check count of items (skip for auto move for same player from bank)
9836 uint8 res = CanTakeMoreSimilarItems(pItem);
9837 if(res != EQUIP_ERR_OK)
9838 return res;
9840 // check this only in game
9841 if(not_loading)
9843 // May be here should be more stronger checks; STUNNED checked
9844 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9845 if (hasUnitState(UNIT_STAT_STUNNED))
9846 return EQUIP_ERR_YOU_ARE_STUNNED;
9848 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9849 // - combat
9850 // - in-progress arenas
9851 if( !pProto->CanChangeEquipStateInCombat() )
9853 if( isInCombat() )
9854 return EQUIP_ERR_NOT_IN_COMBAT;
9856 if(BattleGround* bg = GetBattleGround())
9857 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9858 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9861 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9862 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9864 if(IsNonMeleeSpellCasted(false))
9865 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9868 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0;
9869 // check allowed level (extend range to upper values if MaxLevel more or equal max player level, this let GM set high level with 1...max range items)
9870 if (ssd && ssd->MaxLevel < DEFAULT_MAX_LEVEL && ssd->MaxLevel < getLevel())
9871 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9873 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9874 if (eslot == NULL_SLOT)
9875 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9877 uint8 msg = CanUseItem(pItem , not_loading);
9878 if (msg != EQUIP_ERR_OK)
9879 return msg;
9880 if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
9881 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9883 // if swap ignore item (equipped also)
9884 if (uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9885 return res2;
9887 // check unique-equipped special item classes
9888 if (pProto->Class == ITEM_CLASS_QUIVER)
9890 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9892 if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
9894 if (pBag != pItem)
9896 if (ItemPrototype const* pBagProto = pBag->GetProto())
9898 if (pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot))
9899 return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9900 ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
9901 : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9908 uint32 type = pProto->InventoryType;
9910 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9912 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9914 if (!CanDualWield())
9915 return EQUIP_ERR_CANT_DUAL_WIELD;
9917 else if (type == INVTYPE_2HWEAPON)
9919 if (!CanDualWield() || !CanTitanGrip())
9920 return EQUIP_ERR_CANT_DUAL_WIELD;
9923 if (IsTwoHandUsed())
9924 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9927 // equip two-hand weapon case (with possible unequip 2 items)
9928 if (type == INVTYPE_2HWEAPON)
9930 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9932 if (!CanTitanGrip())
9933 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9935 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9936 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9938 if (!CanTitanGrip())
9940 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9941 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9942 ItemPosCountVec off_dest;
9943 if (offItem && (!not_loading ||
9944 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9945 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ))
9946 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9949 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9950 return EQUIP_ERR_OK;
9954 return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9957 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9959 // Applied only to equipped items and bank bags
9960 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9961 return EQUIP_ERR_OK;
9963 Item* pItem = GetItemByPos(pos);
9965 // Applied only to existed equipped item
9966 if( !pItem )
9967 return EQUIP_ERR_OK;
9969 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9971 ItemPrototype const *pProto = pItem->GetProto();
9972 if( !pProto )
9973 return EQUIP_ERR_ITEM_NOT_FOUND;
9975 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9976 // - combat
9977 // - in-progress arenas
9978 if( !pProto->CanChangeEquipStateInCombat() )
9980 if( isInCombat() )
9981 return EQUIP_ERR_NOT_IN_COMBAT;
9983 if(BattleGround* bg = GetBattleGround())
9984 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9985 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9988 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9989 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9991 return EQUIP_ERR_OK;
9994 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9996 if (!pItem)
9997 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9999 if (pItem->m_lootGenerated)
10000 return EQUIP_ERR_ITEM_LOCKED;
10002 uint32 count = pItem->GetCount();
10004 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
10005 ItemPrototype const *pProto = pItem->GetProto();
10006 if (!pProto)
10007 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10009 if (pItem->IsBindedNotWith(this))
10010 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10012 // check count of items (skip for auto move for same player from bank)
10013 uint8 res = CanTakeMoreSimilarItems(pItem);
10014 if (res != EQUIP_ERR_OK)
10015 return res;
10017 // in specific slot
10018 if (bag != NULL_BAG && slot != NULL_SLOT)
10020 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
10022 if (!pItem->IsBag())
10023 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
10025 if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
10026 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
10028 if (uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK)
10029 return cantuse;
10032 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
10033 if (res!=EQUIP_ERR_OK)
10034 return res;
10036 if (count==0)
10037 return EQUIP_ERR_OK;
10040 // not specific slot or have space for partly store only in specific slot
10042 // in specific bag
10043 if( bag != NULL_BAG )
10045 if( pProto->InventoryType == INVTYPE_BAG )
10047 Bag *pBag = (Bag*)pItem;
10048 if( pBag && !pBag->IsEmpty() )
10049 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
10052 // search stack in bag for merge to
10053 if( pProto->Stackable != 1 )
10055 if( bag == INVENTORY_SLOT_BAG_0 )
10057 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10058 if(res!=EQUIP_ERR_OK)
10059 return res;
10061 if(count==0)
10062 return EQUIP_ERR_OK;
10064 else
10066 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
10067 if(res!=EQUIP_ERR_OK)
10068 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
10070 if(res!=EQUIP_ERR_OK)
10071 return res;
10073 if(count==0)
10074 return EQUIP_ERR_OK;
10078 // search free slot in bag
10079 if( bag == INVENTORY_SLOT_BAG_0 )
10081 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10082 if(res!=EQUIP_ERR_OK)
10083 return res;
10085 if(count==0)
10086 return EQUIP_ERR_OK;
10088 else
10090 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
10091 if(res != EQUIP_ERR_OK)
10092 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
10094 if(res != EQUIP_ERR_OK)
10095 return res;
10097 if(count == 0)
10098 return EQUIP_ERR_OK;
10102 // not specific bag or have space for partly store only in specific bag
10104 // search stack for merge to
10105 if( pProto->Stackable != 1 )
10107 // in slots
10108 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10109 if(res != EQUIP_ERR_OK)
10110 return res;
10112 if(count == 0)
10113 return EQUIP_ERR_OK;
10115 // in special bags
10116 if( pProto->BagFamily )
10118 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10120 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
10121 if(res!=EQUIP_ERR_OK)
10122 continue;
10124 if(count==0)
10125 return EQUIP_ERR_OK;
10129 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10131 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
10132 if(res!=EQUIP_ERR_OK)
10133 continue;
10135 if(count==0)
10136 return EQUIP_ERR_OK;
10140 // search free place in special bag
10141 if( pProto->BagFamily )
10143 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10145 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
10146 if(res!=EQUIP_ERR_OK)
10147 continue;
10149 if(count==0)
10150 return EQUIP_ERR_OK;
10154 // search free space
10155 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10156 if(res!=EQUIP_ERR_OK)
10157 return res;
10159 if(count==0)
10160 return EQUIP_ERR_OK;
10162 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10164 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
10165 if(res!=EQUIP_ERR_OK)
10166 continue;
10168 if(count==0)
10169 return EQUIP_ERR_OK;
10171 return EQUIP_ERR_BANK_FULL;
10174 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
10176 if (pItem)
10178 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
10180 if (!isAlive() && not_loading)
10181 return EQUIP_ERR_YOU_ARE_DEAD;
10183 //if (isStunned())
10184 // return EQUIP_ERR_YOU_ARE_STUNNED;
10186 ItemPrototype const *pProto = pItem->GetProto();
10187 if (pProto)
10189 if (pItem->IsBindedNotWith(this))
10190 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10192 if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0)
10193 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10195 if (uint32 item_use_skill = pItem->GetSkill())
10197 if (GetSkillValue(item_use_skill) == 0)
10199 // armor items with scaling stats can downgrade armor skill reqs if related class can learn armor use at some level
10200 if (pProto->Class != ITEM_CLASS_ARMOR)
10201 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10203 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : NULL;
10204 if (!ssd)
10205 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10207 bool allowScaleSkill = false;
10208 for (uint32 i = 0; i < sSkillLineAbilityStore.GetNumRows(); ++i)
10210 SkillLineAbilityEntry const *skillInfo = sSkillLineAbilityStore.LookupEntry(i);
10211 if (!skillInfo)
10212 continue;
10214 if (skillInfo->skillId != item_use_skill)
10215 continue;
10217 // can't learn
10218 if (skillInfo->classmask && (skillInfo->classmask & getClassMask()) == 0)
10219 continue;
10221 if (skillInfo->racemask && (skillInfo->racemask & getRaceMask()) == 0)
10222 continue;
10224 allowScaleSkill = true;
10225 break;
10228 if (!allowScaleSkill)
10229 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10233 if (pProto->RequiredSkill != 0)
10235 if (GetSkillValue( pProto->RequiredSkill ) == 0)
10236 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10238 if (GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank)
10239 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10242 if (pProto->RequiredSpell != 0 && !HasSpell(pProto->RequiredSpell))
10243 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10245 if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
10246 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10248 if (getLevel() < pProto->RequiredLevel)
10249 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10251 return EQUIP_ERR_OK;
10254 return EQUIP_ERR_ITEM_NOT_FOUND;
10257 bool Player::CanUseItem( ItemPrototype const *pProto )
10259 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10261 if( pProto )
10263 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10264 return false;
10265 if( pProto->RequiredSkill != 0 )
10267 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10268 return false;
10269 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10270 return false;
10272 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10273 return false;
10274 if( getLevel() < pProto->RequiredLevel )
10275 return false;
10276 return true;
10278 return false;
10281 uint8 Player::CanUseAmmo( uint32 item ) const
10283 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10284 if( !isAlive() )
10285 return EQUIP_ERR_YOU_ARE_DEAD;
10286 //if( isStunned() )
10287 // return EQUIP_ERR_YOU_ARE_STUNNED;
10288 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype( item );
10289 if( pProto )
10291 if( pProto->InventoryType!= INVTYPE_AMMO )
10292 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10293 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10294 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10295 if( pProto->RequiredSkill != 0 )
10297 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10298 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10299 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10300 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10302 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10303 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10304 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
10305 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10307 if( getLevel() < pProto->RequiredLevel )
10308 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10310 // Requires No Ammo
10311 if(GetDummyAura(46699))
10312 return EQUIP_ERR_BAG_FULL6;
10314 return EQUIP_ERR_OK;
10316 return EQUIP_ERR_ITEM_NOT_FOUND;
10319 void Player::SetAmmo( uint32 item )
10321 if(!item)
10322 return;
10324 // already set
10325 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10326 return;
10328 // check ammo
10329 if(item)
10331 uint8 msg = CanUseAmmo( item );
10332 if( msg != EQUIP_ERR_OK )
10334 SendEquipError( msg, NULL, NULL );
10335 return;
10339 SetUInt32Value(PLAYER_AMMO_ID, item);
10341 _ApplyAmmoBonuses();
10344 void Player::RemoveAmmo()
10346 SetUInt32Value(PLAYER_AMMO_ID, 0);
10348 m_ammoDPS = 0.0f;
10350 if(CanModifyStats())
10351 UpdateDamagePhysical(RANGED_ATTACK);
10354 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10355 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10357 uint32 count = 0;
10358 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10359 count += itr->count;
10361 Item *pItem = Item::CreateItem( item, count, this );
10362 if( pItem )
10364 ItemAddedQuestCheck( item, count );
10365 if(randomPropertyId)
10366 pItem->SetItemRandomProperties(randomPropertyId);
10367 pItem = StoreItem( dest, pItem, update );
10369 return pItem;
10372 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10374 if( !pItem )
10375 return NULL;
10377 Item* lastItem = pItem;
10378 uint32 entry = pItem->GetEntry();
10379 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10381 uint16 pos = itr->pos;
10382 uint32 count = itr->count;
10384 ++itr;
10386 if(itr == dest.end())
10388 lastItem = _StoreItem(pos,pItem,count,false,update);
10389 break;
10392 lastItem = _StoreItem(pos,pItem,count,true,update);
10394 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
10395 return lastItem;
10398 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10399 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10401 if( !pItem )
10402 return NULL;
10404 uint8 bag = pos >> 8;
10405 uint8 slot = pos & 255;
10407 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10409 Item *pItem2 = GetItemByPos( bag, slot );
10411 if (!pItem2)
10413 if (clone)
10414 pItem = pItem->CloneItem(count, this);
10415 else
10416 pItem->SetCount(count);
10418 if (!pItem)
10419 return NULL;
10421 if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10422 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10423 (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10424 pItem->SetBinding( true );
10426 if (bag == INVENTORY_SLOT_BAG_0)
10428 m_items[slot] = pItem;
10429 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10430 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10431 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10433 pItem->SetSlot( slot );
10434 pItem->SetContainer( NULL );
10436 // need update known currency
10437 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10438 UpdateKnownCurrencies(pItem->GetEntry(), true);
10440 if (IsInWorld() && update)
10442 pItem->AddToWorld();
10443 pItem->SendCreateUpdateToPlayer( this );
10446 pItem->SetState(ITEM_CHANGED, this);
10448 else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10450 pBag->StoreItem( slot, pItem, update );
10451 if( IsInWorld() && update )
10453 pItem->AddToWorld();
10454 pItem->SendCreateUpdateToPlayer( this );
10456 pItem->SetState(ITEM_CHANGED, this);
10457 pBag->SetState(ITEM_CHANGED, this);
10460 AddEnchantmentDurations(pItem);
10461 AddItemDurations(pItem);
10463 return pItem;
10465 else
10467 if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10468 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10469 (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10470 pItem2->SetBinding( true );
10472 pItem2->SetCount( pItem2->GetCount() + count );
10473 if (IsInWorld() && update)
10474 pItem2->SendCreateUpdateToPlayer( this );
10476 if (!clone)
10478 // delete item (it not in any slot currently)
10479 if (IsInWorld() && update)
10481 pItem->RemoveFromWorld();
10482 pItem->DestroyForPlayer( this );
10485 RemoveEnchantmentDurations(pItem);
10486 RemoveItemDurations(pItem);
10488 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10489 pItem->SetState(ITEM_REMOVED, this);
10492 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10493 AddEnchantmentDurations(pItem2);
10495 pItem2->SetState(ITEM_CHANGED, this);
10497 return pItem2;
10501 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10503 if (Item *pItem = Item::CreateItem( item, 1, this ))
10505 ItemAddedQuestCheck( item, 1 );
10506 return EquipItem( pos, pItem, update );
10509 return NULL;
10512 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10514 AddEnchantmentDurations(pItem);
10515 AddItemDurations(pItem);
10517 uint8 bag = pos >> 8;
10518 uint8 slot = pos & 255;
10520 Item *pItem2 = GetItemByPos( bag, slot );
10522 if( !pItem2 )
10524 VisualizeItem( slot, pItem);
10526 if(isAlive())
10528 ItemPrototype const *pProto = pItem->GetProto();
10530 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10531 if(pProto && pProto->ItemSet)
10532 AddItemsSetItem(this, pItem);
10534 _ApplyItemMods(pItem, slot, true);
10536 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10538 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10540 if (getClass() == CLASS_ROGUE)
10541 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10543 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10545 if (!spellProto)
10546 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10547 else
10549 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10551 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10552 data << uint64(GetGUID());
10553 data << uint8(1);
10554 data << uint32(cooldownSpell);
10555 data << uint32(0);
10556 GetSession()->SendPacket(&data);
10561 if( IsInWorld() && update )
10563 pItem->AddToWorld();
10564 pItem->SendCreateUpdateToPlayer( this );
10567 ApplyEquipCooldown(pItem);
10569 if( slot == EQUIPMENT_SLOT_MAINHAND )
10571 UpdateExpertise(BASE_ATTACK);
10572 UpdateArmorPenetration();
10574 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10576 UpdateExpertise(OFF_ATTACK);
10577 UpdateArmorPenetration();
10580 else
10582 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10583 if( IsInWorld() && update )
10584 pItem2->SendCreateUpdateToPlayer( this );
10586 // delete item (it not in any slot currently)
10587 //pItem->DeleteFromDB();
10588 if( IsInWorld() && update )
10590 pItem->RemoveFromWorld();
10591 pItem->DestroyForPlayer( this );
10594 RemoveEnchantmentDurations(pItem);
10595 RemoveItemDurations(pItem);
10597 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10598 pItem->SetState(ITEM_REMOVED, this);
10599 pItem2->SetState(ITEM_CHANGED, this);
10601 ApplyEquipCooldown(pItem2);
10603 return pItem2;
10606 // only for full equip instead adding to stack
10607 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10609 return pItem;
10612 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10614 if( pItem )
10616 AddEnchantmentDurations(pItem);
10617 AddItemDurations(pItem);
10619 uint8 slot = pos & 255;
10620 VisualizeItem( slot, pItem);
10622 if( IsInWorld() )
10624 pItem->AddToWorld();
10625 pItem->SendCreateUpdateToPlayer( this );
10628 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10632 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10634 if(pItem)
10636 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
10637 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
10638 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT));
10640 else
10642 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
10643 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
10647 void Player::VisualizeItem( uint8 slot, Item *pItem)
10649 if(!pItem)
10650 return;
10652 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10653 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10654 pItem->SetBinding( true );
10656 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10658 m_items[slot] = pItem;
10659 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10660 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10661 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10662 pItem->SetSlot( slot );
10663 pItem->SetContainer( NULL );
10665 if( slot < EQUIPMENT_SLOT_END )
10666 SetVisibleItemSlot(slot, pItem);
10668 pItem->SetState(ITEM_CHANGED, this);
10671 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10673 // note: removeitem does not actually change the item
10674 // it only takes the item out of storage temporarily
10675 // note2: if removeitem is to be used for delinking
10676 // the item must be removed from the player's updatequeue
10678 Item *pItem = GetItemByPos( bag, slot );
10679 if( pItem )
10681 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10683 RemoveEnchantmentDurations(pItem);
10684 RemoveItemDurations(pItem);
10686 if( bag == INVENTORY_SLOT_BAG_0 )
10688 if ( slot < INVENTORY_SLOT_BAG_END )
10690 ItemPrototype const *pProto = pItem->GetProto();
10691 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10693 if(pProto && pProto->ItemSet)
10694 RemoveItemsSetItem(this, pProto);
10696 _ApplyItemMods(pItem, slot, false);
10698 // remove item dependent auras and casts (only weapon and armor slots)
10699 if(slot < EQUIPMENT_SLOT_END)
10701 RemoveItemDependentAurasAndCasts(pItem);
10703 // remove held enchantments, update expertise
10704 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10706 if (pItem->GetItemSuffixFactor())
10708 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10709 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10711 else
10713 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10714 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10717 UpdateExpertise(BASE_ATTACK);
10718 UpdateArmorPenetration();
10720 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10722 UpdateExpertise(OFF_ATTACK);
10723 UpdateArmorPenetration();
10727 // need update known currency
10728 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10729 UpdateKnownCurrencies(pItem->GetEntry(), false);
10731 m_items[slot] = NULL;
10732 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10734 if ( slot < EQUIPMENT_SLOT_END )
10735 SetVisibleItemSlot(slot, NULL);
10737 else
10739 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10740 if( pBag )
10741 pBag->RemoveItem(slot, update);
10743 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10744 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10745 pItem->SetSlot( NULL_SLOT );
10746 if( IsInWorld() && update )
10747 pItem->SendCreateUpdateToPlayer( this );
10751 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10752 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10754 if(Item* it = GetItemByPos(bag,slot))
10756 ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
10757 RemoveItem(bag, slot, update);
10758 it->RemoveFromUpdateQueueOf(this);
10759 if(it->IsInWorld())
10761 it->RemoveFromWorld();
10762 it->DestroyForPlayer( this );
10767 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10768 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10770 // update quest counters
10771 ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
10773 // store item
10774 Item* pLastItem = StoreItem(dest, pItem, update);
10776 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10777 if(pLastItem == pItem)
10779 // update owner for last item (this can be original item with wrong owner
10780 if(pLastItem->GetOwnerGUID() != GetGUID())
10781 pLastItem->SetOwnerGUID(GetGUID());
10783 // if this original item then it need create record in inventory
10784 // in case trade we already have item in other player inventory
10785 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10789 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10791 Item *pItem = GetItemByPos( bag, slot );
10792 if( pItem )
10794 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10796 // start from destroy contained items (only equipped bag can have its)
10797 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10799 for (int i = 0; i < MAX_BAG_SIZE; ++i)
10800 DestroyItem(slot, i, update);
10803 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10804 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10806 RemoveEnchantmentDurations(pItem);
10807 RemoveItemDurations(pItem);
10809 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10811 if( bag == INVENTORY_SLOT_BAG_0 )
10813 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10815 // equipment and equipped bags can have applied bonuses
10816 if ( slot < INVENTORY_SLOT_BAG_END )
10818 ItemPrototype const *pProto = pItem->GetProto();
10820 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10821 if(pProto && pProto->ItemSet)
10822 RemoveItemsSetItem(this, pProto);
10824 _ApplyItemMods(pItem, slot, false);
10827 if ( slot < EQUIPMENT_SLOT_END )
10829 // remove item dependent auras and casts (only weapon and armor slots)
10830 RemoveItemDependentAurasAndCasts(pItem);
10832 // update expertise
10833 if( slot == EQUIPMENT_SLOT_MAINHAND )
10835 UpdateExpertise(BASE_ATTACK);
10836 UpdateArmorPenetration();
10838 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10840 UpdateExpertise(OFF_ATTACK);
10841 UpdateArmorPenetration();
10844 // equipment visual show
10845 SetVisibleItemSlot(slot, NULL);
10847 // need update known currency
10848 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10849 UpdateKnownCurrencies(pItem->GetEntry(), false);
10851 m_items[slot] = NULL;
10853 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10854 pBag->RemoveItem(slot, update);
10856 if( IsInWorld() && update )
10858 pItem->RemoveFromWorld();
10859 pItem->DestroyForPlayer(this);
10862 //pItem->SetOwnerGUID(0);
10863 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10864 pItem->SetSlot( NULL_SLOT );
10865 pItem->SetState(ITEM_REMOVED, this);
10869 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10871 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10872 uint32 remcount = 0;
10874 // in inventory
10875 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10877 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10879 if (pItem->GetEntry() == item)
10881 if (pItem->GetCount() + remcount <= count)
10883 // all items in inventory can unequipped
10884 remcount += pItem->GetCount();
10885 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10887 if (remcount >= count)
10888 return;
10890 else
10892 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10893 pItem->SetCount( pItem->GetCount() - count + remcount );
10894 if (IsInWorld() & update)
10895 pItem->SendCreateUpdateToPlayer( this );
10896 pItem->SetState(ITEM_CHANGED, this);
10897 return;
10903 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10905 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10907 if (pItem->GetEntry() == item)
10909 if (pItem->GetCount() + remcount <= count)
10911 // all keys can be unequipped
10912 remcount += pItem->GetCount();
10913 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10915 if (remcount >= count)
10916 return;
10918 else
10920 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10921 pItem->SetCount( pItem->GetCount() - count + remcount );
10922 if (IsInWorld() & update)
10923 pItem->SendCreateUpdateToPlayer( this );
10924 pItem->SetState(ITEM_CHANGED, this);
10925 return;
10931 // in inventory bags
10932 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10934 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10936 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10938 if(Item* pItem = pBag->GetItemByPos(j))
10940 if (pItem->GetEntry() == item)
10942 // all items in bags can be unequipped
10943 if (pItem->GetCount() + remcount <= count)
10945 remcount += pItem->GetCount();
10946 DestroyItem( i, j, update );
10948 if (remcount >= count)
10949 return;
10951 else
10953 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10954 pItem->SetCount( pItem->GetCount() - count + remcount );
10955 if (IsInWorld() && update)
10956 pItem->SendCreateUpdateToPlayer( this );
10957 pItem->SetState(ITEM_CHANGED, this);
10958 return;
10966 // in equipment and bag list
10967 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10969 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10971 if (pItem && pItem->GetEntry() == item)
10973 if (pItem->GetCount() + remcount <= count)
10975 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
10977 remcount += pItem->GetCount();
10978 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10980 if (remcount >= count)
10981 return;
10984 else
10986 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10987 pItem->SetCount( pItem->GetCount() - count + remcount );
10988 if (IsInWorld() & update)
10989 pItem->SendCreateUpdateToPlayer( this );
10990 pItem->SetState(ITEM_CHANGED, this);
10991 return;
10998 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
11000 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
11002 // in inventory
11003 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11004 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11005 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11006 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11008 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
11009 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11010 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11011 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11013 // in inventory bags
11014 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11015 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11016 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11017 if (Item* pItem = pBag->GetItemByPos(j))
11018 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11019 DestroyItem(i, j, update);
11021 // in equipment and bag list
11022 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
11023 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11024 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11025 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11028 void Player::DestroyConjuredItems( bool update )
11030 // used when entering arena
11031 // destroys all conjured items
11032 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
11034 // in inventory
11035 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11036 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11037 if (pItem->IsConjuredConsumable())
11038 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11040 // in inventory bags
11041 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11042 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11043 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11044 if (Item* pItem = pBag->GetItemByPos(j))
11045 if (pItem->IsConjuredConsumable())
11046 DestroyItem( i, j, update);
11048 // in equipment and bag list
11049 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
11050 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11051 if (pItem->IsConjuredConsumable())
11052 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11055 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
11057 if(!pItem)
11058 return;
11060 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
11062 if( pItem->GetCount() <= count )
11064 count -= pItem->GetCount();
11066 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
11068 else
11070 ItemRemovedQuestCheck( pItem->GetEntry(), count);
11071 pItem->SetCount( pItem->GetCount() - count );
11072 count = 0;
11073 if( IsInWorld() & update )
11074 pItem->SendCreateUpdateToPlayer( this );
11075 pItem->SetState(ITEM_CHANGED, this);
11079 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
11081 uint8 srcbag = src >> 8;
11082 uint8 srcslot = src & 255;
11084 uint8 dstbag = dst >> 8;
11085 uint8 dstslot = dst & 255;
11087 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11088 if( !pSrcItem )
11090 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11091 return;
11094 // not let split all items (can be only at cheating)
11095 if(pSrcItem->GetCount() == count)
11097 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11098 return;
11101 // not let split more existed items (can be only at cheating)
11102 if(pSrcItem->GetCount() < count)
11104 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
11105 return;
11108 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
11110 //best error message found for attempting to split while looting
11111 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11112 return;
11115 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
11116 Item *pNewItem = pSrcItem->CloneItem( count, this );
11117 if( !pNewItem )
11119 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11120 return;
11123 if( IsInventoryPos( dst ) )
11125 // change item amount before check (for unique max count check)
11126 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11128 ItemPosCountVec dest;
11129 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
11130 if( msg != EQUIP_ERR_OK )
11132 delete pNewItem;
11133 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11134 SendEquipError( msg, pSrcItem, NULL );
11135 return;
11138 if( IsInWorld() )
11139 pSrcItem->SendCreateUpdateToPlayer( this );
11140 pSrcItem->SetState(ITEM_CHANGED, this);
11141 StoreItem( dest, pNewItem, true);
11143 else if( IsBankPos ( dst ) )
11145 // change item amount before check (for unique max count check)
11146 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11148 ItemPosCountVec dest;
11149 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
11150 if( msg != EQUIP_ERR_OK )
11152 delete pNewItem;
11153 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11154 SendEquipError( msg, pSrcItem, NULL );
11155 return;
11158 if( IsInWorld() )
11159 pSrcItem->SendCreateUpdateToPlayer( this );
11160 pSrcItem->SetState(ITEM_CHANGED, this);
11161 BankItem( dest, pNewItem, true);
11163 else if( IsEquipmentPos ( dst ) )
11165 // change item amount before check (for unique max count check), provide space for splitted items
11166 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11168 uint16 dest;
11169 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
11170 if( msg != EQUIP_ERR_OK )
11172 delete pNewItem;
11173 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11174 SendEquipError( msg, pSrcItem, NULL );
11175 return;
11178 if( IsInWorld() )
11179 pSrcItem->SendCreateUpdateToPlayer( this );
11180 pSrcItem->SetState(ITEM_CHANGED, this);
11181 EquipItem( dest, pNewItem, true);
11182 AutoUnequipOffhandIfNeed();
11186 void Player::SwapItem( uint16 src, uint16 dst )
11188 uint8 srcbag = src >> 8;
11189 uint8 srcslot = src & 255;
11191 uint8 dstbag = dst >> 8;
11192 uint8 dstslot = dst & 255;
11194 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11195 Item *pDstItem = GetItemByPos( dstbag, dstslot );
11197 if( !pSrcItem )
11198 return;
11200 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
11202 if(!isAlive() )
11204 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
11205 return;
11208 // SRC checks
11210 if(pSrcItem->m_lootGenerated) // prevent swap looting item
11212 //best error message found for attempting to swap while looting
11213 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
11214 return;
11217 // check unequip potability for equipped items and bank bags
11218 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
11220 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11221 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || (pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty()));
11222 if(msg != EQUIP_ERR_OK)
11224 SendEquipError( msg, pSrcItem, pDstItem );
11225 return;
11229 // prevent put equipped/bank bag in self
11230 if( IsBagPos ( src ) && srcslot == dstbag)
11232 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11233 return;
11236 // DST checks
11238 if (pDstItem)
11240 if(pDstItem->m_lootGenerated) // prevent swap looting item
11242 //best error message found for attempting to swap while looting
11243 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
11244 return;
11247 // check unequip potability for equipped items and bank bags
11248 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11250 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11251 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || (pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty()));
11252 if(msg != EQUIP_ERR_OK)
11254 SendEquipError( msg, pSrcItem, pDstItem );
11255 return;
11260 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11261 // or swap empty bag with another empty or not empty bag (with items exchange)
11263 // Move case
11264 if( !pDstItem )
11266 if( IsInventoryPos( dst ) )
11268 ItemPosCountVec dest;
11269 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
11270 if( msg != EQUIP_ERR_OK )
11272 SendEquipError( msg, pSrcItem, NULL );
11273 return;
11276 RemoveItem(srcbag, srcslot, true);
11277 StoreItem( dest, pSrcItem, true);
11279 else if( IsBankPos ( dst ) )
11281 ItemPosCountVec dest;
11282 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11283 if( msg != EQUIP_ERR_OK )
11285 SendEquipError( msg, pSrcItem, NULL );
11286 return;
11289 RemoveItem(srcbag, srcslot, true);
11290 BankItem( dest, pSrcItem, true);
11292 else if( IsEquipmentPos ( dst ) )
11294 uint16 dest;
11295 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11296 if( msg != EQUIP_ERR_OK )
11298 SendEquipError( msg, pSrcItem, NULL );
11299 return;
11302 RemoveItem(srcbag, srcslot, true);
11303 EquipItem(dest, pSrcItem, true);
11304 AutoUnequipOffhandIfNeed();
11307 return;
11310 // attempt merge to / fill target item
11311 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
11313 uint8 msg;
11314 ItemPosCountVec sDest;
11315 uint16 eDest;
11316 if( IsInventoryPos( dst ) )
11317 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11318 else if( IsBankPos ( dst ) )
11319 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11320 else if( IsEquipmentPos ( dst ) )
11321 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11322 else
11323 return;
11325 // can be merge/fill
11326 if(msg == EQUIP_ERR_OK)
11328 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11330 RemoveItem(srcbag, srcslot, true);
11332 if( IsInventoryPos( dst ) )
11333 StoreItem( sDest, pSrcItem, true);
11334 else if( IsBankPos ( dst ) )
11335 BankItem( sDest, pSrcItem, true);
11336 else if( IsEquipmentPos ( dst ) )
11338 EquipItem( eDest, pSrcItem, true);
11339 AutoUnequipOffhandIfNeed();
11342 else
11344 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11345 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11346 pSrcItem->SetState(ITEM_CHANGED, this);
11347 pDstItem->SetState(ITEM_CHANGED, this);
11348 if( IsInWorld() )
11350 pSrcItem->SendCreateUpdateToPlayer( this );
11351 pDstItem->SendCreateUpdateToPlayer( this );
11354 return;
11358 // impossible merge/fill, do real swap
11359 uint8 msg;
11361 // check src->dest move possibility
11362 ItemPosCountVec sDest;
11363 uint16 eDest = 0;
11364 if( IsInventoryPos( dst ) )
11365 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11366 else if( IsBankPos( dst ) )
11367 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11368 else if( IsEquipmentPos( dst ) )
11370 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11371 if( msg == EQUIP_ERR_OK )
11372 msg = CanUnequipItem( eDest, true );
11375 if( msg != EQUIP_ERR_OK )
11377 SendEquipError( msg, pSrcItem, pDstItem );
11378 return;
11381 // check dest->src move possibility
11382 ItemPosCountVec sDest2;
11383 uint16 eDest2 = 0;
11384 if( IsInventoryPos( src ) )
11385 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11386 else if( IsBankPos( src ) )
11387 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11388 else if( IsEquipmentPos( src ) )
11390 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11391 if( msg == EQUIP_ERR_OK )
11392 msg = CanUnequipItem( eDest2, true);
11395 if( msg != EQUIP_ERR_OK )
11397 SendEquipError( msg, pDstItem, pSrcItem );
11398 return;
11401 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11402 if(pSrcItem->IsBag() && pDstItem->IsBag())
11404 Bag* emptyBag = NULL;
11405 Bag* fullBag = NULL;
11406 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11408 emptyBag = (Bag*)pSrcItem;
11409 fullBag = (Bag*)pDstItem;
11411 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11413 emptyBag = (Bag*)pDstItem;
11414 fullBag = (Bag*)pSrcItem;
11417 // bag swap (with items exchange) case
11418 if(emptyBag && fullBag)
11420 ItemPrototype const* emotyProto = emptyBag->GetProto();
11422 uint32 count = 0;
11424 for(int i=0; i < fullBag->GetBagSize(); ++i)
11426 Item *bagItem = fullBag->GetItemByPos(i);
11427 if (!bagItem)
11428 continue;
11430 ItemPrototype const* bagItemProto = bagItem->GetProto();
11431 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11433 // one from items not go to empty target bag
11434 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11435 return;
11438 ++count;
11442 if (count > emptyBag->GetBagSize())
11444 // too small targeted bag
11445 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11446 return;
11449 // Items swap
11450 count = 0; // will pos in new bag
11451 for(int i = 0; i< fullBag->GetBagSize(); ++i)
11453 Item *bagItem = fullBag->GetItemByPos(i);
11454 if (!bagItem)
11455 continue;
11457 fullBag->RemoveItem(i, true);
11458 emptyBag->StoreItem(count, bagItem, true);
11459 bagItem->SetState(ITEM_CHANGED, this);
11461 ++count;
11466 // now do moves, remove...
11467 RemoveItem(dstbag, dstslot, false);
11468 RemoveItem(srcbag, srcslot, false);
11470 // add to dest
11471 if (IsInventoryPos(dst))
11472 StoreItem(sDest, pSrcItem, true);
11473 else if (IsBankPos(dst))
11474 BankItem(sDest, pSrcItem, true);
11475 else if (IsEquipmentPos(dst))
11476 EquipItem(eDest, pSrcItem, true);
11478 // add to src
11479 if (IsInventoryPos(src))
11480 StoreItem(sDest2, pDstItem, true);
11481 else if (IsBankPos(src))
11482 BankItem(sDest2, pDstItem, true);
11483 else if (IsEquipmentPos(src))
11484 EquipItem(eDest2, pDstItem, true);
11486 AutoUnequipOffhandIfNeed();
11489 void Player::AddItemToBuyBackSlot( Item *pItem )
11491 if (pItem)
11493 uint32 slot = m_currentBuybackSlot;
11494 // if current back slot non-empty search oldest or free
11495 if (m_items[slot])
11497 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11498 uint32 oldest_slot = BUYBACK_SLOT_START;
11500 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11502 // found empty
11503 if (!m_items[i])
11505 slot = i;
11506 break;
11509 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11511 if (oldest_time > i_time)
11513 oldest_time = i_time;
11514 oldest_slot = i;
11518 // find oldest
11519 slot = oldest_slot;
11522 RemoveItemFromBuyBackSlot( slot, true );
11523 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11525 m_items[slot] = pItem;
11526 time_t base = time(NULL);
11527 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11528 uint32 eslot = slot - BUYBACK_SLOT_START;
11530 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID() );
11531 if (ItemPrototype const *pProto = pItem->GetProto())
11532 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11533 else
11534 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11535 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11537 // move to next (for non filled list is move most optimized choice)
11538 if (m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
11539 ++m_currentBuybackSlot;
11543 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11545 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11546 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
11547 return m_items[slot];
11548 return NULL;
11551 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11553 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11554 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
11556 Item *pItem = m_items[slot];
11557 if (pItem)
11559 pItem->RemoveFromWorld();
11560 if(del) pItem->SetState(ITEM_REMOVED, this);
11563 m_items[slot] = NULL;
11565 uint32 eslot = slot - BUYBACK_SLOT_START;
11566 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0 );
11567 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11568 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11570 // if current backslot is filled set to now free slot
11571 if (m_items[m_currentBuybackSlot])
11572 m_currentBuybackSlot = slot;
11576 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11578 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
11579 WorldPacket data(SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : (msg == EQUIP_ERR_OK ? 1 : 18)));
11580 data << uint8(msg);
11582 if (msg != EQUIP_ERR_OK)
11584 data << uint64(pItem ? pItem->GetGUID() : 0);
11585 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11586 data << uint8(0); // not 0 there...
11588 if (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11590 uint32 level = 0;
11592 if (pItem)
11593 if (ItemPrototype const* proto = pItem->GetProto())
11594 level = proto->RequiredLevel;
11596 data << uint32(level); // new 2.4.0
11599 GetSession()->SendPacket(&data);
11602 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11604 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11605 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11606 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11607 data << uint32(item);
11608 if (param > 0)
11609 data << uint32(param);
11610 data << uint8(msg);
11611 GetSession()->SendPacket(&data);
11614 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11616 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11617 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11618 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11619 data << uint64(guid);
11620 if (param > 0)
11621 data << uint32(param);
11622 data << uint8(msg);
11623 GetSession()->SendPacket(&data);
11626 void Player::ClearTrade()
11628 tradeGold = 0;
11629 acceptTrade = false;
11630 for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
11631 tradeItems[i] = NULL_SLOT;
11634 void Player::TradeCancel(bool sendback)
11636 if (pTrader)
11638 // send yellow "Trade canceled" message to both traders
11639 WorldSession* ws;
11640 ws = GetSession();
11641 if (sendback)
11642 ws->SendCancelTrade();
11643 ws = pTrader->GetSession();
11644 if (!ws->PlayerLogout())
11645 ws->SendCancelTrade();
11647 // cleanup
11648 ClearTrade();
11649 pTrader->ClearTrade();
11650 // prevent loss of reference
11651 pTrader->pTrader = NULL;
11652 pTrader = NULL;
11656 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11658 if (m_itemDuration.empty())
11659 return;
11661 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
11663 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); )
11665 Item* item = *itr;
11666 ++itr; // current element can be erased in UpdateDuration
11668 if ((realtimeonly && item->GetProto()->Duration < 0) || !realtimeonly)
11669 item->UpdateDuration(this,time);
11673 void Player::UpdateEnchantTime(uint32 time)
11675 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11677 assert(itr->item);
11678 next = itr;
11679 if (!itr->item->GetEnchantmentId(itr->slot))
11681 next = m_enchantDuration.erase(itr);
11683 else if (itr->leftduration <= time)
11685 ApplyEnchantment(itr->item, itr->slot, false, false);
11686 itr->item->ClearEnchantment(itr->slot);
11687 next = m_enchantDuration.erase(itr);
11689 else if (itr->leftduration > time)
11691 itr->leftduration -= time;
11692 ++next;
11697 void Player::AddEnchantmentDurations(Item *item)
11699 for(int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
11701 if (!item->GetEnchantmentId(EnchantmentSlot(x)))
11702 continue;
11704 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11705 if (duration > 0)
11706 AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
11710 void Player::RemoveEnchantmentDurations(Item *item)
11712 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
11714 if (itr->item == item)
11716 // save duration in item
11717 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
11718 itr = m_enchantDuration.erase(itr);
11720 else
11721 ++itr;
11725 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11727 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11728 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
11730 next = itr;
11731 if (itr->slot == slot)
11733 if (itr->item && itr->item->GetEnchantmentId(slot))
11735 // remove from stats
11736 ApplyEnchantment(itr->item, slot, false, false);
11737 // remove visual
11738 itr->item->ClearEnchantment(slot);
11740 // remove from update list
11741 next = m_enchantDuration.erase(itr);
11743 else
11744 ++next;
11747 // remove enchants from inventory items
11748 // NOTE: no need to remove these from stats, since these aren't equipped
11749 // in inventory
11750 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11751 if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
11752 if (pItem->GetEnchantmentId(slot))
11753 pItem->ClearEnchantment(slot);
11755 // in inventory bags
11756 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11757 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11758 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11759 if (Item* pItem = pBag->GetItemByPos(j))
11760 if (pItem->GetEnchantmentId(slot))
11761 pItem->ClearEnchantment(slot);
11764 // duration == 0 will remove item enchant
11765 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11767 if (!item)
11768 return;
11770 if (slot >= MAX_ENCHANTMENT_SLOT)
11771 return;
11773 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11775 if (itr->item == item && itr->slot == slot)
11777 itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
11778 m_enchantDuration.erase(itr);
11779 break;
11782 if (item && duration > 0 )
11784 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
11785 m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
11789 void Player::ApplyEnchantment(Item *item,bool apply)
11791 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11792 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11795 void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
11797 if (!item)
11798 return;
11800 if (!item->IsEquipped())
11801 return;
11803 if (slot >= MAX_ENCHANTMENT_SLOT)
11804 return;
11806 uint32 enchant_id = item->GetEnchantmentId(slot);
11807 if (!enchant_id)
11808 return;
11810 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11811 if (!pEnchant)
11812 return;
11814 if (!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11815 return;
11817 if (!item->IsBroken())
11819 for (int s = 0; s < 3; ++s)
11821 uint32 enchant_display_type = pEnchant->type[s];
11822 uint32 enchant_amount = pEnchant->amount[s];
11823 uint32 enchant_spell_id = pEnchant->spellid[s];
11825 switch(enchant_display_type)
11827 case ITEM_ENCHANTMENT_TYPE_NONE:
11828 break;
11829 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11830 // processed in Player::CastItemCombatSpell
11831 break;
11832 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11833 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11834 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11835 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11836 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11837 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11838 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11839 break;
11840 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11841 if (enchant_spell_id)
11843 if (apply)
11845 int32 basepoints = 0;
11846 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11847 if (item->GetItemRandomPropertyId())
11849 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11850 if (item_rand)
11852 // Search enchant_amount
11853 for (int k = 0; k < 3; ++k)
11855 if(item_rand->enchant_id[k] == enchant_id)
11857 basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11858 break;
11863 // Cast custom spell vs all equal basepoints getted from enchant_amount
11864 if (basepoints)
11865 CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
11866 else
11867 CastSpell(this, enchant_spell_id, true, item);
11869 else
11870 RemoveAurasDueToItemSpell(item, enchant_spell_id);
11872 break;
11873 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11874 if (!enchant_amount)
11876 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11877 if(item_rand)
11879 for (int k = 0; k < 3; ++k)
11881 if(item_rand->enchant_id[k] == enchant_id)
11883 enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11884 break;
11890 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11891 break;
11892 case ITEM_ENCHANTMENT_TYPE_STAT:
11894 if (!enchant_amount)
11896 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11897 if(item_rand_suffix)
11899 for (int k = 0; k < 3; ++k)
11901 if(item_rand_suffix->enchant_id[k] == enchant_id)
11903 enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11904 break;
11910 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11911 switch (enchant_spell_id)
11913 case ITEM_MOD_MANA:
11914 sLog.outDebug("+ %u MANA",enchant_amount);
11915 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
11916 break;
11917 case ITEM_MOD_HEALTH:
11918 sLog.outDebug("+ %u HEALTH",enchant_amount);
11919 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
11920 break;
11921 case ITEM_MOD_AGILITY:
11922 sLog.outDebug("+ %u AGILITY",enchant_amount);
11923 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11924 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11925 break;
11926 case ITEM_MOD_STRENGTH:
11927 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11928 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11929 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11930 break;
11931 case ITEM_MOD_INTELLECT:
11932 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11933 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11934 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11935 break;
11936 case ITEM_MOD_SPIRIT:
11937 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11938 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11939 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11940 break;
11941 case ITEM_MOD_STAMINA:
11942 sLog.outDebug("+ %u STAMINA",enchant_amount);
11943 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11944 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11945 break;
11946 case ITEM_MOD_DEFENSE_SKILL_RATING:
11947 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11948 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11949 break;
11950 case ITEM_MOD_DODGE_RATING:
11951 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11952 sLog.outDebug("+ %u DODGE", enchant_amount);
11953 break;
11954 case ITEM_MOD_PARRY_RATING:
11955 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11956 sLog.outDebug("+ %u PARRY", enchant_amount);
11957 break;
11958 case ITEM_MOD_BLOCK_RATING:
11959 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11960 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11961 break;
11962 case ITEM_MOD_HIT_MELEE_RATING:
11963 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11964 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11965 break;
11966 case ITEM_MOD_HIT_RANGED_RATING:
11967 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11968 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11969 break;
11970 case ITEM_MOD_HIT_SPELL_RATING:
11971 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11972 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11973 break;
11974 case ITEM_MOD_CRIT_MELEE_RATING:
11975 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11976 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11977 break;
11978 case ITEM_MOD_CRIT_RANGED_RATING:
11979 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11980 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11981 break;
11982 case ITEM_MOD_CRIT_SPELL_RATING:
11983 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11984 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11985 break;
11986 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11987 // in Enchantments
11988 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11989 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11990 // break;
11991 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11992 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11993 // break;
11994 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11995 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11996 // break;
11997 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11998 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11999 // break;
12000 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
12001 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12002 // break;
12003 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
12004 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12005 // break;
12006 // case ITEM_MOD_HASTE_MELEE_RATING:
12007 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12008 // break;
12009 // case ITEM_MOD_HASTE_RANGED_RATING:
12010 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12011 // break;
12012 case ITEM_MOD_HASTE_SPELL_RATING:
12013 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12014 break;
12015 case ITEM_MOD_HIT_RATING:
12016 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
12017 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
12018 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
12019 sLog.outDebug("+ %u HIT", enchant_amount);
12020 break;
12021 case ITEM_MOD_CRIT_RATING:
12022 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12023 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12024 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12025 sLog.outDebug("+ %u CRITICAL", enchant_amount);
12026 break;
12027 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
12028 // case ITEM_MOD_HIT_TAKEN_RATING:
12029 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12030 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12031 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12032 // break;
12033 // case ITEM_MOD_CRIT_TAKEN_RATING:
12034 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12035 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12036 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12037 // break;
12038 case ITEM_MOD_RESILIENCE_RATING:
12039 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12040 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12041 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12042 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
12043 break;
12044 case ITEM_MOD_HASTE_RATING:
12045 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12046 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12047 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12048 sLog.outDebug("+ %u HASTE", enchant_amount);
12049 break;
12050 case ITEM_MOD_EXPERTISE_RATING:
12051 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
12052 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
12053 break;
12054 case ITEM_MOD_ATTACK_POWER:
12055 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
12056 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12057 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
12058 break;
12059 case ITEM_MOD_RANGED_ATTACK_POWER:
12060 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12061 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
12062 break;
12063 case ITEM_MOD_FERAL_ATTACK_POWER:
12064 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
12065 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
12066 break;
12067 case ITEM_MOD_MANA_REGENERATION:
12068 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
12069 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
12070 break;
12071 case ITEM_MOD_ARMOR_PENETRATION_RATING:
12072 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
12073 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
12074 break;
12075 case ITEM_MOD_SPELL_POWER:
12076 ((Player*)this)->ApplySpellPowerBonus(enchant_amount, apply);
12077 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
12078 break;
12079 case ITEM_MOD_SPELL_HEALING_DONE: // deprecated
12080 case ITEM_MOD_SPELL_DAMAGE_DONE: // deprecated
12081 default:
12082 break;
12084 break;
12086 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
12088 if(getClass() == CLASS_SHAMAN)
12090 float addValue = 0.0f;
12091 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
12093 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
12094 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
12096 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
12098 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
12099 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
12102 break;
12104 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
12105 // processed in Player::CastItemUseSpell
12106 break;
12107 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
12108 // nothing do..
12109 break;
12110 default:
12111 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
12112 break;
12113 } /*switch(enchant_display_type)*/
12114 } /*for*/
12117 // visualize enchantment at player and equipped items
12118 if(slot == PERM_ENCHANTMENT_SLOT)
12119 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
12121 if(slot == TEMP_ENCHANTMENT_SLOT)
12122 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
12125 if(apply_dur)
12127 if(apply)
12129 // set duration
12130 uint32 duration = item->GetEnchantmentDuration(slot);
12131 if(duration > 0)
12132 AddEnchantmentDuration(item, slot, duration);
12134 else
12136 // duration == 0 will remove EnchantDuration
12137 AddEnchantmentDuration(item, slot, 0);
12142 void Player::SendEnchantmentDurations()
12144 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
12146 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
12150 void Player::SendItemDurations()
12152 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
12154 (*itr)->SendTimeUpdate(this);
12158 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
12160 if(!item) // prevent crash
12161 return;
12163 // last check 2.0.10
12164 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
12165 data << uint64(GetGUID()); // player GUID
12166 data << uint32(received); // 0=looted, 1=from npc
12167 data << uint32(created); // 0=received, 1=created
12168 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
12169 data << uint8(item->GetBagSlot()); // bagslot
12170 // item slot, but when added to stack: 0xFFFFFFFF
12171 data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
12172 data << uint32(item->GetEntry()); // item id
12173 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
12174 data << uint32(item->GetItemRandomPropertyId()); // random item property id
12175 data << uint32(count); // count of items
12176 data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
12178 if (broadcast && GetGroup())
12179 GetGroup()->BroadcastPacket(&data, true);
12180 else
12181 GetSession()->SendPacket(&data);
12184 /*********************************************************/
12185 /*** GOSSIP SYSTEM ***/
12186 /*********************************************************/
12188 void Player::PrepareGossipMenu(WorldObject *pSource, uint32 menuId)
12190 PlayerMenu* pMenu = PlayerTalkClass;
12191 pMenu->ClearMenus();
12193 pMenu->GetGossipMenu().SetMenuId(menuId);
12195 GossipMenuItemsMapBounds pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(menuId);
12197 // if default menuId and no menu options exist for this, use options from default options
12198 if (pMenuItemBounds.first == pMenuItemBounds.second && menuId == GetDefaultGossipMenuForSource(pSource))
12199 pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(0);
12201 for(GossipMenuItemsMap::const_iterator itr = pMenuItemBounds.first; itr != pMenuItemBounds.second; ++itr)
12203 bool bCanTalk = true;
12205 if (itr->second.cond_1 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_1))
12206 continue;
12208 if (itr->second.cond_2 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
12209 continue;
12211 if (itr->second.cond_3 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_3))
12212 continue;
12214 if (pSource->GetTypeId() == TYPEID_UNIT)
12216 Creature *pCreature = (Creature*)pSource;
12218 uint32 npcflags = pCreature->GetUInt32Value(UNIT_NPC_FLAGS);
12220 if (!(itr->second.npc_option_npcflag & npcflags))
12221 continue;
12223 switch(itr->second.option_id)
12225 case GOSSIP_OPTION_QUESTGIVER:
12226 PrepareQuestMenu(pSource->GetGUID());
12227 bCanTalk = false;
12228 break;
12229 case GOSSIP_OPTION_ARMORER:
12230 bCanTalk = false; // added in special mode
12231 break;
12232 case GOSSIP_OPTION_SPIRITHEALER:
12233 if (!isDead())
12234 bCanTalk = false;
12235 break;
12236 case GOSSIP_OPTION_VENDOR:
12238 VendorItemData const* vItems = pCreature->GetVendorItems();
12239 if (!vItems || vItems->Empty())
12241 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", pCreature->GetGUIDLow(), pCreature->GetEntry());
12242 bCanTalk = false;
12244 break;
12246 case GOSSIP_OPTION_TRAINER:
12247 if (!pCreature->isCanTrainingOf(this, false))
12248 bCanTalk = false;
12249 break;
12250 case GOSSIP_OPTION_UNLEARNTALENTS:
12251 if (!pCreature->isCanTrainingAndResetTalentsOf(this))
12252 bCanTalk = false;
12253 break;
12254 case GOSSIP_OPTION_UNLEARNPETSKILLS:
12255 if (!GetPet() || GetPet()->getPetType() != HUNTER_PET || GetPet()->m_spells.size() <= 1 || pCreature->GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || pCreature->GetCreatureInfo()->trainer_class != CLASS_HUNTER)
12256 bCanTalk = false;
12257 break;
12258 case GOSSIP_OPTION_TAXIVENDOR:
12259 if (GetSession()->SendLearnNewTaxiNode(pCreature))
12260 return;
12261 break;
12262 case GOSSIP_OPTION_BATTLEFIELD:
12263 if (!pCreature->isCanInteractWithBattleMaster(this, false))
12264 bCanTalk = false;
12265 break;
12266 case GOSSIP_OPTION_STABLEPET:
12267 if (getClass() != CLASS_HUNTER)
12268 bCanTalk = false;
12269 break;
12270 case GOSSIP_OPTION_GOSSIP:
12271 case GOSSIP_OPTION_SPIRITGUIDE:
12272 case GOSSIP_OPTION_INNKEEPER:
12273 case GOSSIP_OPTION_BANKER:
12274 case GOSSIP_OPTION_PETITIONER:
12275 case GOSSIP_OPTION_TABARDDESIGNER:
12276 case GOSSIP_OPTION_AUCTIONEER:
12277 break; // no checks
12278 default:
12279 sLog.outErrorDb("Creature entry %u have unknown gossip option %u for menu %u", pCreature->GetEntry(), itr->second.option_id, itr->second.menu_id);
12280 bCanTalk = false;
12281 break;
12284 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12286 GameObject *pGo = (GameObject*)pSource;
12288 switch(itr->second.option_id)
12290 case GOSSIP_OPTION_QUESTGIVER:
12291 if (pGo->GetGoType() == GAMEOBJECT_TYPE_QUESTGIVER)
12292 PrepareQuestMenu(pSource->GetGUID());
12293 bCanTalk = false;
12294 break;
12295 case GOSSIP_OPTION_GOSSIP:
12296 if (pGo->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER && pGo->GetGoType() != GAMEOBJECT_TYPE_GOOBER)
12297 bCanTalk = false;
12298 break;
12299 default:
12300 bCanTalk = false;
12301 break;
12305 if (bCanTalk)
12307 std::string strOptionText = itr->second.option_text;
12308 std::string strBoxText = itr->second.box_text;
12310 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12312 if (loc_idx >= 0)
12314 uint32 idxEntry = MAKE_PAIR32(menuId, itr->second.id);
12316 if (GossipMenuItemsLocale const *no = sObjectMgr.GetGossipMenuItemsLocale(idxEntry))
12318 if (no->OptionText.size() > (size_t)loc_idx && !no->OptionText[loc_idx].empty())
12319 strOptionText = no->OptionText[loc_idx];
12321 if (no->BoxText.size() > (size_t)loc_idx && !no->BoxText[loc_idx].empty())
12322 strBoxText = no->BoxText[loc_idx];
12326 pMenu->GetGossipMenu().AddMenuItem(itr->second.option_icon, strOptionText, 0, itr->second.option_id, strBoxText, itr->second.box_money, itr->second.box_coded);
12327 pMenu->GetGossipMenu().AddGossipMenuItemData(itr->second.action_menu_id, itr->second.action_poi_id, itr->second.action_script_id);
12331 // some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
12332 /*if (pMenu->Empty())
12334 if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
12336 // output error message if need
12337 pCreature->isCanTrainingOf(this, true);
12340 if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
12342 // output error message if need
12343 pCreature->isCanInteractWithBattleMaster(this, true);
12348 void Player::SendPreparedGossip(WorldObject *pSource)
12350 if (!pSource)
12351 return;
12353 if (pSource->GetTypeId() == TYPEID_UNIT)
12355 // in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
12356 if (!((Creature*)pSource)->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_GOSSIP) && !PlayerTalkClass->GetQuestMenu().Empty())
12358 SendPreparedQuest(pSource->GetGUID());
12359 return;
12362 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12364 // probably need to find a better way here
12365 if (!PlayerTalkClass->GetGossipMenu().GetMenuId() && !PlayerTalkClass->GetQuestMenu().Empty())
12367 SendPreparedQuest(pSource->GetGUID());
12368 return;
12372 // in case non empty gossip menu (that not included quests list size) show it
12373 // (quest entries from quest menu will be included in list)
12375 uint32 textId = GetGossipTextId(pSource);
12377 if (uint32 menuId = PlayerTalkClass->GetGossipMenu().GetMenuId())
12378 textId = GetGossipTextId(menuId);
12380 PlayerTalkClass->SendGossipMenu(textId, pSource->GetGUID());
12383 void Player::OnGossipSelect(WorldObject* pSource, uint32 gossipListId, uint32 menuId)
12385 GossipMenu& gossipmenu = PlayerTalkClass->GetGossipMenu();
12387 if (gossipListId >= gossipmenu.MenuItemCount())
12388 return;
12390 // if not same, then something funky is going on
12391 if (menuId != gossipmenu.GetMenuId())
12392 return;
12394 uint32 gossipOptionId = gossipmenu.GetItem(gossipListId).m_gOptionId;
12395 uint64 guid = pSource->GetGUID();
12397 if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12399 if (gossipOptionId > GOSSIP_OPTION_QUESTGIVER)
12401 sLog.outError("Player guid %u request invalid gossip option for GameObject entry %u", GetGUIDLow(), pSource->GetEntry());
12402 return;
12406 GossipMenuItemData pMenuData = gossipmenu.GetItemData(gossipListId);
12408 switch(gossipOptionId)
12410 case GOSSIP_OPTION_GOSSIP:
12412 if (pMenuData.m_gAction_menu)
12414 PrepareGossipMenu(pSource, pMenuData.m_gAction_menu);
12415 SendPreparedGossip(pSource);
12418 if (pMenuData.m_gAction_poi)
12419 PlayerTalkClass->SendPointOfInterest(pMenuData.m_gAction_poi);
12421 if (pMenuData.m_gAction_script)
12423 if (pSource->GetTypeId() == TYPEID_UNIT)
12424 GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, this, pSource);
12425 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12426 GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, pSource, this);
12429 break;
12431 case GOSSIP_OPTION_SPIRITHEALER:
12432 if (isDead())
12433 ((Creature*)pSource)->CastSpell(((Creature*)pSource),17251,true,NULL,NULL,GetGUID());
12434 break;
12435 case GOSSIP_OPTION_QUESTGIVER:
12436 PrepareQuestMenu(guid);
12437 SendPreparedQuest(guid);
12438 break;
12439 case GOSSIP_OPTION_VENDOR:
12440 case GOSSIP_OPTION_ARMORER:
12441 GetSession()->SendListInventory(guid);
12442 break;
12443 case GOSSIP_OPTION_STABLEPET:
12444 GetSession()->SendStablePet(guid);
12445 break;
12446 case GOSSIP_OPTION_TRAINER:
12447 GetSession()->SendTrainerList(guid);
12448 break;
12449 case GOSSIP_OPTION_UNLEARNTALENTS:
12450 PlayerTalkClass->CloseGossip();
12451 SendTalentWipeConfirm(guid);
12452 break;
12453 case GOSSIP_OPTION_UNLEARNPETSKILLS:
12454 PlayerTalkClass->CloseGossip();
12455 SendPetSkillWipeConfirm();
12456 break;
12457 case GOSSIP_OPTION_TAXIVENDOR:
12458 GetSession()->SendTaxiMenu(((Creature*)pSource));
12459 break;
12460 case GOSSIP_OPTION_INNKEEPER:
12461 PlayerTalkClass->CloseGossip();
12462 SetBindPoint(guid);
12463 break;
12464 case GOSSIP_OPTION_BANKER:
12465 GetSession()->SendShowBank(guid);
12466 break;
12467 case GOSSIP_OPTION_PETITIONER:
12468 PlayerTalkClass->CloseGossip();
12469 GetSession()->SendPetitionShowList(guid);
12470 break;
12471 case GOSSIP_OPTION_TABARDDESIGNER:
12472 PlayerTalkClass->CloseGossip();
12473 GetSession()->SendTabardVendorActivate(guid);
12474 break;
12475 case GOSSIP_OPTION_AUCTIONEER:
12476 GetSession()->SendAuctionHello(guid, ((Creature*)pSource));
12477 break;
12478 case GOSSIP_OPTION_SPIRITGUIDE:
12479 PrepareGossipMenu(pSource);
12480 SendPreparedGossip(pSource);
12481 break;
12482 case GOSSIP_OPTION_BATTLEFIELD:
12484 BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(pSource->GetEntry());
12486 if (bgTypeId == BATTLEGROUND_TYPE_NONE)
12488 sLog.outError("a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUIDLow());
12489 return;
12492 GetSession()->SendBattlegGroundList(guid, bgTypeId);
12493 break;
12498 uint32 Player::GetGossipTextId(WorldObject *pSource)
12500 if (!pSource || pSource->GetTypeId() != TYPEID_UNIT || !((Creature*)pSource)->GetDBTableGUIDLow())
12501 return DEFAULT_GOSSIP_MESSAGE;
12503 if (uint32 pos = sObjectMgr.GetNpcGossip(((Creature*)pSource)->GetDBTableGUIDLow()))
12504 return pos;
12506 return DEFAULT_GOSSIP_MESSAGE;
12509 uint32 Player::GetGossipTextId(uint32 menuId)
12511 uint32 textId = DEFAULT_GOSSIP_MESSAGE;
12513 if (!menuId)
12514 return textId;
12516 GossipMenusMapBounds pMenuBounds = sObjectMgr.GetGossipMenusMapBounds(menuId);
12518 for(GossipMenusMap::const_iterator itr = pMenuBounds.first; itr != pMenuBounds.second; ++itr)
12520 if (sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_1) && sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
12521 textId = itr->second.text_id;
12524 return textId;
12527 uint32 Player::GetDefaultGossipMenuForSource(WorldObject *pSource)
12529 if (pSource->GetTypeId() == TYPEID_UNIT)
12530 return ((Creature*)pSource)->GetCreatureInfo()->GossipMenuId;
12531 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12532 return((GameObject*)pSource)->GetGOInfo()->GetGossipMenuId();
12534 return 0;
12537 /*********************************************************/
12538 /*** QUEST SYSTEM ***/
12539 /*********************************************************/
12541 void Player::PrepareQuestMenu( uint64 guid )
12543 Object *pObject;
12544 QuestRelations* pObjectQR;
12545 QuestRelations* pObjectQIR;
12547 // pets also can have quests
12548 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12550 pObject = (Object*)pCreature;
12551 pObjectQR = &sObjectMgr.mCreatureQuestRelations;
12552 pObjectQIR = &sObjectMgr.mCreatureQuestInvolvedRelations;
12554 else
12556 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12557 //only for quests which cast teleport spells on player
12558 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
12559 ASSERT(_map);
12560 GameObject *pGameObject = _map->GetGameObject(guid);
12561 if( pGameObject )
12563 pObject = (Object*)pGameObject;
12564 pObjectQR = &sObjectMgr.mGOQuestRelations;
12565 pObjectQIR = &sObjectMgr.mGOQuestInvolvedRelations;
12567 else
12568 return;
12571 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
12572 qm.ClearMenu();
12574 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
12576 uint32 quest_id = i->second;
12577 QuestStatus status = GetQuestStatus( quest_id );
12578 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
12579 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12580 else if ( status == QUEST_STATUS_INCOMPLETE )
12581 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12582 else if (status == QUEST_STATUS_AVAILABLE )
12583 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12586 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
12588 uint32 quest_id = i->second;
12589 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
12590 if(!pQuest) continue;
12592 QuestStatus status = GetQuestStatus( quest_id );
12594 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
12595 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12596 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
12597 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12601 void Player::SendPreparedQuest(uint64 guid)
12603 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
12605 if (questMenu.Empty())
12606 return;
12608 QuestMenuItem const& qmi0 = questMenu.GetItem(0);
12610 uint32 status = qmi0.m_qIcon;
12612 // single element case
12613 if (questMenu.MenuItemCount() == 1)
12615 // Auto open -- maybe also should verify there is no greeting
12616 uint32 quest_id = qmi0.m_qId;
12617 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
12619 if (pQuest)
12621 if (status == DIALOG_STATUS_UNK2 && !GetQuestRewardStatus(quest_id))
12622 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
12623 else if (status == DIALOG_STATUS_UNK2)
12624 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
12625 // Send completable on repeatable and autoCompletable quest if player don't have quest
12626 // TODO: verify if check for !pQuest->IsDaily() is really correct (possibly not)
12627 else if (pQuest->IsAutoComplete() && pQuest->IsRepeatable() && !pQuest->IsDaily())
12628 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanCompleteRepeatableQuest(pQuest), true);
12629 else
12630 PlayerTalkClass->SendQuestGiverQuestDetails(pQuest, guid, true);
12633 // multiply entries
12634 else
12636 QEmote qe;
12637 qe._Delay = 0;
12638 qe._Emote = 0;
12639 std::string title = "";
12641 // need pet case for some quests
12642 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12644 uint32 textid = GetGossipTextId(pCreature);
12646 GossipText const* gossiptext = sObjectMgr.GetGossipText(textid);
12647 if (!gossiptext)
12649 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12650 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12651 title = "";
12653 else
12655 qe = gossiptext->Options[0].Emotes[0];
12657 if(!gossiptext->Options[0].Text_0.empty())
12659 title = gossiptext->Options[0].Text_0;
12661 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12662 if (loc_idx >= 0)
12664 NpcTextLocale const *nl = sObjectMgr.GetNpcTextLocale(textid);
12665 if (nl)
12667 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12668 title = nl->Text_0[0][loc_idx];
12672 else
12674 title = gossiptext->Options[0].Text_1;
12676 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12677 if (loc_idx >= 0)
12679 NpcTextLocale const *nl = sObjectMgr.GetNpcTextLocale(textid);
12680 if (nl)
12682 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12683 title = nl->Text_1[0][loc_idx];
12689 PlayerTalkClass->SendQuestGiverQuestList(qe, title, guid);
12693 bool Player::IsActiveQuest( uint32 quest_id ) const
12695 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12697 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12700 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12702 Object *pObject;
12703 QuestRelations* pObjectQR;
12704 QuestRelations* pObjectQIR;
12706 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12708 pObject = (Object*)pCreature;
12709 pObjectQR = &sObjectMgr.mCreatureQuestRelations;
12710 pObjectQIR = &sObjectMgr.mCreatureQuestInvolvedRelations;
12712 else
12714 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12715 //only for quests which cast teleport spells on player
12716 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
12717 ASSERT(_map);
12718 GameObject *pGameObject = _map->GetGameObject(guid);
12719 if( pGameObject )
12721 pObject = (Object*)pGameObject;
12722 pObjectQR = &sObjectMgr.mGOQuestRelations;
12723 pObjectQIR = &sObjectMgr.mGOQuestInvolvedRelations;
12725 else
12726 return NULL;
12729 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12730 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12732 if (itr->second == nextQuestID)
12733 return sObjectMgr.GetQuestTemplate(nextQuestID);
12736 return NULL;
12739 bool Player::CanSeeStartQuest( Quest const *pQuest )
12741 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12742 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12743 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12744 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12746 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12749 return false;
12752 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12754 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12755 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12756 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12757 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12758 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12759 && SatisfyQuestDay( pQuest, msg );
12762 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12764 if( !SatisfyQuestLog( msg ) )
12765 return false;
12767 uint32 srcitem = pQuest->GetSrcItemId();
12768 if( srcitem > 0 )
12770 uint32 count = pQuest->GetSrcItemCount();
12771 ItemPosCountVec dest;
12772 uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12774 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12775 if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12776 return true;
12777 else if( msg2 != EQUIP_ERR_OK )
12779 SendEquipError( msg2, NULL, NULL );
12780 return false;
12783 return true;
12786 bool Player::CanCompleteQuest( uint32 quest_id )
12788 if( quest_id )
12790 QuestStatusData& q_status = mQuestStatus[quest_id];
12791 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12792 return false; // not allow re-complete quest
12794 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
12796 if(!qInfo)
12797 return false;
12799 // auto complete quest
12800 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12801 return true;
12803 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12806 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12808 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
12810 if( qInfo->ReqItemCount[i] != 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12811 return false;
12815 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12817 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12819 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12820 continue;
12822 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12823 return false;
12827 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12828 return false;
12830 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12831 return false;
12833 if ( qInfo->GetRewOrReqMoney() < 0 )
12835 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12836 return false;
12839 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12840 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12841 return false;
12843 return true;
12846 return false;
12849 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12851 // Solve problem that player don't have the quest and try complete it.
12852 // if repeatable she must be able to complete event if player don't have it.
12853 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12854 if( !CanTakeQuest(pQuest, false) )
12855 return false;
12857 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12858 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
12859 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i], pQuest->ReqItemCount[i]) )
12860 return false;
12862 if( !CanRewardQuest(pQuest, false) )
12863 return false;
12865 return true;
12868 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12870 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12871 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12872 return false;
12874 // daily quest can't be rewarded (25 daily quest already completed)
12875 if(!SatisfyQuestDay(pQuest,true))
12876 return false;
12878 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12879 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12880 return false;
12882 // prevent receive reward with quest items in bank
12883 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12885 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
12887 if( pQuest->ReqItemCount[i] != 0 &&
12888 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12890 if(msg)
12891 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12892 return false;
12897 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12898 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12899 return false;
12901 return true;
12904 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12906 // prevent receive reward with quest items in bank or for not completed quest
12907 if(!CanRewardQuest(pQuest,msg))
12908 return false;
12910 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12912 if( pQuest->RewChoiceItemId[reward] )
12914 ItemPosCountVec dest;
12915 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12916 if( res != EQUIP_ERR_OK )
12918 SendEquipError( res, NULL, NULL );
12919 return false;
12924 if ( pQuest->GetRewItemsCount() > 0 )
12926 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12928 if( pQuest->RewItemId[i] )
12930 ItemPosCountVec dest;
12931 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12932 if( res != EQUIP_ERR_OK )
12934 SendEquipError( res, NULL, NULL );
12935 return false;
12941 return true;
12944 void Player::SendPetTameFailure(PetTameFailureReason reason)
12946 WorldPacket data(SMSG_PET_TAME_FAILURE, 1);
12947 data << uint8(reason);
12948 GetSession()->SendPacket(&data);
12951 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12953 uint16 log_slot = FindQuestSlot( 0 );
12954 assert(log_slot < MAX_QUEST_LOG_SIZE);
12956 uint32 quest_id = pQuest->GetQuestId();
12958 // if not exist then created with set uState==NEW and rewarded=false
12959 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12961 // check for repeatable quests status reset
12962 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12963 questStatusData.m_explored = false;
12965 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12967 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
12968 questStatusData.m_itemcount[i] = 0;
12971 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12973 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12974 questStatusData.m_creatureOrGOcount[i] = 0;
12977 GiveQuestSourceItem( pQuest );
12978 AdjustQuestReqItemCount( pQuest, questStatusData );
12980 if( pQuest->GetRepObjectiveFaction() )
12981 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
12982 GetReputationMgr().SetVisible(factionEntry);
12984 uint32 qtime = 0;
12985 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12987 uint32 limittime = pQuest->GetLimitTime();
12989 // shared timed quest
12990 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12991 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
12993 AddTimedQuest( quest_id );
12994 questStatusData.m_timer = limittime * IN_MILISECONDS;
12995 qtime = static_cast<uint32>(time(NULL)) + limittime;
12997 else
12998 questStatusData.m_timer = 0;
13000 SetQuestSlot(log_slot, quest_id, qtime);
13002 if (questStatusData.uState != QUEST_NEW)
13003 questStatusData.uState = QUEST_CHANGED;
13005 //starting initial quest script
13006 if(questGiver && pQuest->GetQuestStartScript()!=0)
13007 GetMap()->ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
13009 // Some spells applied at quest activation
13010 SpellAreaForQuestMapBounds saBounds = sSpellMgr.GetSpellAreaForQuestMapBounds(quest_id,true);
13011 if(saBounds.first != saBounds.second)
13013 uint32 zone, area;
13014 GetZoneAndAreaId(zone,area);
13016 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
13017 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
13018 if( !HasAura(itr->second->spellId,0) )
13019 CastSpell(this,itr->second->spellId,true);
13022 UpdateForQuestWorldObjects();
13025 void Player::CompleteQuest( uint32 quest_id )
13027 if( quest_id )
13029 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
13031 uint16 log_slot = FindQuestSlot( quest_id );
13032 if( log_slot < MAX_QUEST_LOG_SIZE)
13033 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
13035 if(Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id))
13037 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
13038 RewardQuest(qInfo,0,this,false);
13039 else
13040 SendQuestComplete( quest_id );
13045 void Player::IncompleteQuest( uint32 quest_id )
13047 if( quest_id )
13049 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
13051 uint16 log_slot = FindQuestSlot( quest_id );
13052 if( log_slot < MAX_QUEST_LOG_SIZE)
13053 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
13057 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
13059 //this THING should be here to protect code from quest, which cast on player far teleport as a reward
13060 //should work fine, cause far teleport will be executed in Player::Update()
13061 SetCanDelayTeleport(true);
13063 uint32 quest_id = pQuest->GetQuestId();
13065 for (int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i )
13067 if (pQuest->ReqItemId[i])
13068 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
13071 RemoveTimedQuest(quest_id);
13073 if (BattleGround* bg = GetBattleGround())
13074 if (bg->GetTypeID() == BATTLEGROUND_AV)
13075 ((BattleGroundAV*)bg)->HandleQuestComplete(pQuest->GetQuestId(), this);
13077 if (pQuest->GetRewChoiceItemsCount() > 0)
13079 if (uint32 itemId = pQuest->RewChoiceItemId[reward])
13081 ItemPosCountVec dest;
13082 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK)
13084 Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
13085 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
13090 if (pQuest->GetRewItemsCount() > 0)
13092 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
13094 if (uint32 itemId = pQuest->RewItemId[i])
13096 ItemPosCountVec dest;
13097 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewItemCount[i] ) == EQUIP_ERR_OK)
13099 Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
13100 SendNewItem(item, pQuest->RewItemCount[i], true, false);
13106 RewardReputation( pQuest );
13108 uint16 log_slot = FindQuestSlot( quest_id );
13109 if (log_slot < MAX_QUEST_LOG_SIZE)
13110 SetQuestSlot(log_slot,0);
13112 QuestStatusData& q_status = mQuestStatus[quest_id];
13114 // Not give XP in case already completed once repeatable quest
13115 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
13117 if (getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
13118 GiveXP( XP , NULL );
13119 else
13121 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
13122 ModifyMoney( money );
13123 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
13126 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
13127 if (pQuest->GetRewOrReqMoney())
13129 ModifyMoney( pQuest->GetRewOrReqMoney() );
13131 if (pQuest->GetRewOrReqMoney() > 0)
13132 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
13135 // honor reward
13136 if (pQuest->GetRewHonorableKills())
13137 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13139 // title reward
13140 if (pQuest->GetCharTitleId())
13142 if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
13143 SetTitle(titleEntry);
13146 if (pQuest->GetBonusTalents())
13148 m_questRewardTalentCount+=pQuest->GetBonusTalents();
13149 InitTalentForLevel();
13152 // Send reward mail
13153 if (uint32 mail_template_id = pQuest->GetRewMailTemplateId())
13154 MailDraft(mail_template_id).SendMailTo(this, questGiver, MAIL_CHECK_MASK_NONE, pQuest->GetRewMailDelaySecs());
13156 if (pQuest->IsDaily())
13158 SetDailyQuestStatus(quest_id);
13159 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
13162 if (!pQuest->IsRepeatable())
13163 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
13164 else
13165 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
13167 q_status.m_rewarded = true;
13168 if (q_status.uState != QUEST_NEW)
13169 q_status.uState = QUEST_CHANGED;
13171 if (announce)
13172 SendQuestReward( pQuest, XP, questGiver );
13174 // cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data)
13175 if (pQuest->GetRewSpellCast() > 0)
13176 CastSpell( this, pQuest->GetRewSpellCast(), true);
13177 else if ( pQuest->GetRewSpell() > 0)
13178 CastSpell( this, pQuest->GetRewSpell(), true);
13180 if (pQuest->GetZoneOrSort() > 0)
13181 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
13182 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
13183 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
13185 uint32 zone = 0;
13186 uint32 area = 0;
13188 // remove auras from spells with quest reward state limitations
13189 SpellAreaForQuestMapBounds saEndBounds = sSpellMgr.GetSpellAreaForQuestEndMapBounds(quest_id);
13190 if(saEndBounds.first != saEndBounds.second)
13192 GetZoneAndAreaId(zone,area);
13194 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
13195 if(!itr->second->IsFitToRequirements(this,zone,area))
13196 RemoveAurasDueToSpell(itr->second->spellId);
13199 // Some spells applied at quest reward
13200 SpellAreaForQuestMapBounds saBounds = sSpellMgr.GetSpellAreaForQuestMapBounds(quest_id,false);
13201 if(saBounds.first != saBounds.second)
13203 if(!zone || !area)
13204 GetZoneAndAreaId(zone,area);
13206 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
13207 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
13208 if( !HasAura(itr->second->spellId,0) )
13209 CastSpell(this,itr->second->spellId,true);
13212 //lets remove flag for delayed teleports
13213 SetCanDelayTeleport(false);
13216 void Player::FailQuest(uint32 questId)
13218 if (Quest const* pQuest = sObjectMgr.GetQuestTemplate(questId))
13220 SetQuestStatus(questId, QUEST_STATUS_FAILED);
13222 uint16 log_slot = FindQuestSlot(questId);
13224 if (log_slot < MAX_QUEST_LOG_SIZE)
13226 SetQuestSlotTimer(log_slot, 1);
13227 SetQuestSlotState(log_slot, QUEST_STATE_FAIL);
13230 if (pQuest->HasFlag(QUEST_MANGOS_FLAGS_TIMED))
13232 QuestStatusData& q_status = mQuestStatus[questId];
13234 RemoveTimedQuest(questId);
13235 q_status.m_timer = 0;
13237 SendQuestTimerFailed(questId);
13239 else
13240 SendQuestFailed(questId);
13244 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
13246 int32 zoneOrSort = qInfo->GetZoneOrSort();
13247 int32 skillOrClass = qInfo->GetSkillOrClass();
13249 // skip zone zoneOrSort and 0 case skillOrClass
13250 if( zoneOrSort >= 0 && skillOrClass == 0 )
13251 return true;
13253 int32 questSort = -zoneOrSort;
13254 uint8 reqSortClass = ClassByQuestSort(questSort);
13256 // check class sort cases in zoneOrSort
13257 if( reqSortClass != 0 && getClass() != reqSortClass)
13259 if( msg )
13260 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13261 return false;
13264 // check class
13265 if( skillOrClass < 0 )
13267 uint8 reqClass = -int32(skillOrClass);
13268 if(getClass() != reqClass)
13270 if( msg )
13271 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13272 return false;
13275 // check skill
13276 else if( skillOrClass > 0 )
13278 uint32 reqSkill = skillOrClass;
13279 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
13281 if( msg )
13282 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13283 return false;
13287 return true;
13290 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
13292 if( getLevel() < qInfo->GetMinLevel() )
13294 if( msg )
13295 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13296 return false;
13298 return true;
13301 bool Player::SatisfyQuestLog( bool msg )
13303 // exist free slot
13304 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
13305 return true;
13307 if( msg )
13309 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
13310 GetSession()->SendPacket( &data );
13311 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
13313 return false;
13316 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
13318 // No previous quest (might be first quest in a series)
13319 if( qInfo->prevQuests.empty())
13320 return true;
13322 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
13324 uint32 prevId = abs(*iter);
13326 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
13327 Quest const* qPrevInfo = sObjectMgr.GetQuestTemplate(prevId);
13329 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
13331 // If any of the positive previous quests completed, return true
13332 if( *iter > 0 && i_prevstatus->second.m_rewarded )
13334 // skip one-from-all exclusive group
13335 if(qPrevInfo->GetExclusiveGroup() >= 0)
13336 return true;
13338 // each-from-all exclusive group ( < 0)
13339 // can be start if only all quests in prev quest exclusive group completed and rewarded
13340 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = sObjectMgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13341 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13343 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13345 for(; iter2 != end; ++iter2)
13347 uint32 exclude_Id = iter2->second;
13349 // skip checked quest id, only state of other quests in group is interesting
13350 if(exclude_Id == prevId)
13351 continue;
13353 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
13355 // alternative quest from group also must be completed and rewarded(reported)
13356 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
13358 if( msg )
13359 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13360 return false;
13363 return true;
13365 // If any of the negative previous quests active, return true
13366 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13367 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
13369 // skip one-from-all exclusive group
13370 if(qPrevInfo->GetExclusiveGroup() >= 0)
13371 return true;
13373 // each-from-all exclusive group ( < 0)
13374 // can be start if only all quests in prev quest exclusive group active
13375 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = sObjectMgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13376 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13378 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13380 for(; iter2 != end; ++iter2)
13382 uint32 exclude_Id = iter2->second;
13384 // skip checked quest id, only state of other quests in group is interesting
13385 if(exclude_Id == prevId)
13386 continue;
13388 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
13390 // alternative quest from group also must be active
13391 if( i_exstatus == mQuestStatus.end() ||
13392 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
13393 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
13395 if( msg )
13396 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13397 return false;
13400 return true;
13405 // Has only positive prev. quests in non-rewarded state
13406 // and negative prev. quests in non-active state
13407 if( msg )
13408 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13410 return false;
13413 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
13415 uint32 reqraces = qInfo->GetRequiredRaces();
13416 if ( reqraces == 0 )
13417 return true;
13418 if( (reqraces & getRaceMask()) == 0 )
13420 if( msg )
13421 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
13422 return false;
13424 return true;
13427 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
13429 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
13430 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
13432 if( msg )
13433 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13434 return false;
13437 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
13438 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
13440 if( msg )
13441 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13442 return false;
13445 return true;
13448 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
13450 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
13451 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
13453 if( msg )
13454 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
13455 return false;
13457 return true;
13460 bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg)
13462 if (!m_timedquests.empty() && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED))
13464 if (msg)
13465 SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED);
13467 return false;
13469 return true;
13472 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
13474 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13475 if(qInfo->GetExclusiveGroup() <= 0)
13476 return true;
13478 ObjectMgr::ExclusiveQuestGroups::const_iterator iter = sObjectMgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
13479 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
13481 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
13483 for(; iter != end; ++iter)
13485 uint32 exclude_Id = iter->second;
13487 // skip checked quest id, only state of other quests in group is interesting
13488 if(exclude_Id == qInfo->GetQuestId())
13489 continue;
13491 // not allow have daily quest if daily quest from exclusive group already recently completed
13492 Quest const* Nquest = sObjectMgr.GetQuestTemplate(exclude_Id);
13493 if( !SatisfyQuestDay(Nquest, false) )
13495 if( msg )
13496 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13497 return false;
13500 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13502 // alternative quest already started or completed
13503 if( i_exstatus != mQuestStatus.end()
13504 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
13506 if( msg )
13507 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13508 return false;
13511 return true;
13514 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
13516 if(!qInfo->GetNextQuestInChain())
13517 return true;
13519 // next quest in chain already started or completed
13520 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
13521 if( itr != mQuestStatus.end()
13522 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
13524 if( msg )
13525 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13526 return false;
13529 // check for all quests further up the chain
13530 // only necessary if there are quest chains with more than one quest that can be skipped
13531 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13532 return true;
13535 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
13537 // No previous quest in chain
13538 if( qInfo->prevChainQuests.empty())
13539 return true;
13541 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
13543 uint32 prevId = *iter;
13545 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
13547 if( i_prevstatus != mQuestStatus.end() )
13549 // If any of the previous quests in chain active, return false
13550 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13551 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
13553 if( msg )
13554 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13555 return false;
13559 // check for all quests further down the chain
13560 // only necessary if there are quest chains with more than one quest that can be skipped
13561 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13562 // return false;
13565 // No previous quest in chain active
13566 return true;
13569 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
13571 if(!qInfo->IsDaily())
13572 return true;
13574 bool have_slot = false;
13575 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
13577 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
13578 if(qInfo->GetQuestId()==id)
13579 return false;
13581 if(!id)
13582 have_slot = true;
13585 if(!have_slot)
13587 if( msg )
13588 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
13589 return false;
13592 return true;
13595 bool Player::GiveQuestSourceItem( Quest const *pQuest )
13597 uint32 srcitem = pQuest->GetSrcItemId();
13598 if( srcitem > 0 )
13600 uint32 count = pQuest->GetSrcItemCount();
13601 if( count <= 0 )
13602 count = 1;
13604 ItemPosCountVec dest;
13605 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13606 if( msg == EQUIP_ERR_OK )
13608 Item * item = StoreNewItem(dest, srcitem, true);
13609 SendNewItem(item, count, true, false);
13610 return true;
13612 // player already have max amount required item, just report success
13613 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13614 return true;
13615 else
13616 SendEquipError( msg, NULL, NULL );
13617 return false;
13620 return true;
13623 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13625 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13626 if( qInfo )
13628 uint32 srcitem = qInfo->GetSrcItemId();
13629 if( srcitem > 0 )
13631 uint32 count = qInfo->GetSrcItemCount();
13632 if( count <= 0 )
13633 count = 1;
13635 // exist one case when destroy source quest item not possible:
13636 // non un-equippable item (equipped non-empty bag, for example)
13637 uint8 res = CanUnequipItems(srcitem,count);
13638 if(res != EQUIP_ERR_OK)
13640 if(msg)
13641 SendEquipError( res, NULL, NULL );
13642 return false;
13645 DestroyItemCount(srcitem, count, true, true);
13648 return true;
13651 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13653 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13654 if( qInfo )
13656 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13657 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13658 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13659 && !qInfo->IsRepeatable() )
13660 return itr->second.m_rewarded;
13662 return false;
13664 return false;
13667 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13669 if( quest_id )
13671 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13672 if( itr != mQuestStatus.end() )
13673 return itr->second.m_status;
13675 return QUEST_STATUS_NONE;
13678 bool Player::CanShareQuest(uint32 quest_id) const
13680 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13681 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13683 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13684 if( itr != mQuestStatus.end() )
13685 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13687 return false;
13690 void Player::SetQuestStatus(uint32 quest_id, QuestStatus status)
13692 if (Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id))
13694 QuestStatusData& q_status = mQuestStatus[quest_id];
13696 q_status.m_status = status;
13698 if (q_status.uState != QUEST_NEW)
13699 q_status.uState = QUEST_CHANGED;
13702 UpdateForQuestWorldObjects();
13705 // not used in MaNGOS, but used in scripting code
13706 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13708 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13709 if( !qInfo )
13710 return 0;
13712 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13713 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13714 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13716 return 0;
13719 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13721 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13723 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13725 uint32 reqitemcount = pQuest->ReqItemCount[i];
13726 if( reqitemcount != 0 )
13728 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i], true);
13730 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13731 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13737 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13739 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13740 if ( GetQuestSlotQuestId(i) == quest_id )
13741 return i;
13743 return MAX_QUEST_LOG_SIZE;
13746 void Player::AreaExploredOrEventHappens( uint32 questId )
13748 if( questId )
13750 uint16 log_slot = FindQuestSlot( questId );
13751 if( log_slot < MAX_QUEST_LOG_SIZE)
13753 QuestStatusData& q_status = mQuestStatus[questId];
13755 if(!q_status.m_explored)
13757 q_status.m_explored = true;
13758 if (q_status.uState != QUEST_NEW)
13759 q_status.uState = QUEST_CHANGED;
13762 if( CanCompleteQuest( questId ) )
13763 CompleteQuest( questId );
13767 //not used in mangosd, function for external script library
13768 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13770 if( Group *pGroup = GetGroup() )
13772 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13774 Player *pGroupGuy = itr->getSource();
13776 // for any leave or dead (with not released body) group member at appropriate distance
13777 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13778 pGroupGuy->AreaExploredOrEventHappens(questId);
13781 else
13782 AreaExploredOrEventHappens(questId);
13785 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13787 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13789 uint32 questid = GetQuestSlotQuestId(i);
13790 if ( questid == 0 )
13791 continue;
13793 QuestStatusData& q_status = mQuestStatus[questid];
13795 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13796 continue;
13798 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
13799 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13800 continue;
13802 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
13804 uint32 reqitem = qInfo->ReqItemId[j];
13805 if ( reqitem == entry )
13807 uint32 reqitemcount = qInfo->ReqItemCount[j];
13808 uint32 curitemcount = q_status.m_itemcount[j];
13809 if ( curitemcount < reqitemcount )
13811 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13812 q_status.m_itemcount[j] += additemcount;
13813 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13815 SendQuestUpdateAddItem( qInfo, j, additemcount );
13817 if ( CanCompleteQuest( questid ) )
13818 CompleteQuest( questid );
13819 return;
13823 UpdateForQuestWorldObjects();
13826 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13828 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13830 uint32 questid = GetQuestSlotQuestId(i);
13831 if(!questid)
13832 continue;
13833 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
13834 if ( !qInfo )
13835 continue;
13836 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13837 continue;
13839 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
13841 uint32 reqitem = qInfo->ReqItemId[j];
13842 if ( reqitem == entry )
13844 QuestStatusData& q_status = mQuestStatus[questid];
13846 uint32 reqitemcount = qInfo->ReqItemCount[j];
13847 uint32 curitemcount;
13848 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13849 curitemcount = q_status.m_itemcount[j];
13850 else
13851 curitemcount = GetItemCount(entry, true);
13852 if ( curitemcount < reqitemcount + count )
13854 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13855 q_status.m_itemcount[j] = curitemcount - remitemcount;
13856 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13858 IncompleteQuest( questid );
13860 return;
13864 UpdateForQuestWorldObjects();
13867 void Player::KilledMonster( CreatureInfo const* cInfo, uint64 guid )
13869 if(cInfo->Entry)
13870 KilledMonsterCredit(cInfo->Entry,guid);
13872 for(int i = 0; i < MAX_KILL_CREDIT; ++i)
13873 if(cInfo->KillCredit[i])
13874 KilledMonsterCredit(cInfo->KillCredit[i],guid);
13877 void Player::KilledMonsterCredit( uint32 entry, uint64 guid )
13879 uint32 addkillcount = 1;
13880 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13881 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13883 uint32 questid = GetQuestSlotQuestId(i);
13884 if(!questid)
13885 continue;
13887 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
13888 if( !qInfo )
13889 continue;
13890 // just if !ingroup || !noraidgroup || raidgroup
13891 QuestStatusData& q_status = mQuestStatus[questid];
13892 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13894 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13896 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13898 // skip GO activate objective or none
13899 if(qInfo->ReqCreatureOrGOId[j] <=0)
13900 continue;
13902 // skip Cast at creature objective
13903 if(qInfo->ReqSpell[j] !=0 )
13904 continue;
13906 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13908 if ( reqkill == entry )
13910 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13911 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13912 if ( curkillcount < reqkillcount )
13914 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13915 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13917 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13919 if ( CanCompleteQuest( questid ) )
13920 CompleteQuest( questid );
13922 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13923 continue;
13931 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13933 bool isCreature = IS_CREATURE_GUID(guid);
13935 uint32 addCastCount = 1;
13936 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
13938 uint32 questid = GetQuestSlotQuestId(i);
13939 if(!questid)
13940 continue;
13942 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
13943 if ( !qInfo )
13944 continue;
13946 QuestStatusData& q_status = mQuestStatus[questid];
13948 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13950 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13952 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13954 // skip kill creature objective (0) or wrong spell casts
13955 if(qInfo->ReqSpell[j] != spell_id )
13956 continue;
13958 uint32 reqTarget = 0;
13960 if(isCreature)
13962 // creature activate objectives
13963 if(qInfo->ReqCreatureOrGOId[j] > 0)
13964 // checked at quest_template loading
13965 reqTarget = qInfo->ReqCreatureOrGOId[j];
13967 else
13969 // GO activate objective
13970 if(qInfo->ReqCreatureOrGOId[j] < 0)
13971 // checked at quest_template loading
13972 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13975 // other not this creature/GO related objectives
13976 if( reqTarget != entry )
13977 continue;
13979 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13980 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13981 if ( curCastCount < reqCastCount )
13983 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13984 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13986 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13989 if ( CanCompleteQuest( questid ) )
13990 CompleteQuest( questid );
13992 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13993 break;
14000 void Player::TalkedToCreature( uint32 entry, uint64 guid )
14002 uint32 addTalkCount = 1;
14003 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14005 uint32 questid = GetQuestSlotQuestId(i);
14006 if(!questid)
14007 continue;
14009 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14010 if ( !qInfo )
14011 continue;
14013 QuestStatusData& q_status = mQuestStatus[questid];
14015 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14017 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
14019 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
14021 // skip spell casts and Gameobject objectives
14022 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
14023 continue;
14025 uint32 reqTarget = 0;
14027 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
14028 // checked at quest_template loading
14029 reqTarget = qInfo->ReqCreatureOrGOId[j];
14030 else
14031 continue;
14033 if ( reqTarget == entry )
14035 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
14036 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
14037 if ( curTalkCount < reqTalkCount )
14039 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
14040 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14042 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
14044 if ( CanCompleteQuest( questid ) )
14045 CompleteQuest( questid );
14047 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14048 continue;
14056 void Player::MoneyChanged( uint32 count )
14058 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14060 uint32 questid = GetQuestSlotQuestId(i);
14061 if (!questid)
14062 continue;
14064 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14065 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
14067 QuestStatusData& q_status = mQuestStatus[questid];
14069 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14071 if(int32(count) >= -qInfo->GetRewOrReqMoney())
14073 if ( CanCompleteQuest( questid ) )
14074 CompleteQuest( questid );
14077 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
14079 if(int32(count) < -qInfo->GetRewOrReqMoney())
14080 IncompleteQuest( questid );
14086 void Player::ReputationChanged(FactionEntry const* factionEntry )
14088 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14090 if(uint32 questid = GetQuestSlotQuestId(i))
14092 if(Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid))
14094 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
14096 QuestStatusData& q_status = mQuestStatus[questid];
14097 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14099 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
14100 if ( CanCompleteQuest( questid ) )
14101 CompleteQuest( questid );
14103 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
14105 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
14106 IncompleteQuest( questid );
14114 bool Player::HasQuestForItem( uint32 itemid ) const
14116 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14118 uint32 questid = GetQuestSlotQuestId(i);
14119 if ( questid == 0 )
14120 continue;
14122 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
14123 if(qs_itr == mQuestStatus.end())
14124 continue;
14126 QuestStatusData const& q_status = qs_itr->second;
14128 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
14130 Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid);
14131 if(!qinfo)
14132 continue;
14134 // hide quest if player is in raid-group and quest is no raid quest
14135 if (GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID
14136 && !InBattleGround())
14137 continue;
14139 // There should be no mixed ReqItem/ReqSource drop
14140 // This part for ReqItem drop
14141 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
14143 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
14144 return true;
14146 // This part - for ReqSource
14147 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
14149 // examined item is a source item
14150 if (qinfo->ReqSourceId[j] == itemid)
14152 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(itemid);
14154 // 'unique' item
14155 if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
14156 return true;
14158 // allows custom amount drop when not 0
14159 if (qinfo->ReqSourceCount[j])
14161 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
14162 return true;
14163 } else if (GetItemCount(itemid,true) < pProto->Stackable)
14164 return true;
14169 return false;
14172 void Player::SendQuestComplete( uint32 quest_id )
14174 if( quest_id )
14176 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
14177 data << uint32(quest_id);
14178 GetSession()->SendPacket( &data );
14179 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
14183 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
14185 uint32 questid = pQuest->GetQuestId();
14186 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
14187 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
14188 data << uint32(questid);
14190 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
14192 data << uint32(XP);
14193 data << uint32(pQuest->GetRewOrReqMoney());
14195 else
14197 data << uint32(0);
14198 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
14201 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
14202 data << uint32(pQuest->GetBonusTalents()); // bonus talents
14203 GetSession()->SendPacket( &data );
14205 if (pQuest->GetQuestCompleteScript() != 0)
14206 GetMap()->ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
14209 void Player::SendQuestFailed( uint32 quest_id )
14211 if( quest_id )
14213 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
14214 data << uint32(quest_id);
14215 data << uint32(0); // failed reason (4 for inventory is full)
14216 GetSession()->SendPacket( &data );
14217 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
14221 void Player::SendQuestTimerFailed( uint32 quest_id )
14223 if( quest_id )
14225 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
14226 data << uint32(quest_id);
14227 GetSession()->SendPacket( &data );
14228 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
14232 void Player::SendCanTakeQuestResponse( uint32 msg )
14234 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
14235 data << uint32(msg);
14236 GetSession()->SendPacket( &data );
14237 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
14240 void Player::SendQuestConfirmAccept(const Quest* pQuest, Player* pReceiver)
14242 if (pReceiver)
14244 std::string strTitle = pQuest->GetTitle();
14246 int loc_idx = pReceiver->GetSession()->GetSessionDbLocaleIndex();
14248 if (loc_idx >= 0)
14250 if (const QuestLocale* pLocale = sObjectMgr.GetQuestLocale(pQuest->GetQuestId()))
14252 if (pLocale->Title.size() > loc_idx && !pLocale->Title[loc_idx].empty())
14253 strTitle = pLocale->Title[loc_idx];
14257 WorldPacket data(SMSG_QUEST_CONFIRM_ACCEPT, (4 + strTitle.size() + 8));
14258 data << uint32(pQuest->GetQuestId());
14259 data << strTitle;
14260 data << uint64(GetGUID());
14261 pReceiver->GetSession()->SendPacket(&data);
14263 sLog.outDebug("WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT");
14267 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
14269 if( pPlayer )
14271 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
14272 data << uint64(pPlayer->GetGUID());
14273 data << uint8(msg); // valid values: 0-8
14274 GetSession()->SendPacket( &data );
14275 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
14279 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
14281 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
14282 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
14283 //data << pQuest->ReqItemId[item_idx];
14284 //data << count;
14285 GetSession()->SendPacket( &data );
14288 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
14290 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
14292 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
14293 if (entry < 0)
14294 // client expected gameobject template id in form (id|0x80000000)
14295 entry = (-entry) | 0x80000000;
14297 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
14298 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
14299 data << uint32(pQuest->GetQuestId());
14300 data << uint32(entry);
14301 data << uint32(old_count + add_count);
14302 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
14303 data << uint64(guid);
14304 GetSession()->SendPacket(&data);
14306 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
14307 if( log_slot < MAX_QUEST_LOG_SIZE)
14308 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
14311 /*********************************************************/
14312 /*** LOAD SYSTEM ***/
14313 /*********************************************************/
14315 void Player::_LoadDeclinedNames(QueryResult* result)
14317 if(!result)
14318 return;
14320 if(m_declinedname)
14321 delete m_declinedname;
14323 m_declinedname = new DeclinedName;
14324 Field *fields = result->Fetch();
14325 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
14326 m_declinedname->name[i] = fields[i].GetCppString();
14328 delete result;
14331 void Player::_LoadArenaTeamInfo(QueryResult *result)
14333 // arenateamid, played_week, played_season, personal_rating
14334 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32) * MAX_ARENA_SLOT * ARENA_TEAM_END);
14335 if (!result)
14336 return;
14340 Field *fields = result->Fetch();
14342 uint32 arenateamid = fields[0].GetUInt32();
14343 uint32 played_week = fields[1].GetUInt32();
14344 uint32 played_season = fields[2].GetUInt32();
14345 uint32 wons_season = fields[3].GetUInt32();
14346 uint32 personal_rating = fields[4].GetUInt32();
14348 ArenaTeam* aTeam = sObjectMgr.GetArenaTeamById(arenateamid);
14349 if(!aTeam)
14351 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u", arenateamid);
14352 continue;
14354 uint8 arenaSlot = aTeam->GetSlot();
14356 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_ID] = arenateamid; // TeamID
14357 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_TYPE] = aTeam->GetType(); // team type
14358 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_MEMBER] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
14359 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_GAMES_WEEK] = played_week; // Played Week
14360 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_GAMES_SEASON] = played_season; // Played Season
14361 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_WINS_SEASON] = wons_season; // wins season
14362 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_PERSONAL_RATING] = personal_rating; // Personal Rating
14364 } while (result->NextRow());
14365 delete result;
14368 void Player::_LoadEquipmentSets(QueryResult *result)
14370 // 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));
14371 if (!result)
14372 return;
14374 uint32 count = 0;
14377 Field *fields = result->Fetch();
14379 EquipmentSet eqSet;
14381 eqSet.Guid = fields[0].GetUInt64();
14382 uint32 index = fields[1].GetUInt32();
14383 eqSet.Name = fields[2].GetCppString();
14384 eqSet.IconName = fields[3].GetCppString();
14385 eqSet.state = EQUIPMENT_SET_UNCHANGED;
14387 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
14388 eqSet.Items[i] = fields[4+i].GetUInt32();
14390 m_EquipmentSets[index] = eqSet;
14392 ++count;
14394 if(count >= MAX_EQUIPMENT_SET_INDEX) // client limit
14395 break;
14396 } while (result->NextRow());
14397 delete result;
14400 void Player::_LoadBGData(QueryResult* result)
14402 if (!result)
14403 return;
14405 // Expecting only one row
14406 Field *fields = result->Fetch();
14407 /* bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
14408 m_bgData.bgInstanceID = fields[0].GetUInt32();
14409 m_bgData.bgTeam = fields[1].GetUInt32();
14410 m_bgData.joinPos = WorldLocation(fields[6].GetUInt32(), // Map
14411 fields[2].GetFloat(), // X
14412 fields[3].GetFloat(), // Y
14413 fields[4].GetFloat(), // Z
14414 fields[5].GetFloat()); // Orientation
14415 m_bgData.taxiPath[0] = fields[7].GetUInt32();
14416 m_bgData.taxiPath[1] = fields[8].GetUInt32();
14417 m_bgData.mountSpell = fields[9].GetUInt32();
14419 delete result;
14422 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
14424 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
14425 if(!result)
14426 return false;
14428 Field *fields = result->Fetch();
14430 x = fields[0].GetFloat();
14431 y = fields[1].GetFloat();
14432 z = fields[2].GetFloat();
14433 o = fields[3].GetFloat();
14434 mapid = fields[4].GetUInt32();
14435 in_flight = !fields[5].GetCppString().empty();
14437 delete result;
14438 return true;
14441 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
14443 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
14444 if( !result )
14445 return false;
14447 Field *fields = result->Fetch();
14449 data = StrSplit(fields[0].GetCppString(), " ");
14451 delete result;
14453 return true;
14456 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
14458 if(index >= data.size())
14459 return 0;
14461 return (uint32)atoi(data[index].c_str());
14464 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
14466 float result;
14467 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
14468 memcpy(&result, &temp, sizeof(result));
14470 return result;
14473 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
14475 Tokens data;
14476 if(!LoadValuesArrayFromDB(data,guid))
14477 return 0;
14479 return GetUInt32ValueFromArray(data,index);
14482 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
14484 float result;
14485 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
14486 memcpy(&result, &temp, sizeof(result));
14488 return result;
14491 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
14493 //// 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
14494 //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty, arena_pending_points FROM characters WHERE guid = '%u'", guid);
14495 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
14497 if(!result)
14499 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
14500 return false;
14503 Field *fields = result->Fetch();
14505 uint32 dbAccountId = fields[1].GetUInt32();
14507 // check if the character's account in the db and the logged in account match.
14508 // player should be able to load/delete character only with correct account!
14509 if( dbAccountId != GetSession()->GetAccountId() )
14511 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
14512 delete result;
14513 return false;
14516 Object::_Create( guid, 0, HIGHGUID_PLAYER );
14518 m_name = fields[3].GetCppString();
14520 // check name limitations
14521 if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS ||
14522 (GetSession()->GetSecurity() == SEC_PLAYER && sObjectMgr.IsReservedName(m_name)))
14524 delete result;
14525 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
14526 return false;
14529 if(!LoadValues( fields[2].GetString()))
14531 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid));
14532 delete result;
14533 return false;
14536 // overwrite possible wrong/corrupted guid
14537 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
14539 // overwrite some data fields
14540 uint32 bytes0 = GetUInt32Value(UNIT_FIELD_BYTES_0) & 0xFF000000;
14541 bytes0 |= fields[4].GetUInt8(); // race
14542 bytes0 |= fields[5].GetUInt8() << 8; // class
14543 bytes0 |= fields[6].GetUInt8() << 16; // gender
14544 SetUInt32Value(UNIT_FIELD_BYTES_0, bytes0);
14546 SetUInt32Value(UNIT_FIELD_LEVEL, fields[7].GetUInt8());
14547 SetUInt32Value(PLAYER_XP, fields[8].GetUInt32());
14548 SetUInt32Value(PLAYER_FIELD_COINAGE, fields[9].GetUInt32());
14549 SetUInt32Value(PLAYER_BYTES, fields[10].GetUInt32());
14550 SetUInt32Value(PLAYER_BYTES_2, fields[11].GetUInt32());
14551 SetUInt32Value(PLAYER_BYTES_3, (GetUInt32Value(PLAYER_BYTES_3) & ~1) | fields[6].GetUInt8());
14552 SetUInt32Value(PLAYER_FLAGS, fields[12].GetUInt32());
14554 InitDisplayIds();
14556 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14557 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
14559 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0 );
14560 SetVisibleItemSlot(slot, NULL);
14562 if (m_items[slot])
14564 delete m_items[slot];
14565 m_items[slot] = NULL;
14569 // update money limits
14570 if(GetMoney() > MAX_MONEY_AMOUNT)
14571 SetMoney(MAX_MONEY_AMOUNT);
14573 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
14574 outDebugValues();
14576 //Need to call it to initialize m_team (m_team can be calculated from race)
14577 //Other way is to saves m_team into characters table.
14578 setFactionForRace(getRace());
14579 SetCharm(NULL);
14581 // load home bind and check in same time class/race pair, it used later for restore broken positions
14582 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
14584 delete result;
14585 return false;
14588 InitPrimaryProfessions(); // to max set before any spell loaded
14590 // init saved position, and fix it later if problematic
14591 uint32 transGUID = fields[31].GetUInt32();
14592 Relocate(fields[13].GetFloat(),fields[14].GetFloat(),fields[15].GetFloat(),fields[17].GetFloat());
14593 SetLocationMapId(fields[16].GetUInt32());
14595 uint32 difficulty = fields[39].GetUInt32();
14596 if(difficulty >= MAX_DUNGEON_DIFFICULTY)
14597 difficulty = DUNGEON_DIFFICULTY_NORMAL;
14598 SetDungeonDifficulty(Difficulty(difficulty)); // may be changed in _LoadGroup
14600 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
14602 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
14604 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[40].GetUInt32();
14605 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
14606 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
14608 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
14610 // check arena teams integrity
14611 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
14613 uint32 arena_team_id = GetArenaTeamId(arena_slot);
14614 if(!arena_team_id)
14615 continue;
14617 if(ArenaTeam * at = sObjectMgr.GetArenaTeamById(arena_team_id))
14618 if(at->HaveMember(GetGUID()))
14619 continue;
14621 // arena team not exist or not member, cleanup fields
14622 for(int j = 0; j < ARENA_TEAM_END; ++j)
14623 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arena_slot * ARENA_TEAM_END) + j, 0);
14626 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
14628 if(!IsPositionValid())
14630 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());
14631 RelocateToHomebind();
14633 transGUID = 0;
14635 m_movementInfo.t_x = 0.0f;
14636 m_movementInfo.t_y = 0.0f;
14637 m_movementInfo.t_z = 0.0f;
14638 m_movementInfo.t_o = 0.0f;
14639 m_movementInfo.t_time = 0;
14640 m_movementInfo.t_seat = -1;
14643 _LoadBGData(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBGDATA));
14645 if(m_bgData.bgInstanceID) //saved in BattleGround
14647 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(m_bgData.bgInstanceID, BATTLEGROUND_TYPE_NONE);
14649 if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID()))
14651 BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
14652 AddBattleGroundQueueId(bgQueueTypeId);
14654 m_bgData.bgTypeID = currentBg->GetTypeID();
14656 //join player to battleground group
14657 currentBg->EventPlayerLoggedIn(this, GetGUID());
14658 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), m_bgData.bgTeam);
14660 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
14662 else
14664 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14665 SetLocationMapId(_loc.mapid);
14666 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14668 // We are not in BG anymore
14669 m_bgData.bgInstanceID = 0;
14672 else
14674 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14675 // if server restart after player save in BG or area
14676 // player can have current coordinates in to BG/Arena map, fix this
14677 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
14679 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14680 SetLocationMapId(_loc.mapid);
14681 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14685 if (transGUID != 0)
14687 m_movementInfo.t_x = fields[27].GetFloat();
14688 m_movementInfo.t_y = fields[28].GetFloat();
14689 m_movementInfo.t_z = fields[29].GetFloat();
14690 m_movementInfo.t_o = fields[30].GetFloat();
14692 if( !MaNGOS::IsValidMapCoord(
14693 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14694 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
14695 // transport size limited
14696 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
14698 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14699 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14700 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
14702 RelocateToHomebind();
14704 m_movementInfo.t_x = 0.0f;
14705 m_movementInfo.t_y = 0.0f;
14706 m_movementInfo.t_z = 0.0f;
14707 m_movementInfo.t_o = 0.0f;
14708 m_movementInfo.t_time = 0;
14709 m_movementInfo.t_seat = -1;
14711 transGUID = 0;
14715 if (transGUID != 0)
14717 for (MapManager::TransportSet::const_iterator iter = sMapMgr.m_Transports.begin(); iter != sMapMgr.m_Transports.end(); ++iter)
14719 if( (*iter)->GetGUIDLow() == transGUID)
14721 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
14722 // client without expansion support
14723 if(GetSession()->Expansion() < transMapEntry->Expansion())
14725 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
14726 break;
14729 m_transport = *iter;
14730 m_transport->AddPassenger(this);
14731 SetLocationMapId(m_transport->GetMapId());
14732 break;
14736 if(!m_transport)
14738 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14739 guid,transGUID);
14741 RelocateToHomebind();
14743 m_movementInfo.t_x = 0.0f;
14744 m_movementInfo.t_y = 0.0f;
14745 m_movementInfo.t_z = 0.0f;
14746 m_movementInfo.t_o = 0.0f;
14747 m_movementInfo.t_time = 0;
14748 m_movementInfo.t_seat = -1;
14750 transGUID = 0;
14753 else // not transport case
14755 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14756 // client without expansion support
14757 if(GetSession()->Expansion() < mapEntry->Expansion())
14759 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14760 RelocateToHomebind();
14764 // NOW player must have valid map
14765 // load the player's map here if it's not already loaded
14766 SetMap(sMapMgr.CreateMap(GetMapId(), this));
14768 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14769 if(GetInstanceId() && !sInstanceSaveMgr.GetInstanceSave(GetInstanceId()))
14771 AreaTrigger const* at = sObjectMgr.GetMapEntranceTrigger(GetMapId());
14772 if(at)
14773 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14774 else
14775 sLog.outError("Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no area-trigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), GetMapId());
14778 SaveRecallPosition();
14780 time_t now = time(NULL);
14781 time_t logoutTime = time_t(fields[23].GetUInt64());
14783 // since last logout (in seconds)
14784 uint64 time_diff = uint64(now - logoutTime);
14786 // set value, including drunk invisibility detection
14787 // calculate sobering. after 15 minutes logged out, the player will be sober again
14788 float soberFactor;
14789 if(time_diff > 15*MINUTE)
14790 soberFactor = 0;
14791 else
14792 soberFactor = 1-time_diff/(15.0f*MINUTE);
14793 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14794 SetDrunkValue(newDrunkenValue);
14796 m_rest_bonus = fields[22].GetFloat();
14797 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14798 float bubble0 = 0.031;
14799 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14800 float bubble1 = 0.125;
14802 if(time_diff > 0)
14804 float bubble = fields[24].GetUInt32() > 0
14805 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14806 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14808 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14811 m_cinematic = fields[19].GetUInt32();
14812 m_Played_time[PLAYED_TIME_TOTAL]= fields[20].GetUInt32();
14813 m_Played_time[PLAYED_TIME_LEVEL]= fields[21].GetUInt32();
14815 m_resetTalentsCost = fields[25].GetUInt32();
14816 m_resetTalentsTime = time_t(fields[26].GetUInt64());
14818 // reserve some flags
14819 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14821 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14822 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14824 m_taxi.LoadTaxiMask( fields[18].GetString() ); // must be before InitTaxiNodesForLevel
14826 uint32 extraflags = fields[32].GetUInt32();
14828 m_stableSlots = fields[33].GetUInt32();
14829 if(m_stableSlots > MAX_PET_STABLES)
14831 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
14832 m_stableSlots = MAX_PET_STABLES;
14835 m_atLoginFlags = fields[34].GetUInt32();
14837 // Honor system
14838 // Update Honor kills data
14839 m_lastHonorUpdateTime = logoutTime;
14840 UpdateHonorFields();
14842 m_deathExpireTime = (time_t)fields[37].GetUInt64();
14843 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14844 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14846 std::string taxi_nodes = fields[38].GetCppString();
14848 delete result;
14850 // clear channel spell data (if saved at channel spell casting)
14851 SetChannelObjectGUID(0);
14852 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14854 // clear charm/summon related fields
14855 SetCharm(NULL);
14856 SetPet(NULL);
14857 SetTargetGUID(0);
14858 SetChannelObjectGUID(0);
14859 SetCharmerGUID(0);
14860 SetOwnerGUID(0);
14861 SetCreatorGUID(0);
14863 // reset some aura modifiers before aura apply
14864 SetFarSightGUID(0);
14865 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14866 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14868 // cleanup aura list explicitly before skill load wher some spells can be applied
14869 RemoveAllAuras();
14871 _LoadSkills(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSKILLS));
14873 // make sure the unit is considered out of combat for proper loading
14874 ClearInCombat();
14876 // make sure the unit is considered not in duel for proper loading
14877 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14878 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14880 // remember loaded power/health values to restore after stats initialization and modifier applying
14881 uint32 savedHealth = GetHealth();
14882 uint32 savedPower[MAX_POWERS];
14883 for(uint32 i = 0; i < MAX_POWERS; ++i)
14884 savedPower[i] = GetPower(Powers(i));
14886 // reset stats before loading any modifiers
14887 InitStatsForLevel();
14888 InitTaxiNodesForLevel();
14889 InitGlyphsForLevel();
14890 InitRunes();
14892 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14894 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14895 //_LoadMail();
14897 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14898 _LoadGlyphAuras();
14900 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14901 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14902 m_deathState = DEAD;
14904 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14906 // after spell load, learn rewarded spell if need also
14907 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14908 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14910 // after spell and quest load
14911 InitTalentForLevel();
14912 learnDefaultSpells();
14914 // must be before inventory (some items required reputation check)
14915 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14917 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14919 // update items with duration and realtime
14920 UpdateItemDuration(time_diff, true);
14922 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14924 // unread mails and next delivery time, actual mails not loaded
14925 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14927 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14929 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14930 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14931 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14933 if(!HasTitle(curTitle))
14934 SetUInt32Value(PLAYER_CHOSEN_TITLE, 0);
14937 // Not finish taxi flight path
14938 if(m_bgData.HasTaxiPath())
14940 m_taxi.ClearTaxiDestinations();
14941 for (int i = 0; i < 2; ++i)
14942 m_taxi.AddTaxiDestination(m_bgData.taxiPath[i]);
14944 else if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14946 // problems with taxi path loading
14947 TaxiNodesEntry const* nodeEntry = NULL;
14948 if(uint32 node_id = m_taxi.GetTaxiSource())
14949 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14951 if(!nodeEntry) // don't know taxi start node, to homebind
14953 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14954 RelocateToHomebind();
14956 else // have start node, to it
14958 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14959 SetLocationMapId(nodeEntry->map_id);
14960 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14963 //we can be relocated from taxi and still have an outdated Map pointer!
14964 //so we need to get a new Map pointer!
14965 SetMap(sMapMgr.CreateMap(GetMapId(), this));
14966 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14968 m_taxi.ClearTaxiDestinations();
14971 if(uint32 node_id = m_taxi.GetTaxiSource())
14973 // save source node as recall coord to prevent recall and fall from sky
14974 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14975 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14976 m_recallMap = nodeEntry->map_id;
14977 m_recallX = nodeEntry->x;
14978 m_recallY = nodeEntry->y;
14979 m_recallZ = nodeEntry->z;
14981 // flight will started later
14984 // has to be called after last Relocate() in Player::LoadFromDB
14985 SetFallInformation(0, GetPositionZ());
14987 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14989 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14990 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14991 if(!isAlive())
14992 RemoveAllAurasOnDeath();
14994 //apply all stat bonuses from items and auras
14995 SetCanModifyStats(true);
14996 UpdateAllStats();
14998 // restore remembered power/health values (but not more max values)
14999 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
15000 for(uint32 i = 0; i < MAX_POWERS; ++i)
15001 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
15003 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
15004 outDebugValues();
15006 // GM state
15007 if(GetSession()->GetSecurity() > SEC_PLAYER)
15009 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
15011 default:
15012 case 0: break; // disable
15013 case 1: SetGameMaster(true); break; // enable
15014 case 2: // save state
15015 if(extraflags & PLAYER_EXTRA_GM_ON)
15016 SetGameMaster(true);
15017 break;
15020 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
15022 default:
15023 case 0: SetGMVisible(false); break; // invisible
15024 case 1: break; // visible
15025 case 2: // save state
15026 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
15027 SetGMVisible(false);
15028 break;
15031 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
15033 default:
15034 case 0: break; // disable
15035 case 1: SetAcceptTicket(true); break; // enable
15036 case 2: // save state
15037 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
15038 SetAcceptTicket(true);
15039 break;
15042 switch(sWorld.getConfig(CONFIG_GM_CHAT))
15044 default:
15045 case 0: break; // disable
15046 case 1: SetGMChat(true); break; // enable
15047 case 2: // save state
15048 if(extraflags & PLAYER_EXTRA_GM_CHAT)
15049 SetGMChat(true);
15050 break;
15053 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
15055 default:
15056 case 0: break; // disable
15057 case 1: SetAcceptWhispers(true); break; // enable
15058 case 2: // save state
15059 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
15060 SetAcceptWhispers(true);
15061 break;
15065 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
15067 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
15068 m_achievementMgr.CheckAllAchievementCriteria();
15070 _LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
15072 return true;
15075 bool Player::isAllowedToLoot(Creature* creature)
15077 if(Player* recipient = creature->GetLootRecipient())
15079 if (recipient == this)
15080 return true;
15081 if( Group* otherGroup = recipient->GetGroup())
15083 Group* thisGroup = GetGroup();
15084 if(!thisGroup)
15085 return false;
15086 return thisGroup == otherGroup;
15088 return false;
15090 else
15091 // prevent other players from looting if the recipient got disconnected
15092 return !creature->hasLootRecipient();
15095 void Player::_LoadActions(QueryResult *result)
15097 m_actionButtons.clear();
15099 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
15101 if(result)
15105 Field *fields = result->Fetch();
15107 uint8 button = fields[0].GetUInt8();
15108 uint32 action = fields[1].GetUInt32();
15109 uint8 type = fields[2].GetUInt8();
15111 if(ActionButton* ab = addActionButton(button, action, type))
15112 ab->uState = ACTIONBUTTON_UNCHANGED;
15113 else
15115 sLog.outError( " ...at loading, and will deleted in DB also");
15117 // Will deleted in DB at next save (it can create data until save but marked as deleted)
15118 m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
15121 while( result->NextRow() );
15123 delete result;
15127 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
15129 //RemoveAllAuras(); -- some spells casted before aura load, for example in LoadSkills, aura list explcitly cleaned early
15131 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15133 if(result)
15137 Field *fields = result->Fetch();
15138 uint64 caster_guid = fields[0].GetUInt64();
15139 uint32 spellid = fields[1].GetUInt32();
15140 uint32 effindex = fields[2].GetUInt32();
15141 uint32 stackcount = fields[3].GetUInt32();
15142 int32 damage = (int32)fields[4].GetUInt32();
15143 int32 maxduration = (int32)fields[5].GetUInt32();
15144 int32 remaintime = (int32)fields[6].GetUInt32();
15145 int32 remaincharges = (int32)fields[7].GetUInt32();
15147 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
15148 if(!spellproto)
15150 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
15151 continue;
15154 if(effindex >= 3)
15156 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
15157 continue;
15160 // negative effects should continue counting down after logout
15161 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
15163 if (remaintime/IN_MILISECONDS <= int32(timediff))
15164 continue;
15166 remaintime -= timediff*IN_MILISECONDS;
15169 // prevent wrong values of remaincharges
15170 if(spellproto->procCharges)
15172 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
15173 remaincharges = spellproto->procCharges;
15175 else
15176 remaincharges = 0;
15179 for(uint32 i=0; i<stackcount; ++i)
15181 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
15182 if(!damage)
15183 damage = aura->GetModifier()->m_amount;
15185 // reset stolen single target auras
15186 if (caster_guid != GetGUID() && aura->IsSingleTarget())
15187 aura->SetIsSingleTarget(false);
15189 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
15190 AddAura(aura);
15191 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
15194 while( result->NextRow() );
15196 delete result;
15199 if(getClass() == CLASS_WARRIOR && !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT))
15200 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
15203 void Player::_LoadGlyphAuras()
15205 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
15207 if (uint32 glyph = GetGlyph(i))
15209 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
15211 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
15213 if(gp->TypeFlags == gs->TypeFlags)
15215 CastSpell(this, gp->SpellId, true);
15216 continue;
15218 else
15219 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
15221 else
15222 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
15224 else
15225 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
15227 // On any error remove glyph
15228 SetGlyph(i, 0);
15233 void Player::LoadCorpse()
15235 if( isAlive() )
15237 sObjectAccessor.ConvertCorpseForPlayer(GetGUID());
15239 else
15241 if(Corpse *corpse = GetCorpse())
15243 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
15245 else
15247 //Prevent Dead Player login without corpse
15248 ResurrectPlayer(0.5f);
15253 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
15255 //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());
15256 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
15257 //NOTE: the "order by `bag`" is important because it makes sure
15258 //the bagMap is filled before items in the bags are loaded
15259 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
15260 //expected to be equipped before offhand items (TODO: fixme)
15262 uint32 zone = GetZoneId();
15264 if (result)
15266 std::list<Item*> problematicItems;
15268 // prevent items from being added to the queue when stored
15269 m_itemUpdateQueueBlocked = true;
15272 Field *fields = result->Fetch();
15273 uint32 bag_guid = fields[1].GetUInt32();
15274 uint8 slot = fields[2].GetUInt8();
15275 uint32 item_guid = fields[3].GetUInt32();
15276 uint32 item_id = fields[4].GetUInt32();
15278 ItemPrototype const * proto = ObjectMgr::GetItemPrototype(item_id);
15280 if(!proto)
15282 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15283 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
15284 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
15285 continue;
15288 Item *item = NewItemOrBag(proto);
15290 if(!item->LoadFromDB(item_guid, GetGUID(), result))
15292 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
15293 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15294 item->FSetState(ITEM_REMOVED);
15295 item->SaveToDB(); // it also deletes item object !
15296 continue;
15299 // not allow have in alive state item limited to another map/zone
15300 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
15302 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15303 item->FSetState(ITEM_REMOVED);
15304 item->SaveToDB(); // it also deletes item object !
15305 continue;
15308 // "Conjured items disappear if you are logged out for more than 15 minutes"
15309 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
15311 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15312 item->FSetState(ITEM_REMOVED);
15313 item->SaveToDB(); // it also deletes item object !
15314 continue;
15317 bool success = true;
15319 // the item/bag is not in a bag
15320 if (!bag_guid)
15322 item->SetContainer( NULL );
15323 item->SetSlot(slot);
15325 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
15327 ItemPosCountVec dest;
15328 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
15329 item = StoreItem(dest, item, true);
15330 else
15331 success = false;
15333 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
15335 uint16 dest;
15336 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
15337 QuickEquipItem(dest, item);
15338 else
15339 success = false;
15341 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
15343 ItemPosCountVec dest;
15344 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
15345 item = BankItem(dest, item, true);
15346 else
15347 success = false;
15350 if(success)
15352 // store bags that may contain items in them
15353 if(item->IsBag() && IsBagPos(item->GetPos()))
15354 bagMap[item_guid] = (Bag*)item;
15357 // the item/bag in a bag
15358 else
15360 item->SetSlot(NULL_SLOT);
15361 // the item is in a bag, find the bag
15362 std::map<uint64, Bag*>::const_iterator itr = bagMap.find(bag_guid);
15363 if(itr != bagMap.end() && slot < itr->second->GetBagSize())
15365 ItemPosCountVec dest;
15366 if( CanStoreItem( itr->second->GetSlot(), slot, dest, item, false ) == EQUIP_ERR_OK )
15367 item = StoreItem(dest, item, true);
15368 else
15369 success = false;
15371 else
15372 success = false;
15375 // item's state may have changed after stored
15376 if (success)
15377 item->SetState(ITEM_UNCHANGED, this);
15378 else
15380 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);
15381 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15382 problematicItems.push_back(item);
15384 } while (result->NextRow());
15386 delete result;
15387 m_itemUpdateQueueBlocked = false;
15389 // send by mail problematic items
15390 while(!problematicItems.empty())
15392 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
15394 // fill mail
15395 MailDraft draft(subject);
15397 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
15399 Item* item = problematicItems.front();
15400 problematicItems.pop_front();
15402 draft.AddItem(item);
15405 draft.SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM));
15408 //if(isAlive())
15409 _ApplyAllItemMods();
15412 // load mailed item which should receive current player
15413 void Player::_LoadMailedItems(Mail *mail)
15415 // data needs to be at first place for Item::LoadFromDB
15416 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);
15417 if(!result)
15418 return;
15422 Field *fields = result->Fetch();
15423 uint32 item_guid_low = fields[1].GetUInt32();
15424 uint32 item_template = fields[2].GetUInt32();
15426 mail->AddItem(item_guid_low, item_template);
15428 ItemPrototype const *proto = ObjectMgr::GetItemPrototype(item_template);
15430 if(!proto)
15432 sLog.outError( "Player %u has unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), item_guid_low, item_template,mail->messageID);
15433 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
15434 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
15435 continue;
15438 Item *item = NewItemOrBag(proto);
15440 if(!item->LoadFromDB(item_guid_low, 0, result))
15442 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
15443 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
15444 item->FSetState(ITEM_REMOVED);
15445 item->SaveToDB(); // it also deletes item object !
15446 continue;
15449 AddMItem(item);
15450 } while (result->NextRow());
15452 delete result;
15455 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
15457 //set a count of unread mails
15458 //QueryResult *resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" UI64FMTD "'", GUID_LOPART(playerGuid),(uint64)cTime);
15459 if (resultUnread)
15461 Field *fieldMail = resultUnread->Fetch();
15462 unReadMails = fieldMail[0].GetUInt8();
15463 delete resultUnread;
15466 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
15467 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
15468 if (resultDelivery)
15470 Field *fieldMail = resultDelivery->Fetch();
15471 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
15472 delete resultDelivery;
15476 void Player::_LoadMail()
15478 m_mail.clear();
15479 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
15480 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());
15481 if(result)
15485 Field *fields = result->Fetch();
15486 Mail *m = new Mail;
15487 m->messageID = fields[0].GetUInt32();
15488 m->messageType = fields[1].GetUInt8();
15489 m->sender = fields[2].GetUInt32();
15490 m->receiver = fields[3].GetUInt32();
15491 m->subject = fields[4].GetCppString();
15492 m->itemTextId = fields[5].GetUInt32();
15493 bool has_items = fields[6].GetBool();
15494 m->expire_time = (time_t)fields[7].GetUInt64();
15495 m->deliver_time = (time_t)fields[8].GetUInt64();
15496 m->money = fields[9].GetUInt32();
15497 m->COD = fields[10].GetUInt32();
15498 m->checked = fields[11].GetUInt32();
15499 m->stationery = fields[12].GetUInt8();
15500 m->mailTemplateId = fields[13].GetInt16();
15502 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
15504 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
15505 m->mailTemplateId = 0;
15508 m->state = MAIL_STATE_UNCHANGED;
15510 if (has_items)
15511 _LoadMailedItems(m);
15513 m_mail.push_back(m);
15514 } while( result->NextRow() );
15515 delete result;
15517 m_mailsLoaded = true;
15520 void Player::LoadPet()
15522 //fixme: the pet should still be loaded if the player is not in world
15523 // just not added to the map
15524 if(IsInWorld())
15526 Pet *pet = new Pet;
15527 if(!pet->LoadPetFromDB(this,0,0,true))
15528 delete pet;
15532 void Player::_LoadQuestStatus(QueryResult *result)
15534 mQuestStatus.clear();
15536 uint32 slot = 0;
15538 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15539 //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());
15541 if(result)
15545 Field *fields = result->Fetch();
15547 uint32 quest_id = fields[0].GetUInt32();
15548 // used to be new, no delete?
15549 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
15550 if( pQuest )
15552 // find or create
15553 QuestStatusData& questStatusData = mQuestStatus[quest_id];
15555 uint32 qstatus = fields[1].GetUInt32();
15556 if(qstatus < MAX_QUEST_STATUS)
15557 questStatusData.m_status = QuestStatus(qstatus);
15558 else
15560 questStatusData.m_status = QUEST_STATUS_NONE;
15561 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
15564 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
15565 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
15567 time_t quest_time = time_t(fields[4].GetUInt64());
15569 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
15571 AddTimedQuest( quest_id );
15573 if (quest_time <= sWorld.GetGameTime())
15574 questStatusData.m_timer = 1;
15575 else
15576 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
15578 else
15579 quest_time = 0;
15581 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
15582 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
15583 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
15584 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
15585 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
15586 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
15587 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
15588 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
15590 questStatusData.uState = QUEST_UNCHANGED;
15592 // add to quest log
15593 if (slot < MAX_QUEST_LOG_SIZE &&
15594 ((questStatusData.m_status == QUEST_STATUS_INCOMPLETE ||
15595 questStatusData.m_status == QUEST_STATUS_COMPLETE ||
15596 questStatusData.m_status == QUEST_STATUS_FAILED) &&
15597 (!questStatusData.m_rewarded || pQuest->IsRepeatable())))
15599 SetQuestSlot(slot, quest_id, quest_time);
15601 if (questStatusData.m_status == QUEST_STATUS_COMPLETE)
15602 SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
15604 if (questStatusData.m_status == QUEST_STATUS_FAILED)
15605 SetQuestSlotState(slot, QUEST_STATE_FAIL);
15607 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
15608 if(questStatusData.m_creatureOrGOcount[idx])
15609 SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]);
15611 ++slot;
15614 if(questStatusData.m_rewarded)
15616 // learn rewarded spell if unknown
15617 learnQuestRewardedSpells(pQuest);
15619 // set rewarded title if any
15620 if(pQuest->GetCharTitleId())
15622 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
15623 SetTitle(titleEntry);
15626 if(pQuest->GetBonusTalents())
15627 m_questRewardTalentCount += pQuest->GetBonusTalents();
15630 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
15633 while( result->NextRow() );
15635 delete result;
15638 // clear quest log tail
15639 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
15640 SetQuestSlot(i, 0);
15643 void Player::_LoadDailyQuestStatus(QueryResult *result)
15645 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15646 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
15648 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15650 if(result)
15652 uint32 quest_daily_idx = 0;
15656 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
15658 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15659 break;
15662 Field *fields = result->Fetch();
15664 uint32 quest_id = fields[0].GetUInt32();
15666 // save _any_ from daily quest times (it must be after last reset anyway)
15667 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
15669 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
15670 if( !pQuest )
15671 continue;
15673 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
15674 ++quest_daily_idx;
15676 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
15678 while( result->NextRow() );
15680 delete result;
15683 m_DailyQuestChanged = false;
15686 void Player::_LoadSpells(QueryResult *result)
15688 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15690 if(result)
15694 Field *fields = result->Fetch();
15696 addSpell(fields[0].GetUInt32(), fields[1].GetBool(), false, false, fields[2].GetBool());
15698 while( result->NextRow() );
15700 delete result;
15704 void Player::_LoadGroup(QueryResult *result)
15706 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15707 if (result)
15709 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
15710 delete result;
15712 if (Group* group = sObjectMgr.GetGroupByLeader(leaderGuid))
15714 uint8 subgroup = group->GetMemberGroup(GetGUID());
15715 SetGroup(group, subgroup);
15716 if (getLevel() >= LEVELREQUIREMENT_HEROIC)
15718 // the group leader may change the instance difficulty while the player is offline
15719 SetDungeonDifficulty(group->GetDungeonDifficulty());
15720 SetRaidDifficulty(group->GetRaidDifficulty());
15726 void Player::_LoadBoundInstances(QueryResult *result)
15728 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
15729 m_boundInstances[i].clear();
15731 Group *group = GetGroup();
15733 //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));
15734 if(result)
15738 Field *fields = result->Fetch();
15739 bool perm = fields[1].GetBool();
15740 uint32 mapId = fields[2].GetUInt32();
15741 uint32 instanceId = fields[0].GetUInt32();
15742 uint8 difficulty = fields[3].GetUInt8();
15744 time_t resetTime = (time_t)fields[4].GetUInt64();
15745 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15746 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15747 // and in that case it is not used
15749 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
15750 if(!mapEntry || !mapEntry->IsDungeon())
15752 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
15753 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15754 continue;
15757 if(difficulty >= MAX_DIFFICULTY)
15759 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
15760 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15761 continue;
15764 MapDifficulty const* mapDiff = GetMapDifficultyData(mapId,Difficulty(difficulty));
15765 if(!mapDiff)
15767 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
15768 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15769 continue;
15772 if(!perm && group)
15774 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);
15775 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15776 continue;
15779 // since non permanent binds are always solo bind, they can always be reset
15780 InstanceSave *save = sInstanceSaveMgr.AddInstanceSave(mapId, instanceId, Difficulty(difficulty), resetTime, !perm, true);
15781 if(save) BindToInstance(save, perm, true);
15782 } while(result->NextRow());
15783 delete result;
15787 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty)
15789 // some instances only have one difficulty
15790 MapDifficulty const* mapDiff = GetMapDifficultyData(mapid,difficulty);
15791 if(!mapDiff)
15792 return NULL;
15794 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15795 if(itr != m_boundInstances[difficulty].end())
15796 return &itr->second;
15797 else
15798 return NULL;
15801 void Player::UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload)
15803 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15804 UnbindInstance(itr, difficulty, unload);
15807 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, Difficulty difficulty, bool unload)
15809 if(itr != m_boundInstances[difficulty].end())
15811 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15812 itr->second.save->RemovePlayer(this); // save can become invalid
15813 m_boundInstances[difficulty].erase(itr++);
15817 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15819 if(save)
15821 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15822 if(bind.save)
15824 // update the save when the group kills a boss
15825 if(permanent != bind.perm || save != bind.save)
15826 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());
15828 else
15829 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15831 if(bind.save != save)
15833 if(bind.save) bind.save->RemovePlayer(this);
15834 save->AddPlayer(this);
15837 if(permanent) save->SetCanReset(false);
15839 bind.save = save;
15840 bind.perm = permanent;
15841 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());
15842 return &bind;
15844 else
15845 return NULL;
15848 void Player::SendRaidInfo()
15850 uint32 counter = 0;
15852 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15854 size_t p_counter = data.wpos();
15855 data << uint32(counter); // placeholder
15857 time_t now = time(NULL);
15859 for(int i = 0; i < MAX_DIFFICULTY; ++i)
15861 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15863 if(itr->second.perm)
15865 InstanceSave *save = itr->second.save;
15866 data << uint32(save->GetMapId()); // map id
15867 data << uint32(save->GetDifficulty()); // difficulty
15868 data << uint64(save->GetInstanceId()); // instance id
15869 data << uint8(1); // expired = 0
15870 data << uint8(0); // extended = 1
15871 data << uint32(save->GetResetTime() - now); // reset time
15872 ++counter;
15876 data.put<uint32>(p_counter, counter);
15877 GetSession()->SendPacket(&data);
15881 - called on every successful teleportation to a map
15883 void Player::SendSavedInstances()
15885 bool hasBeenSaved = false;
15886 WorldPacket data;
15888 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
15890 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15892 if(itr->second.perm) // only permanent binds are sent
15894 hasBeenSaved = true;
15895 break;
15900 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15901 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15902 data << uint32(hasBeenSaved);
15903 GetSession()->SendPacket(&data);
15905 if(!hasBeenSaved)
15906 return;
15908 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
15910 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15912 if(itr->second.perm)
15914 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15915 data << uint32(itr->second.save->GetMapId());
15916 GetSession()->SendPacket(&data);
15922 /// convert the player's binds to the group
15923 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15925 bool has_binds = false;
15926 bool has_solo = false;
15928 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15929 assert(player_guid);
15931 // copy all binds to the group, when changing leader it's assumed the character
15932 // will not have any solo binds
15934 if(player)
15936 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
15938 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15940 has_binds = true;
15941 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15942 // permanent binds are not removed
15943 if(!itr->second.perm)
15945 // increments itr in call
15946 player->UnbindInstance(itr, Difficulty(i), true);
15947 has_solo = true;
15949 else
15950 ++itr;
15955 // if the player's not online we don't know what binds it has
15956 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));
15957 // the following should not get executed when changing leaders
15958 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15961 bool Player::_LoadHomeBind(QueryResult *result)
15963 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass());
15964 if(!info)
15966 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
15967 return false;
15970 bool ok = false;
15971 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15972 if (result)
15974 Field *fields = result->Fetch();
15975 m_homebindMapId = fields[0].GetUInt32();
15976 m_homebindZoneId = fields[1].GetUInt16();
15977 m_homebindX = fields[2].GetFloat();
15978 m_homebindY = fields[3].GetFloat();
15979 m_homebindZ = fields[4].GetFloat();
15980 delete result;
15982 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
15984 // accept saved data only for valid position (and non instanceable), and accessable
15985 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15986 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
15988 ok = true;
15990 else
15991 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15994 if(!ok)
15996 m_homebindMapId = info->mapId;
15997 m_homebindZoneId = info->zoneId;
15998 m_homebindX = info->positionX;
15999 m_homebindY = info->positionY;
16000 m_homebindZ = info->positionZ;
16002 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);
16005 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
16006 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
16008 return true;
16011 /*********************************************************/
16012 /*** SAVE SYSTEM ***/
16013 /*********************************************************/
16015 void Player::SaveToDB()
16017 // we should assure this: assert((m_nextSave != sWorld.getConfig(CONFIG_INTERVAL_SAVE)));
16018 // delay auto save at any saves (manual, in code, or autosave)
16019 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
16021 //lets allow only players in world to be saved
16022 if(IsBeingTeleportedFar())
16024 ScheduleDelayedOperation(DELAYED_SAVE_PLAYER);
16025 return;
16028 // first save/honor gain after midnight will also update the player's honor fields
16029 UpdateHonorFields();
16031 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
16032 outDebugValues();
16034 CharacterDatabase.BeginTransaction();
16036 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
16038 std::string sql_name = m_name;
16039 CharacterDatabase.escape_string(sql_name);
16041 std::ostringstream ss;
16042 ss << "INSERT INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags,"
16043 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
16044 "taximask, online, cinematic, "
16045 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
16046 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
16047 "death_expire_time, taxi_path, arena_pending_points) VALUES ("
16048 << GetGUIDLow() << ", "
16049 << GetSession()->GetAccountId() << ", '"
16050 << sql_name << "', "
16051 << (uint32)getRace() << ", "
16052 << (uint32)getClass() << ", "
16053 << (uint32)getGender() << ", "
16054 << getLevel() << ", "
16055 << GetUInt32Value(PLAYER_XP) << ", "
16056 << GetMoney() << ", "
16057 << GetUInt32Value(PLAYER_BYTES) << ", "
16058 << GetUInt32Value(PLAYER_BYTES_2) << ", "
16059 << GetUInt32Value(PLAYER_FLAGS) << ", ";
16061 if(!IsBeingTeleported())
16063 ss << GetMapId() << ", "
16064 << (uint32)GetDungeonDifficulty() << ", "
16065 << finiteAlways(GetPositionX()) << ", "
16066 << finiteAlways(GetPositionY()) << ", "
16067 << finiteAlways(GetPositionZ()) << ", "
16068 << finiteAlways(GetOrientation()) << ", '";
16070 else
16072 ss << GetTeleportDest().mapid << ", "
16073 << (uint32)GetDungeonDifficulty() << ", "
16074 << finiteAlways(GetTeleportDest().coord_x) << ", "
16075 << finiteAlways(GetTeleportDest().coord_y) << ", "
16076 << finiteAlways(GetTeleportDest().coord_z) << ", "
16077 << finiteAlways(GetTeleportDest().orientation) << ", '";
16080 uint16 i;
16081 for( i = 0; i < m_valuesCount; ++i )
16083 ss << GetUInt32Value(i) << " ";
16086 ss << "', ";
16088 ss << m_taxi << ", "; // string with TaxiMaskSize numbers
16090 ss << (IsInWorld() ? 1 : 0) << ", ";
16092 ss << m_cinematic << ", ";
16094 ss << m_Played_time[PLAYED_TIME_TOTAL] << ", ";
16095 ss << m_Played_time[PLAYED_TIME_LEVEL] << ", ";
16097 ss << finiteAlways(m_rest_bonus) << ", ";
16098 ss << (uint64)time(NULL) << ", ";
16099 ss << (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0) << ", ";
16100 //save, far from tavern/city
16101 //save, but in tavern/city
16102 ss << m_resetTalentsCost << ", ";
16103 ss << (uint64)m_resetTalentsTime << ", ";
16105 ss << finiteAlways(m_movementInfo.t_x) << ", ";
16106 ss << finiteAlways(m_movementInfo.t_y) << ", ";
16107 ss << finiteAlways(m_movementInfo.t_z) << ", ";
16108 ss << finiteAlways(m_movementInfo.t_o) << ", ";
16109 if (m_transport)
16110 ss << m_transport->GetGUIDLow();
16111 else
16112 ss << "0";
16113 ss << ", ";
16115 ss << m_ExtraFlags << ", ";
16117 ss << uint32(m_stableSlots) << ", "; // to prevent save uint8 as char
16119 ss << uint32(m_atLoginFlags) << ", ";
16121 ss << GetZoneId() << ", ";
16123 ss << (uint64)m_deathExpireTime << ", '";
16125 ss << m_taxi.SaveTaxiDestinationsToString() << "', ";
16126 ss << "'0' "; // arena_pending_points
16127 ss << ")";
16129 CharacterDatabase.Execute( ss.str().c_str() );
16131 if(m_mailsUpdated) //save mails only when needed
16132 _SaveMail();
16134 _SaveBGData();
16135 _SaveInventory();
16136 _SaveQuestStatus();
16137 _SaveDailyQuestStatus();
16138 _SaveSpells();
16139 _SaveSpellCooldowns();
16140 _SaveActions();
16141 _SaveAuras();
16142 _SaveSkills();
16143 m_achievementMgr.SaveToDB();
16144 m_reputationMgr.SaveToDB();
16145 _SaveEquipmentSets();
16146 GetSession()->SaveTutorialsData(); // changed only while character in game
16148 CharacterDatabase.CommitTransaction();
16150 // save pet (hunter pet level and experience and all type pets health/mana).
16151 if(Pet* pet = GetPet())
16152 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
16155 // fast save function for item/money cheating preventing - save only inventory and money state
16156 void Player::SaveInventoryAndGoldToDB()
16158 _SaveInventory();
16159 SaveGoldToDB();
16162 void Player::SaveGoldToDB()
16164 CharacterDatabase.PExecute("UPDATE characters SET money = '%u' WHERE guid = '%u'", GetMoney(), GetGUIDLow());
16167 void Player::_SaveActions()
16169 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
16171 switch (itr->second.uState)
16173 case ACTIONBUTTON_NEW:
16174 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type) VALUES ('%u', '%u', '%u', '%u')",
16175 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.GetAction(), (uint32)itr->second.GetType() );
16176 itr->second.uState = ACTIONBUTTON_UNCHANGED;
16177 ++itr;
16178 break;
16179 case ACTIONBUTTON_CHANGED:
16180 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u' WHERE guid= '%u' AND button= '%u' ",
16181 (uint32)itr->second.GetAction(), (uint32)itr->second.GetType(), GetGUIDLow(), (uint32)itr->first );
16182 itr->second.uState = ACTIONBUTTON_UNCHANGED;
16183 ++itr;
16184 break;
16185 case ACTIONBUTTON_DELETED:
16186 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
16187 m_actionButtons.erase(itr++);
16188 break;
16189 default:
16190 ++itr;
16191 break;
16196 void Player::_SaveAuras()
16198 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
16200 AuraMap const& auras = GetAuras();
16202 if (auras.empty())
16203 return;
16205 spellEffectPair lastEffectPair = auras.begin()->first;
16206 uint32 stackCounter = 1;
16208 /* copied following sql-code partly from achievementmgr */
16209 bool first_round = true;
16210 std::ostringstream ss;
16211 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
16213 if(itr == auras.end() || lastEffectPair != itr->first)
16215 AuraMap::const_iterator itr2 = itr;
16216 // save previous spellEffectPair to db
16217 itr2--;
16219 //skip all auras from spells that are passive
16220 //do not save single target auras (unless they were cast by the player)
16221 if (!itr2->second->IsPassive() && (itr2->second->GetCasterGUID() == GetGUID() || !itr2->second->IsSingleTarget()))
16223 if (first_round)
16225 ss << "INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges)VALUES ";
16226 first_round = false;
16228 // next new/changed record prefix
16229 else
16230 ss << ", ";
16232 ss << "("<< GetGUIDLow() << "," << itr2->second->GetCasterGUID() << ","
16233 << (uint32)itr2->second->GetId() << "," << (uint32)itr2->second->GetEffIndex() << ","
16234 << stackCounter << "," << itr2->second->GetModifier()->m_amount << ","
16235 <<int(itr2->second->GetAuraMaxDuration()) << "," << int(itr2->second->GetAuraDuration()) << ","
16236 << int(itr2->second->GetAuraCharges()) << ")";
16239 if(itr == auras.end())
16240 break;
16243 if (lastEffectPair == itr->first)
16244 stackCounter++;
16245 else
16247 lastEffectPair = itr->first;
16248 stackCounter = 1;
16252 // if something changed execute
16253 if (!first_round)
16254 CharacterDatabase.Execute( ss.str().c_str() );
16257 void Player::_SaveInventory()
16259 // force items in buyback slots to new state
16260 // and remove those that aren't already
16261 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
16263 Item *item = m_items[i];
16264 if (!item || item->GetState() == ITEM_NEW) continue;
16265 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
16266 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
16267 m_items[i]->FSetState(ITEM_NEW);
16270 // update enchantment durations
16271 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
16273 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
16276 // if no changes
16277 if (m_itemUpdateQueue.empty()) return;
16279 // do not save if the update queue is corrupt
16280 bool error = false;
16281 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
16283 Item *item = m_itemUpdateQueue[i];
16284 if(!item || item->GetState() == ITEM_REMOVED) continue;
16285 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
16287 if (test == NULL)
16289 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());
16290 error = true;
16292 else if (test != item)
16294 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());
16295 error = true;
16299 if (error)
16301 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
16302 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
16303 return;
16306 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
16308 Item *item = m_itemUpdateQueue[i];
16309 if(!item) continue;
16311 Bag *container = item->GetContainer();
16312 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
16314 switch(item->GetState())
16316 case ITEM_NEW:
16317 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());
16318 break;
16319 case ITEM_CHANGED:
16320 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());
16321 break;
16322 case ITEM_REMOVED:
16323 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
16324 break;
16325 case ITEM_UNCHANGED:
16326 break;
16329 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
16331 m_itemUpdateQueue.clear();
16334 void Player::_SaveMail()
16336 if (!m_mailsLoaded)
16337 return;
16339 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
16341 Mail *m = (*itr);
16342 if (m->state == MAIL_STATE_CHANGED)
16344 CharacterDatabase.PExecute("UPDATE mail SET itemTextId = '%u',has_items = '%u',expire_time = '" UI64FMTD "', deliver_time = '" UI64FMTD "',money = '%u',cod = '%u',checked = '%u' WHERE id = '%u'",
16345 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
16346 if(m->removedItems.size())
16348 for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
16349 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
16350 m->removedItems.clear();
16352 m->state = MAIL_STATE_UNCHANGED;
16354 else if (m->state == MAIL_STATE_DELETED)
16356 if (m->HasItems())
16357 for(std::vector<MailItemInfo>::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
16358 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
16359 if (m->itemTextId)
16360 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
16361 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
16362 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
16366 //deallocate deleted mails...
16367 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
16369 if ((*itr)->state == MAIL_STATE_DELETED)
16371 Mail* m = *itr;
16372 m_mail.erase(itr);
16373 delete m;
16374 itr = m_mail.begin();
16376 else
16377 ++itr;
16380 m_mailsUpdated = false;
16383 void Player::_SaveQuestStatus()
16385 // we don't need transactions here.
16386 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
16388 switch (i->second.uState)
16390 case QUEST_NEW :
16391 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
16392 "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
16393 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]);
16394 break;
16395 case QUEST_CHANGED :
16396 CharacterDatabase.PExecute("UPDATE character_queststatus SET status = '%u',rewarded = '%u',explored = '%u',timer = '" UI64FMTD "',mobcount1 = '%u',mobcount2 = '%u',mobcount3 = '%u',mobcount4 = '%u',itemcount1 = '%u',itemcount2 = '%u',itemcount3 = '%u',itemcount4 = '%u' WHERE guid = '%u' AND quest = '%u' ",
16397 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 );
16398 break;
16399 case QUEST_UNCHANGED:
16400 break;
16402 i->second.uState = QUEST_UNCHANGED;
16406 void Player::_SaveDailyQuestStatus()
16408 if(!m_DailyQuestChanged)
16409 return;
16411 m_DailyQuestChanged = false;
16413 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
16415 // we don't need transactions here.
16416 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
16417 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
16418 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
16419 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" UI64FMTD "')",
16420 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
16424 void Player::_SaveSkills()
16426 // we don't need transactions here.
16427 for( SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); )
16429 if(itr->second.uState == SKILL_UNCHANGED)
16431 ++itr;
16432 continue;
16435 if(itr->second.uState == SKILL_DELETED)
16437 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), itr->first );
16438 mSkillStatus.erase(itr++);
16439 continue;
16442 uint32 valueData = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos));
16443 uint16 value = SKILL_VALUE(valueData);
16444 uint16 max = SKILL_MAX(valueData);
16446 switch (itr->second.uState)
16448 case SKILL_NEW:
16449 CharacterDatabase.PExecute("INSERT INTO character_skills (guid, skill, value, max) VALUES ('%u', '%u', '%u', '%u')",
16450 GetGUIDLow(), itr->first, value, max);
16451 break;
16452 case SKILL_CHANGED:
16453 CharacterDatabase.PExecute("UPDATE character_skills SET value = '%u',max = '%u'WHERE guid = '%u' AND skill = '%u' ",
16454 value, max, GetGUIDLow(), itr->first );
16455 break;
16457 itr->second.uState = SKILL_UNCHANGED;
16459 ++itr;
16463 void Player::_SaveSpells()
16465 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
16467 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
16468 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
16470 // add only changed/new not dependent spells
16471 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
16472 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);
16474 if (itr->second->state == PLAYERSPELL_REMOVED)
16476 delete itr->second;
16477 m_spells.erase(itr++);
16479 else
16481 itr->second->state = PLAYERSPELL_UNCHANGED;
16482 ++itr;
16488 void Player::outDebugValues() const
16490 if(!sLog.IsOutDebug()) // optimize disabled debug output
16491 return;
16493 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
16494 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
16495 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
16496 sLog.outDebug("STAMINA is: \t\t%f",GetStat(STAT_STAMINA));
16497 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
16498 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
16499 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
16500 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
16501 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
16502 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
16503 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
16504 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
16507 /*********************************************************/
16508 /*** FLOOD FILTER SYSTEM ***/
16509 /*********************************************************/
16511 void Player::UpdateSpeakTime()
16513 // ignore chat spam protection for GMs in any mode
16514 if(GetSession()->GetSecurity() > SEC_PLAYER)
16515 return;
16517 time_t current = time (NULL);
16518 if(m_speakTime > current)
16520 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
16521 if(!max_count)
16522 return;
16524 ++m_speakCount;
16525 if(m_speakCount >= max_count)
16527 // prevent overwrite mute time, if message send just before mutes set, for example.
16528 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
16529 if(GetSession()->m_muteTime < new_mute)
16530 GetSession()->m_muteTime = new_mute;
16532 m_speakCount = 0;
16535 else
16536 m_speakCount = 0;
16538 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
16541 bool Player::CanSpeak() const
16543 return GetSession()->m_muteTime <= time (NULL);
16546 /*********************************************************/
16547 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
16548 /*********************************************************/
16550 void Player::SendAttackSwingNotInRange()
16552 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
16553 GetSession()->SendPacket( &data );
16556 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
16558 std::ostringstream ss;
16559 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
16560 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
16561 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
16562 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16563 sLog.outDebug(ss.str().c_str());
16564 CharacterDatabase.Execute(ss.str().c_str());
16567 void Player::SaveDataFieldToDB()
16569 std::ostringstream ss;
16570 ss<<"UPDATE characters SET data='";
16572 for(uint16 i = 0; i < m_valuesCount; ++i )
16574 ss << GetUInt32Value(i) << " ";
16576 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16578 CharacterDatabase.Execute(ss.str().c_str());
16581 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
16583 std::ostringstream ss2;
16584 ss2<<"UPDATE characters SET data='";
16585 int i=0;
16586 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
16588 ss2<<tokens[i]<<" ";
16590 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16592 return CharacterDatabase.Execute(ss2.str().c_str());
16595 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
16597 char buf[11];
16598 snprintf(buf,11,"%u",value);
16600 if(index >= tokens.size())
16601 return;
16603 tokens[index] = buf;
16606 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
16608 Tokens tokens;
16609 if(!LoadValuesArrayFromDB(tokens,guid))
16610 return;
16612 if(index >= tokens.size())
16613 return;
16615 char buf[11];
16616 snprintf(buf,11,"%u",value);
16617 tokens[index] = buf;
16619 SaveValuesArrayInDB(tokens,guid);
16622 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
16624 uint32 temp;
16625 memcpy(&temp, &value, sizeof(value));
16626 Player::SetUInt32ValueInDB(index, temp, guid);
16629 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
16631 // 0
16632 QueryResult* result = CharacterDatabase.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
16633 if(!result)
16634 return;
16636 Field* fields = result->Fetch();
16638 uint32 player_bytes2 = fields[0].GetUInt32();
16639 player_bytes2 &= ~0xFF;
16640 player_bytes2 |= facialHair;
16642 CharacterDatabase.PExecute("UPDATE characters SET gender = '%u', playerBytes = '%u', playerBytes2 = '%u' WHERE guid = '%u'", gender, skin | (face << 8) | (hairStyle << 16) | (hairColor << 24), player_bytes2, GUID_LOPART(guid));
16644 delete result;
16647 void Player::SendAttackSwingDeadTarget()
16649 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
16650 GetSession()->SendPacket( &data );
16653 void Player::SendAttackSwingCantAttack()
16655 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
16656 GetSession()->SendPacket( &data );
16659 void Player::SendAttackSwingCancelAttack()
16661 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
16662 GetSession()->SendPacket( &data );
16665 void Player::SendAttackSwingBadFacingAttack()
16667 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
16668 GetSession()->SendPacket( &data );
16671 void Player::SendAutoRepeatCancel(Unit *target)
16673 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, target->GetPackGUID().size());
16674 data.append(target->GetPackGUID()); // may be it's target guid
16675 GetSession()->SendPacket( &data );
16678 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
16680 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
16681 data << Area;
16682 data << Experience;
16683 GetSession()->SendPacket(&data);
16686 void Player::SendDungeonDifficulty(bool IsInGroup)
16688 uint8 val = 0x00000001;
16689 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
16690 data << (uint32)GetDungeonDifficulty();
16691 data << uint32(val);
16692 data << uint32(IsInGroup);
16693 GetSession()->SendPacket(&data);
16696 void Player::SendRaidDifficulty(bool IsInGroup)
16698 uint8 val = 0x00000001;
16699 WorldPacket data(MSG_SET_RAID_DIFFICULTY, 12);
16700 data << uint32(GetRaidDifficulty());
16701 data << uint32(val);
16702 data << uint32(IsInGroup);
16703 GetSession()->SendPacket(&data);
16706 void Player::SendResetFailedNotify(uint32 mapid)
16708 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
16709 data << uint32(mapid);
16710 GetSession()->SendPacket(&data);
16713 /// Reset all solo instances and optionally send a message on success for each
16714 void Player::ResetInstances(uint8 method, bool isRaid)
16716 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16718 // we assume that when the difficulty changes, all instances that can be reset will be
16719 Difficulty diff = GetDifficulty(isRaid);
16721 for (BoundInstancesMap::iterator itr = m_boundInstances[diff].begin(); itr != m_boundInstances[diff].end();)
16723 InstanceSave *p = itr->second.save;
16724 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
16725 if(!entry || entry->IsRaid() != isRaid || !p->CanReset())
16727 ++itr;
16728 continue;
16731 if(method == INSTANCE_RESET_ALL)
16733 // the "reset all instances" method can only reset normal maps
16734 if(entry->map_type == MAP_RAID || diff == DUNGEON_DIFFICULTY_HEROIC)
16736 ++itr;
16737 continue;
16741 // if the map is loaded, reset it
16742 Map *map = sMapMgr.FindMap(p->GetMapId(), p->GetInstanceId());
16743 if(map && map->IsDungeon())
16744 ((InstanceMap*)map)->Reset(method);
16746 // since this is a solo instance there should not be any players inside
16747 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16748 SendResetInstanceSuccess(p->GetMapId());
16750 p->DeleteFromDB();
16751 m_boundInstances[diff].erase(itr++);
16753 // the following should remove the instance save from the manager and delete it as well
16754 p->RemovePlayer(this);
16758 void Player::SendResetInstanceSuccess(uint32 MapId)
16760 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16761 data << MapId;
16762 GetSession()->SendPacket(&data);
16765 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16767 // TODO: find what other fail reasons there are besides players in the instance
16768 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16769 data << reason;
16770 data << MapId;
16771 GetSession()->SendPacket(&data);
16774 /*********************************************************/
16775 /*** Update timers ***/
16776 /*********************************************************/
16778 ///checks the 15 afk reports per 5 minutes limit
16779 void Player::UpdateAfkReport(time_t currTime)
16781 if(m_bgData.bgAfkReportedTimer <= currTime)
16783 m_bgData.bgAfkReportedCount = 0;
16784 m_bgData.bgAfkReportedTimer = currTime+5*MINUTE;
16788 void Player::UpdateContestedPvP(uint32 diff)
16790 if(!m_contestedPvPTimer||isInCombat())
16791 return;
16792 if(m_contestedPvPTimer <= diff)
16794 ResetContestedPvP();
16796 else
16797 m_contestedPvPTimer -= diff;
16800 void Player::UpdatePvPFlag(time_t currTime)
16802 if(!IsPvP())
16803 return;
16804 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16805 return;
16807 UpdatePvP(false);
16810 void Player::UpdateDuelFlag(time_t currTime)
16812 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16813 return;
16815 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16816 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16818 duel->startTimer = 0;
16819 duel->startTime = currTime;
16820 duel->opponent->duel->startTimer = 0;
16821 duel->opponent->duel->startTime = currTime;
16824 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16826 if(!pet)
16827 pet = GetPet();
16829 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16831 //returning of reagents only for players, so best done here
16832 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16833 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16835 if(spellInfo)
16837 for(uint32 i = 0; i < 7; ++i)
16839 if(spellInfo->Reagent[i] > 0)
16841 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16842 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16843 if( msg == EQUIP_ERR_OK )
16845 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16846 if(IsInWorld())
16847 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16852 m_temporaryUnsummonedPetNumber = 0;
16855 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16856 return;
16858 // only if current pet in slot
16859 switch(pet->getPetType())
16861 case MINI_PET:
16862 m_miniPet = 0;
16863 break;
16864 case GUARDIAN_PET:
16865 RemoveGuardian(pet);
16866 break;
16867 default:
16868 if(GetPetGUID() == pet->GetGUID())
16869 SetPet(NULL);
16870 break;
16873 pet->CombatStop();
16875 if(returnreagent)
16877 switch(pet->GetEntry())
16879 //warlock pets except imp are removed(?) when logging out
16880 case 1860:
16881 case 1863:
16882 case 417:
16883 case 17252:
16884 mode = PET_SAVE_NOT_IN_SLOT;
16885 break;
16889 pet->SavePetToDB(mode);
16891 pet->AddObjectToRemoveList();
16892 pet->m_removed = true;
16894 if(pet->isControlled())
16896 RemovePetActionBar();
16898 if(GetGroup())
16899 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16903 void Player::RemoveMiniPet()
16905 if(Pet* pet = GetMiniPet())
16907 pet->Remove(PET_SAVE_AS_DELETED);
16908 m_miniPet = 0;
16912 Pet* Player::GetMiniPet()
16914 if(!m_miniPet)
16915 return NULL;
16916 return GetMap()->GetPet(m_miniPet);
16919 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16921 *data << (uint8)msgtype;
16922 *data << (uint32)language;
16923 *data << (uint64)GetGUID();
16924 *data << (uint32)language; //language 2.1.0 ?
16925 *data << (uint64)GetGUID();
16926 *data << (uint32)(text.length()+1);
16927 *data << text;
16928 *data << (uint8)chatTag();
16931 void Player::Say(const std::string& text, const uint32 language)
16933 WorldPacket data(SMSG_MESSAGECHAT, 200);
16934 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16935 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16938 void Player::Yell(const std::string& text, const uint32 language)
16940 WorldPacket data(SMSG_MESSAGECHAT, 200);
16941 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16942 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16945 void Player::TextEmote(const std::string& text)
16947 WorldPacket data(SMSG_MESSAGECHAT, 200);
16948 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16949 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16952 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16954 if (language != LANG_ADDON) // if not addon data
16955 language = LANG_UNIVERSAL; // whispers should always be readable
16957 Player *rPlayer = sObjectMgr.GetPlayer(receiver);
16959 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16960 if(!rPlayer->isDND() || isGameMaster())
16962 WorldPacket data(SMSG_MESSAGECHAT, 200);
16963 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16964 rPlayer->GetSession()->SendPacket(&data);
16966 // not send confirmation for addon messages
16967 if (language != LANG_ADDON)
16969 data.Initialize(SMSG_MESSAGECHAT, 200);
16970 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16971 GetSession()->SendPacket(&data);
16974 else
16976 // announce to player that player he is whispering to is dnd and cannot receive his message
16977 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16980 if(!isAcceptWhispers())
16982 SetAcceptWhispers(true);
16983 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16986 // announce to player that player he is whispering to is afk
16987 if(rPlayer->isAFK())
16988 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16990 // if player whisper someone, auto turn of dnd to be able to receive an answer
16991 if(isDND() && !rPlayer->isGameMaster())
16992 ToggleDND();
16995 void Player::PetSpellInitialize()
16997 Pet* pet = GetPet();
16999 if(!pet)
17000 return;
17002 sLog.outDebug("Pet Spells Groups");
17004 CharmInfo *charmInfo = pet->GetCharmInfo();
17006 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
17007 data << uint64(pet->GetGUID());
17008 data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
17009 data << uint32(0);
17010 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
17012 // action bar loop
17013 charmInfo->BuildActionBar(&data);
17015 size_t spellsCountPos = data.wpos();
17017 // spells count
17018 uint8 addlist = 0;
17019 data << uint8(addlist); // placeholder
17021 if (pet->IsPermanentPetFor(this))
17023 // spells loop
17024 for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
17026 if(itr->second.state == PETSPELL_REMOVED)
17027 continue;
17029 data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first,itr->second.active));
17030 ++addlist;
17034 data.put<uint8>(spellsCountPos, addlist);
17036 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
17037 data << uint8(cooldownsCount);
17039 time_t curTime = time(NULL);
17041 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
17043 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
17045 data << uint32(itr->first); // spellid
17046 data << uint16(0); // spell category?
17047 data << uint32(cooldown); // cooldown
17048 data << uint32(0); // category cooldown
17051 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
17053 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
17055 data << uint32(itr->first); // spellid
17056 data << uint16(0); // spell category?
17057 data << uint32(0); // cooldown
17058 data << uint32(cooldown); // category cooldown
17061 GetSession()->SendPacket(&data);
17064 void Player::PossessSpellInitialize()
17066 Unit* charm = GetCharm();
17068 if(!charm)
17069 return;
17071 CharmInfo *charmInfo = charm->GetCharmInfo();
17073 if(!charmInfo)
17075 sLog.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
17076 return;
17079 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
17080 data << uint64(charm->GetGUID());
17081 data << uint16(0);
17082 data << uint32(0);
17083 data << uint32(0);
17085 charmInfo->BuildActionBar(&data);
17087 data << uint8(0); // spells count
17088 data << uint8(0); // cooldowns count
17090 GetSession()->SendPacket(&data);
17093 void Player::CharmSpellInitialize()
17095 Unit* charm = GetCharm();
17097 if(!charm)
17098 return;
17100 CharmInfo *charmInfo = charm->GetCharmInfo();
17101 if(!charmInfo)
17103 sLog.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
17104 return;
17107 uint8 addlist = 0;
17109 if(charm->GetTypeId() != TYPEID_PLAYER)
17111 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
17113 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
17115 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
17117 if(charmInfo->GetCharmSpell(i)->GetAction())
17118 ++addlist;
17123 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1);
17124 data << uint64(charm->GetGUID());
17125 data << uint16(0);
17126 data << uint32(0);
17128 if(charm->GetTypeId() != TYPEID_PLAYER)
17129 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
17130 else
17131 data << uint8(0) << uint8(0) << uint16(0);
17133 charmInfo->BuildActionBar(&data);
17135 data << uint8(addlist);
17137 if(addlist)
17139 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
17141 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
17142 if(cspell->GetAction())
17143 data << uint32(cspell->packedData);
17147 data << uint8(0); // cooldowns count
17149 GetSession()->SendPacket(&data);
17152 void Player::RemovePetActionBar()
17154 WorldPacket data(SMSG_PET_SPELLS, 8);
17155 data << uint64(0);
17156 SendDirectMessage(&data);
17159 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
17161 if (!mod || !spellInfo)
17162 return false;
17164 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
17166 // prevent apply to any spell except spell that trigger expire
17167 if(spell)
17169 if(mod->lastAffected != spell)
17170 return false;
17172 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
17173 return false;
17176 return sSpellMgr.IsAffectedByMod(spellInfo, mod);
17179 void Player::AddSpellMod(SpellModifier* mod, bool apply)
17181 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
17183 for(int eff=0;eff<96;++eff)
17185 uint64 _mask = 0;
17186 uint64 _mask2= 0;
17187 if (eff<64) _mask = uint64(1) << (eff- 0);
17188 else _mask2= uint64(1) << (eff-64);
17189 if ( mod->mask & _mask || mod->mask2 & _mask2)
17191 int32 val = 0;
17192 for (SpellModList::const_iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
17194 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
17195 val += (*itr)->value;
17197 val += apply ? mod->value : -(mod->value);
17198 WorldPacket data(Opcode, (1+1+4));
17199 data << uint8(eff);
17200 data << uint8(mod->op);
17201 data << int32(val);
17202 SendDirectMessage(&data);
17206 if (apply)
17207 m_spellMods[mod->op].push_back(mod);
17208 else
17210 if (mod->charges == -1)
17211 --m_SpellModRemoveCount;
17212 m_spellMods[mod->op].remove(mod);
17213 delete mod;
17217 void Player::RemoveSpellMods(Spell const* spell)
17219 if(!spell || (m_SpellModRemoveCount == 0))
17220 return;
17222 for(int i=0;i<MAX_SPELLMOD;++i)
17224 for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
17226 SpellModifier *mod = *itr;
17227 ++itr;
17229 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
17231 RemoveAurasDueToSpell(mod->spellId);
17232 if (m_spellMods[i].empty())
17233 break;
17234 else
17235 itr = m_spellMods[i].begin();
17241 // send Proficiency
17242 void Player::SendProficiency(uint8 pr1, uint32 pr2)
17244 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
17245 data << pr1 << pr2;
17246 GetSession()->SendPacket (&data);
17249 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
17251 QueryResult *result = NULL;
17252 if(type==10)
17253 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
17254 else
17255 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17256 if(result)
17258 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.
17259 { // and SendPetitionQueryOpcode reads data from the DB
17260 Field *fields = result->Fetch();
17261 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
17262 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
17264 // send update if charter owner in game
17265 Player* owner = sObjectMgr.GetPlayer(ownerguid);
17266 if(owner)
17267 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
17269 } while ( result->NextRow() );
17271 delete result;
17273 if(type==10)
17274 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
17275 else
17276 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17279 CharacterDatabase.BeginTransaction();
17280 if(type == 10)
17282 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
17283 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
17285 else
17287 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17288 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17290 CharacterDatabase.CommitTransaction();
17293 void Player::LeaveAllArenaTeams(uint64 guid)
17295 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));
17296 if(!result)
17297 return;
17301 Field *fields = result->Fetch();
17302 uint32 at_id = fields[0].GetUInt32();
17303 if(at_id != 0)
17305 ArenaTeam * at = sObjectMgr.GetArenaTeamById(at_id);
17306 if(at)
17307 at->DelMember(guid);
17309 } while (result->NextRow());
17311 delete result;
17314 void Player::SetRestBonus (float rest_bonus_new)
17316 // Prevent resting on max level
17317 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
17318 rest_bonus_new = 0;
17320 if(rest_bonus_new < 0)
17321 rest_bonus_new = 0;
17323 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
17325 if(rest_bonus_new > rest_bonus_max)
17326 m_rest_bonus = rest_bonus_max;
17327 else
17328 m_rest_bonus = rest_bonus_new;
17330 // update data for client
17331 if(m_rest_bonus>10)
17332 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
17333 else if(m_rest_bonus<=1)
17334 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
17336 //RestTickUpdate
17337 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
17340 void Player::HandleStealthedUnitsDetection()
17342 std::list<Unit*> stealthedUnits;
17344 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
17345 Cell cell(p);
17346 cell.data.Part.reserved = ALL_DISTRICT;
17347 cell.SetNoCreate();
17349 MaNGOS::AnyStealthedCheck u_check;
17350 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
17352 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
17353 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
17355 CellLock<GridReadGuard> cell_lock(cell, p);
17356 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE);
17357 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE);
17359 WorldObject const* viewPoint = GetViewPoint();
17361 for (std::list<Unit*>::const_iterator i = stealthedUnits.begin(); i != stealthedUnits.end(); ++i)
17363 if((*i)==this)
17364 continue;
17366 bool hasAtClient = HaveAtClient((*i));
17367 bool hasDetected = (*i)->isVisibleForOrDetect(this, viewPoint, true);
17369 if (hasDetected)
17371 if(!hasAtClient)
17373 (*i)->SendCreateUpdateToPlayer(this);
17374 m_clientGUIDs.insert((*i)->GetGUID());
17376 #ifdef MANGOS_DEBUG
17377 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17378 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
17379 #endif
17381 // target aura duration for caster show only if target exist at caster client
17382 // send data at target visibility change (adding to client)
17383 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
17384 SendAurasForTarget(*i);
17387 else
17389 if(hasAtClient)
17391 (*i)->DestroyForPlayer(this);
17392 m_clientGUIDs.erase((*i)->GetGUID());
17398 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
17400 if(nodes.size() < 2)
17401 return false;
17403 // 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
17404 if(GetSession()->isLogingOut() || isInCombat())
17406 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17407 data << uint32(ERR_TAXIPLAYERBUSY);
17408 GetSession()->SendPacket(&data);
17409 return false;
17412 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
17413 return false;
17415 // taximaster case
17416 if(npc)
17418 // not let cheating with start flight mounted
17419 if(IsMounted())
17421 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17422 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
17423 GetSession()->SendPacket(&data);
17424 return false;
17427 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
17429 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17430 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
17431 GetSession()->SendPacket(&data);
17432 return false;
17435 // 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
17436 if(IsNonMeleeSpellCasted(false))
17438 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17439 data << uint32(ERR_TAXIPLAYERBUSY);
17440 GetSession()->SendPacket(&data);
17441 return false;
17444 // cast case or scripted call case
17445 else
17447 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
17449 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
17450 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
17452 if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
17453 if (spell->m_spellInfo->Id != spellid)
17454 InterruptSpell(CURRENT_GENERIC_SPELL,false);
17456 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false);
17458 if (Spell* spell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
17459 if (spell->m_spellInfo->Id != spellid)
17460 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
17463 uint32 sourcenode = nodes[0];
17465 // starting node too far away (cheat?)
17466 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
17467 if (!node)
17469 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17470 data << uint32(ERR_TAXINOSUCHPATH);
17471 GetSession()->SendPacket(&data);
17472 return false;
17475 // check node starting pos data set case if provided
17476 if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
17478 if (node->map_id != GetMapId() ||
17479 (node->x - GetPositionX())*(node->x - GetPositionX())+
17480 (node->y - GetPositionY())*(node->y - GetPositionY())+
17481 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
17482 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
17484 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17485 data << uint32(ERR_TAXITOOFARAWAY);
17486 GetSession()->SendPacket(&data);
17487 return false;
17490 // node must have pos if taxi master case (npc != NULL)
17491 else if (npc)
17493 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17494 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17495 GetSession()->SendPacket(&data);
17496 return false;
17499 // Prepare to flight start now
17501 // stop combat at start taxi flight if any
17502 CombatStop();
17504 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
17505 TradeCancel(true);
17507 // clean not finished taxi path if any
17508 m_taxi.ClearTaxiDestinations();
17510 // 0 element current node
17511 m_taxi.AddTaxiDestination(sourcenode);
17513 // fill destinations path tail
17514 uint32 sourcepath = 0;
17515 uint32 totalcost = 0;
17517 uint32 prevnode = sourcenode;
17518 uint32 lastnode = 0;
17520 for(uint32 i = 1; i < nodes.size(); ++i)
17522 uint32 path, cost;
17524 lastnode = nodes[i];
17525 sObjectMgr.GetTaxiPath(prevnode, lastnode, path, cost);
17527 if(!path)
17529 m_taxi.ClearTaxiDestinations();
17530 return false;
17533 totalcost += cost;
17535 if(prevnode == sourcenode)
17536 sourcepath = path;
17538 m_taxi.AddTaxiDestination(lastnode);
17540 prevnode = lastnode;
17543 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
17544 uint32 mount_display_id = sObjectMgr.GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL);
17546 // in spell case allow 0 model
17547 if ((mount_display_id == 0 && spellid == 0) || sourcepath == 0)
17549 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17550 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17551 GetSession()->SendPacket(&data);
17552 m_taxi.ClearTaxiDestinations();
17553 return false;
17556 uint32 money = GetMoney();
17558 if (npc)
17559 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
17561 if(money < totalcost)
17563 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17564 data << uint32(ERR_TAXINOTENOUGHMONEY);
17565 GetSession()->SendPacket(&data);
17566 m_taxi.ClearTaxiDestinations();
17567 return false;
17570 //Checks and preparations done, DO FLIGHT
17571 ModifyMoney(-(int32)totalcost);
17572 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
17573 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
17575 // prevent stealth flight
17576 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
17578 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17579 data << uint32(ERR_TAXIOK);
17580 GetSession()->SendPacket(&data);
17582 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17584 GetSession()->SendDoFlight(mount_display_id, sourcepath);
17586 return true;
17589 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ )
17591 TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
17592 if(!entry)
17593 return false;
17595 std::vector<uint32> nodes;
17597 nodes.resize(2);
17598 nodes[0] = entry->from;
17599 nodes[1] = entry->to;
17601 return ActivateTaxiPathTo(nodes,NULL,spellid);
17604 void Player::ContinueTaxiFlight()
17606 uint32 sourceNode = m_taxi.GetTaxiSource();
17607 if (!sourceNode)
17608 return;
17610 sLog.outDebug( "WORLD: Restart character %u taxi flight", GetGUIDLow() );
17612 uint32 mountDisplayId = sObjectMgr.GetTaxiMountDisplayId(sourceNode, GetTeam(),true);
17613 uint32 path = m_taxi.GetCurrentTaxiPath();
17615 // search appropriate start path node
17616 uint32 startNode = 0;
17618 TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];
17620 float distPrev = MAP_SIZE*MAP_SIZE;
17621 float distNext =
17622 (nodeList[0].x-GetPositionX())*(nodeList[0].x-GetPositionX())+
17623 (nodeList[0].y-GetPositionY())*(nodeList[0].y-GetPositionY())+
17624 (nodeList[0].z-GetPositionZ())*(nodeList[0].z-GetPositionZ());
17626 for(uint32 i = 1; i < nodeList.size(); ++i)
17628 TaxiPathNode const& node = nodeList[i];
17629 TaxiPathNode const& prevNode = nodeList[i-1];
17631 // skip nodes at another map
17632 if(node.mapid != GetMapId())
17633 continue;
17635 distPrev = distNext;
17637 distNext =
17638 (node.x-GetPositionX())*(node.x-GetPositionX())+
17639 (node.y-GetPositionY())*(node.y-GetPositionY())+
17640 (node.z-GetPositionZ())*(node.z-GetPositionZ());
17642 float distNodes =
17643 (node.x-prevNode.x)*(node.x-prevNode.x)+
17644 (node.y-prevNode.y)*(node.y-prevNode.y)+
17645 (node.z-prevNode.z)*(node.z-prevNode.z);
17647 if(distNext + distPrev < distNodes)
17649 startNode = i;
17650 break;
17654 GetSession()->SendDoFlight(mountDisplayId, path, startNode);
17657 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
17659 // last check 2.0.10
17660 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
17661 data << GetGUID();
17662 data << uint8(0x0); // flags (0x1, 0x2)
17663 time_t curTime = time(NULL);
17664 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17666 if (itr->second->state == PLAYERSPELL_REMOVED)
17667 continue;
17668 uint32 unSpellId = itr->first;
17669 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
17670 if (!spellInfo)
17672 ASSERT(spellInfo);
17673 continue;
17676 // Not send cooldown for this spells
17677 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
17678 continue;
17680 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
17682 data << uint32(unSpellId);
17683 data << uint32(unTimeMs); // in m.secs
17684 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
17687 GetSession()->SendPacket(&data);
17690 void Player::InitDataForForm(bool reapplyMods)
17692 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
17693 if(ssEntry && ssEntry->attackSpeed)
17695 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
17696 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
17697 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
17699 else
17700 SetRegularAttackTime();
17702 switch(m_form)
17704 case FORM_CAT:
17706 if(getPowerType()!=POWER_ENERGY)
17707 setPowerType(POWER_ENERGY);
17708 break;
17710 case FORM_BEAR:
17711 case FORM_DIREBEAR:
17713 if(getPowerType()!=POWER_RAGE)
17714 setPowerType(POWER_RAGE);
17715 break;
17717 default: // 0, for example
17719 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
17720 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
17721 setPowerType(Powers(cEntry->powerType));
17722 break;
17726 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17727 if (!reapplyMods)
17728 UpdateEquipSpellsAtFormChange();
17730 UpdateAttackPowerAndDamage();
17731 UpdateAttackPowerAndDamage(true);
17734 void Player::InitDisplayIds()
17736 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass());
17737 if(!info)
17739 sLog.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
17740 return;
17743 uint8 gender = getGender();
17744 switch(gender)
17746 case GENDER_FEMALE:
17747 SetDisplayId(info->displayId_f );
17748 SetNativeDisplayId(info->displayId_f );
17749 break;
17750 case GENDER_MALE:
17751 SetDisplayId(info->displayId_m );
17752 SetNativeDisplayId(info->displayId_m );
17753 break;
17754 default:
17755 sLog.outError("Invalid gender %u for player",gender);
17756 return;
17760 // Return true is the bought item has a max count to force refresh of window by caller
17761 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint8 bag, uint8 slot)
17763 // cheating attempt
17764 if (count < 1) count = 1;
17766 if (!isAlive())
17767 return false;
17769 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype( item );
17770 if (!pProto)
17772 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
17773 return false;
17776 Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
17777 if (!pCreature)
17779 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
17780 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
17781 return false;
17784 VendorItemData const* vItems = pCreature->GetVendorItems();
17785 if(!vItems || vItems->Empty())
17787 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17788 return false;
17791 size_t vendor_slot = vItems->FindItemSlot(item);
17792 if (vendor_slot >= vItems->GetItemCount())
17794 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17795 return false;
17798 VendorItem const* crItem = vItems->m_items[vendor_slot];
17800 // check current item amount if it limited
17801 if (crItem->maxcount != 0)
17803 if (pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
17805 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
17806 return false;
17810 if (uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
17812 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
17813 return false;
17816 if (crItem->ExtendedCost)
17818 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17819 if (!iece)
17821 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
17822 return false;
17825 // honor points price
17826 if (GetHonorPoints() < (iece->reqhonorpoints * count))
17828 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
17829 return false;
17832 // arena points price
17833 if (GetArenaPoints() < (iece->reqarenapoints * count))
17835 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
17836 return false;
17839 // item base price
17840 for (uint8 i = 0; i < 5; ++i)
17842 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17844 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17845 return false;
17849 // check for personal arena rating requirement
17850 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
17852 // probably not the proper equip err
17853 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17854 return false;
17858 uint32 price = pProto->BuyPrice * count;
17860 // reputation discount
17861 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17863 if (GetMoney() < price)
17865 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17866 return false;
17869 if ((bag == NULL_BAG && slot == NULL_SLOT) || IsInventoryPos(bag, slot))
17871 ItemPosCountVec dest;
17872 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17873 if (msg != EQUIP_ERR_OK)
17875 SendEquipError( msg, NULL, NULL );
17876 return false;
17879 ModifyMoney( -(int32)price );
17880 if (crItem->ExtendedCost) // case for new honor system
17882 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17883 if (iece->reqhonorpoints)
17884 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17885 if (iece->reqarenapoints)
17886 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17887 for (uint8 i = 0; i < 5; ++i)
17889 if (iece->reqitem[i])
17890 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17894 if (Item *it = StoreNewItem( dest, item, true ))
17896 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17898 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17899 data << uint64(pCreature->GetGUID());
17900 data << uint32(vendor_slot+1); // numbered from 1 at client
17901 data << uint32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17902 data << uint32(count);
17903 GetSession()->SendPacket(&data);
17905 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17908 else if (IsEquipmentPos(bag, slot))
17910 if (pProto->BuyCount * count != 1)
17912 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17913 return false;
17916 uint16 dest;
17917 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17918 if (msg != EQUIP_ERR_OK)
17920 SendEquipError( msg, NULL, NULL );
17921 return false;
17924 ModifyMoney( -(int32)price );
17925 if (crItem->ExtendedCost) // case for new honor system
17927 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17928 if (iece->reqhonorpoints)
17929 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17930 if (iece->reqarenapoints)
17931 ModifyArenaPoints( - int32(iece->reqarenapoints));
17932 for (uint8 i = 0; i < 5; ++i)
17934 if(iece->reqitem[i])
17935 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17939 if (Item *it = EquipNewItem( dest, item, true ))
17941 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17943 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17944 data << uint64(pCreature->GetGUID());
17945 data << uint32(vendor_slot + 1); // numbered from 1 at client
17946 data << uint32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17947 data << uint32(count);
17948 GetSession()->SendPacket(&data);
17950 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17952 AutoUnequipOffhandIfNeed();
17955 else
17957 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17958 return false;
17961 return crItem->maxcount != 0;
17964 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17966 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17967 // the personal rating of the arena team must match the required limit as well
17968 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17969 uint32 max_personal_rating = 0;
17970 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17972 if(ArenaTeam * at = sObjectMgr.GetArenaTeamById(GetArenaTeamId(i)))
17974 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * ARENA_TEAM_END) + ARENA_TEAM_PERSONAL_RATING);
17975 uint32 t_rating = at->GetRating();
17976 p_rating = p_rating < t_rating ? p_rating : t_rating;
17977 if(max_personal_rating < p_rating)
17978 max_personal_rating = p_rating;
17981 return max_personal_rating;
17984 void Player::UpdateHomebindTime(uint32 time)
17986 // GMs never get homebind timer online
17987 if (m_InstanceValid || isGameMaster())
17989 if(m_HomebindTimer) // instance valid, but timer not reset
17991 // hide reminder
17992 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17993 data << uint32(0);
17994 data << uint32(0);
17995 GetSession()->SendPacket(&data);
17997 // instance is valid, reset homebind timer
17998 m_HomebindTimer = 0;
18000 else if (m_HomebindTimer > 0)
18002 if (time >= m_HomebindTimer)
18004 // teleport to nearest graveyard
18005 RepopAtGraveyard();
18007 else
18008 m_HomebindTimer -= time;
18010 else
18012 // instance is invalid, start homebind timer
18013 m_HomebindTimer = 60000;
18014 // send message to player
18015 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
18016 data << uint32(m_HomebindTimer);
18017 data << uint32(1);
18018 GetSession()->SendPacket(&data);
18019 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
18023 void Player::UpdatePvP(bool state, bool ovrride)
18025 if(!state || ovrride)
18027 SetPvP(state);
18028 pvpInfo.endTimer = 0;
18030 else
18032 if(pvpInfo.endTimer != 0)
18033 pvpInfo.endTimer = time(NULL);
18034 else
18035 SetPvP(state);
18039 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
18041 // init cooldown values
18042 uint32 cat = 0;
18043 int32 rec = -1;
18044 int32 catrec = -1;
18046 // some special item spells without correct cooldown in SpellInfo
18047 // cooldown information stored in item prototype
18048 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
18050 if(itemId)
18052 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
18054 for(int idx = 0; idx < 5; ++idx)
18056 if(proto->Spells[idx].SpellId == spellInfo->Id)
18058 cat = proto->Spells[idx].SpellCategory;
18059 rec = proto->Spells[idx].SpellCooldown;
18060 catrec = proto->Spells[idx].SpellCategoryCooldown;
18061 break;
18067 // if no cooldown found above then base at DBC data
18068 if(rec < 0 && catrec < 0)
18070 cat = spellInfo->Category;
18071 rec = spellInfo->RecoveryTime;
18072 catrec = spellInfo->CategoryRecoveryTime;
18075 time_t curTime = time(NULL);
18077 time_t catrecTime;
18078 time_t recTime;
18080 // overwrite time for selected category
18081 if(infinityCooldown)
18083 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
18084 // but not allow ignore until reset or re-login
18085 catrecTime = catrec > 0 ? curTime+infinityCooldownDelay : 0;
18086 recTime = rec > 0 ? curTime+infinityCooldownDelay : catrecTime;
18088 else
18090 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
18091 // prevent 0 cooldowns set by another way
18092 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
18093 rec = GetAttackTime(RANGED_ATTACK);
18095 // Now we have cooldown data (if found any), time to apply mods
18096 if(rec > 0)
18097 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
18099 if(catrec > 0)
18100 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
18102 // replace negative cooldowns by 0
18103 if (rec < 0) rec = 0;
18104 if (catrec < 0) catrec = 0;
18106 // no cooldown after applying spell mods
18107 if( rec == 0 && catrec == 0)
18108 return;
18110 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
18111 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
18114 // self spell cooldown
18115 if(recTime > 0)
18116 AddSpellCooldown(spellInfo->Id, itemId, recTime);
18118 // category spells
18119 if (cat && catrec > 0)
18121 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
18122 if(i_scstore != sSpellCategoryStore.end())
18124 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
18126 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
18127 continue;
18129 AddSpellCooldown(*i_scset, itemId, catrecTime);
18135 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
18137 SpellCooldown sc;
18138 sc.end = end_time;
18139 sc.itemid = itemid;
18140 m_spellCooldowns[spellid] = sc;
18143 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
18145 // start cooldowns at server side, if any
18146 AddSpellAndCategoryCooldowns(spellInfo, itemId, spell);
18148 // Send activate cooldown timer (possible 0) at client side
18149 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
18150 data << uint32(spellInfo->Id);
18151 data << uint64(GetGUID());
18152 SendDirectMessage(&data);
18155 void Player::UpdatePotionCooldown(Spell* spell)
18157 // no potion used i combat or still in combat
18158 if(!m_lastPotionId || isInCombat())
18159 return;
18161 // Call not from spell cast, send cooldown event for item spells if no in combat
18162 if(!spell)
18164 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
18165 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
18166 for(int idx = 0; idx < 5; ++idx)
18167 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
18168 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
18169 SendCooldownEvent(spellInfo,m_lastPotionId);
18171 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
18172 else
18173 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
18175 m_lastPotionId = 0;
18178 //slot to be excluded while counting
18179 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
18181 if(!enchantmentcondition)
18182 return true;
18184 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
18186 if(!Condition)
18187 return true;
18189 uint8 curcount[4] = {0, 0, 0, 0};
18191 //counting current equipped gem colors
18192 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
18194 if(i == slot)
18195 continue;
18196 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
18197 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
18199 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18201 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18202 if(!enchant_id)
18203 continue;
18205 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18206 if(!enchantEntry)
18207 continue;
18209 uint32 gemid = enchantEntry->GemID;
18210 if(!gemid)
18211 continue;
18213 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
18214 if(!gemProto)
18215 continue;
18217 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
18218 if(!gemProperty)
18219 continue;
18221 uint8 GemColor = gemProperty->color;
18223 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
18225 if(tmpcolormask & GemColor)
18226 ++curcount[b];
18232 bool activate = true;
18234 for(int i = 0; i < 5; ++i)
18236 if(!Condition->Color[i])
18237 continue;
18239 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
18241 // if have <CompareColor> use them as count, else use <value> from Condition
18242 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
18244 switch(Condition->Comparator[i])
18246 case 2: // requires less <color> than (<value> || <comparecolor>) gems
18247 activate &= (_cur_gem < _cmp_gem) ? true : false;
18248 break;
18249 case 3: // requires more <color> than (<value> || <comparecolor>) gems
18250 activate &= (_cur_gem > _cmp_gem) ? true : false;
18251 break;
18252 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
18253 activate &= (_cur_gem >= _cmp_gem) ? true : false;
18254 break;
18258 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");
18260 return activate;
18263 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
18265 //cycle all equipped items
18266 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
18268 //enchants for the slot being socketed are handled by Player::ApplyItemMods
18269 if(slot == exceptslot)
18270 continue;
18272 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
18274 if(!pItem || !pItem->GetProto()->Socket[0].Color)
18275 continue;
18277 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18279 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18280 if(!enchant_id)
18281 continue;
18283 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18284 if(!enchantEntry)
18285 continue;
18287 uint32 condition = enchantEntry->EnchantmentCondition;
18288 if(condition)
18290 //was enchant active with/without item?
18291 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
18292 //should it now be?
18293 if(wasactive != EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
18295 // ignore item gem conditions
18296 //if state changed, (dis)apply enchant
18297 ApplyEnchantment(pItem, EnchantmentSlot(enchant_slot), !wasactive, true, true);
18304 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
18305 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
18307 //cycle all equipped items
18308 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
18310 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
18311 if(slot == exceptslot)
18312 continue;
18314 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
18316 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
18317 continue;
18319 //cycle all (gem)enchants
18320 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18322 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18323 if(!enchant_id) //if no enchant go to next enchant(slot)
18324 continue;
18326 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18327 if(!enchantEntry)
18328 continue;
18330 //only metagems to be (de)activated, so only enchants with condition
18331 uint32 condition = enchantEntry->EnchantmentCondition;
18332 if(condition)
18333 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
18338 void Player::SetBattleGroundEntryPoint()
18340 // Taxi path store
18341 if (!m_taxi.empty())
18343 m_bgData.mountSpell = 0;
18344 m_bgData.taxiPath[0] = m_taxi.GetTaxiSource();
18345 m_bgData.taxiPath[1] = m_taxi.GetTaxiDestination();
18347 // On taxi we don't need check for dungeon
18348 m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
18349 return;
18351 else
18353 m_bgData.ClearTaxiPath();
18355 // Mount spell id storing
18356 if (IsMounted())
18358 AuraList const& auras = GetAurasByType(SPELL_AURA_MOUNTED);
18359 if (!auras.empty())
18360 m_bgData.mountSpell = (*auras.begin())->GetId();
18362 else
18363 m_bgData.mountSpell = 0;
18365 // If map is dungeon find linked graveyard
18366 if(GetMap()->IsDungeon())
18368 if (const WorldSafeLocsEntry* entry = sObjectMgr.GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
18370 m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f);
18371 return;
18373 else
18374 sLog.outError("SetBattleGroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId());
18376 // If new entry point is not BG or arena set it
18377 else if (!GetMap()->IsBattleGroundOrArena())
18379 m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
18380 return;
18384 // In error cases use homebind position
18385 m_bgData.joinPos = WorldLocation(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, 0.0f);
18388 void Player::LeaveBattleground(bool teleportToEntryPoint)
18390 if(BattleGround *bg = GetBattleGround())
18392 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
18394 // call after remove to be sure that player resurrected for correct cast
18395 if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) )
18397 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
18399 //lets check if player was teleported from BG and schedule delayed Deserter spell cast
18400 if(IsBeingTeleportedFar())
18402 ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER);
18403 return;
18406 CastSpell(this, 26013, true); // Deserter
18412 bool Player::CanJoinToBattleground() const
18414 // check Deserter debuff
18415 if(GetDummyAura(26013))
18416 return false;
18418 return true;
18421 bool Player::CanReportAfkDueToLimit()
18423 // a player can complain about 15 people per 5 minutes
18424 if(m_bgData.bgAfkReportedCount++ >= 15)
18425 return false;
18427 return true;
18430 ///This player has been blamed to be inactive in a battleground
18431 void Player::ReportedAfkBy(Player* reporter)
18433 BattleGround *bg = GetBattleGround();
18434 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
18435 return;
18437 // check if player has 'Idle' or 'Inactive' debuff
18438 if(m_bgData.bgAfkReporter.find(reporter->GetGUIDLow()) == m_bgData.bgAfkReporter.end() && !HasAura(43680, 0) && !HasAura(43681, 0) && reporter->CanReportAfkDueToLimit())
18440 m_bgData.bgAfkReporter.insert(reporter->GetGUIDLow());
18441 // 3 players have to complain to apply debuff
18442 if(m_bgData.bgAfkReporter.size() >= 3)
18444 // cast 'Idle' spell
18445 CastSpell(this, 43680, true);
18446 m_bgData.bgAfkReporter.clear();
18451 WorldObject const* Player::GetViewPoint() const
18453 if(uint64 far_sight = GetFarSight())
18455 WorldObject const* viewPoint = GetMap()->GetWorldObject(far_sight);
18456 return viewPoint ? viewPoint : this; // always expected not NULL
18458 else
18459 return this;
18462 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
18464 // gamemaster in GM mode see all, including ghosts
18465 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
18466 return true;
18468 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
18469 if (InBattleGround())
18471 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
18472 return false;
18473 return true;
18476 // Live player see live player or dead player with not realized corpse
18477 if(pl->isAlive() || pl->m_deathTimer > 0)
18479 return isAlive() || m_deathTimer > 0;
18482 // Ghost see other friendly ghosts, that's for sure
18483 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
18484 return true;
18486 // Dead player see live players near own corpse
18487 if(isAlive())
18489 Corpse *corpse = pl->GetCorpse();
18490 if(corpse)
18492 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
18493 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
18494 return true;
18498 // and not see any other
18499 return false;
18502 bool Player::IsVisibleGloballyFor( Player* u ) const
18504 if(!u)
18505 return false;
18507 // Always can see self
18508 if (u==this)
18509 return true;
18511 // Visible units, always are visible for all players
18512 if (GetVisibility() == VISIBILITY_ON)
18513 return true;
18515 // GMs are visible for higher gms (or players are visible for gms)
18516 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
18517 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
18519 // non faction visibility non-breakable for non-GMs
18520 if (GetVisibility() == VISIBILITY_OFF)
18521 return false;
18523 // non-gm stealth/invisibility not hide from global player lists
18524 return true;
18527 template<class T>
18528 inline void BeforeVisibilityDestroy(T* /*t*/, Player* /*p*/)
18532 template<>
18533 inline void BeforeVisibilityDestroy<Creature>(Creature* t, Player* p)
18535 if (p->GetPetGUID()==t->GetGUID() && ((Creature*)t)->isPet())
18536 ((Pet*)t)->Remove(PET_SAVE_NOT_IN_SLOT, true);
18539 void Player::UpdateVisibilityOf(WorldObject const* viewPoint, WorldObject* target)
18541 if(HaveAtClient(target))
18543 if(!target->isVisibleForInState(this, viewPoint, true))
18545 if (target->GetTypeId()==TYPEID_UNIT)
18546 BeforeVisibilityDestroy<Creature>((Creature*)target,this);
18548 target->DestroyForPlayer(this);
18549 m_clientGUIDs.erase(target->GetGUID());
18551 #ifdef MANGOS_DEBUG
18552 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18553 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
18554 #endif
18557 else
18559 if(target->isVisibleForInState(this, viewPoint, false))
18561 target->SendCreateUpdateToPlayer(this);
18562 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
18563 m_clientGUIDs.insert(target->GetGUID());
18565 #ifdef MANGOS_DEBUG
18566 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18567 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
18568 #endif
18570 // target aura duration for caster show only if target exist at caster client
18571 // send data at target visibility change (adding to client)
18572 if(target!=this && target->isType(TYPEMASK_UNIT))
18573 SendAurasForTarget((Unit*)target);
18575 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
18576 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
18581 template<class T>
18582 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
18584 s64.insert(target->GetGUID());
18587 template<>
18588 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
18590 if(!target->IsTransport())
18591 s64.insert(target->GetGUID());
18594 template<class T>
18595 void Player::UpdateVisibilityOf(WorldObject const* viewPoint, T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
18597 if(HaveAtClient(target))
18599 if(!target->isVisibleForInState(this,viewPoint,true))
18601 BeforeVisibilityDestroy<T>(target,this);
18603 target->BuildOutOfRangeUpdateBlock(&data);
18604 m_clientGUIDs.erase(target->GetGUID());
18606 #ifdef MANGOS_DEBUG
18607 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18608 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));
18609 #endif
18612 else
18614 if(target->isVisibleForInState(this,viewPoint,false))
18616 visibleNow.insert(target);
18617 target->BuildCreateUpdateBlockForPlayer(&data, this);
18618 UpdateVisibilityOf_helper(m_clientGUIDs,target);
18620 #ifdef MANGOS_DEBUG
18621 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18622 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));
18623 #endif
18628 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18629 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18630 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18631 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18632 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18634 void Player::InitPrimaryProfessions()
18636 SetFreePrimaryProfessions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
18639 void Player::SendComboPoints()
18641 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
18642 if (combotarget)
18644 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
18645 data.append(combotarget->GetPackGUID());
18646 data << uint8(m_comboPoints);
18647 GetSession()->SendPacket(&data);
18651 void Player::AddComboPoints(Unit* target, int8 count)
18653 if(!count)
18654 return;
18656 // without combo points lost (duration checked in aura)
18657 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18659 if(target->GetGUID() == m_comboTarget)
18661 m_comboPoints += count;
18663 else
18665 if(m_comboTarget)
18666 if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget))
18667 target2->RemoveComboPointHolder(GetGUIDLow());
18669 m_comboTarget = target->GetGUID();
18670 m_comboPoints = count;
18672 target->AddComboPointHolder(GetGUIDLow());
18675 if (m_comboPoints > 5) m_comboPoints = 5;
18676 if (m_comboPoints < 0) m_comboPoints = 0;
18678 SendComboPoints();
18681 void Player::ClearComboPoints()
18683 if(!m_comboTarget)
18684 return;
18686 // without combopoints lost (duration checked in aura)
18687 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18689 m_comboPoints = 0;
18691 SendComboPoints();
18693 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
18694 target->RemoveComboPointHolder(GetGUIDLow());
18696 m_comboTarget = 0;
18699 void Player::SetGroup(Group *group, int8 subgroup)
18701 if(group == NULL)
18702 m_group.unlink();
18703 else
18705 // never use SetGroup without a subgroup unless you specify NULL for group
18706 assert(subgroup >= 0);
18707 m_group.link(group, this);
18708 m_group.setSubGroup((uint8)subgroup);
18712 void Player::SendInitialPacketsBeforeAddToMap()
18714 GetSocial()->SendSocialList();
18716 // guild bank list wtf?
18718 // Homebind
18719 WorldPacket data(SMSG_BINDPOINTUPDATE, 5*4);
18720 data << m_homebindX << m_homebindY << m_homebindZ;
18721 data << (uint32) m_homebindMapId;
18722 data << (uint32) m_homebindZoneId;
18723 GetSession()->SendPacket(&data);
18725 // SMSG_SET_PROFICIENCY
18726 // SMSG_SET_PCT_SPELL_MODIFIER
18727 // SMSG_SET_FLAT_SPELL_MODIFIER
18728 // SMSG_UPDATE_AURA_DURATION
18730 SendTalentsInfoData(false);
18732 // SMSG_INSTANCE_DIFFICULTY
18734 SendInitialSpells();
18736 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
18737 data << uint32(0); // count, for(count) uint32;
18738 GetSession()->SendPacket(&data);
18740 SendInitialActionButtons();
18741 m_reputationMgr.SendInitialReputations();
18742 // SMSG_INIT_WORLD_STATES
18743 m_achievementMgr.SendAllAchievementData();
18745 SendEquipmentSetList();
18747 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4);
18748 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
18749 data << (float)0.01666667f; // game speed
18750 data << uint32(0); // added in 3.1.2
18751 GetSession()->SendPacket( &data );
18753 // SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...)
18754 // SMSG_PET_GUIDS
18755 // SMSG_UPDATE_WORLD_STATE
18756 // SMSG_POWER_UPDATE
18758 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
18759 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || HasAuraType(SPELL_AURA_FLY) || isInFlight())
18760 m_movementInfo.AddMovementFlag(MOVEMENTFLAG_FLYING2);
18762 m_mover = this;
18765 void Player::SendInitialPacketsAfterAddToMap()
18767 // update zone
18768 uint32 newzone, newarea;
18769 GetZoneAndAreaId(newzone,newarea);
18770 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
18772 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
18773 data << uint32(0x00000000); // on blizz it increments periodically
18774 GetSession()->SendPacket(&data);
18776 CastSpell(this, 836, true); // LOGINEFFECT
18778 // set some aura effects that send packet to player client after add player to map
18779 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
18780 // same auras state lost at far teleport, send it one more time in this case also
18781 static const AuraType auratypes[] =
18783 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
18784 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
18785 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
18787 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
18789 Unit::AuraList const& auraList = GetAurasByType(*itr);
18790 if(!auraList.empty())
18791 auraList.front()->ApplyModifier(true,true);
18794 if(HasAuraType(SPELL_AURA_MOD_STUN))
18795 SetMovement(MOVE_ROOT);
18797 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
18798 if(HasAuraType(SPELL_AURA_MOD_ROOT))
18800 WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
18801 data2.append(GetPackGUID());
18802 data2 << (uint32)2;
18803 SendMessageToSet(&data2,true);
18806 SendAurasForTarget(this);
18807 SendEnchantmentDurations(); // must be after add to map
18808 SendItemDurations(); // must be after add to map
18811 void Player::SendUpdateToOutOfRangeGroupMembers()
18813 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
18814 return;
18815 if(Group* group = GetGroup())
18816 group->UpdatePlayerOutOfRange(this);
18818 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
18819 m_auraUpdateMask = 0;
18820 if(Pet *pet = GetPet())
18821 pet->ResetAuraUpdateMask();
18824 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
18826 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
18827 data << uint32(mapid);
18828 data << uint8(reason); // transfer abort reason
18829 switch(reason)
18831 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
18832 case TRANSFER_ABORT_DIFFICULTY:
18833 case TRANSFER_ABORT_UNIQUE_MESSAGE:
18834 data << uint8(arg);
18835 break;
18837 GetSession()->SendPacket(&data);
18840 void Player::SendInstanceResetWarning( uint32 mapid, Difficulty difficulty, uint32 time )
18842 // type of warning, based on the time remaining until reset
18843 uint32 type;
18844 if(time > 3600)
18845 type = RAID_INSTANCE_WELCOME;
18846 else if(time > 900 && time <= 3600)
18847 type = RAID_INSTANCE_WARNING_HOURS;
18848 else if(time > 300 && time <= 900)
18849 type = RAID_INSTANCE_WARNING_MIN;
18850 else
18851 type = RAID_INSTANCE_WARNING_MIN_SOON;
18853 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4);
18854 data << uint32(type);
18855 data << uint32(mapid);
18856 data << uint32(difficulty); // difficulty
18857 data << uint32(time);
18858 if(type == RAID_INSTANCE_WELCOME)
18860 data << uint8(0); // is your (1)
18861 data << uint8(0); // is extended (1), ignored if prev field is 0
18863 GetSession()->SendPacket(&data);
18866 void Player::ApplyEquipCooldown( Item * pItem )
18868 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
18870 _Spell const& spellData = pItem->GetProto()->Spells[i];
18872 // no spell
18873 if( !spellData.SpellId )
18874 continue;
18876 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18877 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
18878 continue;
18880 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
18882 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
18883 data << pItem->GetGUID();
18884 data << uint32(spellData.SpellId);
18885 GetSession()->SendPacket(&data);
18889 void Player::resetSpells()
18891 // not need after this call
18892 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
18893 RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS,true);
18895 // make full copy of map (spells removed and marked as deleted at another spell remove
18896 // and we can't use original map for safe iterative with visit each spell at loop end
18897 PlayerSpellMap smap = GetSpellMap();
18899 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
18900 removeSpell(iter->first,false,false); // only iter->first can be accessed, object by iter->second can be deleted already
18902 learnDefaultSpells();
18903 learnQuestRewardedSpells();
18906 void Player::learnDefaultSpells()
18908 // learn default race/class spells
18909 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(),getClass());
18910 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
18912 uint32 tspell = *itr;
18913 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
18914 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18915 addSpell(tspell,true,true,true,false);
18916 else // but send in normal spell in game learn case
18917 learnSpell(tspell,true);
18921 void Player::learnQuestRewardedSpells(Quest const* quest)
18923 uint32 spell_id = quest->GetRewSpellCast();
18925 // skip quests without rewarded spell
18926 if( !spell_id )
18927 return;
18929 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
18930 if(!spellInfo)
18931 return;
18933 // check learned spells state
18934 bool found = false;
18935 for(int i=0; i < 3; ++i)
18937 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
18939 found = true;
18940 break;
18944 // skip quests with not teaching spell or already known spell
18945 if(!found)
18946 return;
18948 // prevent learn non first rank unknown profession and second specialization for same profession)
18949 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
18950 if( sSpellMgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
18952 // not have first rank learned (unlearned prof?)
18953 uint32 first_spell = sSpellMgr.GetFirstSpellInChain(learned_0);
18954 if( !HasSpell(first_spell) )
18955 return;
18957 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
18958 if(!learnedInfo)
18959 return;
18961 // specialization
18962 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
18964 // search other specialization for same prof
18965 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
18967 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
18968 continue;
18970 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
18971 if(!itrInfo)
18972 return;
18974 // compare only specializations
18975 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18976 continue;
18978 // compare same chain spells
18979 if(sSpellMgr.GetFirstSpellInChain(itr->first) != first_spell)
18980 continue;
18982 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18983 if(!sSpellMgr.IsHighRankOfSpell(learned_0,itr->first))
18984 return;
18989 CastSpell( this, spell_id, true);
18992 void Player::learnQuestRewardedSpells()
18994 // learn spells received from quest completing
18995 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18997 // skip no rewarded quests
18998 if(!itr->second.m_rewarded)
18999 continue;
19001 Quest const* quest = sObjectMgr.GetQuestTemplate(itr->first);
19002 if( !quest )
19003 continue;
19005 learnQuestRewardedSpells(quest);
19009 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
19011 uint32 raceMask = getRaceMask();
19012 uint32 classMask = getClassMask();
19013 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
19015 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
19016 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
19017 continue;
19018 // Check race if set
19019 if (pAbility->racemask && !(pAbility->racemask & raceMask))
19020 continue;
19021 // Check class if set
19022 if (pAbility->classmask && !(pAbility->classmask & classMask))
19023 continue;
19025 if (sSpellStore.LookupEntry(pAbility->spellId))
19027 // need unlearn spell
19028 if (skill_value < pAbility->req_skill_value)
19029 removeSpell(pAbility->spellId);
19030 // need learn
19031 else if (!IsInWorld())
19032 addSpell(pAbility->spellId,true,true,true,false);
19033 else
19034 learnSpell(pAbility->spellId,true);
19039 void Player::SendAurasForTarget(Unit *target)
19041 if(target->GetVisibleAuras()->empty()) // speedup things
19042 return;
19044 WorldPacket data(SMSG_AURA_UPDATE_ALL);
19045 data.append(target->GetPackGUID());
19047 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
19048 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
19050 for(uint32 j = 0; j < 3; ++j)
19052 if(Aura *aura = target->GetAura(itr->second, j))
19054 data << uint8(aura->GetAuraSlot());
19055 data << uint32(aura->GetId());
19057 if(aura->GetId())
19059 uint8 auraFlags = aura->GetAuraFlags();
19060 // flags
19061 data << uint8(auraFlags);
19062 // level
19063 data << uint8(aura->GetAuraLevel());
19064 // charges
19065 if (aura->GetAuraCharges())
19066 data << uint8(aura->GetAuraCharges() * aura->GetStackAmount());
19067 else
19068 data << uint8(aura->GetStackAmount());
19070 if(!(auraFlags & AFLAG_NOT_CASTER))
19072 data << uint8(0); // packed GUID of someone (caster?)
19075 if(auraFlags & AFLAG_DURATION) // include aura duration
19077 data << uint32(aura->GetAuraMaxDuration());
19078 data << uint32(aura->GetAuraDuration());
19081 break;
19086 GetSession()->SendPacket(&data);
19089 void Player::SetDailyQuestStatus( uint32 quest_id )
19091 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
19093 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
19095 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
19096 m_lastDailyQuestTime = time(NULL); // last daily quest time
19097 m_DailyQuestChanged = true;
19098 break;
19103 void Player::ResetDailyQuestStatus()
19105 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
19106 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
19108 // DB data deleted in caller
19109 m_DailyQuestChanged = false;
19110 m_lastDailyQuestTime = 0;
19113 BattleGround* Player::GetBattleGround() const
19115 if(GetBattleGroundId()==0)
19116 return NULL;
19118 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgData.bgTypeID);
19121 bool Player::InArena() const
19123 BattleGround *bg = GetBattleGround();
19124 if(!bg || !bg->isArena())
19125 return false;
19127 return true;
19130 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
19132 // get a template bg instead of running one
19133 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
19134 if(!bg)
19135 return false;
19137 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
19138 return false;
19140 return true;
19143 BGQueueIdBasedOnLevel Player::GetBattleGroundQueueIdFromLevel() const
19145 // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 - 79, 80
19146 uint32 queue_id = ( getLevel() / 10) - 1;
19147 if( queue_id >= MAX_BATTLEGROUND_QUEUES )
19149 sLog.outError("BattleGround: too high queue_id %u for player %u (acc: %u) with level %u", queue_id, GetGUIDLow(), GetSession()->GetAccountId(), getLevel());
19150 return QUEUE_ID_MAX_LEVEL_80;
19152 return BGQueueIdBasedOnLevel(queue_id);
19155 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
19157 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
19158 if(!vendor_faction || !vendor_faction->faction)
19159 return 1.0f;
19161 ReputationRank rank = GetReputationRank(vendor_faction->faction);
19162 if(rank <= REP_NEUTRAL)
19163 return 1.0f;
19165 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
19168 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
19170 uint32 racemask = getRaceMask();
19171 uint32 classmask = getClassMask();
19173 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
19174 if (bounds.first==bounds.second)
19175 return true;
19177 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
19179 // skip wrong race skills
19180 if (_spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
19181 continue;
19183 // skip wrong class skills
19184 if (_spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
19185 continue;
19187 return true;
19190 return false;
19193 bool Player::HasQuestForGO(int32 GOId) const
19195 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
19197 uint32 questid = GetQuestSlotQuestId(i);
19198 if ( questid == 0 )
19199 continue;
19201 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
19202 if(qs_itr == mQuestStatus.end())
19203 continue;
19205 QuestStatusData const& qs = qs_itr->second;
19207 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
19209 Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid);
19210 if(!qinfo)
19211 continue;
19213 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
19214 continue;
19216 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
19218 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
19219 continue;
19221 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
19222 return true;
19226 return false;
19229 void Player::UpdateForQuestWorldObjects()
19231 if(m_clientGUIDs.empty())
19232 return;
19234 UpdateData udata;
19235 WorldPacket packet;
19236 for(ClientGUIDs::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
19238 if(IS_GAMEOBJECT_GUID(*itr))
19240 GameObject *obj = GetMap()->GetGameObject(*itr);
19241 if(obj)
19242 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
19244 else if(IS_CREATURE_GUID(*itr) || IS_VEHICLE_GUID(*itr))
19246 Creature *obj = GetMap()->GetCreatureOrPetOrVehicle(*itr);
19247 if(!obj)
19248 continue;
19250 // check if this unit requires quest specific flags
19251 if(!obj->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
19252 continue;
19254 SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(obj->GetEntry());
19255 for(SpellClickInfoMap::const_iterator _itr = clickPair.first; _itr != clickPair.second; ++_itr)
19257 if(_itr->second.questStart || _itr->second.questEnd)
19259 obj->BuildCreateUpdateBlockForPlayer(&udata,this);
19260 break;
19265 udata.BuildPacket(&packet);
19266 GetSession()->SendPacket(&packet);
19269 void Player::SummonIfPossible(bool agree)
19271 if(!agree)
19273 m_summon_expire = 0;
19274 return;
19277 // expire and auto declined
19278 if(m_summon_expire < time(NULL))
19279 return;
19281 // stop taxi flight at summon
19282 if(isInFlight())
19284 GetMotionMaster()->MovementExpired();
19285 m_taxi.ClearTaxiDestinations();
19288 // drop flag at summon
19289 // 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
19290 if(BattleGround *bg = GetBattleGround())
19291 bg->EventPlayerDroppedFlag(this);
19293 m_summon_expire = 0;
19295 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
19297 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
19300 void Player::RemoveItemDurations( Item *item )
19302 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
19304 if(*itr==item)
19306 m_itemDuration.erase(itr);
19307 break;
19312 void Player::AddItemDurations( Item *item )
19314 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
19316 m_itemDuration.push_back(item);
19317 item->SendTimeUpdate(this);
19321 void Player::AutoUnequipOffhandIfNeed()
19323 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
19324 if(!offItem)
19325 return;
19327 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
19328 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
19329 return;
19331 ItemPosCountVec off_dest;
19332 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
19333 if( off_msg == EQUIP_ERR_OK )
19335 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
19336 StoreItem( off_dest, offItem, true );
19338 else
19340 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
19341 CharacterDatabase.BeginTransaction();
19342 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
19343 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
19344 CharacterDatabase.CommitTransaction();
19346 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
19347 MailDraft(subject).AddItem(offItem).SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM));
19351 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
19353 if(spellInfo->EquippedItemClass < 0)
19354 return true;
19356 // scan other equipped items for same requirements (mostly 2 daggers/etc)
19357 // for optimize check 2 used cases only
19358 switch(spellInfo->EquippedItemClass)
19360 case ITEM_CLASS_WEAPON:
19362 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
19363 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
19364 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19365 return true;
19366 break;
19368 case ITEM_CLASS_ARMOR:
19370 // tabard not have dependent spells
19371 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
19372 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
19373 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19374 return true;
19376 // shields can be equipped to offhand slot
19377 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
19378 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19379 return true;
19381 // ranged slot can have some armor subclasses
19382 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
19383 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19384 return true;
19386 break;
19388 default:
19389 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
19390 break;
19393 return false;
19396 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
19398 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
19399 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
19400 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
19401 return true;
19403 // Check no reagent use mask
19404 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
19405 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
19406 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
19407 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
19408 return true;
19410 return false;
19413 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
19415 AuraMap& auras = GetAuras();
19416 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); )
19418 Aura* aura = itr->second;
19420 // skip passive (passive item dependent spells work in another way) and not self applied auras
19421 SpellEntry const* spellInfo = aura->GetSpellProto();
19422 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
19424 ++itr;
19425 continue;
19428 // skip if not item dependent or have alternative item
19429 if(HasItemFitToSpellReqirements(spellInfo,pItem))
19431 ++itr;
19432 continue;
19435 // no alt item, remove aura, restart check
19436 RemoveAurasDueToSpell(aura->GetId());
19437 itr = auras.begin();
19440 // currently casted spells can be dependent from item
19441 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
19442 if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i)))
19443 if (spell->getState()!=SPELL_STATE_DELAYED && !HasItemFitToSpellReqirements(spell->m_spellInfo,pItem) )
19444 InterruptSpell(CurrentSpellTypes(i));
19447 uint32 Player::GetResurrectionSpellId()
19449 // search priceless resurrection possibilities
19450 uint32 prio = 0;
19451 uint32 spell_id = 0;
19452 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
19453 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
19455 // Soulstone Resurrection // prio: 3 (max, non death persistent)
19456 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
19458 switch((*itr)->GetId())
19460 case 20707: spell_id = 3026; break; // rank 1
19461 case 20762: spell_id = 20758; break; // rank 2
19462 case 20763: spell_id = 20759; break; // rank 3
19463 case 20764: spell_id = 20760; break; // rank 4
19464 case 20765: spell_id = 20761; break; // rank 5
19465 case 27239: spell_id = 27240; break; // rank 6
19466 case 47883: spell_id = 47882; break; // rank 7
19467 default:
19468 sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
19469 continue;
19472 prio = 3;
19474 // Twisting Nether // prio: 2 (max)
19475 else if((*itr)->GetId()==23701 && roll_chance_i(10))
19477 prio = 2;
19478 spell_id = 23700;
19482 // Reincarnation (passive spell) // prio: 1
19483 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
19484 spell_id = 21169;
19486 return spell_id;
19489 // Used in triggers for check "Only to targets that grant experience or honor" req
19490 bool Player::isHonorOrXPTarget(Unit* pVictim)
19492 uint32 v_level = pVictim->getLevel();
19493 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
19495 // Victim level less gray level
19496 if(v_level<=k_grey)
19497 return false;
19499 if(pVictim->GetTypeId() == TYPEID_UNIT)
19501 if (((Creature*)pVictim)->isTotem() ||
19502 ((Creature*)pVictim)->isPet() ||
19503 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
19504 return false;
19506 return true;
19509 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
19511 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
19513 // prepare data for near group iteration (PvP and !PvP cases)
19514 uint32 xp = 0;
19515 bool honored_kill = false;
19517 if(Group *pGroup = GetGroup())
19519 uint32 count = 0;
19520 uint32 sum_level = 0;
19521 Player* member_with_max_level = NULL;
19522 Player* not_gray_member_with_max_level = NULL;
19524 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
19526 if(member_with_max_level)
19528 /// not get Xp in PvP or no not gray players in group
19529 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
19531 /// skip in check PvP case (for speed, not used)
19532 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
19533 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
19534 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
19536 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19538 Player* pGroupGuy = itr->getSource();
19539 if(!pGroupGuy)
19540 continue;
19542 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
19543 continue; // member (alive or dead) or his corpse at req. distance
19545 // honor can be in PvP and !PvP (racial leader) cases (for alive)
19546 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
19547 honored_kill = true;
19549 // xp and reputation only in !PvP case
19550 if(!PvP)
19552 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
19554 // if is in dungeon then all receive full reputation at kill
19555 // rewarded any alive/dead/near_corpse group member
19556 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
19558 // XP updated only for alive group member
19559 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
19560 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
19562 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
19564 pGroupGuy->GiveXP(itr_xp, pVictim);
19565 if(Pet* pet = pGroupGuy->GetPet())
19566 pet->GivePetXP(itr_xp/2);
19569 // quest objectives updated only for alive group member or dead but with not released body
19570 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
19572 // normal creature (not pet/etc) can be only in !PvP case
19573 if(pVictim->GetTypeId()==TYPEID_UNIT)
19574 pGroupGuy->KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
19580 else // if (!pGroup)
19582 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
19584 // honor can be in PvP and !PvP (racial leader) cases
19585 if(RewardHonor(pVictim,1))
19586 honored_kill = true;
19588 // xp and reputation only in !PvP case
19589 if(!PvP)
19591 RewardReputation(pVictim,1);
19592 GiveXP(xp, pVictim);
19594 if(Pet* pet = GetPet())
19595 pet->GivePetXP(xp);
19597 // normal creature (not pet/etc) can be only in !PvP case
19598 if(pVictim->GetTypeId()==TYPEID_UNIT)
19599 KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
19602 return xp || honored_kill;
19605 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
19607 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
19609 // prepare data for near group iteration
19610 if(Group *pGroup = GetGroup())
19612 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19614 Player* pGroupGuy = itr->getSource();
19615 if(!pGroupGuy)
19616 continue;
19618 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
19619 continue; // member (alive or dead) or his corpse at req. distance
19621 // quest objectives updated only for alive group member or dead but with not released body
19622 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
19623 pGroupGuy->KilledMonsterCredit(creature_id, creature_guid);
19626 else // if (!pGroup)
19627 KilledMonsterCredit(creature_id, creature_guid);
19630 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
19632 if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE)))
19633 return true;
19635 if (isAlive())
19636 return false;
19638 Corpse* corpse = GetCorpse();
19639 if (!corpse)
19640 return false;
19642 return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE));
19645 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
19647 Item* item = GetWeaponForAttack(attType,true,true);
19649 // unarmed only with base attack
19650 if(attType != BASE_ATTACK && !item)
19651 return 0;
19653 // weapon skill or (unarmed for base attack)
19654 uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
19655 return GetBaseSkillValue(skill);
19658 void Player::ResurectUsingRequestData()
19660 /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
19661 if(IS_PLAYER_GUID(m_resurrectGUID))
19662 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
19664 //we cannot resurrect player when we triggered far teleport
19665 //player will be resurrected upon teleportation
19666 if(IsBeingTeleportedFar())
19668 ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER);
19669 return;
19672 ResurrectPlayer(0.0f,false);
19674 if(GetMaxHealth() > m_resurrectHealth)
19675 SetHealth( m_resurrectHealth );
19676 else
19677 SetHealth( GetMaxHealth() );
19679 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
19680 SetPower(POWER_MANA, m_resurrectMana );
19681 else
19682 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
19684 SetPower(POWER_RAGE, 0 );
19686 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
19688 SpawnCorpseBones();
19691 void Player::SetClientControl(Unit* target, uint8 allowMove)
19693 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
19694 data.append(target->GetPackGUID());
19695 data << uint8(allowMove);
19696 GetSession()->SendPacket(&data);
19699 void Player::UpdateZoneDependentAuras( uint32 newZone )
19701 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
19702 SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAreaMapBounds(newZone);
19703 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19704 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
19705 if( !HasAura(itr->second->spellId,0) )
19706 CastSpell(this,itr->second->spellId,true);
19709 void Player::UpdateAreaDependentAuras( uint32 newArea )
19711 // remove auras from spells with area limitations
19712 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
19714 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
19715 if(sSpellMgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
19716 RemoveAura(iter);
19717 else
19718 ++iter;
19721 // some auras applied at subzone enter
19722 SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAreaMapBounds(newArea);
19723 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19724 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
19725 if( !HasAura(itr->second->spellId,0) )
19726 CastSpell(this,itr->second->spellId,true);
19729 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
19731 if ((pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
19732 (!pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
19734 return copseReclaimDelay[0];
19737 time_t now = time(NULL);
19738 // 0..2 full period
19739 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
19740 return copseReclaimDelay[count];
19743 void Player::UpdateCorpseReclaimDelay()
19745 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
19747 if ((pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
19748 (!pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
19749 return;
19751 time_t now = time(NULL);
19752 if(now < m_deathExpireTime)
19754 // full and partly periods 1..3
19755 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
19756 if(count < MAX_DEATH_COUNT)
19757 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
19758 else
19759 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
19761 else
19762 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
19765 void Player::SendCorpseReclaimDelay(bool load)
19767 Corpse* corpse = GetCorpse();
19768 if(!corpse)
19769 return;
19771 uint32 delay;
19772 if(load)
19774 if(corpse->GetGhostTime() > m_deathExpireTime)
19775 return;
19777 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
19779 uint32 count;
19780 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19781 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19783 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
19784 if(count>=MAX_DEATH_COUNT)
19785 count = MAX_DEATH_COUNT-1;
19787 else
19788 count=0;
19790 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
19792 time_t now = time(NULL);
19793 if(now >= expected_time)
19794 return;
19796 delay = expected_time-now;
19798 else
19799 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
19801 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19802 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
19803 data << uint32(delay*IN_MILISECONDS);
19804 GetSession()->SendPacket( &data );
19807 Player* Player::GetNextRandomRaidMember(float radius)
19809 Group *pGroup = GetGroup();
19810 if(!pGroup)
19811 return NULL;
19813 std::vector<Player*> nearMembers;
19814 nearMembers.reserve(pGroup->GetMembersCount());
19816 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19818 Player* Target = itr->getSource();
19820 // IsHostileTo check duel and controlled by enemy
19821 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
19822 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
19823 nearMembers.push_back(Target);
19826 if (nearMembers.empty())
19827 return NULL;
19829 uint32 randTarget = urand(0,nearMembers.size()-1);
19830 return nearMembers[randTarget];
19833 PartyResult Player::CanUninviteFromGroup() const
19835 const Group* grp = GetGroup();
19836 if(!grp)
19837 return PARTY_RESULT_YOU_NOT_IN_GROUP;
19839 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
19840 return PARTY_RESULT_YOU_NOT_LEADER;
19842 if(InBattleGround())
19843 return PARTY_RESULT_INVITE_RESTRICTED;
19845 return PARTY_RESULT_OK;
19848 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
19850 //we must move references from m_group to m_originalGroup
19851 SetOriginalGroup(GetGroup(), GetSubGroup());
19853 m_group.unlink();
19854 m_group.link(group, this);
19855 m_group.setSubGroup((uint8)subgroup);
19858 void Player::RemoveFromBattleGroundRaid()
19860 //remove existing reference
19861 m_group.unlink();
19862 if( Group* group = GetOriginalGroup() )
19864 m_group.link(group, this);
19865 m_group.setSubGroup(GetOriginalSubGroup());
19867 SetOriginalGroup(NULL);
19870 void Player::SetOriginalGroup(Group *group, int8 subgroup)
19872 if( group == NULL )
19873 m_originalGroup.unlink();
19874 else
19876 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
19877 assert(subgroup >= 0);
19878 m_originalGroup.link(group, this);
19879 m_originalGroup.setSubGroup((uint8)subgroup);
19883 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
19885 LiquidData liquid_status;
19886 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
19887 if (!res)
19889 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
19890 // Small hack for enable breath in WMO
19891 if (IsInWater())
19892 m_MirrorTimerFlags|=UNDERWATER_INWATER;
19893 return;
19896 // All liquids type - check under water position
19897 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
19899 if ( res & LIQUID_MAP_UNDER_WATER)
19900 m_MirrorTimerFlags |= UNDERWATER_INWATER;
19901 else
19902 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
19905 // Allow travel in dark water on taxi or transport
19906 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
19907 m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
19908 else
19909 m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
19911 // in lava check, anywhere in lava level
19912 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
19914 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19915 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
19916 else
19917 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
19919 // in slime check, anywhere in slime level
19920 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
19922 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19923 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
19924 else
19925 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
19929 void Player::SetCanParry( bool value )
19931 if(m_canParry==value)
19932 return;
19934 m_canParry = value;
19935 UpdateParryPercentage();
19938 void Player::SetCanBlock( bool value )
19940 if(m_canBlock==value)
19941 return;
19943 m_canBlock = value;
19944 UpdateBlockPercentage();
19947 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
19949 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
19950 if(itr->pos == pos)
19951 return true;
19953 return false;
19956 bool Player::CanUseBattleGroundObject()
19958 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
19959 // maybe gameobject code should handle that ForceReaction usage
19960 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
19961 return ( //InBattleGround() && // in battleground - not need, check in other cases
19962 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
19963 //player cannot use object when he is invulnerable (immune)
19964 !isTotalImmune() && // not totally immune
19965 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
19966 !HasStealthAura() && // not stealthed
19967 !HasInvisibilityAura() && // not invisible
19968 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
19969 isAlive() // live player
19973 bool Player::CanCaptureTowerPoint()
19975 return ( !HasStealthAura() && // not stealthed
19976 !HasInvisibilityAura() && // not invisible
19977 isAlive() // live player
19981 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
19983 uint32 level = getLevel();
19985 if(level > GT_MAX_LEVEL)
19986 level = GT_MAX_LEVEL; // max level in this dbc
19988 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
19989 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
19990 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
19992 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
19993 return 0;
19995 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
19997 if(!bsc) // shouldn't happen
19998 return 0xFFFFFFFF;
20000 float cost = 0;
20002 if(hairstyle != newhairstyle)
20003 cost += bsc->cost; // full price
20005 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
20006 cost += bsc->cost * 0.5f; // +1/2 of price
20008 if(facialhair != newfacialhair)
20009 cost += bsc->cost * 0.75f; // +3/4 of price
20011 return uint32(cost);
20014 void Player::InitGlyphsForLevel()
20016 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
20017 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
20018 if(gs->Order)
20019 SetGlyphSlot(gs->Order - 1, gs->Id);
20021 uint32 level = getLevel();
20022 uint32 value = 0;
20024 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
20025 if(level >= 15)
20026 value |= (0x01 | 0x02);
20027 if(level >= 30)
20028 value |= 0x08;
20029 if(level >= 50)
20030 value |= 0x04;
20031 if(level >= 70)
20032 value |= 0x10;
20033 if(level >= 80)
20034 value |= 0x20;
20036 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
20039 void Player::EnterVehicle(Vehicle *vehicle)
20041 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
20042 if(!ve)
20043 return;
20045 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
20046 if(!veSeat)
20047 return;
20049 vehicle->SetCharmerGUID(GetGUID());
20050 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
20051 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
20052 vehicle->setFaction(getFaction());
20054 SetCharm(vehicle); // charm
20055 SetFarSightGUID(vehicle->GetGUID()); // set view
20057 SetClientControl(vehicle, 1); // redirect controls to vehicle
20058 SetMover(vehicle);
20060 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
20061 GetSession()->SendPacket(&data);
20063 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
20064 data.append(GetPackGUID());
20065 data << uint32(0); // counter?
20066 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
20067 data << uint16(0); // special flags
20068 data << uint32(getMSTime()); // time
20069 data << vehicle->GetPositionX(); // x
20070 data << vehicle->GetPositionY(); // y
20071 data << vehicle->GetPositionZ(); // z
20072 data << vehicle->GetOrientation(); // o
20073 // transport part, TODO: load/calculate seat offsets
20074 data << uint64(vehicle->GetGUID()); // transport guid
20075 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
20076 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
20077 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
20078 data << float(0); // transport orientation
20079 data << uint32(getMSTime()); // transport time
20080 data << uint8(0); // seat
20081 // end of transport part
20082 data << uint32(0); // fall time
20083 GetSession()->SendPacket(&data);
20085 data.Initialize(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
20086 data << uint64(vehicle->GetGUID());
20087 data << uint16(0);
20088 data << uint32(0);
20089 data << uint32(0x00000101);
20091 for(uint32 i = 0; i < 10; ++i)
20092 data << uint16(0) << uint8(0) << uint8(i+8);
20094 data << uint8(0);
20095 data << uint8(0);
20096 GetSession()->SendPacket(&data);
20099 void Player::ExitVehicle(Vehicle *vehicle)
20101 vehicle->SetCharmerGUID(0);
20102 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
20103 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
20104 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
20106 SetCharm(NULL);
20107 SetFarSightGUID(0);
20109 SetClientControl(vehicle, 0);
20110 SetMover(NULL);
20112 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
20113 data.append(GetPackGUID());
20114 data << uint32(0); // counter?
20115 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
20116 data << uint16(0x40); // special flags
20117 data << uint32(getMSTime()); // time
20118 data << vehicle->GetPositionX(); // x
20119 data << vehicle->GetPositionY(); // y
20120 data << vehicle->GetPositionZ(); // z
20121 data << vehicle->GetOrientation(); // o
20122 data << uint32(0); // fall time
20123 GetSession()->SendPacket(&data);
20125 RemovePetActionBar();
20127 // maybe called at dummy aura remove?
20128 // CastSpell(this, 45472, true); // Parachute
20131 bool Player::isTotalImmune()
20133 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
20135 uint32 immuneMask = 0;
20136 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
20138 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
20139 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
20140 return true;
20142 return false;
20145 bool Player::HasTitle(uint32 bitIndex)
20147 if (bitIndex > MAX_TITLE_INDEX)
20148 return false;
20150 uint32 fieldIndexOffset = bitIndex / 32;
20151 uint32 flag = 1 << (bitIndex % 32);
20152 return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20155 void Player::SetTitle(CharTitlesEntry const* title, bool lost)
20157 uint32 fieldIndexOffset = title->bit_index / 32;
20158 uint32 flag = 1 << (title->bit_index % 32);
20160 if(lost)
20162 if(!HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
20163 return;
20165 RemoveFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20167 else
20169 if(HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
20170 return;
20172 SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20175 WorldPacket data(SMSG_TITLE_EARNED, 4 + 4);
20176 data << uint32(title->bit_index);
20177 data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost
20178 GetSession()->SendPacket(&data);
20181 void Player::ConvertRune(uint8 index, RuneType newType)
20183 SetCurrentRune(index, newType);
20185 WorldPacket data(SMSG_CONVERT_RUNE, 2);
20186 data << uint8(index);
20187 data << uint8(newType);
20188 GetSession()->SendPacket(&data);
20191 void Player::ResyncRunes(uint8 count)
20193 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
20194 for(uint32 i = 0; i < count; ++i)
20196 data << uint8(GetCurrentRune(i)); // rune type
20197 data << uint8(255 - ((GetRuneCooldown(i) / REGEN_TIME_FULL) * 51)); // passed cooldown time (0-255)
20199 GetSession()->SendPacket(&data);
20202 void Player::AddRunePower(uint8 index)
20204 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
20205 data << uint32(1 << index); // mask (0x00-0x3F probably)
20206 GetSession()->SendPacket(&data);
20209 static RuneType runeSlotTypes[MAX_RUNES] = {
20210 /*0*/ RUNE_BLOOD,
20211 /*1*/ RUNE_BLOOD,
20212 /*2*/ RUNE_UNHOLY,
20213 /*3*/ RUNE_UNHOLY,
20214 /*4*/ RUNE_FROST,
20215 /*5*/ RUNE_FROST
20218 void Player::InitRunes()
20220 if(getClass() != CLASS_DEATH_KNIGHT)
20221 return;
20223 m_runes = new Runes;
20225 m_runes->runeState = 0;
20227 for(uint32 i = 0; i < MAX_RUNES; ++i)
20229 SetBaseRune(i, runeSlotTypes[i]); // init base types
20230 SetCurrentRune(i, runeSlotTypes[i]); // init current types
20231 SetRuneCooldown(i, 0); // reset cooldowns
20232 m_runes->SetRuneState(i);
20235 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
20236 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
20240 bool Player::IsBaseRuneSlotsOnCooldown( RuneType runeType ) const
20242 for(uint32 i = 0; i < MAX_RUNES; ++i)
20243 if (GetBaseRune(i) == runeType && GetRuneCooldown(i) == 0)
20244 return false;
20246 return true;
20249 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
20251 Loot loot;
20252 loot.FillLoot (loot_id,store,this,true);
20254 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
20255 for(uint32 i = 0; i < max_slot; ++i)
20257 LootItem* lootItem = loot.LootItemInSlot(i,this);
20259 ItemPosCountVec dest;
20260 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
20261 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
20262 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
20263 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
20264 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
20265 if(msg != EQUIP_ERR_OK)
20267 SendEquipError( msg, NULL, NULL );
20268 continue;
20271 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
20272 SendNewItem(pItem, lootItem->count, false, false, broadcast);
20276 uint32 Player::CalculateTalentsPoints() const
20278 uint32 base_talent = getLevel() < 10 ? 0 : getLevel()-9;
20280 if(getClass() != CLASS_DEATH_KNIGHT)
20281 return uint32(base_talent * sWorld.getRate(RATE_TALENT));
20283 uint32 talentPointsForLevel = getLevel() < 56 ? 0 : getLevel() - 55;
20284 talentPointsForLevel += m_questRewardTalentCount;
20286 if(talentPointsForLevel > base_talent)
20287 talentPointsForLevel = base_talent;
20289 return uint32(talentPointsForLevel * sWorld.getRate(RATE_TALENT));
20292 bool Player::IsKnowHowFlyIn(uint32 mapid, uint32 zone) const
20294 // continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update
20295 uint32 v_map = GetVirtualMapForMapAndZone(mapid, zone);
20296 return v_map != 571 || HasSpell(54197); // Cold Weather Flying
20299 struct DoPlayerLearnSpell
20301 DoPlayerLearnSpell(Player& _player) : player(_player) {}
20302 void operator() (uint32 spell_id) { player.learnSpell(spell_id,false); }
20303 Player& player;
20306 void Player::learnSpellHighRank(uint32 spellid)
20308 learnSpell(spellid,false);
20310 DoPlayerLearnSpell worker(*this);
20311 sSpellMgr.doForHighRanks(spellid,worker);
20314 void Player::_LoadSkills(QueryResult *result)
20316 // 0 1 2
20317 // SetPQuery(PLAYER_LOGIN_QUERY_LOADSKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = '%u'", GUID_LOPART(m_guid));
20319 uint32 count = 0;
20320 if (result)
20324 Field *fields = result->Fetch();
20326 uint16 skill = fields[0].GetUInt16();
20327 uint16 value = fields[1].GetUInt16();
20328 uint16 max = fields[2].GetUInt16();
20330 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(skill);
20331 if(!pSkill)
20333 sLog.outError("Character %u has skill %u that does not exist.", GetGUIDLow(), skill);
20334 continue;
20337 // set fixed skill ranges
20338 switch(GetSkillRangeType(pSkill,false))
20340 case SKILL_RANGE_LANGUAGE: // 300..300
20341 value = max = 300;
20342 break;
20343 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
20344 value = max = 1;
20345 break;
20346 default:
20347 break;
20350 if(value == 0)
20352 sLog.outError("Character %u has skill %u with value 0. Will be deleted.", GetGUIDLow(), skill);
20353 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), skill );
20354 continue;
20357 // enable unlearn button for primary professions only
20358 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
20359 SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,1));
20360 else
20361 SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,0));
20363 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),MAKE_SKILL_VALUE(value, max));
20364 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
20366 mSkillStatus.insert(SkillStatusMap::value_type(skill, SkillStatusData(count, SKILL_UNCHANGED)));
20368 learnSkillRewardedSpells(skill, value);
20370 ++count;
20372 if(count >= PLAYER_MAX_SKILLS) // client limit
20374 sLog.outError("Character %u has more than %u skills.", PLAYER_MAX_SKILLS);
20375 break;
20377 } while (result->NextRow());
20378 delete result;
20381 for (; count < PLAYER_MAX_SKILLS; ++count)
20383 SetUInt32Value(PLAYER_SKILL_INDEX(count), 0);
20384 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),0);
20385 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
20388 // special settings
20389 if(getClass()==CLASS_DEATH_KNIGHT)
20391 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
20392 if(base_level < 1)
20393 base_level = 1;
20394 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
20395 if(base_skill < 1)
20396 base_skill = 1; // skill mast be known and then > 0 in any case
20398 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
20399 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
20400 if(GetPureSkillValue (SKILL_AXES) < base_skill)
20401 SetSkill(SKILL_AXES, base_skill,base_skill);
20402 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
20403 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
20404 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
20405 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
20406 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
20407 SetSkill(SKILL_SWORDS, base_skill,base_skill);
20408 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
20409 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
20410 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
20411 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
20412 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
20413 SetSkill(SKILL_UNARMED, base_skill,base_skill);
20417 uint32 Player::GetPhaseMaskForSpawn() const
20419 uint32 phase = PHASEMASK_NORMAL;
20420 if(!isGameMaster())
20421 phase = GetPhaseMask();
20422 else
20424 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
20425 if(!phases.empty())
20426 phase = phases.front()->GetMiscValue();
20429 // some aura phases include 1 normal map in addition to phase itself
20430 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
20431 return n_phase;
20433 return PHASEMASK_NORMAL;
20436 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
20438 ItemPrototype const* pProto = pItem->GetProto();
20440 // proto based limitations
20441 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
20442 return res;
20444 // check unique-equipped on gems
20445 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
20447 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
20448 if(!enchant_id)
20449 continue;
20450 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
20451 if(!enchantEntry)
20452 continue;
20454 ItemPrototype const* pGem = ObjectMgr::GetItemPrototype(enchantEntry->GemID);
20455 if(!pGem)
20456 continue;
20458 // include for check equip another gems with same limit category for not equipped item (and then not counted)
20459 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
20460 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
20462 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
20463 return res;
20466 return EQUIP_ERR_OK;
20469 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
20471 // check unique-equipped on item
20472 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
20474 // there is an equip limit on this item
20475 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
20476 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
20479 // check unique-equipped limit
20480 if (itemProto->ItemLimitCategory)
20482 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
20483 if(!limitEntry)
20484 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
20486 if(limit_count > limitEntry->maxCount)
20487 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
20489 // there is an equip limit on this item
20490 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
20491 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
20494 return EQUIP_ERR_OK;
20497 void Player::HandleFall(MovementInfo const& movementInfo)
20499 // calculate total z distance of the fall
20500 float z_diff = m_lastFallZ - movementInfo.z;
20501 sLog.outDebug("zDiff = %f", z_diff);
20503 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
20504 // 14.57 can be calculated by resolving damageperc formula below to 0
20505 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
20506 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
20507 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
20509 //Safe fall, fall height reduction
20510 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
20512 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
20514 if(damageperc >0 )
20516 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
20518 float height = movementInfo.z;
20519 UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
20521 if (damage > 0)
20523 //Prevent fall damage from being more than the player maximum health
20524 if (damage > GetMaxHealth())
20525 damage = GetMaxHealth();
20527 // Gust of Wind
20528 if (GetDummyAura(43621))
20529 damage = GetMaxHealth()/2;
20531 uint32 original_health = GetHealth();
20532 uint32 final_damage = EnvironmentalDamage(DAMAGE_FALL, damage);
20534 // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
20535 if (isAlive() && final_damage < original_health)
20536 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
20539 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
20540 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);
20545 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
20547 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
20550 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
20552 uint32 CurTalentPoints = GetFreeTalentPoints();
20554 if(CurTalentPoints == 0)
20555 return;
20557 if (talentRank >= MAX_TALENT_RANK)
20558 return;
20560 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
20562 if(!talentInfo)
20563 return;
20565 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
20567 if(!talentTabInfo)
20568 return;
20570 // prevent learn talent for different class (cheating)
20571 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
20572 return;
20574 // find current max talent rank
20575 int32 curtalent_maxrank = 0;
20576 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
20578 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
20580 curtalent_maxrank = k + 1;
20581 break;
20585 // we already have same or higher talent rank learned
20586 if(curtalent_maxrank >= (talentRank + 1))
20587 return;
20589 // check if we have enough talent points
20590 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
20591 return;
20593 // Check if it requires another talent
20594 if (talentInfo->DependsOn > 0)
20596 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
20598 bool hasEnoughRank = false;
20599 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
20601 if (depTalentInfo->RankID[i] != 0)
20602 if (HasSpell(depTalentInfo->RankID[i]))
20603 hasEnoughRank = true;
20605 if (!hasEnoughRank)
20606 return;
20610 // Find out how many points we have in this field
20611 uint32 spentPoints = 0;
20613 uint32 tTab = talentInfo->TalentTab;
20614 if (talentInfo->Row > 0)
20616 unsigned int numRows = sTalentStore.GetNumRows();
20617 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
20619 // Someday, someone needs to revamp
20620 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
20621 if (tmpTalent) // the way talents are tracked
20623 if (tmpTalent->TalentTab == tTab)
20625 for (int j = 0; j < MAX_TALENT_RANK; ++j)
20627 if (tmpTalent->RankID[j] != 0)
20629 if (HasSpell(tmpTalent->RankID[j]))
20631 spentPoints += j + 1;
20640 // not have required min points spent in talent tree
20641 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
20642 return;
20644 // spell not set in talent.dbc
20645 uint32 spellid = talentInfo->RankID[talentRank];
20646 if( spellid == 0 )
20648 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
20649 return;
20652 // already known
20653 if(HasSpell(spellid))
20654 return;
20656 // learn! (other talent ranks will unlearned at learning)
20657 learnSpell(spellid, false);
20658 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
20660 // update free talent points
20661 SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
20664 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
20666 Pet *pet = GetPet();
20668 if(!pet)
20669 return;
20671 if(petGuid != pet->GetGUID())
20672 return;
20674 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
20676 if(CurTalentPoints == 0)
20677 return;
20679 if (talentRank >= MAX_PET_TALENT_RANK)
20680 return;
20682 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
20684 if(!talentInfo)
20685 return;
20687 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
20689 if(!talentTabInfo)
20690 return;
20692 CreatureInfo const *ci = pet->GetCreatureInfo();
20694 if(!ci)
20695 return;
20697 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
20699 if(!pet_family)
20700 return;
20702 if(pet_family->petTalentType < 0) // not hunter pet
20703 return;
20705 // prevent learn talent for different family (cheating)
20706 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
20707 return;
20709 // find current max talent rank
20710 int32 curtalent_maxrank = 0;
20711 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
20713 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
20715 curtalent_maxrank = k + 1;
20716 break;
20720 // we already have same or higher talent rank learned
20721 if(curtalent_maxrank >= (talentRank + 1))
20722 return;
20724 // check if we have enough talent points
20725 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
20726 return;
20728 // Check if it requires another talent
20729 if (talentInfo->DependsOn > 0)
20731 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
20733 bool hasEnoughRank = false;
20734 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
20736 if (depTalentInfo->RankID[i] != 0)
20737 if (pet->HasSpell(depTalentInfo->RankID[i]))
20738 hasEnoughRank = true;
20740 if (!hasEnoughRank)
20741 return;
20745 // Find out how many points we have in this field
20746 uint32 spentPoints = 0;
20748 uint32 tTab = talentInfo->TalentTab;
20749 if (talentInfo->Row > 0)
20751 unsigned int numRows = sTalentStore.GetNumRows();
20752 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
20754 // Someday, someone needs to revamp
20755 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
20756 if (tmpTalent) // the way talents are tracked
20758 if (tmpTalent->TalentTab == tTab)
20760 for (int j = 0; j < MAX_TALENT_RANK; ++j)
20762 if (tmpTalent->RankID[j] != 0)
20764 if (pet->HasSpell(tmpTalent->RankID[j]))
20766 spentPoints += j + 1;
20775 // not have required min points spent in talent tree
20776 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
20777 return;
20779 // spell not set in talent.dbc
20780 uint32 spellid = talentInfo->RankID[talentRank];
20781 if( spellid == 0 )
20783 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
20784 return;
20787 // already known
20788 if(pet->HasSpell(spellid))
20789 return;
20791 // learn! (other talent ranks will unlearned at learning)
20792 pet->learnSpell(spellid);
20793 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
20795 // update free talent points
20796 pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
20799 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
20801 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
20803 if(apply)
20804 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(UI64LIT(1) << (ctEntry->BitIndex-1)));
20805 else
20806 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(UI64LIT(1) << (ctEntry->BitIndex-1)));
20810 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
20812 if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <=minfo.z || opcode == MSG_MOVE_FALL_LAND)
20813 SetFallInformation(minfo.fallTime, minfo.z);
20816 void Player::UnsummonPetTemporaryIfAny()
20818 Pet* pet = GetPet();
20819 if(!pet)
20820 return;
20822 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
20824 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
20825 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
20828 RemovePet(pet, PET_SAVE_AS_CURRENT);
20831 void Player::ResummonPetTemporaryUnSummonedIfAny()
20833 if(!m_temporaryUnsummonedPetNumber)
20834 return;
20836 // not resummon in not appropriate state
20837 if(IsPetNeedBeTemporaryUnsummoned())
20838 return;
20840 if(GetPetGUID())
20841 return;
20843 Pet* NewPet = new Pet;
20844 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
20845 delete NewPet;
20847 m_temporaryUnsummonedPetNumber = 0;
20850 bool Player::canSeeSpellClickOn(Creature const *c) const
20852 if(!c->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
20853 return false;
20855 SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(c->GetEntry());
20856 for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
20857 if(itr->second.IsFitToRequirements(this))
20858 return true;
20860 return false;
20863 void Player::BuildPlayerTalentsInfoData(WorldPacket *data)
20865 *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
20866 *data << uint8(m_specsCount); // talent group count (0, 1 or 2)
20867 *data << uint8(m_activeSpec); // talent group index (0 or 1)
20869 if(m_specsCount)
20871 // loop through all specs (only 1 for now)
20872 for(uint32 specIdx = 0; specIdx < m_specsCount; ++specIdx)
20874 uint8 talentIdCount = 0;
20875 size_t pos = data->wpos();
20876 *data << uint8(talentIdCount); // [PH], talentIdCount
20878 // find class talent tabs (all players have 3 talent tabs)
20879 uint32 const* talentTabIds = GetTalentTabPages(getClass());
20881 for(uint32 i = 0; i < 3; ++i)
20883 uint32 talentTabId = talentTabIds[i];
20885 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
20887 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
20888 if(!talentInfo)
20889 continue;
20891 // skip another tab talents
20892 if(talentInfo->TalentTab != talentTabId)
20893 continue;
20895 // find max talent rank
20896 int32 curtalent_maxrank = -1;
20897 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
20899 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
20901 curtalent_maxrank = k;
20902 break;
20906 // not learned talent
20907 if(curtalent_maxrank < 0)
20908 continue;
20910 *data << uint32(talentInfo->TalentID); // Talent.dbc
20911 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
20913 ++talentIdCount;
20917 data->put<uint8>(pos, talentIdCount); // put real count
20919 *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
20921 for(uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
20922 *data << uint16(GetGlyph(i)); // GlyphProperties.dbc
20927 void Player::BuildPetTalentsInfoData(WorldPacket *data)
20929 uint32 unspentTalentPoints = 0;
20930 size_t pointsPos = data->wpos();
20931 *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
20933 uint8 talentIdCount = 0;
20934 size_t countPos = data->wpos();
20935 *data << uint8(talentIdCount); // [PH], talentIdCount
20937 Pet *pet = GetPet();
20938 if(!pet)
20939 return;
20941 unspentTalentPoints = pet->GetFreeTalentPoints();
20943 data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
20945 CreatureInfo const *ci = pet->GetCreatureInfo();
20946 if(!ci)
20947 return;
20949 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
20950 if(!pet_family || pet_family->petTalentType < 0)
20951 return;
20953 for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
20955 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
20956 if(!talentTabInfo)
20957 continue;
20959 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
20960 continue;
20962 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
20964 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
20965 if(!talentInfo)
20966 continue;
20968 // skip another tab talents
20969 if(talentInfo->TalentTab != talentTabId)
20970 continue;
20972 // find max talent rank
20973 int32 curtalent_maxrank = -1;
20974 for(int32 k = 4; k > -1; --k)
20976 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
20978 curtalent_maxrank = k;
20979 break;
20983 // not learned talent
20984 if(curtalent_maxrank < 0)
20985 continue;
20987 *data << uint32(talentInfo->TalentID); // Talent.dbc
20988 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
20990 ++talentIdCount;
20993 data->put<uint8>(countPos, talentIdCount); // put real count
20995 break;
20999 void Player::SendTalentsInfoData(bool pet)
21001 WorldPacket data(SMSG_TALENTS_INFO, 50);
21002 data << uint8(pet ? 1 : 0);
21003 if(pet)
21004 BuildPetTalentsInfoData(&data);
21005 else
21006 BuildPlayerTalentsInfoData(&data);
21007 GetSession()->SendPacket(&data);
21010 void Player::BuildEnchantmentsInfoData(WorldPacket *data)
21012 uint32 slotUsedMask = 0;
21013 size_t slotUsedMaskPos = data->wpos();
21014 *data << uint32(slotUsedMask); // slotUsedMask < 0x80000
21016 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
21018 Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
21020 if(!item)
21021 continue;
21023 slotUsedMask |= (1 << i);
21025 *data << uint32(item->GetEntry()); // item entry
21027 uint16 enchantmentMask = 0;
21028 size_t enchantmentMaskPos = data->wpos();
21029 *data << uint16(enchantmentMask); // enchantmentMask < 0x1000
21031 for(uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
21033 uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
21035 if(!enchId)
21036 continue;
21038 enchantmentMask |= (1 << j);
21040 *data << uint16(enchId); // enchantmentId?
21043 data->put<uint16>(enchantmentMaskPos, enchantmentMask);
21045 *data << uint16(0); // ?
21046 *data << uint8(0); // PGUID!
21047 *data << uint32(0); // seed?
21050 data->put<uint32>(slotUsedMaskPos, slotUsedMask);
21053 void Player::SendEquipmentSetList()
21055 uint32 count = 0;
21056 WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4);
21057 size_t count_pos = data.wpos();
21058 data << uint32(count); // count placeholder
21059 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21061 if(itr->second.state==EQUIPMENT_SET_DELETED)
21062 continue;
21063 data.appendPackGUID(itr->second.Guid);
21064 data << uint32(itr->first);
21065 data << itr->second.Name;
21066 data << itr->second.IconName;
21067 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
21068 data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM));
21070 ++count; // client have limit but it checked at loading and set
21072 data.put<uint32>(count_pos, count);
21073 GetSession()->SendPacket(&data);
21076 void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
21078 if(eqset.Guid != 0)
21080 bool found = false;
21082 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21084 if((itr->second.Guid == eqset.Guid) && (itr->first == index))
21086 found = true;
21087 break;
21091 if(!found) // something wrong...
21093 sLog.outError("Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
21094 return;
21098 EquipmentSet& eqslot = m_EquipmentSets[index];
21100 EquipmentSetUpdateState old_state = eqslot.state;
21102 eqslot = eqset;
21104 if(eqset.Guid == 0)
21106 eqslot.Guid = sObjectMgr.GenerateEquipmentSetGuid();
21108 WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1);
21109 data << uint32(index);
21110 data.appendPackGUID(eqslot.Guid);
21111 GetSession()->SendPacket(&data);
21114 eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
21117 void Player::_SaveEquipmentSets()
21119 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
21121 uint32 index = itr->first;
21122 EquipmentSet& eqset = itr->second;
21123 switch(eqset.state)
21125 case EQUIPMENT_SET_UNCHANGED:
21126 ++itr;
21127 break; // nothing do
21128 case EQUIPMENT_SET_CHANGED:
21129 CharacterDatabase.PExecute("UPDATE character_equipmentsets SET name='%s', iconname='%s', item0='%u', item1='%u', item2='%u', item3='%u', item4='%u', item5='%u', item6='%u', item7='%u', item8='%u', item9='%u', item10='%u', item11='%u', item12='%u', item13='%u', item14='%u', item15='%u', item16='%u', item17='%u', item18='%u' WHERE guid='%u' AND setguid='"UI64FMTD"' AND setindex='%u'",
21130 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],
21131 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);
21132 eqset.state = EQUIPMENT_SET_UNCHANGED;
21133 ++itr;
21134 break;
21135 case EQUIPMENT_SET_NEW:
21136 CharacterDatabase.PExecute("INSERT INTO character_equipmentsets VALUES ('%u', '"UI64FMTD"', '%u', '%s', '%s', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
21137 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],
21138 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]);
21139 eqset.state = EQUIPMENT_SET_UNCHANGED;
21140 ++itr;
21141 break;
21142 case EQUIPMENT_SET_DELETED:
21143 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE setguid="UI64FMTD, eqset.Guid);
21144 m_EquipmentSets.erase(itr++);
21145 break;
21150 void Player::_SaveBGData()
21152 CharacterDatabase.PExecute("DELETE FROM character_battleground_data WHERE guid='%u'", GetGUIDLow());
21153 if (m_bgData.bgInstanceID)
21155 /* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
21156 CharacterDatabase.PExecute("INSERT INTO character_battleground_data VALUES ('%u', '%u', '%u', '%f', '%f', '%f', '%f', '%u', '%u', '%u', '%u')",
21157 GetGUIDLow(), m_bgData.bgInstanceID, m_bgData.bgTeam, m_bgData.joinPos.coord_x, m_bgData.joinPos.coord_y, m_bgData.joinPos.coord_z,
21158 m_bgData.joinPos.orientation, m_bgData.joinPos.mapid, m_bgData.taxiPath[0], m_bgData.taxiPath[1], m_bgData.mountSpell);
21162 void Player::DeleteEquipmentSet(uint64 setGuid)
21164 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21166 if(itr->second.Guid == setGuid)
21168 if(itr->second.state == EQUIPMENT_SET_NEW)
21169 m_EquipmentSets.erase(itr);
21170 else
21171 itr->second.state = EQUIPMENT_SET_DELETED;
21172 break;
21177 void Player::ActivateSpec(uint32 specNum)
21179 if(GetActiveSpec() == specNum)
21180 return;
21182 resetTalents(true);
21185 void Player::RemoveAtLoginFlag( AtLoginFlags f, bool in_db_also /*= false*/ )
21187 m_atLoginFlags &= ~f;
21189 if(in_db_also)
21190 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f), GetGUIDLow());
21193 void Player::SendClearCooldown( uint32 spell_id, Unit* target )
21195 WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
21196 data << uint32(spell_id);
21197 data << uint64(target->GetGUID());
21198 SendDirectMessage(&data);
21201 void Player::BuildTeleportAckMsg( WorldPacket *data, float x, float y, float z, float ang ) const
21203 data->Initialize(MSG_MOVE_TELEPORT_ACK, 41);
21204 data->append(GetPackGUID());
21205 *data << uint32(0); // this value increments every time
21206 *data << uint32(m_movementInfo.GetMovementFlags()); // movement flags
21207 *data << uint16(0); // 2.3.0
21208 *data << uint32(getMSTime()); // time
21209 *data << x;
21210 *data << y;
21211 *data << z;
21212 *data << ang;
21213 *data << uint32(0);
21216 bool Player::HasMovementFlag( MovementFlags f ) const
21218 return m_movementInfo.HasMovementFlag(f);
21221 void Player::SetFarSightGUID( uint64 guid )
21223 if(GetFarSight() == guid)
21224 return;
21226 SetUInt64Value(PLAYER_FARSIGHT, guid);
21228 // need triggering load grids around new view point
21229 UpdateVisibilityForPlayer();
21232 void Player::UpdateVisibilityForPlayer()
21234 WorldObject const* viewPoint = GetViewPoint();
21235 Map* m = GetMap();
21237 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
21238 Cell cell(p);
21240 m->UpdatePlayerVisibility(this, cell, p);
21242 if (this != viewPoint)
21244 CellPair pView(MaNGOS::ComputeCellPair(viewPoint->GetPositionX(), viewPoint->GetPositionY()));
21245 Cell cellView(pView);
21247 m->UpdateObjectsVisibilityFor(this, cellView, pView);
21249 else
21250 m->UpdateObjectsVisibilityFor(this, cell, p);
21253 void Player::SendDuelCountdown(uint32 counter)
21255 WorldPacket data(SMSG_DUEL_COUNTDOWN, 4);
21256 data << uint32(counter); // seconds
21257 GetSession()->SendPacket(&data);
21260 bool Player::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
21262 switch(spellInfo->Effect[index])
21264 case SPELL_EFFECT_ATTACK_ME:
21265 return true;
21266 default:
21267 break;
21269 switch(spellInfo->EffectApplyAuraName[index])
21271 case SPELL_AURA_MOD_TAUNT:
21272 return true;
21273 default:
21274 break;
21276 return Unit::IsImmunedToSpellEffect(spellInfo, index);
21279 void Player::SetHomebindToCurrentPos()
21281 m_homebindMapId = GetMapId();
21282 m_homebindZoneId = GetZoneId();
21283 m_homebindX = GetPositionX();
21284 m_homebindY = GetPositionY();
21285 m_homebindZ = GetPositionZ();
21287 // update sql homebind
21288 CharacterDatabase.PExecute("UPDATE character_homebind SET map = '%u', zone = '%u', position_x = '%f', position_y = '%f', position_z = '%f' WHERE guid = '%u'",
21289 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ, GetGUIDLow());