aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/game/Player.cpp46276
-rw-r--r--src/game/Player.h5274
-rw-r--r--src/game/Spell.cpp13910
-rw-r--r--src/game/Unit.cpp32580
4 files changed, 49020 insertions, 49020 deletions
diff --git a/src/game/Player.cpp b/src/game/Player.cpp
index 6fc290467a2..8379ec77d58 100644
--- a/src/game/Player.cpp
+++ b/src/game/Player.cpp
@@ -1,23138 +1,23138 @@
-/*
- * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
- *
- * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-#include "Common.h"
-#include "Language.h"
-#include "Database/DatabaseEnv.h"
-#include "Log.h"
-#include "Opcodes.h"
-#include "SpellMgr.h"
-#include "World.h"
-#include "WorldPacket.h"
-#include "WorldSession.h"
-#include "UpdateMask.h"
-#include "Player.h"
-#include "Vehicle.h"
-#include "SkillDiscovery.h"
-#include "QuestDef.h"
-#include "GossipDef.h"
-#include "UpdateData.h"
-#include "Channel.h"
-#include "ChannelMgr.h"
-#include "MapManager.h"
-#include "MapInstanced.h"
-#include "InstanceSaveMgr.h"
-#include "GridNotifiers.h"
-#include "GridNotifiersImpl.h"
-#include "CellImpl.h"
-#include "ObjectMgr.h"
-#include "ObjectAccessor.h"
-#include "CreatureAI.h"
-#include "Formulas.h"
-#include "Group.h"
-#include "Guild.h"
-#include "Pet.h"
-#include "Util.h"
-#include "Transports.h"
-#include "Weather.h"
-#include "BattleGround.h"
-#include "BattleGroundAV.h"
-#include "BattleGroundMgr.h"
-#include "OutdoorPvP.h"
-#include "OutdoorPvPMgr.h"
-#include "ArenaTeam.h"
-#include "Chat.h"
-#include "Database/DatabaseImpl.h"
-#include "Spell.h"
-#include "SocialMgr.h"
-#include "GameEventMgr.h"
-#include "AchievementMgr.h"
-#include "SpellAuras.h"
-#include "SpellAuraEffects.h"
-
-#include <cmath>
-
-#define ZONE_UPDATE_INTERVAL (1*IN_MILISECONDS)
-
-#define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
-#define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
-#define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
-
-#define SKILL_VALUE(x) PAIR32_LOPART(x)
-#define SKILL_MAX(x) PAIR32_HIPART(x)
-#define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
-
-#define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
-#define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
-#define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
-
-enum CharacterFlags
-{
- CHARACTER_FLAG_NONE = 0x00000000,
- CHARACTER_FLAG_UNK1 = 0x00000001,
- CHARACTER_FLAG_UNK2 = 0x00000002,
- CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
- CHARACTER_FLAG_UNK4 = 0x00000008,
- CHARACTER_FLAG_UNK5 = 0x00000010,
- CHARACTER_FLAG_UNK6 = 0x00000020,
- CHARACTER_FLAG_UNK7 = 0x00000040,
- CHARACTER_FLAG_UNK8 = 0x00000080,
- CHARACTER_FLAG_UNK9 = 0x00000100,
- CHARACTER_FLAG_UNK10 = 0x00000200,
- CHARACTER_FLAG_HIDE_HELM = 0x00000400,
- CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
- CHARACTER_FLAG_UNK13 = 0x00001000,
- CHARACTER_FLAG_GHOST = 0x00002000,
- CHARACTER_FLAG_RENAME = 0x00004000,
- CHARACTER_FLAG_UNK16 = 0x00008000,
- CHARACTER_FLAG_UNK17 = 0x00010000,
- CHARACTER_FLAG_UNK18 = 0x00020000,
- CHARACTER_FLAG_UNK19 = 0x00040000,
- CHARACTER_FLAG_UNK20 = 0x00080000,
- CHARACTER_FLAG_UNK21 = 0x00100000,
- CHARACTER_FLAG_UNK22 = 0x00200000,
- CHARACTER_FLAG_UNK23 = 0x00400000,
- CHARACTER_FLAG_UNK24 = 0x00800000,
- CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
- CHARACTER_FLAG_DECLINED = 0x02000000,
- CHARACTER_FLAG_UNK27 = 0x04000000,
- CHARACTER_FLAG_UNK28 = 0x08000000,
- CHARACTER_FLAG_UNK29 = 0x10000000,
- CHARACTER_FLAG_UNK30 = 0x20000000,
- CHARACTER_FLAG_UNK31 = 0x40000000,
- CHARACTER_FLAG_UNK32 = 0x80000000
-};
-
-enum CharacterCustomizeFlags
-{
- CHAR_CUSTOMIZE_FLAG_NONE = 0x00000000,
- CHAR_CUSTOMIZE_FLAG_CUSTOMIZE = 0x00000001, // name, gender, etc...
- CHAR_CUSTOMIZE_FLAG_FACTION = 0x00010000, // name, gender, faction, etc...
- CHAR_CUSTOMIZE_FLAG_RACE = 0x00100000 // name, gender, race, etc...
-};
-
-// corpse reclaim times
-#define DEATH_EXPIRE_STEP (5*MINUTE)
-#define MAX_DEATH_COUNT 3
-
-static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
-
-//== PlayerTaxi ================================================
-
-PlayerTaxi::PlayerTaxi()
-{
- // Taxi nodes
- memset(m_taximask, 0, sizeof(m_taximask));
-}
-
-void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint8 level)
-{
- // class specific initial known nodes
- switch(chrClass)
- {
- case CLASS_DEATH_KNIGHT:
- {
- for (uint8 i = 0; i < TaxiMaskSize; ++i)
- m_taximask[i] |= sOldContinentsNodesMask[i];
- break;
- }
- }
-
- // race specific initial known nodes: capital and taxi hub masks
- switch(race)
- {
- case RACE_HUMAN: SetTaximaskNode(2); break; // Human
- case RACE_ORC: SetTaximaskNode(23); break; // Orc
- case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
- case RACE_NIGHTELF: SetTaximaskNode(26);
- SetTaximaskNode(27); break; // Night Elf
- case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
- case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
- case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
- case RACE_TROLL: SetTaximaskNode(23); break; // Troll
- case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
- case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
- }
-
- // new continent starting masks (It will be accessible only at new map)
- switch(Player::TeamForRace(race))
- {
- case ALLIANCE: SetTaximaskNode(100); break;
- case HORDE: SetTaximaskNode(99); break;
- }
- // level dependent taxi hubs
- if(level>=68)
- SetTaximaskNode(213); //Shattered Sun Staging Area
-}
-
-void PlayerTaxi::LoadTaxiMask(const char* data)
-{
- Tokens tokens = StrSplit(data, " ");
-
- uint8 index;
- Tokens::iterator iter;
- for (iter = tokens.begin(), index = 0;
- (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
- {
- // load and set bits only for existed taxi nodes
- m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
- }
-}
-
-void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
-{
- if(all)
- {
- for (uint8 i=0; i<TaxiMaskSize; i++)
- data << uint32(sTaxiNodesMask[i]); // all existed nodes
- }
- else
- {
- for (uint8 i=0; i<TaxiMaskSize; i++)
- data << uint32(m_taximask[i]); // known nodes
- }
-}
-
-bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team )
-{
- ClearTaxiDestinations();
-
- Tokens tokens = StrSplit(values," ");
-
- for (Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
- {
- uint32 node = uint32(atol(iter->c_str()));
- AddTaxiDestination(node);
- }
-
- if(m_TaxiDestinations.empty())
- return true;
-
- // Check integrity
- if(m_TaxiDestinations.size() < 2)
- return false;
-
- for (size_t i = 1; i < m_TaxiDestinations.size(); ++i)
- {
- uint32 cost;
- uint32 path;
- objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
- if(!path)
- return false;
- }
-
- // can't load taxi path without mount set (quest taxi path?)
- if(!objmgr.GetTaxiMountDisplayId(GetTaxiSource(),team,true))
- return false;
-
- return true;
-}
-
-std::string PlayerTaxi::SaveTaxiDestinationsToString()
-{
- if(m_TaxiDestinations.empty())
- return "";
-
- std::ostringstream ss;
-
- for (size_t i=0; i < m_TaxiDestinations.size(); ++i)
- ss << m_TaxiDestinations[i] << " ";
-
- return ss.str();
-}
-
-uint32 PlayerTaxi::GetCurrentTaxiPath() const
-{
- if(m_TaxiDestinations.size() < 2)
- return 0;
-
- uint32 path;
- uint32 cost;
-
- objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
-
- return path;
-}
-
-std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
-{
- ss << "'";
- for (uint8 i = 0; i < TaxiMaskSize; ++i)
- ss << taxi.m_taximask[i] << " ";
- ss << "'";
- return ss;
-}
-
-//== Player ====================================================
-
-UpdateMask Player::updateVisualBits;
-
-Player::Player (WorldSession *session): Unit(), m_achievementMgr(this), m_reputationMgr(this)
-{
- m_speakTime = 0;
- m_speakCount = 0;
-
- m_objectType |= TYPEMASK_PLAYER;
- m_objectTypeId = TYPEID_PLAYER;
-
- m_valuesCount = PLAYER_END;
-
- m_session = session;
-
- m_divider = 0;
-
- m_ExtraFlags = 0;
-
- m_spellModTakingSpell = NULL;
- //m_pad = 0;
-
- // players always accept
- if(GetSession()->GetSecurity() == SEC_PLAYER)
- SetAcceptWhispers(true);
-
- m_curSelection = 0;
- m_lootGuid = 0;
-
- m_comboTarget = 0;
- m_comboPoints = 0;
-
- m_usedTalentCount = 0;
- m_questRewardTalentCount = 0;
-
- m_regenTimer = 0;
- m_regenTimerCount = 0;
- m_weaponChangeTimer = 0;
-
- m_zoneUpdateId = 0;
- m_zoneUpdateTimer = 0;
-
- m_areaUpdateId = 0;
-
- m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
-
- clearResurrectRequestData();
-
- memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
-
- m_social = NULL;
-
- // group is initialized in the reference constructor
- SetGroupInvite(NULL);
- m_groupUpdateMask = 0;
- m_auraRaidUpdateMask = 0;
-
- duel = NULL;
-
- m_GuildIdInvited = 0;
- m_ArenaTeamIdInvited = 0;
-
- m_atLoginFlags = AT_LOGIN_NONE;
-
- mSemaphoreTeleport_Near = false;
- mSemaphoreTeleport_Far = false;
-
- m_DelayedOperations = 0;
- m_bCanDelayTeleport = false;
- m_bHasDelayedTeleport = false;
- m_teleport_options = 0;
-
- pTrader = 0;
- ClearTrade();
-
- m_cinematic = 0;
-
- PlayerTalkClass = new PlayerMenu( GetSession() );
- m_currentBuybackSlot = BUYBACK_SLOT_START;
-
- m_DailyQuestChanged = false;
- m_lastDailyQuestTime = 0;
-
- for (uint8 i=0; i<MAX_TIMERS; i++)
- m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
-
- m_MirrorTimerFlags = UNDERWATER_NONE;
- m_MirrorTimerFlagsLast = UNDERWATER_NONE;
- m_isInWater = false;
- m_drunkTimer = 0;
- m_drunk = 0;
- m_restTime = 0;
- m_deathTimer = 0;
- m_deathExpireTime = 0;
-
- m_swingErrorMsg = 0;
-
- m_DetectInvTimer = 1*IN_MILISECONDS;
-
- for (uint8 j = 0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
- {
- m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
- m_bgBattleGroundQueueID[j].invitedToInstance = 0;
- }
-
- m_logintime = time(NULL);
- m_Last_tick = m_logintime;
- m_WeaponProficiency = 0;
- m_ArmorProficiency = 0;
- m_canParry = false;
- m_canBlock = false;
- m_canDualWield = false;
- m_canTitanGrip = false;
- m_ammoDPS = 0.0f;
-
- m_temporaryUnsummonedPetNumber = 0;
- //cache for UNIT_CREATED_BY_SPELL to allow
- //returning reagents for temporarily removed pets
- //when dying/logging out
- m_oldpetspell = 0;
- m_lastpetnumber = 0;
-
- ////////////////////Rest System/////////////////////
- time_inn_enter=0;
- inn_pos_mapid=0;
- inn_pos_x=0;
- inn_pos_y=0;
- inn_pos_z=0;
- m_rest_bonus=0;
- rest_type=REST_TYPE_NO;
- ////////////////////Rest System/////////////////////
-
- m_mailsLoaded = false;
- m_mailsUpdated = false;
- unReadMails = 0;
- m_nextMailDelivereTime = 0;
-
- m_resetTalentsCost = 0;
- m_resetTalentsTime = 0;
- m_itemUpdateQueueBlocked = false;
-
- for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i)
- m_forced_speed_changes[i] = 0;
-
- m_stableSlots = 0;
-
- /////////////////// Instance System /////////////////////
-
- m_HomebindTimer = 0;
- m_InstanceValid = true;
- m_dungeonDifficulty = DUNGEON_DIFFICULTY_NORMAL;
- m_raidDifficulty = RAID_DIFFICULTY_10MAN_NORMAL;
-
- m_lastPotionId = 0;
-
- m_activeSpec = 0;
- m_specsCount = 1;
-
- for (uint8 i = 0; i < MAX_TALENT_SPECS; ++i)
- {
- for (uint8 g = 0; g < MAX_GLYPH_SLOT_INDEX; ++g)
- m_Glyphs[i][g] = 0;
-
- m_talents[i] = new PlayerTalentMap();
- }
-
- for (uint8 i = 0; i < BASEMOD_END; ++i)
- {
- m_auraBaseMod[i][FLAT_MOD] = 0.0f;
- m_auraBaseMod[i][PCT_MOD] = 1.0f;
- }
-
- for (uint8 i = 0; i < MAX_COMBAT_RATING; i++)
- m_baseRatingValue[i] = 0;
-
- m_baseSpellPower = 0;
- m_baseFeralAP = 0;
- m_baseManaRegen = 0;
- m_baseHealthRegen = 0;
-
- // Honor System
- m_lastHonorUpdateTime = time(NULL);
-
- // Player summoning
- m_summon_expire = 0;
- m_summon_mapid = 0;
- m_summon_x = 0.0f;
- m_summon_y = 0.0f;
- m_summon_z = 0.0f;
-
- //Default movement to run mode
- //m_unit_movement_flags = 0;
-
- m_mover = this;
- m_movedPlayer = this;
- m_seer = this;
-
- m_contestedPvPTimer = 0;
-
- m_declinedname = NULL;
-
- m_isActive = true;
-
- m_runes = NULL;
-
- m_lastFallTime = 0;
- m_lastFallZ = 0;
-
- m_ControlledByPlayer = true;
- m_isWorldObject = true;
-
- sWorld.IncreasePlayerCount();
-
- m_ChampioningFaction = 0;
-
- for (int i = 0; i < MAX_POWERS; ++i)
- m_powerFraction[i] = 0;
-}
-
-Player::~Player ()
-{
- // it must be unloaded already in PlayerLogout and accessed only for loggined player
- //m_social = NULL;
-
- // Note: buy back item already deleted from DB when player was saved
- for (uint8 i = 0; i < PLAYER_SLOTS_COUNT; ++i)
- {
- if(m_items[i])
- delete m_items[i];
- }
-
- for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
- delete itr->second;
-
- for (uint8 i = 0; i < MAX_TALENT_SPECS; ++i)
- {
- for (PlayerTalentMap::const_iterator itr = m_talents[i]->begin(); itr != m_talents[i]->end(); ++itr)
- delete itr->second;
- delete m_talents[i];
- }
-
- //all mailed items should be deleted, also all mail should be deallocated
- for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
- delete *itr;
-
- for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
- delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
-
- delete PlayerTalkClass;
-
- for (size_t x = 0; x < ItemSetEff.size(); x++)
- if(ItemSetEff[x])
- delete ItemSetEff[x];
-
- delete m_declinedname;
- delete m_runes;
-
- sWorld.DecreasePlayerCount();
-}
-
-void Player::CleanupsBeforeDelete(bool finalCleanup)
-{
- TradeCancel(false);
- DuelComplete(DUEL_INTERUPTED);
-
- Unit::CleanupsBeforeDelete(finalCleanup);
-
- if (m_transport)
- m_transport->RemovePassenger(this);
-
- // clean up player-instance binds, may unload some instance saves
- for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
- for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
- itr->second.save->RemovePlayer(this);
-}
-
-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 )
-{
- //FIXME: outfitId not used in player creating
-
- Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
-
- m_name = name;
-
- PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
- if(!info)
- {
- sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
- return false;
- }
-
- for (uint8 i = 0; i < PLAYER_SLOTS_COUNT; i++)
- m_items[i] = NULL;
-
- Relocate(info->positionX,info->positionY,info->positionZ);
-
- ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
- if(!cEntry)
- {
- sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
- return false;
- }
-
- SetMap(MapManager::Instance().CreateMap(info->mapId, this, 0));
-
- uint8 powertype = cEntry->powerType;
-
- SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
- SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
-
- setFactionForRace(race);
-
- uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
-
- SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
- InitDisplayIds();
- if(sWorld.getConfig(CONFIG_GAME_TYPE) == REALM_TYPE_PVP || sWorld.getConfig(CONFIG_GAME_TYPE) == REALM_TYPE_RPPVP)
- {
- SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
- SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
- }
- SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
- SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
- SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
-
- // -1 is default value
- SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
-
- SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
- SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
- SetByteValue(PLAYER_BYTES_3, 0, gender);
-
- SetUInt32Value( PLAYER_GUILDID, 0 );
- SetUInt32Value( PLAYER_GUILDRANK, 0 );
- SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
-
- SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
- SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
- SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES2, 0 ); // 0=disabled
- SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
- SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
- SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORABLE_KILLS, 0 );
- SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
- SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
-
- // set starting level
- uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
- ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
- : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
-
- if (GetSession()->GetSecurity() >= SEC_MODERATOR)
- {
- uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
- if(gm_level > start_level)
- start_level = gm_level;
- }
-
- SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
-
- InitRunes();
-
- SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
- SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
- SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
-
- // start with every map explored
- if(sWorld.getConfig(CONFIG_START_ALL_EXPLORED))
- {
- for (uint8 i=0; i<64; i++)
- SetFlag(PLAYER_EXPLORED_ZONES_1+i,0xFFFFFFFF);
- }
-
- //Reputations if "StartAllReputation" is enabled, -- TODO: Fix this in a better way
- if(sWorld.getConfig(CONFIG_START_ALL_REP))
- {
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(942),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(935),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(936),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(1011),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(970),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(967),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(989),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(932),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(934),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(1038),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(1077),42999);
-
- // Factions depending on team, like cities and some more stuff
- switch(GetTeam())
- {
- case ALLIANCE:
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(72),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(47),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(69),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(930),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(730),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(978),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(54),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(946),42999);
- break;
- case HORDE:
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(76),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(68),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(81),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(911),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(729),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(941),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(530),42999);
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(947),42999);
- break;
- default:
- break;
- }
- }
-
- // Played time
- m_Last_tick = time(NULL);
- m_Played_time[PLAYED_TIME_TOTAL] = 0;
- m_Played_time[PLAYED_TIME_LEVEL] = 0;
-
- // base stats and related field values
- InitStatsForLevel();
- InitTaxiNodesForLevel();
- InitGlyphsForLevel();
- InitTalentForLevel();
- InitPrimaryProfessions(); // to max set before any spell added
-
- // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
- UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
- SetHealth(GetMaxHealth());
- if (getPowerType()==POWER_MANA)
- {
- UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
- SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
- }
-
- if(getPowerType() == POWER_RUNIC_POWER)
- {
- SetPower(POWER_RUNE, 8);
- SetMaxPower(POWER_RUNE, 8);
- SetPower(POWER_RUNIC_POWER, 0);
- SetMaxPower(POWER_RUNIC_POWER, 1000);
- }
-
- // original spells
- learnDefaultSpells();
-
- // original action bar
- for (PlayerCreateInfoActions::const_iterator action_itr = info->action.begin(); action_itr != info->action.end(); ++action_itr)
- addActionButton(action_itr->button,action_itr->action,action_itr->type);
-
- // original items
- CharStartOutfitEntry const* oEntry = NULL;
- for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
- {
- if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
- {
- if(entry->RaceClassGender == RaceClassGender)
- {
- oEntry = entry;
- break;
- }
- }
- }
-
- if(oEntry)
- {
- for (int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
- {
- if(oEntry->ItemId[j] <= 0)
- continue;
-
- uint32 item_id = oEntry->ItemId[j];
-
- // just skip, reported in ObjectMgr::LoadItemPrototypes
- ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
- if (!iProto)
- continue;
-
- // BuyCount by default
- uint32 count = iProto->BuyCount;
-
- // special amount for food/drink
- if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
- {
- switch(iProto->Spells[0].SpellCategory)
- {
- case SPELL_CATEGORY_FOOD: // food
- count = getClass()==CLASS_DEATH_KNIGHT ? 10 : 4;
- break;
- case SPELL_CATEGORY_DRINK: // drink
- count = 2;
- break;
- }
- if(iProto->Stackable < count)
- count = iProto->Stackable;
- }
- // special amount for daggers
- else if(iProto->Class==ITEM_CLASS_WEAPON && iProto->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER)
- {
- count = 2; // will placed to 2 slots
- }
-
- StoreNewItemInBestSlots(item_id, count);
- }
- }
-
- for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
- StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
-
- // bags and main-hand weapon must equipped at this moment
- // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
- // or ammo not equipped in special bag
- for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
- {
- if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- {
- uint16 eDest;
- // equip offhand weapon/shield if it attempt equipped before main-hand weapon
- uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
- if( msg == EQUIP_ERR_OK )
- {
- RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
- EquipItem( eDest, pItem, true);
- }
- // move other items to more appropriate slots (ammo not equipped in special bag)
- else
- {
- ItemPosCountVec sDest;
- msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
- if( msg == EQUIP_ERR_OK )
- {
- RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
- pItem = StoreItem( sDest, pItem, true);
- }
-
- // if this is ammo then use it
- msg = CanUseAmmo( pItem->GetEntry() );
- if( msg == EQUIP_ERR_OK )
- SetAmmo( pItem->GetEntry() );
- }
- }
- }
- // all item positions resolved
-
- return true;
-}
-
-bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
-{
- sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
-
- // attempt equip by one
- while(titem_amount > 0)
- {
- uint16 eDest;
- uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
- if( msg != EQUIP_ERR_OK )
- break;
-
- EquipNewItem( eDest, titem_id, true);
- AutoUnequipOffhandIfNeed();
- --titem_amount;
- }
-
- if(titem_amount == 0)
- return true; // equipped
-
- // attempt store
- ItemPosCountVec sDest;
- // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
- uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
- if( msg == EQUIP_ERR_OK )
- {
- StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
- return true; // stored
- }
-
- // item can't be added
- sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
- return false;
-}
-
-void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
-{
- if (int(MaxValue) == DISABLED_MIRROR_TIMER)
- {
- if (int(CurrentValue) != DISABLED_MIRROR_TIMER)
- StopMirrorTimer(Type);
- return;
- }
- WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
- data << (uint32)Type;
- data << CurrentValue;
- data << MaxValue;
- data << Regen;
- data << (uint8)0;
- data << (uint32)0; // spell id
- GetSession()->SendPacket( &data );
-}
-
-void Player::StopMirrorTimer(MirrorTimerType Type)
-{
- m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
- WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
- data << (uint32)Type;
- GetSession()->SendPacket( &data );
-}
-
-uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
-{
- if(!isAlive() || isGameMaster())
- return 0;
-
- // Absorb, resist some environmental damage type
- uint32 absorb = 0;
- uint32 resist = 0;
- if (type == DAMAGE_LAVA)
- CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
- else if (type == DAMAGE_SLIME)
- CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
-
- damage-=absorb+resist;
-
- DealDamageMods(this,damage,&absorb);
-
- WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
- data << uint64(GetGUID());
- data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
- data << uint32(damage);
- data << uint32(absorb);
- data << uint32(resist);
- SendMessageToSet(&data, true);
-
- uint32 final_damage = DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
-
- if(!isAlive())
- {
- if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
- {
- DEBUG_LOG("We are fall to death, loosing 10 percents durability");
- DurabilityLossAll(0.10f,false);
- // durability lost message
- WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
- GetSession()->SendPacket(&data2);
- }
-
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
- }
-
- return final_damage;
-}
-
-int32 Player::getMaxTimer(MirrorTimerType timer)
-{
- switch (timer)
- {
- case FATIGUE_TIMER:
- return MINUTE*IN_MILISECONDS;
- case BREATH_TIMER:
- {
- if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
- return DISABLED_MIRROR_TIMER;
- int32 UnderWaterTime = 3*MINUTE*IN_MILISECONDS;
- AuraEffectList const& mModWaterBreathing = GetAuraEffectsByType(SPELL_AURA_MOD_WATER_BREATHING);
- for (AuraEffectList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
- UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetAmount()) / 100.0f);
- return UnderWaterTime;
- }
- case FIRE_TIMER:
- {
- if (!isAlive())
- return DISABLED_MIRROR_TIMER;
- return 1*IN_MILISECONDS;
- }
- default:
- return 0;
- }
- return 0;
-}
-
-void Player::UpdateMirrorTimers()
-{
- // Desync flags for update on next HandleDrowning
- if (m_MirrorTimerFlags)
- m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
-}
-
-void Player::HandleDrowning(uint32 time_diff)
-{
- if (!m_MirrorTimerFlags)
- return;
-
- // In water
- if (m_MirrorTimerFlags & UNDERWATER_INWATER)
- {
- // Breath timer not activated - activate it
- if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
- {
- m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
- SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
- }
- else // If activated - do tick
- {
- m_MirrorTimer[BREATH_TIMER]-=time_diff;
- // Timer limit - need deal damage
- if (m_MirrorTimer[BREATH_TIMER] < 0)
- {
- m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILISECONDS;
- // Calculate and deal damage
- // TODO: Check this formula
- uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
- EnvironmentalDamage(DAMAGE_DROWNING, damage);
- }
- else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
- SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
- }
- }
- else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
- {
- int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
- // Need breath regen
- m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
- if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
- StopMirrorTimer(BREATH_TIMER);
- else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
- SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
- }
-
- // In dark water
- if (m_MirrorTimerFlags & UNDERWARER_INDARKWATER)
- {
- // Fatigue timer not activated - activate it
- if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
- {
- m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
- SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
- }
- else
- {
- m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
- // Timer limit - need deal damage or teleport ghost to graveyard
- if (m_MirrorTimer[FATIGUE_TIMER] < 0)
- {
- m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILISECONDS;
- if (isAlive()) // Calculate and deal damage
- {
- uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
- EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
- }
- else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
- RepopAtGraveyard();
- }
- else if (!(m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER))
- SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
- }
- }
- else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
- {
- int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
- m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
- if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
- StopMirrorTimer(FATIGUE_TIMER);
- else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER)
- SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
- }
-
- if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
- {
- // Breath timer not activated - activate it
- if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
- m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
- else
- {
- m_MirrorTimer[FIRE_TIMER]-=time_diff;
- if (m_MirrorTimer[FIRE_TIMER] < 0)
- {
- m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILISECONDS;
- // Calculate and deal damage
- // TODO: Check this formula
- uint32 damage = urand(600, 700);
- if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
- EnvironmentalDamage(DAMAGE_LAVA, damage);
- else
- EnvironmentalDamage(DAMAGE_SLIME, damage);
- }
- }
- }
- else
- m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
-
- // Recheck timers flag
- m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
- for (uint8 i = 0; i< MAX_TIMERS; ++i)
- if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
- {
- m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
- break;
- }
- m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
-}
-
-///The player sobers by 256 every 10 seconds
-void Player::HandleSobering()
-{
- m_drunkTimer = 0;
-
- uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
- SetDrunkValue(drunk);
-}
-
-DrunkenState Player::GetDrunkenstateByValue(uint16 value)
-{
- if(value >= 23000)
- return DRUNKEN_SMASHED;
- if(value >= 12800)
- return DRUNKEN_DRUNK;
- if(value & 0xFFFE)
- return DRUNKEN_TIPSY;
- return DRUNKEN_SOBER;
-}
-
-void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
-{
- uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
-
- m_drunk = newDrunkenValue;
- SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
-
- uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
-
- // special drunk invisibility detection
- if(newDrunkenState >= DRUNKEN_DRUNK)
- m_detectInvisibilityMask |= (1<<6);
- else
- m_detectInvisibilityMask &= ~(1<<6);
-
- if(newDrunkenState == oldDrunkenState)
- return;
-
- WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
- data << uint64(GetGUID());
- data << uint32(newDrunkenState);
- data << uint32(itemId);
-
- SendMessageToSet(&data, true);
-}
-
-void Player::Update( uint32 p_time )
-{
- if (!IsInWorld())
- return;
-
- // undelivered mail
- if (m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
- {
- SendNewMail();
- ++unReadMails;
-
- // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
- m_nextMailDelivereTime = 0;
- }
-
- // If this is set during update SetSpellModTakingSpell call is missing somewhere in the code
- // Having this would prevent more aura charges to be dropped, so let's crash
- //assert (!m_spellModTakingSpell);
- if (/*m_pad ||*/ m_spellModTakingSpell)
- {
- //sLog.outCrash("Player has m_pad %u during update!", m_pad);
- //if(m_spellModTakingSpell)
- sLog.outCrash("Player has m_spellModTakingSpell %u during update!", m_spellModTakingSpell->m_spellInfo->Id);
- return;
- m_spellModTakingSpell = NULL;
- }
-
- //used to implement delayed far teleports
- SetCanDelayTeleport(true);
- Unit::Update(p_time);
- SetCanDelayTeleport(false);
-
- time_t now = time(NULL);
-
- UpdatePvPFlag(now);
-
- UpdateContestedPvP(p_time);
-
- UpdateDuelFlag(now);
-
- CheckDuelDistance(now);
-
- UpdateAfkReport(now);
-
- if (isCharmed())
- if (Unit *charmer = GetCharmer())
- if (charmer->GetTypeId() == TYPEID_UNIT && charmer->isAlive())
- UpdateCharmedAI();
-
- // Update items that have just a limited lifetime
- if (now > m_Last_tick)
- UpdateItemDuration(uint32(now - m_Last_tick));
-
- if (!m_timedquests.empty())
- {
- std::set<uint32>::iterator iter = m_timedquests.begin();
- while (iter != m_timedquests.end())
- {
- QuestStatusData& q_status = mQuestStatus[*iter];
- if (q_status.m_timer <= p_time)
- {
- uint32 quest_id = *iter;
- ++iter; // current iter will be removed in FailQuest
- FailQuest(quest_id);
- }
- else
- {
- q_status.m_timer -= p_time;
- if (q_status.uState != QUEST_NEW)
- q_status.uState = QUEST_CHANGED;
- ++iter;
- }
- }
- }
-
- if (hasUnitState(UNIT_STAT_MELEE_ATTACKING) && !hasUnitState(UNIT_STAT_CASTING))
- {
- if (Unit *pVictim = getVictim())
- {
- // default combat reach 10
- // TODO add weapon,skill check
-
- if (isAttackReady(BASE_ATTACK))
- {
- if (!IsWithinMeleeRange(pVictim))
- {
- setAttackTimer(BASE_ATTACK,100);
- if (m_swingErrorMsg != 1) // send single time (client auto repeat)
- {
- SendAttackSwingNotInRange();
- m_swingErrorMsg = 1;
- }
- }
- //120 degrees of radiant range
- else if (!HasInArc(2*M_PI/3, pVictim))
- {
- setAttackTimer(BASE_ATTACK,100);
- if (m_swingErrorMsg != 2) // send single time (client auto repeat)
- {
- SendAttackSwingBadFacingAttack();
- m_swingErrorMsg = 2;
- }
- }
- else
- {
- m_swingErrorMsg = 0; // reset swing error state
-
- // prevent base and off attack in same time, delay attack at 0.2 sec
- if (haveOffhandWeapon())
- if (getAttackTimer(OFF_ATTACK) < ATTACK_DISPLAY_DELAY)
- setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
-
- // do attack
- AttackerStateUpdate(pVictim, BASE_ATTACK);
- resetAttackTimer(BASE_ATTACK);
- }
- }
-
- if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
- {
- if (!IsWithinMeleeRange(pVictim))
- setAttackTimer(OFF_ATTACK,100);
- else if (!HasInArc(2*M_PI/3, pVictim))
- setAttackTimer(OFF_ATTACK,100);
- else
- {
- // prevent base and off attack in same time, delay attack at 0.2 sec
- if (getAttackTimer(BASE_ATTACK) < ATTACK_DISPLAY_DELAY)
- setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
-
- // do attack
- AttackerStateUpdate(pVictim, OFF_ATTACK);
- resetAttackTimer(OFF_ATTACK);
- }
- }
-
- /*Unit *owner = pVictim->GetOwner();
- Unit *u = owner ? owner : pVictim;
- if(u->IsPvP() && (!duel || duel->opponent != u))
- {
- UpdatePvP(true);
- RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
- }*/
- }
- }
-
- if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
- {
- if (roll_chance_i(3) && GetTimeInnEnter() > 0) // freeze update
- {
- int time_inn = time(NULL)-GetTimeInnEnter();
- if (time_inn >= 10) // freeze update
- {
- float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
- // speed collect rest bonus (section/in hour)
- SetRestBonus(GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
- UpdateInnerTime(time(NULL));
- }
- }
- }
-
- if (m_weaponChangeTimer > 0)
- {
- if (p_time >= m_weaponChangeTimer)
- m_weaponChangeTimer = 0;
- else
- m_weaponChangeTimer -= p_time;
- }
-
- if (m_zoneUpdateTimer > 0)
- {
- if (p_time >= m_zoneUpdateTimer)
- {
- uint32 newzone, newarea;
- GetZoneAndAreaId(newzone,newarea);
-
- if (m_zoneUpdateId != newzone)
- UpdateZone(newzone,newarea); // also update area
- else
- {
- // use area updates as well
- // needed for free far all arenas for example
- if (m_areaUpdateId != newarea)
- UpdateArea(newarea);
-
- m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
- }
- }
- else
- m_zoneUpdateTimer -= p_time;
- }
-
- if (m_timeSyncTimer > 0)
- {
- if(p_time >= m_timeSyncTimer)
- SendTimeSync();
- else
- m_timeSyncTimer -= p_time;
- }
-
- if (isAlive())
- {
- m_regenTimer += p_time;
- RegenerateAll();
- }
-
- if (m_deathState == JUST_DIED)
- KillPlayer();
-
- if (m_nextSave > 0)
- {
- if (p_time >= m_nextSave)
- {
- // m_nextSave reseted in SaveToDB call
- SaveToDB();
- sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
- }
- else
- m_nextSave -= p_time;
- }
-
- //Handle Water/drowning
- HandleDrowning(p_time);
-
- //Handle detect stealth players
- if (m_DetectInvTimer > 0)
- {
- if (p_time >= m_DetectInvTimer)
- {
- HandleStealthedUnitsDetection();
- m_DetectInvTimer = 3000;
- }
- else
- m_DetectInvTimer -= p_time;
- }
-
- // Played time
- if (now > m_Last_tick)
- {
- uint32 elapsed = uint32(now - m_Last_tick);
- m_Played_time[PLAYED_TIME_TOTAL] += elapsed; // Total played time
- m_Played_time[PLAYED_TIME_LEVEL] += elapsed; // Level played time
- m_Last_tick = now;
- }
-
- if (m_drunk)
- {
- m_drunkTimer += p_time;
-
- if (m_drunkTimer > 10*IN_MILISECONDS)
- HandleSobering();
- }
-
- // not auto-free ghost from body in instances
- if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
- {
- if(p_time >= m_deathTimer)
- {
- m_deathTimer = 0;
- BuildPlayerRepop();
- RepopAtGraveyard();
- }
- else
- m_deathTimer -= p_time;
- }
-
- UpdateEnchantTime(p_time);
- UpdateHomebindTime(p_time);
-
- // group update
- SendUpdateToOutOfRangeGroupMembers();
-
- Pet* pet = GetPet();
- if (pet && !pet->IsWithinDistInMap(this, GetMap()->GetVisibilityDistance()) && !pet->isPossessed())
- //if(pet && !pet->IsWithinDistInMap(this, GetMap()->GetVisibilityDistance()) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
- RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
-
- //we should execute delayed teleports only for alive(!) players
- //because we don't want player's ghost teleported from graveyard
- if (IsHasDelayedTeleport() && isAlive())
- TeleportTo(m_teleport_dest, m_teleport_options);
-}
-
-void Player::setDeathState(DeathState s)
-{
- uint32 ressSpellId = 0;
-
- bool cur = isAlive();
-
- if (s == JUST_DIED)
- {
- if (!cur)
- {
- sLog.outError("setDeathState: attempt to kill a dead player %s(%d)", GetName(), GetGUIDLow());
- return;
- }
-
- // drunken state is cleared on death
- SetDrunkValue(0);
- // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
- ClearComboPoints();
-
- clearResurrectRequestData();
-
- // remove form before other mods to prevent incorrect stats calculation
- RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
-
- //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
- RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
-
- // save value before aura remove in Unit::setDeathState
- ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
-
- // passive spell
- if(!ressSpellId)
- ressSpellId = GetResurrectionSpellId();
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
- }
- Unit::setDeathState(s);
-
- // restore resurrection spell id for player after aura remove
- if (s == JUST_DIED && cur && ressSpellId)
- SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
-
- if (isAlive() && !cur)
- {
- //clear aura case after resurrection by another way (spells will be applied before next death)
- SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
-
- // restore default warrior stance
- if (getClass() == CLASS_WARRIOR)
- CastSpell(this, 2457, true);
- }
-}
-
-bool Player::BuildEnumData( QueryResult_AutoPtr result, WorldPacket * p_data )
-{
- // 0 1 2 3 4 5 6 7
- // "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.playerBytes, characters.playerBytes2, characters.level, "
- // 8 9 10 11 12 13 14
- // "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, "
- // 15 16 17 18 19 20
- // "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.data, character_declinedname.genitive "
-
- Field *fields = result->Fetch();
-
- uint32 guid = fields[0].GetUInt32();
- uint8 pRace = fields[2].GetUInt8();
- uint8 pClass = fields[3].GetUInt8();
-
- PlayerInfo const *info = objmgr.GetPlayerInfo(pRace, pClass);
- if (!info)
- {
- sLog.outError("Player %u has incorrect race/class pair. Don't build enum.", guid);
- return false;
- }
-
- *p_data << uint64(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
- *p_data << fields[1].GetString(); // name
- *p_data << uint8(pRace); // race
- *p_data << uint8(pClass); // class
- *p_data << uint8(fields[4].GetUInt8()); // gender
-
- uint32 playerBytes = fields[5].GetUInt32();
- *p_data << uint8(playerBytes); // skin
- *p_data << uint8(playerBytes >> 8); // face
- *p_data << uint8(playerBytes >> 16); // hair style
- *p_data << uint8(playerBytes >> 24); // hair color
-
- uint32 playerBytes2 = fields[6].GetUInt32();
- *p_data << uint8(playerBytes2 & 0xFF); // facial hair
-
- *p_data << uint8(fields[7].GetUInt8()); // level
- *p_data << uint32(fields[8].GetUInt32()); // zone
- *p_data << uint32(fields[9].GetUInt32()); // map
-
- *p_data << fields[10].GetFloat(); // x
- *p_data << fields[11].GetFloat(); // y
- *p_data << fields[12].GetFloat(); // z
-
- *p_data << uint32(fields[13].GetUInt32()); // guild id
-
- uint32 char_flags = 0;
- uint32 playerFlags = fields[14].GetUInt32();
- uint32 atLoginFlags = fields[15].GetUInt32();
- if (playerFlags & PLAYER_FLAGS_HIDE_HELM)
- char_flags |= CHARACTER_FLAG_HIDE_HELM;
- if (playerFlags & PLAYER_FLAGS_HIDE_CLOAK)
- char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
- if (playerFlags & PLAYER_FLAGS_GHOST)
- char_flags |= CHARACTER_FLAG_GHOST;
- if (atLoginFlags & AT_LOGIN_RENAME)
- char_flags |= CHARACTER_FLAG_RENAME;
- if (sWorld.getConfig(CONFIG_DECLINED_NAMES_USED))
- {
- if (!fields[20].GetCppString().empty())
- char_flags |= CHARACTER_FLAG_DECLINED;
- }
- else
- char_flags |= CHARACTER_FLAG_DECLINED;
-
- *p_data << uint32(char_flags); // character flags
- // character customize flags
- *p_data << uint32(atLoginFlags & AT_LOGIN_CUSTOMIZE ? CHAR_CUSTOMIZE_FLAG_CUSTOMIZE : CHAR_CUSTOMIZE_FLAG_NONE);
- // First login
- *p_data << uint8(atLoginFlags & AT_LOGIN_FIRST ? 1 : 0);
-
- // Pets info
- {
- uint32 petDisplayId = 0;
- uint32 petLevel = 0;
- uint32 petFamily = 0;
-
- // show pet at selection character in character list only for non-ghost character
- if (result && !(playerFlags & PLAYER_FLAGS_GHOST) && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER || pClass == CLASS_DEATH_KNIGHT))
- {
- uint32 entry = fields[16].GetUInt32();
- CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
- if (cInfo)
- {
- petDisplayId = fields[17].GetUInt32();
- petLevel = fields[18].GetUInt32();
- petFamily = cInfo->family;
- }
- }
-
- *p_data << uint32(petDisplayId);
- *p_data << uint32(petLevel);
- *p_data << uint32(petFamily);
- }
-
- // TODO: do not access data field here
- Tokens data = StrSplit(fields[19].GetCppString(), " ");
-
- for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; ++slot)
- {
- uint32 visualbase = PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2);
- uint32 item_id = GetUInt32ValueFromArray(data, visualbase);
- const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
- if (!proto)
- {
- *p_data << uint32(0);
- *p_data << uint8(0);
- *p_data << uint32(0);
- continue;
- }
-
- SpellItemEnchantmentEntry const *enchant = NULL;
-
- uint32 enchants = GetUInt32ValueFromArray(data, visualbase + 1);
- for (uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot)
- {
- // values stored in 2 uint16
- uint32 enchantId = 0x0000FFFF & (enchants >> enchantSlot*16);
- if (!enchantId)
- continue;
-
- if ((enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId)))
- break;
- }
-
- *p_data << uint32(proto->DisplayInfoID);
- *p_data << uint8(proto->InventoryType);
- *p_data << uint32(enchant ? enchant->aura_id : 0);
- }
- *p_data << uint32(0); // first bag display id
- *p_data << uint8(0); // first bag inventory type
- *p_data << uint32(0); // enchant?
-
- return true;
-}
-
-bool Player::ToggleAFK()
-{
- ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
-
- bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
-
- // afk player not allowed in battleground
- if (state && InBattleGround())
- LeaveBattleground();
-
- return state;
-}
-
-bool Player::ToggleDND()
-{
- ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
-
- return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
-}
-
-uint8 Player::chatTag() const
-{
- // it's bitmask
- // 0x8 - ??
- // 0x4 - gm
- // 0x2 - dnd
- // 0x1 - afk
- if (isGMChat())
- return 4;
- else if (isDND())
- return 3;
- if (isAFK())
- return 1;
- else
- return 0;
-}
-
-void Player::SendTeleportAckMsg()
-{
- WorldPacket data(MSG_MOVE_TELEPORT_ACK, 41);
- data.append(GetPackGUID());
- data << uint32(0); // this value increments every time
- BuildMovementPacket(&data);
- GetSession()->SendPacket(&data);
-}
-
-// this is not used anywhere
-void Player::TeleportOutOfMap(Map *oldMap)
-{
- while (IsBeingTeleportedFar())
- GetSession()->HandleMoveWorldportAckOpcode();
-
- if (GetMap() != oldMap)
- return;
-
- TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
-
- while (IsBeingTeleportedFar())
- GetSession()->HandleMoveWorldportAckOpcode();
-
- if (GetMap() == oldMap)
- {
- sLog.outCrash("Cannot teleport player out of map!");
- ResetMap();
- assert(false);
- }
-}
-
-bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
-{
- if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
- {
- sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
- return false;
- }
-
- if((GetSession()->GetSecurity() < SEC_GAMEMASTER) && !sWorld.IsAllowedMap(mapid))
- {
- sLog.outError("Player %s tried to enter a forbidden map", GetName());
- return false;
- }
-
- // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
- Pet* pet = GetPet();
-
- MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
-
- // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
- // don't let gm level > 1 either
- if (!InBattleGround() && mEntry->IsBattleGroundOrArena())
- return false;
-
- // client without expansion support
- if (GetSession()->Expansion() < mEntry->Expansion())
- {
- sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
-
- if (GetTransport())
- RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
-
- SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
-
- return false; // normal client can't teleport to this map...
- }
- else
- sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
-
- // reset movement flags at teleport, because player will continue move with these flags after teleport
- SetUnitMovementFlags(0);
-
- if (m_transport)
- {
- if (options & TELE_TO_NOT_LEAVE_TRANSPORT)
- AddUnitMovementFlag(MOVEMENTFLAG_ONTRANSPORT);
- else
- {
- m_transport->RemovePassenger(this);
- m_transport = NULL;
- m_movementInfo.t_x = 0.0f;
- m_movementInfo.t_y = 0.0f;
- m_movementInfo.t_z = 0.0f;
- m_movementInfo.t_o = 0.0f;
- m_movementInfo.t_time = 0;
- m_movementInfo.t_seat = -1;
- }
- }
-
- // The player was ported to another map and looses the duel immediately.
- // We have to perform this check before the teleport, otherwise the
- // ObjectAccessor won't find the flag.
- if (duel && GetMapId() != mapid)
- if (GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER)))
- DuelComplete(DUEL_FLED);
-
- if (GetMapId() == mapid && !m_transport)
- {
- //lets reset far teleport flag if it wasn't reset during chained teleports
- SetSemaphoreTeleportFar(false);
- //setup delayed teleport flag
- SetDelayedTeleportFlag(IsCanDelayTeleport());
- //if teleport spell is casted in Unit::Update() func
- //then we need to delay it until update process will be finished
- if(IsHasDelayedTeleport())
- {
- SetSemaphoreTeleportNear(true);
- //lets save teleport destination for player
- m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
- m_teleport_options = options;
- return true;
- }
-
- if (!(options & TELE_TO_NOT_UNSUMMON_PET))
- {
- //same map, only remove pet if out of range for new position
- if(pet && !pet->IsWithinDist3d(x,y,z, GetMap()->GetVisibilityDistance()))
- UnsummonPetTemporaryIfAny();
- }
-
- if (!(options & TELE_TO_NOT_LEAVE_COMBAT))
- CombatStop();
-
- // this will be used instead of the current location in SaveToDB
- m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
- SetFallInformation(0, z);
-
- // code for finish transfer called in WorldSession::HandleMovementOpcodes()
- // at client packet MSG_MOVE_TELEPORT_ACK
- SetSemaphoreTeleportNear(true);
- // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
- if(!GetSession()->PlayerLogout())
- {
- Position oldPos;
- GetPosition(&oldPos);
- Relocate(x, y, z, orientation);
- SendTeleportAckMsg();
- Relocate(&oldPos);
- }
- }
- else
- {
- if (getClass() == CLASS_DEATH_KNIGHT && GetMapId() == 609 && !isGameMaster() && !HasSpell(50977))
- return false;
-
- // far teleport to another map
- Map* oldmap = IsInWorld() ? GetMap() : NULL;
- // check if we can enter before stopping combat / removing pet / totems / interrupting spells
-
- // Check enter rights before map getting to avoid creating instance copy for player
- // this check not dependent from map instance copy and same for all instance copies of selected map
- if (!MapManager::Instance().CanPlayerEnter(mapid, this))
- return false;
-
- // If the map is not created, assume it is possible to enter it.
- // It will be created in the WorldPortAck.
- Map *map = MapManager::Instance().FindMap(mapid);
- if (!map || map->CanEnter(this))
- {
- //lets reset near teleport flag if it wasn't reset during chained teleports
- SetSemaphoreTeleportNear(false);
- //setup delayed teleport flag
- SetDelayedTeleportFlag(IsCanDelayTeleport());
- //if teleport spell is casted in Unit::Update() func
- //then we need to delay it until update process will be finished
- if(IsHasDelayedTeleport())
- {
- SetSemaphoreTeleportFar(true);
- //lets save teleport destination for player
- m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
- m_teleport_options = options;
- return true;
- }
-
- SetSelection(0);
-
- CombatStop();
-
- ResetContestedPvP();
-
- // remove player from battleground on far teleport (when changing maps)
- if(BattleGround const* bg = GetBattleGround())
- {
- // Note: at battleground join battleground id set before teleport
- // and we already will found "current" battleground
- // just need check that this is targeted map or leave
- if (bg->GetMapId() != mapid)
- LeaveBattleground(false); // don't teleport to entry point
- }
-
- // remove pet on map change
- if (pet)
- UnsummonPetTemporaryIfAny();
-
- // remove all dyn objects
- RemoveAllDynObjects();
-
- // stop spellcasting
- // not attempt interrupt teleportation spell at caster teleport
- if(!(options & TELE_TO_SPELL))
- if(IsNonMeleeSpellCasted(true))
- InterruptNonMeleeSpells(true);
-
- //remove auras before removing from map...
- RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
-
- if (!GetSession()->PlayerLogout())
- {
- // send transfer packets
- WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
- data << uint32(mapid);
- if (m_transport)
- {
- data << m_transport->GetEntry() << GetMapId();
- }
- GetSession()->SendPacket(&data);
-
- data.Initialize(SMSG_NEW_WORLD, (20));
- if (m_transport)
- data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
- else
- data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
-
- GetSession()->SendPacket( &data );
- SendSavedInstances();
- }
-
- // remove from old map now
- if(oldmap)
- oldmap->Remove(this, false);
-
- // new final coordinates
- float final_x = x;
- float final_y = y;
- float final_z = z;
- float final_o = orientation;
-
- if (m_transport)
- {
- final_x += m_movementInfo.t_x;
- final_y += m_movementInfo.t_y;
- final_z += m_movementInfo.t_z;
- final_o += m_movementInfo.t_o;
- }
-
- m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
- SetFallInformation(0, final_z);
- // if the player is saved before worldportack (at logout for example)
- // this will be used instead of the current location in SaveToDB
-
- // move packet sent by client always after far teleport
- // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
- SetSemaphoreTeleportFar(true);
- }
- else
- return false;
- }
- return true;
-}
-
-bool Player::TeleportToBGEntryPoint()
-{
- ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE);
- ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE);
- return TeleportTo(m_bgData.joinPos);
-}
-
-void Player::ProcessDelayedOperations()
-{
- if (m_DelayedOperations == 0)
- return;
-
- if (m_DelayedOperations & DELAYED_RESURRECT_PLAYER)
- {
- ResurrectPlayer(0.0f, false);
-
- if (GetMaxHealth() > m_resurrectHealth)
- SetHealth(m_resurrectHealth);
- else
- SetHealth(GetMaxHealth());
-
- if (GetMaxPower(POWER_MANA) > m_resurrectMana)
- SetPower(POWER_MANA, m_resurrectMana);
- else
- SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
-
- SetPower(POWER_RAGE, 0);
- SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
-
- SpawnCorpseBones();
- }
-
- if (m_DelayedOperations & DELAYED_SAVE_PLAYER)
- SaveToDB();
-
- if (m_DelayedOperations & DELAYED_SPELL_CAST_DESERTER)
- CastSpell(this, 26013, true); // Deserter
-
- if (m_DelayedOperations & DELAYED_BG_MOUNT_RESTORE)
- {
- if (m_bgData.mountSpell)
- {
- CastSpell(this, m_bgData.mountSpell, true);
- m_bgData.mountSpell = 0;
- }
- }
-
- if (m_DelayedOperations & DELAYED_BG_TAXI_RESTORE)
- {
- if (m_bgData.HasTaxiPath())
- {
- m_taxi.AddTaxiDestination(m_bgData.taxiPath[0]);
- m_taxi.AddTaxiDestination(m_bgData.taxiPath[1]);
- m_bgData.ClearTaxiPath();
-
- ContinueTaxiFlight();
- }
- }
-
- //we have executed ALL delayed ops, so clear the flag
- m_DelayedOperations = 0;
-}
-
-void Player::AddToWorld()
-{
- ///- Do not add/remove the player from the object storage
- ///- It will crash when updating the ObjectAccessor
- ///- The player should only be added when logging in
- Unit::AddToWorld();
-
- for (uint8 i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
- if(m_items[i])
- m_items[i]->AddToWorld();
-}
-
-void Player::RemoveFromWorld()
-{
- // cleanup
- if(IsInWorld())
- {
- ///- Release charmed creatures, unsummon totems and remove pets/guardians
- StopCastingCharm();
- StopCastingBindSight();
- UnsummonPetTemporaryIfAny();
- sOutdoorPvPMgr.HandlePlayerLeaveZone(this, m_zoneUpdateId);
- }
-
- ///- Do not add/remove the player from the object storage
- ///- It will crash when updating the ObjectAccessor
- ///- The player should only be removed when logging out
- Unit::RemoveFromWorld();
-
- for (uint8 i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
- {
- if (m_items[i])
- m_items[i]->RemoveFromWorld();
- }
-
- for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
- iter->second->RemoveFromWorld();
-
- if (m_uint32Values)
- {
- if (WorldObject *viewpoint = GetViewpoint())
- {
- sLog.outCrash("Player %s has viewpoint %u %u when removed from world", GetName(), viewpoint->GetEntry(), viewpoint->GetTypeId());
- SetViewpoint(viewpoint, false);
- }
- }
-}
-
-void Player::RegenerateAll()
-{
- //if (m_regenTimer <= 500)
- // return;
-
- m_regenTimerCount += m_regenTimer;
-
- Regenerate(POWER_ENERGY);
-
- Regenerate(POWER_MANA);
-
- // Runes act as cooldowns, and they don't need to send any data
- if(getClass() == CLASS_DEATH_KNIGHT)
- for (uint32 i = 0; i < MAX_RUNES; ++i)
- if(uint32 cd = GetRuneCooldown(i))
- SetRuneCooldown(i, (cd > m_regenTimer) ? cd - m_regenTimer : 0);
-
- if (m_regenTimerCount >= 2000)
- {
- // Not in combat or they have regeneration
- if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
- HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
- {
- RegenerateHealth();
- }
-
- Regenerate(POWER_RAGE);
- if (getClass() == CLASS_DEATH_KNIGHT)
- Regenerate(POWER_RUNIC_POWER);
-
- m_regenTimerCount -= 2000;
- }
-
- m_regenTimer = 0;
-}
-
-void Player::Regenerate(Powers power)
-{
- uint32 maxValue = GetMaxPower(power);
- if (!maxValue)
- return;
-
- uint32 curValue = GetPower(power);
-
- // TODO: possible use of miscvalueb instead of amount
- if (HasAuraTypeWithValue(SPELL_AURA_PREVENT_REGENERATE_POWER, power))
- return;
-
- float addvalue = 0.0f;
-
- switch (power)
- {
- case POWER_MANA:
- {
- bool recentCast = IsUnderLastManaUseEffect();
- float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
-
- if (getLevel() < 15)
- ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA) * (2.066f - (getLevel() * 0.066f));
-
- if (recentCast) // Trinity Updates Mana in intervals of 2s, which is correct
- addvalue += GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 0.001f * m_regenTimer;
- else
- addvalue += GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 0.001f * m_regenTimer;
- } break;
- case POWER_RAGE: // Regenerate rage
- {
- if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
- {
- float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
- addvalue += -20 * RageDecreaseRate; // 2 rage by tick (= 2 seconds => 1 rage/sec)
- }
- } break;
- case POWER_ENERGY: // Regenerate energy (rogue)
- addvalue += 0.01f * m_regenTimer;
- break;
- case POWER_RUNIC_POWER:
- {
- if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
- {
- float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
- addvalue += -30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
- }
- } break;
- case POWER_RUNE:
- case POWER_FOCUS:
- case POWER_HAPPINESS:
- case POWER_HEALTH:
- break;
- }
-
- // Mana regen calculated in Player::UpdateManaRegen()
- if (power != POWER_MANA)
- {
- AuraEffectList const& ModPowerRegenPCTAuras = GetAuraEffectsByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
- for (AuraEffectList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
- if ((*i)->GetMiscValue() == power)
- addvalue *= ((*i)->GetAmount() + 100) / 100.0f;
-
- // Butchery requires combat for this effect
- if (power != POWER_RUNIC_POWER || isInCombat())
- addvalue += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_POWER_REGEN, power) * ((power != POWER_ENERGY) ? m_regenTimerCount : m_regenTimer) / (5 * IN_MILISECONDS);
- }
-
- if (addvalue < 0.0f)
- {
- if (curValue == 0)
- return;
- }
- else if (addvalue > 0.0f)
- {
- if (curValue == maxValue)
- return;
- }
- else
- return;
-
- addvalue += m_powerFraction[power];
- uint32 integerValue = uint32(abs(addvalue));
-
- if (addvalue < 0.0f)
- {
- if(curValue > integerValue)
- {
- curValue -= integerValue;
- m_powerFraction[power] = addvalue + integerValue;
- }
- else
- {
- curValue = 0;
- m_powerFraction[power] = 0;
- }
- }
- else
- {
- curValue += integerValue;
-
- if (curValue > maxValue)
- {
- curValue = maxValue;
- m_powerFraction[power] = 0;
- }
- else
- m_powerFraction[power] = addvalue - integerValue;
- }
- if(m_regenTimerCount >= 2000)
- SetPower(power, curValue);
- else
- UpdateUInt32Value(UNIT_FIELD_POWER1 + power, curValue);
-}
-
-void Player::RegenerateHealth()
-{
- uint32 curValue = GetHealth();
- uint32 maxValue = GetMaxHealth();
-
- if (curValue >= maxValue)
- return;
-
- float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
-
- if (getLevel() < 15)
- HealthIncreaseRate = sWorld.getRate(RATE_HEALTH) * (2.066f - (getLevel() * 0.066f));
-
- float addvalue = 0.0f;
-
- // polymorphed case
- if (IsPolymorphed())
- addvalue = GetMaxHealth()/3;
- // normal regen case (maybe partly in combat case)
- else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
- {
- addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
- if (!isInCombat())
- {
- AuraEffectList const& mModHealthRegenPct = GetAuraEffectsByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
- for (AuraEffectList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
- addvalue *= (100.0f + (*i)->GetAmount()) / 100.0f;
-
- addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_REGEN) * 2 * IN_MILISECONDS / (5 * IN_MILISECONDS);
- }
- else if (HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
- addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
-
- if (!IsStandState())
- addvalue *= 1.5;
- }
-
- // always regeneration bonus (including combat)
- addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
- addvalue += m_baseHealthRegen / 2.5f;
-
- if (addvalue < 0)
- addvalue = 0;
-
- ModifyHealth(int32(addvalue));
-}
-
-bool Player::CanInteractWithNPCs(bool alive) const
-{
- if (alive && !isAlive())
- return false;
- if (isInFlight())
- return false;
-
- return true;
-}
-
-Creature*
-Player::GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask)
-{
- // unit checks
- if (!guid)
- return NULL;
-
- if (!IsInWorld())
- return NULL;
-
- // exist (we need look pets also for some interaction (quest/etc)
- Creature *unit = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
- if (!unit)
- return NULL;
-
- // player check
- if (!CanInteractWithNPCs(!unit->isSpiritService()))
- return NULL;
-
- // appropriate npc type
- if (npcflagmask && !unit->HasFlag(UNIT_NPC_FLAGS, npcflagmask))
- return NULL;
-
- // alive or spirit healer
- if (!unit->isAlive() && (!unit->isSpiritService() || isAlive()))
- return NULL;
-
- // not allow interaction under control, but allow with own pets
- if (unit->GetCharmerGUID())
- return NULL;
-
- // not enemy
- if (unit->IsHostileTo(this))
- return NULL;
-
- // not unfriendly
- if (FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction()))
- if (factionTemplate->faction)
- if (FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
- if (faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
- return NULL;
-
- // not too far
- if (!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE))
- return NULL;
-
- return unit;
-}
-
-GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const
-{
- if (GameObject *go = GetMap()->GetGameObject(guid))
- {
- if (go->GetGoType() == type)
- {
- float maxdist;
- switch (type)
- {
- // TODO: find out how the client calculates the maximal usage distance to spellless working
- // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
- case GAMEOBJECT_TYPE_GUILD_BANK:
- case GAMEOBJECT_TYPE_MAILBOX:
- maxdist = 10.0f;
- break;
- case GAMEOBJECT_TYPE_FISHINGHOLE:
- maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
- break;
- default:
- maxdist = INTERACTION_DISTANCE;
- break;
- }
-
- if (go->IsWithinDistInMap(this, maxdist))
- return go;
-
- sLog.outDebug("IsGameObjectOfTypeInRange: GameObject '%s' [GUID: %u] is too far away from player %s [GUID: %u] to be used by him (distance=%f, maximal 10 is allowed)", go->GetGOInfo()->name,
- go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
- }
- }
- return NULL;
-}
-
-bool Player::IsUnderWater() const
-{
- return IsInWater() &&
- GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(),GetPositionY())-2);
-}
-
-void Player::SetInWater(bool apply)
-{
- if(m_isInWater==apply)
- return;
-
- //define player in water by opcodes
- //move player's guid into HateOfflineList of those mobs
- //which can't swim and move guid back into ThreatList when
- //on surface.
- //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
- m_isInWater = apply;
-
- // remove auras that need water/land
- RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
-
- getHostilRefManager().updateThreatTables();
-}
-
-void Player::SetGameMaster(bool on)
-{
- if(on)
- {
- m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
- setFaction(35);
- SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
-
- if (Pet* pet = GetPet())
- {
- pet->setFaction(35);
- pet->getHostilRefManager().setOnlineOfflineState(false);
- }
-
- RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
- ResetContestedPvP();
-
- getHostilRefManager().setOnlineOfflineState(false);
- CombatStopWithPets();
-
- SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
- }
- else
- {
- // restore phase
- AuraEffectList const& phases = GetAuraEffectsByType(SPELL_AURA_PHASE);
- SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
-
- m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
- setFactionForRace(getRace());
- RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
-
- if (Pet* pet = GetPet())
- {
- pet->setFaction(getFaction());
- pet->getHostilRefManager().setOnlineOfflineState(true);
- }
-
- // restore FFA PvP Server state
- if(sWorld.IsFFAPvPRealm())
- SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
-
- // restore FFA PvP area state, remove not allowed for GM mounts
- UpdateArea(m_areaUpdateId);
-
- getHostilRefManager().setOnlineOfflineState(true);
- }
-
- //ObjectAccessor::UpdateVisibilityForPlayer(this);
- SetToNotify();
-}
-
-void Player::SetGMVisible(bool on)
-{
- if(on)
- {
- m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
-
- // Reapply stealth/invisibility if active or show if not any
- if(HasAuraType(SPELL_AURA_MOD_STEALTH))
- SetVisibility(VISIBILITY_GROUP_STEALTH);
- //else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
- // SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
- else
- SetVisibility(VISIBILITY_ON);
- }
- else
- {
- m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
-
- SetAcceptWhispers(false);
- SetGameMaster(true);
-
- SetVisibility(VISIBILITY_OFF);
- }
-}
-
-bool Player::IsGroupVisibleFor(Player* p) const
-{
- switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
- {
- default: return IsInSameGroupWith(p);
- case 1: return IsInSameRaidWith(p);
- case 2: return GetTeam()==p->GetTeam();
- }
-}
-
-bool Player::IsInSameGroupWith(Player const* p) const
-{
- return (p==this || (GetGroup() != NULL &&
- GetGroup() == p->GetGroup() &&
- GetGroup()->SameSubGroup((Player*)this, (Player*)p)));
-}
-
-///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
-/// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
-void Player::UninviteFromGroup()
-{
- Group* group = GetGroupInvite();
- if(!group)
- return;
-
- group->RemoveInvite(this);
-
- if(group->GetMembersCount() <= 1) // group has just 1 member => disband
- {
- if(group->IsCreated())
- {
- group->Disband(true);
- objmgr.RemoveGroup(group);
- }
- else
- group->RemoveAllInvites();
-
- delete group;
- }
-}
-
-void Player::RemoveFromGroup(Group* group, uint64 guid)
-{
- if(group)
- {
- if (group->RemoveMember(guid, 0) <= 1)
- {
- // group->Disband(); already disbanded in RemoveMember
- objmgr.RemoveGroup(group);
- delete group;
- // removemember sets the player's group pointer to NULL
- }
- }
-}
-
-void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
-{
- WorldPacket data(SMSG_LOG_XPGAIN, 21);
- data << uint64(victim ? victim->GetGUID() : 0); // guid
- data << uint32(GivenXP+RestXP); // given experience
- data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
- if(victim)
- {
- data << uint32(GivenXP); // experience without rested bonus
- data << float(1); // 1 - none 0 - 100% group bonus output
- }
- data << uint8(0); // new 2.4.0
- GetSession()->SendPacket(&data);
-}
-
-void Player::GiveXP(uint32 xp, Unit* victim)
-{
- if ( xp < 1 )
- return;
-
- if(!isAlive())
- return;
-
- if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_NO_XP_GAIN))
- return;
-
- uint8 level = getLevel();
-
- // Favored experience increase START
- uint32 zone = GetZoneId();
- float favored_exp_mult = 0;
- if( (HasAura(32096) || HasAura(32098)) && (zone == 3483 || zone == 3562 || zone == 3836 || zone == 3713 || zone == 3714) ) favored_exp_mult = 0.05; // Thrallmar's Favor and Honor Hold's Favor
- xp *= (1 + favored_exp_mult);
- // Favored experience increase END
-
- // XP to money conversion processed in Player::RewardQuest
- if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
- return;
-
- // XP resting bonus for kill
- uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
-
- // Heirloom Experience Bonus
- float heirloomModifier = 1.0f;
- for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
- if (m_items[i] && m_items[i]->GetProto()->Spells->SpellId == 57353)
- heirloomModifier += 0.1f;
- xp = uint32(xp * heirloomModifier);
-
- SendLogXPGain(xp,victim,rested_bonus_xp);
-
- uint32 curXP = GetUInt32Value(PLAYER_XP);
- uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
- uint32 newXP = curXP + xp + rested_bonus_xp;
-
- while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
- {
- newXP -= nextLvlXP;
-
- if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
- GiveLevel(level + 1);
-
- level = getLevel();
- nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
- }
- newXP = GetSession()->HandleOnGetXP(newXP);
- SetUInt32Value(PLAYER_XP, newXP);
-}
-
-// Update player to next level
-// Current player experience not update (must be update by caller)
-void Player::GiveLevel(uint8 level)
-{
- if (level == getLevel())
- return;
-
- PlayerLevelInfo info;
- objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
-
- PlayerClassLevelInfo classInfo;
- objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
-
- // send levelup info to client
- WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
- data << uint32(level);
- data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
- // for (int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
- data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
- data << uint32(0);
- data << uint32(0);
- data << uint32(0);
- data << uint32(0);
- data << uint32(0);
- data << uint32(0);
- // end for
- for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
- data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
-
- GetSession()->SendPacket(&data);
-
- SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level));
-
- //update level, max level of skills
- m_Played_time[PLAYED_TIME_LEVEL] = 0; // Level Played Time reset
-
- _ApplyAllLevelScaleItemMods(false);
-
- SetLevel(level);
-
- UpdateSkillsForLevel();
-
- // save base values (bonuses already included in stored stats
- for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i)
- SetCreateStat(Stats(i), info.stats[i]);
-
- SetCreateHealth(classInfo.basehealth);
- SetCreateMana(classInfo.basemana);
-
- InitTalentForLevel();
- InitTaxiNodesForLevel();
- InitGlyphsForLevel();
-
- UpdateAllStats();
-
- if(sWorld.getConfig(CONFIG_ALWAYS_MAXSKILL)) // Max weapon skill when leveling up
- UpdateSkillsToMaxSkillsForLevel();
-
- // set current level health and mana/energy to maximum after applying all mods.
- SetHealth(GetMaxHealth());
- SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
- SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
- if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
- SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
- SetPower(POWER_FOCUS, 0);
- SetPower(POWER_HAPPINESS, 0);
-
- _ApplyAllLevelScaleItemMods(true);
-
- // update level to hunter/summon pet
- if (Pet* pet = GetPet())
- pet->SynchronizeLevelWithOwner();
-
- if (MailLevelReward const* mailReward = objmgr.GetMailLevelReward(level,getRaceMask()))
- MailDraft(mailReward->mailTemplateId).SendMailTo(this,MailSender(MAIL_CREATURE,mailReward->senderEntry));
-
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
-}
-
-void Player::InitTalentForLevel()
-{
- uint8 level = getLevel();
- // talents base at level diff ( talents = level - 9 but some can be used already)
- if (level < 10)
- {
- // Remove all talent points
- if(m_usedTalentCount > 0) // Free any used talents
- {
- resetTalents(true);
- SetFreeTalentPoints(0);
- }
- }
- else
- {
- if (level < sWorld.getConfig(CONFIG_MIN_DUALSPEC_LEVEL) || m_specsCount == 0)
- {
- m_specsCount = 1;
- m_activeSpec = 0;
- }
-
- uint32 talentPointsForLevel = CalculateTalentsPoints();
-
- // if used more that have then reset
- if(m_usedTalentCount > talentPointsForLevel)
- {
- if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
- resetTalents(true);
- else
- SetFreeTalentPoints(0);
- }
- // else update amount of free points
- else
- SetFreeTalentPoints(talentPointsForLevel - m_usedTalentCount);
- }
-
- if(!GetSession()->PlayerLoading())
- SendTalentsInfoData(false); // update at client
-}
-
-void Player::InitStatsForLevel(bool reapplyMods)
-{
- if (reapplyMods) //reapply stats values only on .reset stats (level) command
- _RemoveAllStatBonuses();
-
- PlayerClassLevelInfo classInfo;
- objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
-
- PlayerLevelInfo info;
- objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
-
- SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
- SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel()));
-
- // reset before any aura state sources (health set/aura apply)
- SetUInt32Value(UNIT_FIELD_AURASTATE, 0);
-
- UpdateSkillsForLevel ();
-
- // set default cast time multiplier
- SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
-
- // reset size before reapply auras
- SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
-
- // save base values (bonuses already included in stored stats
- for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i)
- SetCreateStat(Stats(i), info.stats[i]);
-
- for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i)
- SetStat(Stats(i), info.stats[i]);
-
- SetCreateHealth(classInfo.basehealth);
-
- //set create powers
- SetCreateMana(classInfo.basemana);
-
- SetArmor(int32(m_createStats[STAT_AGILITY]*2));
-
- InitStatBuffMods();
-
- //reset rating fields values
- for (uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
- SetUInt32Value(index, 0);
-
- SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
- for (uint8 i = 0; i < 7; ++i)
- {
- SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
- SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
- SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
- }
-
- //reset attack power, damage and attack speed fields
- SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f);
- SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f); // offhand attack time
- SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f);
-
- SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f);
- SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f);
- SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f);
- SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f);
- SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f);
- SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f);
-
- SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0);
- SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0);
- SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
- SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0);
- SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0);
- SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
-
- // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
- SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
- SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
- SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
-
- // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
- for (uint8 i = 0; i < 7; ++i)
- SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
-
- SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
- SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
- SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
-
- // Dodge percentage
- SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
-
- // set armor (resistance 0) to original value (create_agility*2)
- SetArmor(int32(m_createStats[STAT_AGILITY]*2));
- SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
- SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
- // set other resistance to original value (0)
- for (uint8 i = 1; i < MAX_SPELL_SCHOOL; ++i)
- {
- SetResistance(SpellSchools(i), 0);
- SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
- SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
- }
-
- SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
- SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
- for (uint8 i = 0; i < MAX_SPELL_SCHOOL; ++i)
- {
- SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
- SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
- }
- // Reset no reagent cost field
- for (uint8 i = 0; i < 3; ++i)
- SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
- // Init data for form but skip reapply item mods for form
- InitDataForForm(reapplyMods);
-
- // save new stats
- for (uint8 i = POWER_MANA; i < MAX_POWERS; ++i)
- SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
-
- SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
-
- // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
- SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
-
- // cleanup unit flags (will be re-applied if need at aura load).
- RemoveFlag( UNIT_FIELD_FLAGS,
- UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
- UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
- UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
- UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
- UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
- SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
-
- SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
-
- // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
- RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST | PLAYER_ALLOW_ONLY_ABILITY);
-
- RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
- RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
-
- // restore if need some important flags
- SetUInt32Value(PLAYER_FIELD_BYTES2, 0); // flags empty by default
-
- if (reapplyMods) // reapply stats values only on .reset stats (level) command
- _ApplyAllStatBonuses();
-
- // set current level health and mana/energy to maximum after applying all mods.
- SetHealth(GetMaxHealth());
- SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
- SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
- if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
- SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
- SetPower(POWER_FOCUS, 0);
- SetPower(POWER_HAPPINESS, 0);
- SetPower(POWER_RUNIC_POWER, 0);
-
- // update level to hunter/summon pet
- if (Pet* pet = GetPet())
- pet->SynchronizeLevelWithOwner();
-}
-
-void Player::SendInitialSpells()
-{
- time_t curTime = time(NULL);
- time_t infTime = curTime + infinityCooldownDelayCheck;
-
- uint16 spellCount = 0;
-
- WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
- data << uint8(0);
-
- size_t countPos = data.wpos();
- data << uint16(spellCount); // spell count placeholder
-
- for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
- {
- if(itr->second->state == PLAYERSPELL_REMOVED)
- continue;
-
- if(!itr->second->active || itr->second->disabled)
- continue;
-
- data << uint32(itr->first);
- data << uint16(0); // it's not slot id
-
- spellCount +=1;
- }
-
- data.put<uint16>(countPos,spellCount); // write real count value
-
- uint16 spellCooldowns = m_spellCooldowns.size();
- data << uint16(spellCooldowns);
- for (SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
- {
- SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
- if(!sEntry)
- continue;
-
- data << uint32(itr->first);
-
- data << uint16(itr->second.itemid); // cast item id
- data << uint16(sEntry->Category); // spell category
-
- // send infinity cooldown in special format
- if(itr->second.end >= infTime)
- {
- data << uint32(1); // cooldown
- data << uint32(0x80000000); // category cooldown
- continue;
- }
-
- time_t cooldown = itr->second.end > curTime ? (itr->second.end-curTime)*IN_MILISECONDS : 0;
-
- if(sEntry->Category) // may be wrong, but anyway better than nothing...
- {
- data << uint32(0); // cooldown
- data << uint32(cooldown); // category cooldown
- }
- else
- {
- data << uint32(cooldown); // cooldown
- data << uint32(0); // category cooldown
- }
- }
-
- GetSession()->SendPacket(&data);
-
- sLog.outDetail( "CHARACTER: Sent Initial Spells" );
-}
-
-void Player::RemoveMail(uint32 id)
-{
- for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
- {
- if ((*itr)->messageID == id)
- {
- //do not delete item, because Player::removeMail() is called when returning mail to sender.
- m_mail.erase(itr);
- return;
- }
- }
-}
-
-void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
-{
- WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
- data << (uint32) mailId;
- data << (uint32) mailAction;
- data << (uint32) mailError;
- if ( mailError == MAIL_ERR_EQUIP_ERROR )
- data << (uint32) equipError;
- else if( mailAction == MAIL_ITEM_TAKEN )
- {
- data << (uint32) item_guid; // item guid low?
- data << (uint32) item_count; // item count?
- }
- GetSession()->SendPacket(&data);
-}
-
-void Player::SendNewMail()
-{
- // deliver undelivered mail
- WorldPacket data(SMSG_RECEIVED_MAIL, 4);
- data << (uint32) 0;
- GetSession()->SendPacket(&data);
-}
-
-void Player::UpdateNextMailTimeAndUnreads()
-{
- // calculate next delivery time (min. from non-delivered mails
- // and recalculate unReadMail
- time_t cTime = time(NULL);
- m_nextMailDelivereTime = 0;
- unReadMails = 0;
- for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
- {
- if((*itr)->deliver_time > cTime)
- {
- if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
- m_nextMailDelivereTime = (*itr)->deliver_time;
- }
- else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
- ++unReadMails;
- }
-}
-
-void Player::AddNewMailDeliverTime(time_t deliver_time)
-{
- if(deliver_time <= time(NULL)) // ready now
- {
- ++unReadMails;
- SendNewMail();
- }
- else // not ready and no have ready mails
- {
- if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
- m_nextMailDelivereTime = deliver_time;
- }
-}
-
-bool Player::AddTalent(uint32 spell_id, uint8 spec, bool learning)
-{
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
- if (!spellInfo)
- {
- // do character spell book cleanup (all characters)
- if(!IsInWorld() && !learning) // spell load case
- {
- sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
- CharacterDatabase.PExecute("DELETE FROM character_talent WHERE spell = '%u'",spell_id);
- }
- else
- sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
-
- return false;
- }
-
- if(!SpellMgr::IsSpellValid(spellInfo,this,false))
- {
- // do character spell book cleanup (all characters)
- if(!IsInWorld() && !learning) // spell load case
- {
- sLog.outError("Player::addTalent: Broken spell #%u learning not allowed, deleting for all characters in `character_talent`.",spell_id);
- CharacterDatabase.PExecute("DELETE FROM character_talent WHERE spell = '%u'",spell_id);
- }
- else
- sLog.outError("Player::addTalent: Broken spell #%u learning not allowed.",spell_id);
-
- return false;
- }
-
- PlayerTalentMap::iterator itr = m_talents[spec]->find(spell_id);
- if (itr != m_talents[spec]->end())
- itr->second->state = PLAYERSPELL_UNCHANGED;
- else if (TalentSpellPos const *talentPos = GetTalentSpellPos(spell_id))
- {
- if (TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
- {
- for (uint8 rank = 0; rank < MAX_TALENT_RANK; ++rank)
- {
- // skip learning spell and no rank spell case
- uint32 rankSpellId = talentInfo->RankID[rank];
- if (!rankSpellId || rankSpellId == spell_id)
- continue;
-
- PlayerTalentMap::iterator itr = m_talents[spec]->find(rankSpellId);
- if (itr != m_talents[spec]->end())
- itr->second->state = PLAYERSPELL_REMOVED;
- }
- }
-
- PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
- PlayerTalent *newtalent = new PlayerTalent();
-
- newtalent->state = state;
- newtalent->spec = spec;
-
- (*m_talents[spec])[spell_id] = newtalent;
- return true;
- }
- return false;
-}
-
-bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
-{
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
- if (!spellInfo)
- {
- // do character spell book cleanup (all characters)
- if(!IsInWorld() && !learning) // spell load case
- {
- sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
- CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
- }
- else
- sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
-
- return false;
- }
-
- if(!SpellMgr::IsSpellValid(spellInfo,this,false))
- {
- // do character spell book cleanup (all characters)
- if(!IsInWorld() && !learning) // spell load case
- {
- sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
- CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
- }
- else
- sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
-
- return false;
- }
-
- PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
-
- bool dependent_set = false;
- bool disabled_case = false;
- bool superceded_old = false;
-
- PlayerSpellMap::iterator itr = m_spells.find(spell_id);
-
- // Remove temporary spell if found to prevent conflicts
- if (itr != m_spells.end() && itr->second->state == PLAYERSPELL_TEMPORARY)
- RemoveTemporarySpell(spell_id);
- else if (itr != m_spells.end())
- {
- uint32 next_active_spell_id = 0;
- // fix activate state for non-stackable low rank (and find next spell for !active case)
- if(!SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
- {
- if(uint32 next = spellmgr.GetNextSpellInChain(spell_id))
- {
- if(HasSpell(next))
- {
- // high rank already known so this must !active
- active = false;
- next_active_spell_id = next;
- }
- }
- }
-
- // not do anything if already known in expected state
- if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
- itr->second->dependent == dependent && itr->second->disabled == disabled)
- {
- if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
- itr->second->state = PLAYERSPELL_UNCHANGED;
-
- return false;
- }
-
- // dependent spell known as not dependent, overwrite state
- if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
- {
- itr->second->dependent = dependent;
- if (itr->second->state != PLAYERSPELL_NEW)
- itr->second->state = PLAYERSPELL_CHANGED;
- dependent_set = true;
- }
-
- // update active state for known spell
- if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
- {
- itr->second->active = active;
-
- if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
- itr->second->state = PLAYERSPELL_UNCHANGED;
- else if(itr->second->state != PLAYERSPELL_NEW)
- itr->second->state = PLAYERSPELL_CHANGED;
-
- if(active)
- {
- if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
- CastSpell (this,spell_id,true);
- }
- else if(IsInWorld())
- {
- if(next_active_spell_id)
- {
- // update spell ranks in spellbook and action bar
- WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
- data << uint32(spell_id);
- data << uint32(next_active_spell_id);
- GetSession()->SendPacket( &data );
- }
- else
- {
- WorldPacket data(SMSG_REMOVED_SPELL, 4);
- data << uint32(spell_id);
- GetSession()->SendPacket(&data);
- }
- }
-
- return active; // learn (show in spell book if active now)
- }
-
- if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
- {
- if(itr->second->state != PLAYERSPELL_NEW)
- itr->second->state = PLAYERSPELL_CHANGED;
- itr->second->disabled = disabled;
-
- if(disabled)
- return false;
-
- disabled_case = true;
- }
- else switch(itr->second->state)
- {
- case PLAYERSPELL_UNCHANGED: // known saved spell
- return false;
- case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
- {
- delete itr->second;
- m_spells.erase(itr);
- state = PLAYERSPELL_CHANGED;
- break; // need re-add
- }
- default: // known not saved yet spell (new or modified)
- {
- // can be in case spell loading but learned at some previous spell loading
- if(!IsInWorld() && !learning && !dependent_set)
- itr->second->state = PLAYERSPELL_UNCHANGED;
-
- return false;
- }
- }
- }
-
- if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
- {
- // talent: unlearn all other talent ranks (high and low)
- if(TalentSpellPos const *talentPos = GetTalentSpellPos(spell_id))
- {
- if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
- {
- for (uint8 rank = 0; rank < MAX_TALENT_RANK; ++rank)
- {
- // skip learning spell and no rank spell case
- uint32 rankSpellId = talentInfo->RankID[rank];
- if(!rankSpellId || rankSpellId == spell_id)
- continue;
-
- removeSpell(rankSpellId,false,false);
- }
- }
- }
- // non talent spell: learn low ranks (recursive call)
- else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
- {
- if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
- addSpell(prev_spell,active,true,true,disabled);
- else // at normal learning
- learnSpell(prev_spell,true);
- }
-
- PlayerSpell *newspell = new PlayerSpell;
- newspell->state = state;
- newspell->active = active;
- newspell->dependent = dependent;
- newspell->disabled = disabled;
-
- // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
- if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
- {
- for (PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
- {
- if(itr2->second->state == PLAYERSPELL_REMOVED) continue;
- SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
- if(!i_spellInfo) continue;
-
- if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
- {
- if(itr2->second->active)
- {
- if(spellmgr.IsHighRankOfSpell(spell_id,itr2->first))
- {
- if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
- {
- WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
- data << uint32(itr2->first);
- data << uint32(spell_id);
- GetSession()->SendPacket( &data );
- }
-
- // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
- itr2->second->active = false;
- if(itr2->second->state != PLAYERSPELL_NEW)
- itr2->second->state = PLAYERSPELL_CHANGED;
- superceded_old = true; // new spell replace old in action bars and spell book.
- }
- else if(spellmgr.IsHighRankOfSpell(itr2->first,spell_id))
- {
- if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
- {
- WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
- data << uint32(spell_id);
- data << uint32(itr2->first);
- GetSession()->SendPacket( &data );
- }
-
- // mark new spell as disable (not learned yet for client and will not learned)
- newspell->active = false;
- if(newspell->state != PLAYERSPELL_NEW)
- newspell->state = PLAYERSPELL_CHANGED;
- }
- }
- }
- }
- }
-
- m_spells[spell_id] = newspell;
-
- // return false if spell disabled
- if (newspell->disabled)
- return false;
- }
-
- uint32 talentCost = GetTalentSpellCost(spell_id);
-
- // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
- // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
- if (talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL))
- {
- // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
- CastSpell(this, spell_id, true);
- }
- // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
- else if (IsPassiveSpell(spell_id))
- {
- if (IsNeedCastPassiveSpellAtLearn(spellInfo))
- CastSpell(this, spell_id, true);
- }
- else if (IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP))
- {
- CastSpell(this, spell_id, true);
- return false;
- }
-
- // update used talent points count
- m_usedTalentCount += talentCost;
-
- // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
- if (uint32 freeProfs = GetFreePrimaryProfessionPoints())
- {
- if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
- SetFreePrimaryProfessions(freeProfs-1);
- }
-
- // add dependent skills
- uint16 maxskill = GetMaxSkillValueForLevel();
-
- SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
-
- SkillLineAbilityMapBounds skill_bounds = spellmgr.GetSkillLineAbilityMapBounds(spell_id);
-
- if (spellLearnSkill)
- {
- uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
- uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
-
- if (skill_value < spellLearnSkill->value)
- skill_value = spellLearnSkill->value;
-
- uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
-
- if (skill_max_value < new_skill_max_value)
- skill_max_value = new_skill_max_value;
-
- SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
- }
- else
- {
- // not ranked skills
- for (SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
- {
- SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
- if (!pSkill)
- continue;
-
- if (HasSkill(pSkill->id))
- continue;
-
- if (_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
- // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
- ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
- {
- switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
- {
- case SKILL_RANGE_LANGUAGE:
- SetSkill(pSkill->id, 300, 300 );
- break;
- case SKILL_RANGE_LEVEL:
- SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
- break;
- case SKILL_RANGE_MONO:
- SetSkill(pSkill->id, 1, 1 );
- break;
- default:
- break;
- }
- }
- }
- }
-
- // learn dependent spells
- SpellLearnSpellMapBounds spell_bounds = spellmgr.GetSpellLearnSpellMapBounds(spell_id);
-
- for (SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
- {
- if (!itr2->second.autoLearned)
- {
- if (!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
- addSpell(itr2->second.spell,itr2->second.active,true,true,false);
- else // at normal learning
- learnSpell(itr2->second.spell,true);
- }
- }
-
- if (!GetSession()->PlayerLoading())
- {
- // not ranked skills
- for (SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
- {
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
- }
-
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
- }
-
- // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
- return active && !disabled && !superceded_old;
-}
-
-void Player::AddTemporarySpell(uint32 spellId)
-{
- PlayerSpellMap::iterator itr = m_spells.find(spellId);
- // spell already added - do not do anything
- if (itr != m_spells.end())
- return;
- PlayerSpell *newspell = new PlayerSpell;
- newspell->state = PLAYERSPELL_TEMPORARY;
- newspell->active = true;
- newspell->dependent = false;
- newspell->disabled = false;
- m_spells[spellId] = newspell;
-}
-
-void Player::RemoveTemporarySpell(uint32 spellId)
-{
- PlayerSpellMap::iterator itr = m_spells.find(spellId);
- // spell already not in list - do not do anything
- if (itr == m_spells.end())
- return;
- // spell has other state than temporary - do not change it
- if (itr->second->state != PLAYERSPELL_TEMPORARY)
- return;
- delete itr->second;
- m_spells.erase(itr);
-}
-
-bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
-{
- // note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell
- // talent dependent passives activated at form apply have proper stance data
- bool need_cast = (!spellInfo->Stances || (m_form != 0 && (spellInfo->Stances & (1<<(m_form-1)))));
-
- //Check CasterAuraStates
- return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
-}
-
-void Player::learnSpell(uint32 spell_id, bool dependent)
-{
- PlayerSpellMap::iterator itr = m_spells.find(spell_id);
-
- bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
- bool active = disabled ? itr->second->active : true;
-
- bool learning = addSpell(spell_id,active,true,dependent,false);
-
- // learn all disabled higher ranks (recursive)
- if (disabled)
- {
- SpellChainNode const* node = spellmgr.GetSpellChainNode(spell_id);
- if (node)
- {
- PlayerSpellMap::iterator iter = m_spells.find(node->next);
- if (iter != m_spells.end() && iter->second->disabled)
- learnSpell(node->next,false);
- }
- }
-
- // prevent duplicated entires in spell book, also not send if not in world (loading)
- if (!learning || !IsInWorld())
- return;
-
- WorldPacket data(SMSG_LEARNED_SPELL, 4);
- data << uint32(spell_id);
- GetSession()->SendPacket(&data);
-}
-
-void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank)
-{
- PlayerSpellMap::iterator itr = m_spells.find(spell_id);
- if (itr == m_spells.end())
- return;
-
- if (itr->second->state == PLAYERSPELL_REMOVED || (disabled && itr->second->disabled) || itr->second->state == PLAYERSPELL_TEMPORARY)
- return;
-
- // unlearn non talent higher ranks (recursive)
- if (SpellChainNode const* node = spellmgr.GetSpellChainNode(spell_id))
- {
- if (HasSpell(node->next) && !GetTalentSpellPos(node->next))
- removeSpell(node->next,disabled, false);
- }
- //unlearn spells dependent from recently removed spells
- SpellsRequiringSpellMapBounds spellsRequiringSpell = spellmgr.GetSpellsRequiringSpellBounds(spell_id);
- for (SpellsRequiringSpellMap::const_iterator itr2 = spellsRequiringSpell.first; itr2 != spellsRequiringSpell.second; ++itr2)
- removeSpell(itr2->second,disabled);
-
- // re-search, it can be corrupted in prev loop
- itr = m_spells.find(spell_id);
- if (itr == m_spells.end())
- return; // already unleared
-
- bool cur_active = itr->second->active;
- bool cur_dependent = itr->second->dependent;
-
- if (disabled)
- {
- itr->second->disabled = disabled;
- if (itr->second->state != PLAYERSPELL_NEW)
- itr->second->state = PLAYERSPELL_CHANGED;
- }
- else
- {
- if (itr->second->state == PLAYERSPELL_NEW)
- {
- delete itr->second;
- m_spells.erase(itr);
- }
- else
- itr->second->state = PLAYERSPELL_REMOVED;
- }
-
- RemoveAurasDueToSpell(spell_id);
-
- // remove pet auras
- for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
- if (PetAura const *petSpell = spellmgr.GetPetAura(spell_id, i))
- RemovePetAura(petSpell);
-
- // free talent points
- uint32 talentCosts = GetTalentSpellCost(spell_id);
- if (talentCosts > 0)
- {
- if (talentCosts < m_usedTalentCount)
- m_usedTalentCount -= talentCosts;
- else
- m_usedTalentCount = 0;
- }
-
- // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
- if (spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
- {
- uint32 freeProfs = GetFreePrimaryProfessionPoints()+1;
- if (freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
- SetFreePrimaryProfessions(freeProfs);
- }
-
- // remove dependent skill
- SpellLearnSkillNode const *spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
- if (spellLearnSkill)
- {
- uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
- if (!prev_spell) // first rank, remove skill
- SetSkill(spellLearnSkill->skill,0,0);
- else
- {
- // search prev. skill setting by spell ranks chain
- SpellLearnSkillNode const *prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
- while (!prevSkill && prev_spell)
- {
- prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
- prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
- }
-
- if (!prevSkill) // not found prev skill setting, remove skill
- SetSkill(spellLearnSkill->skill,0,0);
- else // set to prev. skill setting values
- {
- uint32 skill_value = GetPureSkillValue(prevSkill->skill);
- uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
-
- if (skill_value > prevSkill->value)
- skill_value = prevSkill->value;
-
- uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
-
- if (skill_max_value > new_skill_max_value)
- skill_max_value = new_skill_max_value;
-
- SetSkill(prevSkill->skill,skill_value,skill_max_value);
- }
- }
-
- }
- else
- {
- // not ranked skills
- SkillLineAbilityMapBounds bounds = spellmgr.GetSkillLineAbilityMapBounds(spell_id);
-
- for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
- {
- SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
- if (!pSkill)
- continue;
-
- if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL &&
- pSkill->categoryId != SKILL_CATEGORY_CLASS ||// not unlearn class skills (spellbook/talent pages)
- // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
- ((pSkill->id == SKILL_LOCKPICKING || pSkill->id == SKILL_RUNEFORGING) && _spell_idx->second->max_value == 0))
- {
- // not reset skills for professions and racial abilities
- if ((pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
- (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0))
- continue;
-
- SetSkill(pSkill->id, 0, 0);
- }
- }
- }
-
- // remove dependent spells
- SpellLearnSpellMapBounds spell_bounds = spellmgr.GetSpellLearnSpellMapBounds(spell_id);
-
- for (SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
- removeSpell(itr2->second.spell, disabled);
-
- // activate lesser rank in spellbook/action bar, and cast it if need
- bool prev_activate = false;
-
- if (uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id))
- {
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
-
- // if talent then lesser rank also talent and need learn
- if (talentCosts)
- {
- // I cannot see why mangos has these lines.
- //if (learn_low_rank)
- // learnSpell(prev_id,false);
- }
- // if ranked non-stackable spell: need activate lesser rank and update dendence state
- else if (cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
- {
- // need manually update dependence state (learn spell ignore like attempts)
- PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
- if (prev_itr != m_spells.end())
- {
- if (prev_itr->second->dependent != cur_dependent)
- {
- prev_itr->second->dependent = cur_dependent;
- if (prev_itr->second->state != PLAYERSPELL_NEW)
- prev_itr->second->state = PLAYERSPELL_CHANGED;
- }
-
- // now re-learn if need re-activate
- if (cur_active && !prev_itr->second->active && learn_low_rank)
- {
- if (addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
- {
- // downgrade spell ranks in spellbook and action bar
- WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
- data << uint32(spell_id);
- data << uint32(prev_id);
- GetSession()->SendPacket(&data);
- prev_activate = true;
- }
- }
- }
- }
- }
-
- if (spell_id == 46917 && m_canTitanGrip)
- SetCanTitanGrip(false);
-
- if (sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_SPELL_UNLEARN))
- AutoUnequipOffhandIfNeed();
-
- // remove from spell book if not replaced by lesser rank
- if (!prev_activate)
- {
- WorldPacket data(SMSG_REMOVED_SPELL, 4);
- data << uint32(spell_id);
- GetSession()->SendPacket(&data);
- }
-}
-
-void Player::RemoveSpellCooldown( uint32 spell_id, bool update /* = false */)
-{
- m_spellCooldowns.erase(spell_id);
-
- if (update)
- SendClearCooldown(spell_id, this);
-}
-
-// I am not sure which one is more efficient
-void Player::RemoveCategoryCooldown(uint32 cat)
-{
- SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
- if (i_scstore != sSpellCategoryStore.end())
- for (SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
- RemoveSpellCooldown(*i_scset, true);
-}
-
-void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */)
-{
- SpellCategoryStore::const_iterator ct = sSpellCategoryStore.find(cat);
- if (ct == sSpellCategoryStore.end())
- return;
-
- const SpellCategorySet& ct_set = ct->second;
- for (SpellCooldowns::const_iterator i = m_spellCooldowns.begin(); i != m_spellCooldowns.end();)
- {
- if (ct_set.find(i->first) != ct_set.end())
- RemoveSpellCooldown((i++)->first, update);
- else
- ++i;
- }
-}
-
-void Player::RemoveArenaSpellCooldowns()
-{
- // remove cooldowns on spells that has < 15 min CD
- SpellCooldowns::iterator itr, next;
- // iterate spell cooldowns
- for (itr = m_spellCooldowns.begin(); itr != m_spellCooldowns.end(); itr = next)
- {
- next = itr;
- ++next;
- SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
- // check if spellentry is present and if the cooldown is less than 10 mins
- if( entry &&
- entry->RecoveryTime <= 10 * MINUTE * IN_MILISECONDS &&
- entry->CategoryRecoveryTime <= 10 * MINUTE * IN_MILISECONDS )
- {
- // remove & notify
- RemoveSpellCooldown(itr->first, true);
- }
- }
-}
-
-void Player::RemoveAllSpellCooldown()
-{
- if (!m_spellCooldowns.empty())
- {
- for (SpellCooldowns::const_iterator itr = m_spellCooldowns.begin(); itr != m_spellCooldowns.end(); ++itr)
- SendClearCooldown(itr->first, this);
-
- m_spellCooldowns.clear();
- }
-}
-
-void Player::_LoadSpellCooldowns(QueryResult_AutoPtr result)
-{
- // some cooldowns can be already set at aura loading...
-
- //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
-
- if (result)
- {
- time_t curTime = time(NULL);
-
- do
- {
- Field *fields = result->Fetch();
-
- uint32 spell_id = fields[0].GetUInt32();
- uint32 item_id = fields[1].GetUInt32();
- time_t db_time = (time_t)fields[2].GetUInt64();
-
- if(!sSpellStore.LookupEntry(spell_id))
- {
- sLog.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
- continue;
- }
-
- // skip outdated cooldown
- if(db_time <= curTime)
- continue;
-
- AddSpellCooldown(spell_id, item_id, db_time);
-
- sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
- }
- while( result->NextRow() );
- }
-}
-
-void Player::_SaveSpellCooldowns()
-{
- CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
-
- time_t curTime = time(NULL);
- time_t infTime = curTime + infinityCooldownDelayCheck;
-
- bool first_round = true;
- std::ostringstream ss;
-
- // remove outdated and save active
- for (SpellCooldowns::iterator itr = m_spellCooldowns.begin(); itr != m_spellCooldowns.end();)
- {
- if(itr->second.end <= curTime)
- m_spellCooldowns.erase(itr++);
- else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
- {
- if (first_round)
- {
- ss << "INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ";
- first_round = false;
- }
- // next new/changed record prefix
- else
- ss << ", ";
- ss << "(" << GetGUIDLow() << "," << itr->first << "," << itr->second.itemid << "," << uint64(itr->second.end) << ")";
- ++itr;
- }
- else
- ++itr;
-
- }
- // if something changed execute
- if (!first_round)
- CharacterDatabase.Execute( ss.str().c_str() );
-}
-
-uint32 Player::resetTalentsCost() const
-{
- // The first time reset costs 1 gold
- if(m_resetTalentsCost < 1*GOLD)
- return 1*GOLD;
- // then 5 gold
- else if(m_resetTalentsCost < 5*GOLD)
- return 5*GOLD;
- // After that it increases in increments of 5 gold
- else if(m_resetTalentsCost < 10*GOLD)
- return 10*GOLD;
- else
- {
- uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
- if(months > 0)
- {
- // This cost will be reduced by a rate of 5 gold per month
- int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
- // to a minimum of 10 gold.
- return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
- }
- else
- {
- // After that it increases in increments of 5 gold
- int32 new_cost = m_resetTalentsCost + 5*GOLD;
- // until it hits a cap of 50 gold.
- if(new_cost > 50*GOLD)
- new_cost = 50*GOLD;
- return new_cost;
- }
- }
-}
-
-bool Player::resetTalents(bool no_cost)
-{
- // not need after this call
- if (HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
- RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS, true);
-
- uint32 talentPointsForLevel = CalculateTalentsPoints();
-
- if (m_usedTalentCount == 0)
- {
- SetFreeTalentPoints(talentPointsForLevel);
- return false;
- }
-
- uint32 cost = 0;
-
- if (!no_cost && !sWorld.getConfig(CONFIG_NO_RESET_TALENT_COST))
- {
- cost = resetTalentsCost();
-
- if (GetMoney() < cost)
- {
- SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
- return false;
- }
- }
-
- for (uint32 i = 0; i < sTalentStore.GetNumRows(); ++i)
- {
- TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
-
- if (!talentInfo)
- continue;
-
- TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
-
- if (!talentTabInfo)
- continue;
-
- // unlearn only talents for character class
- // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
- // to prevent unexpected lost normal learned spell skip another class talents
- if ((getClassMask() & talentTabInfo->ClassMask) == 0)
- continue;
-
- for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
- {
- // skip non-existant talent ranks
- if (talentInfo->RankID[rank] == 0)
- continue;
- removeSpell(talentInfo->RankID[rank], true);
- if (const SpellEntry *_spellEntry = sSpellStore.LookupEntry(talentInfo->RankID[rank]))
- for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) // search through the SpellEntry for valid trigger spells
- if (_spellEntry->EffectTriggerSpell[i] > 0 && _spellEntry->Effect[i] == SPELL_EFFECT_LEARN_SPELL)
- removeSpell(_spellEntry->EffectTriggerSpell[i], true); // and remove any spells that the talent teaches
- // if this talent rank can be found in the PlayerTalentMap, mark the talent as removed so it gets deleted
- PlayerTalentMap::iterator plrTalent = m_talents[m_activeSpec]->find(talentInfo->RankID[rank]);
- if (plrTalent != m_talents[m_activeSpec]->end())
- plrTalent->second->state = PLAYERSPELL_REMOVED;
- }
- }
-
- _SaveSpells();
-
- SetFreeTalentPoints(talentPointsForLevel);
-
- if (!no_cost)
- {
- ModifyMoney(-(int32)cost);
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
-
- m_resetTalentsCost = cost;
- m_resetTalentsTime = time(NULL);
- }
-
- //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
- RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
- /* when prev line will dropped use next line
- if(Pet* pet = GetPet())
- {
- if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
- RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
- }
- */
-
- return true;
-}
-
-Mail* Player::GetMail(uint32 id)
-{
- for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
- if ((*itr)->messageID == id)
- return (*itr);
-
- return NULL;
-}
-
-void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
-{
- if(target == this)
- Object::_SetCreateBits(updateMask, target);
- else
- {
- for (uint16 index = 0; index < m_valuesCount; index++)
- if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
- updateMask->SetBit(index);
- }
-}
-
-void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
-{
- if(target == this)
- Object::_SetUpdateBits(updateMask, target);
- else
- {
- Object::_SetUpdateBits(updateMask, target);
- *updateMask &= updateVisualBits;
- }
-}
-
-void Player::InitVisibleBits()
-{
- updateVisualBits.SetCount(PLAYER_END);
-
- updateVisualBits.SetBit(OBJECT_FIELD_GUID);
- updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
- updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
- updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
- updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
- updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
- updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
- updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
- updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
- updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
- updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
- updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
- updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
- updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
- updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
- updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
- updateVisualBits.SetBit(UNIT_FIELD_POWER1);
- updateVisualBits.SetBit(UNIT_FIELD_POWER2);
- updateVisualBits.SetBit(UNIT_FIELD_POWER3);
- updateVisualBits.SetBit(UNIT_FIELD_POWER4);
- updateVisualBits.SetBit(UNIT_FIELD_POWER5);
- updateVisualBits.SetBit(UNIT_FIELD_POWER6);
- updateVisualBits.SetBit(UNIT_FIELD_POWER7);
- updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
- updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
- updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
- updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
- updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
- updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
- updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
- updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
- updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
- updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
- updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
- updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
- updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
- updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
- updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
- updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
- updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
- updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
- updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
- updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
- updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
- updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
- updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
- updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
- updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
- updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
- updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
- updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
- updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
- updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
- updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
- updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
-
- updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
- updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
- updateVisualBits.SetBit(PLAYER_FLAGS);
- updateVisualBits.SetBit(PLAYER_GUILDID);
- updateVisualBits.SetBit(PLAYER_GUILDRANK);
- updateVisualBits.SetBit(PLAYER_BYTES);
- updateVisualBits.SetBit(PLAYER_BYTES_2);
- updateVisualBits.SetBit(PLAYER_BYTES_3);
- updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
- updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
- updateVisualBits.SetBit(UNIT_NPC_FLAGS);
-
- // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
- for (uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += MAX_QUEST_OFFSET)
- updateVisualBits.SetBit(i);
-
- // Players visible items are not inventory stuff
- for (uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i)
- {
- uint16 offset = i * 2;
-
- // item entry
- updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset);
- // enchant
- updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset);
- }
-
- updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
-}
-
-void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
-{
- for (uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i)
- {
- if(m_items[i] == NULL)
- continue;
-
- m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
- }
-
- if(target == this)
- {
- for (uint8 i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
- {
- if(m_items[i] == NULL)
- continue;
-
- m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
- }
- for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
- {
- if(m_items[i] == NULL)
- continue;
-
- m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
- }
- }
-
- Unit::BuildCreateUpdateBlockForPlayer( data, target );
-}
-
-void Player::DestroyForPlayer( Player *target, bool anim ) const
-{
- Unit::DestroyForPlayer( target, anim );
-
- for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
- {
- if(m_items[i] == NULL)
- continue;
-
- m_items[i]->DestroyForPlayer( target );
- }
-
- if(target == this)
- {
- for (uint8 i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
- {
- if(m_items[i] == NULL)
- continue;
-
- m_items[i]->DestroyForPlayer( target );
- }
- for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
- {
- if(m_items[i] == NULL)
- continue;
-
- m_items[i]->DestroyForPlayer( target );
- }
- }
-}
-
-bool Player::HasSpell(uint32 spell) const
-{
- PlayerSpellMap::const_iterator itr = m_spells.find(spell);
- return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
- !itr->second->disabled);
-}
-
-bool Player::HasTalent(uint32 spell, uint8 spec) const
-{
- PlayerTalentMap::const_iterator itr = m_talents[spec]->find(spell);
- return (itr != m_talents[spec]->end() && itr->second->state != PLAYERSPELL_REMOVED);
-}
-
-bool Player::HasActiveSpell(uint32 spell) const
-{
- PlayerSpellMap::const_iterator itr = m_spells.find(spell);
- return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
- itr->second->active && !itr->second->disabled);
-}
-
-TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
-{
- if (!trainer_spell)
- return TRAINER_SPELL_RED;
-
- bool hasSpell = true;
- for (uint8 i = 0; i < MAX_SPELL_EFFECTS ; ++i)
- {
- if (!trainer_spell->learnedSpell[i])
- continue;
-
- if(!HasSpell(trainer_spell->learnedSpell[i]))
- {
- hasSpell = false;
- break;
- }
- }
- // known spell
- if (hasSpell)
- return TRAINER_SPELL_GRAY;
-
- // check skill requirement
- if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
- return TRAINER_SPELL_RED;
-
- // check level requirement
- if(getLevel() < trainer_spell->reqLevel)
- return TRAINER_SPELL_RED;
-
- for (uint8 i = 0; i < MAX_SPELL_EFFECTS ; ++i)
- {
- if (!trainer_spell->learnedSpell[i])
- continue;
-
- // check race/class requirement
- if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell[i]))
- return TRAINER_SPELL_RED;
-
- if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learnedSpell[i]))
- {
- // check prev.rank requirement
- if(spell_chain->prev && !HasSpell(spell_chain->prev))
- return TRAINER_SPELL_RED;
- }
-
- SpellsRequiringSpellMapBounds spellsRequired = spellmgr.GetSpellsRequiredForSpellBounds(trainer_spell->learnedSpell[i]);
- for (SpellsRequiringSpellMap::const_iterator itr = spellsRequired.first; itr != spellsRequired.second; ++itr)
- {
- // check additional spell requirement
- if(!HasSpell(itr->second))
- return TRAINER_SPELL_RED;
- }
- }
-
- // check primary prof. limit
- // first rank of primary profession spell when there are no proffesions avalible is disabled
- for (uint8 i = 0; i < MAX_SPELL_EFFECTS ; ++i)
- {
- if (!trainer_spell->learnedSpell[i])
- continue;
- if((spellmgr.IsPrimaryProfessionFirstRankSpell(trainer_spell->learnedSpell[i])) && (GetFreePrimaryProfessionPoints() == 0))
- return TRAINER_SPELL_GREEN_DISABLED;
- }
-
- return TRAINER_SPELL_GREEN;
-}
-
-void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
-{
- uint32 guid = GUID_LOPART(playerguid);
-
- // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
- // bones will be deleted by corpse/bones deleting thread shortly
- ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
-
- // remove from guild
- uint32 guildId = GetGuildIdFromDB(playerguid);
- if(guildId != 0)
- {
- Guild* guild = objmgr.GetGuildById(guildId);
- if(guild)
- guild->DelMember(guid);
- }
-
- // remove from arena teams
- LeaveAllArenaTeams(playerguid);
-
- // the player was uninvited already on logout so just remove from group
- QueryResult_AutoPtr resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
- if(resultGroup)
- {
- uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
- Group* group = objmgr.GetGroupByLeader(leaderGuid);
- if(group)
- {
- RemoveFromGroup(group, playerguid);
- }
- }
-
- // remove signs from petitions (also remove petitions if owner);
- RemovePetitionsAndSigns(playerguid, 10);
-
- // return back all mails with COD and Item 0 1 2 3 4 5 6 7
- QueryResult_AutoPtr 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);
- if(resultMail)
- {
- do
- {
- Field *fields = resultMail->Fetch();
-
- uint32 mail_id = fields[0].GetUInt32();
- uint16 mailType = fields[1].GetUInt16();
- uint16 mailTemplateId= fields[2].GetUInt16();
- uint32 sender = fields[3].GetUInt32();
- std::string subject = fields[4].GetCppString();
- uint32 itemTextId = fields[5].GetUInt32();
- uint32 money = fields[6].GetUInt32();
- bool has_items = fields[7].GetBool();
-
- //we can return mail now
- //so firstly delete the old one
- CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
-
- // mail not from player
- if (mailType != MAIL_NORMAL)
- {
- if(has_items)
- CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
- continue;
- }
-
- MailDraft draft(subject, itemTextId);
- if (mailTemplateId)
- draft = MailDraft(mailTemplateId,false); // itesm already included
-
- if(has_items)
- {
- // data needs to be at first place for Item::LoadFromDB
- QueryResult_AutoPtr 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);
- if(resultItems)
- {
- do
- {
- Field *fields2 = resultItems->Fetch();
-
- uint32 item_guidlow = fields2[1].GetUInt32();
- uint32 item_template = fields2[2].GetUInt32();
-
- ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
- if(!itemProto)
- {
- CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
- continue;
- }
-
- Item *pItem = NewItemOrBag(itemProto);
- if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
- {
- pItem->FSetState(ITEM_REMOVED);
- pItem->SaveToDB(); // it also deletes item object !
- continue;
- }
-
- draft.AddItem(pItem);
- }
- while (resultItems->NextRow());
- }
- }
-
- CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
-
- uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
-
- draft.AddMoney(money).SendReturnToSender(pl_account, guid, sender);
- }
- while (resultMail->NextRow());
- }
-
- // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
- // Get guids of character's pets, will deleted in transaction
- QueryResult_AutoPtr resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
-
- // NOW we can finally clear other DB data related to character
- CharacterDatabase.BeginTransaction();
- if (resultPets)
- {
- do
- {
- Field *fields3 = resultPets->Fetch();
- uint32 petguidlow = fields3[0].GetUInt32();
- Pet::DeleteFromDB(petguidlow);
- } while (resultPets->NextRow());
- }
-
- CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_account_data WHERE guid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM groups WHERE leaderGuid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM group_member WHERE leaderGuid = '%u' OR memberGuid = '%u'",guid,guid);
- CharacterDatabase.PExecute("DELETE FROM groups WHERE leaderGuid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM gm_tickets WHERE playerGuid = '%u'", guid);
- CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
- CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u' " // NOTE: These achievements have flags & 256 in DBC.
- "AND achievement NOT BETWEEN '456' AND '467' " // Realm First Level 80
- "AND achievement NOT BETWEEN '1400' AND '1427' " // Realm First Raid Achievements
- "AND achievement NOT IN(1463, 3117, 3259) ", guid); // Realm First Northen Vanguard + Raid Achievements
- CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid1 = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid2 = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM guild_bank_eventlog WHERE PlayerGuid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_battleground_data WHERE guid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_glyphs WHERE guid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u'",guid);
- CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u'",guid);
-
- CharacterDatabase.CommitTransaction();
-
- //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
- if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
-}
-
-void Player::SetMovement(PlayerMovementType pType)
-{
- WorldPacket data;
- switch(pType)
- {
- case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
- case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
- case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
- case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
- default:
- sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
- return;
- }
- data.append(GetPackGUID());
- data << uint32(0);
- GetSession()->SendPacket( &data );
-}
-
-/* Preconditions:
- - a resurrectable corpse must not be loaded for the player (only bones)
- - the player must be in world
-*/
-void Player::BuildPlayerRepop()
-{
- WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
- data.append(GetPackGUID());
- GetSession()->SendPacket(&data);
-
- if (getRace() == RACE_NIGHTELF)
- CastSpell(this, 20584, true);
- CastSpell(this, 8326, true);
-
- // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
- // there must be SMSG.STOP_MIRROR_TIMER
- // there we must send 888 opcode
-
- // the player cannot have a corpse already, only bones which are not returned by GetCorpse
- if(GetCorpse())
- {
- sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
- assert(false);
- }
-
- // create a corpse and place it at the player's location
- CreateCorpse();
- Corpse *corpse = GetCorpse();
- if(!corpse)
- {
- sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
- return;
- }
- GetMap()->Add(corpse);
-
- // convert player body to ghost
- SetHealth( 1 );
-
- SetMovement(MOVE_WATER_WALK);
- if(!GetSession()->isLogingOut())
- SetMovement(MOVE_UNROOT);
-
- // BG - remove insignia related
- RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
-
-// SendCorpseReclaimDelay();
-
- // to prevent cheating
- corpse->ResetGhostTime();
-
- StopMirrorTimers(); //disable timers(bars)
-
- SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
-
- // set and clear other
- SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
-}
-
-void Player::ResurrectPlayer(float restore_percent, bool applySickness)
-{
- WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
- data << uint32(-1);
- data << float(0);
- data << float(0);
- data << float(0);
- GetSession()->SendPacket(&data);
-
- // speed change, land walk
-
- // remove death flag + set aura
- SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
- if (getRace() == RACE_NIGHTELF)
- RemoveAurasDueToSpell(20584); // speed bonuses
- RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
-
- setDeathState(ALIVE);
-
- SetMovement(MOVE_LAND_WALK);
- SetMovement(MOVE_UNROOT);
-
- m_deathTimer = 0;
-
- // set health/powers (0- will be set in caller)
- if(restore_percent>0.0f)
- {
- SetHealth(uint32(GetMaxHealth()*restore_percent));
- SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
- SetPower(POWER_RAGE, 0);
- SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
- }
-
- // trigger update zone for alive state zone updates
- uint32 newzone, newarea;
- GetZoneAndAreaId(newzone,newarea);
- UpdateZone(newzone,newarea);
- sOutdoorPvPMgr.HandlePlayerResurrects(this, newzone);
-
- // update visibility
- //ObjectAccessor::UpdateVisibilityForPlayer(this);
- SetToNotify();
-
- if(!applySickness)
- return;
-
- //Characters from level 1-10 are not affected by resurrection sickness.
- //Characters from level 11-19 will suffer from one minute of sickness
- //for each level they are above 10.
- //Characters level 20 and up suffer from ten minutes of sickness.
- int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
-
- if(int32(getLevel()) >= startLevel)
- {
- // set resurrection sickness
- CastSpell(this, 15007, true);
-
- // not full duration
- if(int32(getLevel()) < startLevel+9)
- {
- int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
-
- if(Aura * aur = GetAura(15007, GetGUID()))
- {
- aur->SetDuration(delta*IN_MILISECONDS);
- }
- }
- }
-}
-
-/**
- * FallMode = 0 implies that the player is dying, or already dead, and the proper death state will be set.
- * = 1 simply causes the player to plummet towards the ground, and not suffer any damage.
- * = 2 causes the player to plummet towards the ground, and causes falling damage, regardless
- * of any auras that might of prevented fall damage.
- */
-bool Player::FallGround(uint8 FallMode)
-{
- // Let's abort after we called this function one time
- if (getDeathState() == DEAD_FALLING && FallMode == 0)
- return false;
-
- float x, y, z;
- GetPosition(x, y, z);
- float ground_Z = GetMap()->GetVmapHeight(x, y, z);
- float z_diff = 0.0f;
- if ((z_diff = fabs(ground_Z - z)) < 0.1f)
- return false;
-
- GetMotionMaster()->MoveFall(ground_Z, EVENT_FALL_GROUND);
-
- // Below formula for falling damage is from Player::HandleFall
- if(FallMode == 2 && z_diff >= 14.57f)
- {
- uint32 damage = std::min(GetMaxHealth(), (uint32)((0.018f*z_diff-0.2426f)*GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL)));
- if(damage > 0) EnvironmentalDamage(DAMAGE_FALL, damage);
- }
- else if(FallMode == 0)
- Unit::setDeathState(DEAD_FALLING);
- return true;
-}
-
-void Player::KillPlayer()
-{
- if(IsFlying() && !GetTransport()) FallGround();
-
- SetMovement(MOVE_ROOT);
-
- StopMirrorTimers(); //disable timers(bars)
-
- setDeathState(CORPSE);
- //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
-
- SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
- ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
-
- // 6 minutes until repop at graveyard
- m_deathTimer = 6*MINUTE*IN_MILISECONDS;
-
- UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
- SendCorpseReclaimDelay();
-
- // don't create corpse at this moment, player might be falling
-
- // update visibility
- UpdateObjectVisibility();
-}
-
-void Player::CreateCorpse()
-{
- // prevent existence 2 corpse for player
- SpawnCorpseBones();
-
- uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
-
- Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
- SetPvPDeath(false);
-
- if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
- {
- delete corpse;
- return;
- }
-
- _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
- _pb = GetUInt32Value(PLAYER_BYTES);
- _pb2 = GetUInt32Value(PLAYER_BYTES_2);
-
- uint8 race = (uint8)(_uf);
- uint8 skin = (uint8)(_pb);
- uint8 face = (uint8)(_pb >> 8);
- uint8 hairstyle = (uint8)(_pb >> 16);
- uint8 haircolor = (uint8)(_pb >> 24);
- uint8 facialhair = (uint8)(_pb2);
-
- _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
- _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
-
- corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
- corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
-
- uint32 flags = CORPSE_FLAG_UNK2;
- if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
- flags |= CORPSE_FLAG_HIDE_HELM;
- if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
- flags |= CORPSE_FLAG_HIDE_CLOAK;
- if(InBattleGround() && !InArena())
- flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
- corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
-
- corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
-
- corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
-
- uint32 iDisplayID;
- uint32 iIventoryType;
- uint32 _cfi;
- for (uint8 i = 0; i < EQUIPMENT_SLOT_END; i++)
- {
- if(m_items[i])
- {
- iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
- iIventoryType = m_items[i]->GetProto()->InventoryType;
-
- _cfi = iDisplayID | (iIventoryType << 24);
- corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i, _cfi);
- }
- }
-
- // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
- const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
- assert(entry);
- if(entry->map_type != MAP_BATTLEGROUND)
- corpse->SaveToDB();
-
- // register for player, but not show
- ObjectAccessor::Instance().AddCorpse(corpse);
-}
-
-void Player::SpawnCorpseBones()
-{
- if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
- if (!GetSession()->PlayerLogoutWithSave()) // at logout we will already store the player
- SaveToDB(); // prevent loading as ghost without corpse
-}
-
-Corpse* Player::GetCorpse() const
-{
- return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
-}
-
-void Player::DurabilityLossAll(double percent, bool inventory)
-{
- for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
- if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- DurabilityLoss(pItem,percent);
-
- if(inventory)
- {
- // bags not have durability
- // for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
-
- for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
- if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- DurabilityLoss(pItem,percent);
-
- // keys not have durability
- //for (int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
-
- for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
- if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- for (uint32 j = 0; j < pBag->GetBagSize(); j++)
- if(Item* pItem = GetItemByPos( i, j ))
- DurabilityLoss(pItem,percent);
- }
-}
-
-void Player::DurabilityLoss(Item* item, double percent)
-{
- if(!item )
- return;
-
- uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
-
- if(!pMaxDurability)
- return;
-
- uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
-
- if(pDurabilityLoss < 1 )
- pDurabilityLoss = 1;
-
- DurabilityPointsLoss(item,pDurabilityLoss);
-}
-
-void Player::DurabilityPointsLossAll(int32 points, bool inventory)
-{
- for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
- if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- DurabilityPointsLoss(pItem,points);
-
- if(inventory)
- {
- // bags not have durability
- // for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
-
- for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
- if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- DurabilityPointsLoss(pItem,points);
-
- // keys not have durability
- //for (int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
-
- for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
- if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- for (uint32 j = 0; j < pBag->GetBagSize(); j++)
- if(Item* pItem = GetItemByPos( i, j ))
- DurabilityPointsLoss(pItem,points);
- }
-}
-
-void Player::DurabilityPointsLoss(Item* item, int32 points)
-{
- int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
- int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
- int32 pNewDurability = pOldDurability - points;
-
- if (pNewDurability < 0)
- pNewDurability = 0;
- else if (pNewDurability > pMaxDurability)
- pNewDurability = pMaxDurability;
-
- if (pOldDurability != pNewDurability)
- {
- // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
- if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
- _ApplyItemMods(item,item->GetSlot(), false);
-
- item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
-
- // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
- if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
- _ApplyItemMods(item,item->GetSlot(), true);
-
- item->SetState(ITEM_CHANGED, this);
- }
-}
-
-void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
-{
- if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
- DurabilityPointsLoss(pItem,1);
-}
-
-uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
-{
- uint32 TotalCost = 0;
- // equipped, backpack, bags itself
- for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
- TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
-
- // bank, buyback and keys not repaired
-
- // items in inventory bags
- for (uint8 j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
- for (uint8 i = 0; i < MAX_BAG_SIZE; i++)
- TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
- return TotalCost;
-}
-
-uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
-{
- Item* item = GetItemByPos(pos);
-
- uint32 TotalCost = 0;
- if(!item)
- return TotalCost;
-
- uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
- if(!maxDurability)
- return TotalCost;
-
- uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
-
- if(cost)
- {
- uint32 LostDurability = maxDurability - curDurability;
- if(LostDurability>0)
- {
- ItemPrototype const *ditemProto = item->GetProto();
-
- DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
- if(!dcost)
- {
- sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
- return TotalCost;
- }
-
- uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
- DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
- if(!dQualitymodEntry)
- {
- sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
- return TotalCost;
- }
-
- uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
- uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
-
- costs = uint32(costs * discountMod) * sWorld.getRate(RATE_REPAIRCOST);
-
- if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
- costs = 1;
-
- if (guildBank)
- {
- if (GetGuildId()==0)
- {
- DEBUG_LOG("You are not member of a guild");
- return TotalCost;
- }
-
- Guild *pGuild = objmgr.GetGuildById(GetGuildId());
- if (!pGuild)
- return TotalCost;
-
- if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
- {
- DEBUG_LOG("You do not have rights to withdraw for repairs");
- return TotalCost;
- }
-
- if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
- {
- DEBUG_LOG("You do not have enough money withdraw amount remaining");
- return TotalCost;
- }
-
- if (pGuild->GetGuildBankMoney() < costs)
- {
- DEBUG_LOG("There is not enough money in bank");
- return TotalCost;
- }
-
- pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
- TotalCost = costs;
- }
- else if (GetMoney() < costs)
- {
- DEBUG_LOG("You do not have enough money");
- return TotalCost;
- }
- else
- ModifyMoney( -int32(costs) );
- }
- }
-
- item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
- item->SetState(ITEM_CHANGED, this);
-
- // reapply mods for total broken and repaired item if equipped
- if(IsEquipmentPos(pos) && !curDurability)
- _ApplyItemMods(item,pos & 255, true);
- return TotalCost;
-}
-
-void Player::RepopAtGraveyard()
-{
- // note: this can be called also when the player is alive
- // for example from WorldSession::HandleMovementOpcodes
-
- AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
-
- // Such zones are considered unreachable as a ghost and the player must be automatically revived
- if ((!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY) || GetTransport() || GetPositionZ() < -500.0f)
- {
- ResurrectPlayer(0.5f);
- SpawnCorpseBones();
- }
-
- WorldSafeLocsEntry const *ClosestGrave = NULL;
-
- // Special handle for battleground maps
- if( BattleGround *bg = GetBattleGround() )
- ClosestGrave = bg->GetClosestGraveYard(this);
- else
- ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
-
- // stop countdown until repop
- m_deathTimer = 0;
-
- // if no grave found, stay at the current location
- // and don't show spirit healer location
- if(ClosestGrave)
- {
- TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
- if(isDead()) // not send if alive, because it used in TeleportTo()
- {
- WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
- data << ClosestGrave->map_id;
- data << ClosestGrave->x;
- data << ClosestGrave->y;
- data << ClosestGrave->z;
- GetSession()->SendPacket(&data);
- }
- }
- else if(GetPositionZ() < -500.0f)
- TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
-}
-
-void Player::JoinedChannel(Channel *c)
-{
- m_channels.push_back(c);
-}
-
-void Player::LeftChannel(Channel *c)
-{
- m_channels.remove(c);
-}
-
-void Player::CleanupChannels()
-{
- while(!m_channels.empty())
- {
- Channel* ch = *m_channels.begin();
- m_channels.erase(m_channels.begin()); // remove from player's channel list
- ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
- if (ChannelMgr* cMgr = channelMgr(GetTeam()))
- cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
-
- }
- sLog.outDebug("Player: channels cleaned up!");
-}
-
-void Player::UpdateLocalChannels(uint32 newZone )
-{
- if(m_channels.empty())
- return;
-
- AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
- if(!current_zone)
- return;
-
- ChannelMgr* cMgr = channelMgr(GetTeam());
- if(!cMgr)
- return;
-
- std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
-
- for (JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
- {
- next = i; ++next;
-
- // skip non built-in channels
- if(!(*i)->IsConstant())
- continue;
-
- ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
- if(!ch)
- continue;
-
- if((ch->flags & 4) == 4) // global channel without zone name in pattern
- continue;
-
- // new channel
- char new_channel_name_buf[100];
- snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
- Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
-
- if((*i)!=new_channel)
- {
- new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
-
- // leave old channel
- (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
- std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
- LeftChannel(*i); // remove from player's channel list
- cMgr->LeftChannel(name); // delete if empty
- }
- }
- sLog.outDebug("Player: channels cleaned up!");
-}
-
-void Player::LeaveLFGChannel()
-{
- for (JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
- {
- if((*i)->IsLFG())
- {
- (*i)->Leave(GetGUID());
- break;
- }
- }
-}
-
-void Player::UpdateDefense()
-{
- uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
-
- if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
- {
- // update dependent from defense skill part
- UpdateDefenseBonusesMod();
- }
-}
-
-void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
-{
- if(modGroup >= BASEMOD_END || modType >= MOD_END)
- {
- sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
- return;
- }
-
- float val = 1.0f;
-
- switch(modType)
- {
- case FLAT_MOD:
- m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
- break;
- case PCT_MOD:
- if(amount <= -100.0f)
- amount = -200.0f;
-
- val = (100.0f + amount) / 100.0f;
- m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
- break;
- }
-
- if(!CanModifyStats())
- return;
-
- switch(modGroup)
- {
- case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
- case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
- case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
- case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
- default: break;
- }
-}
-
-float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
-{
- if(modGroup >= BASEMOD_END || modType > MOD_END)
- {
- sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
- return 0.0f;
- }
-
- if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
- return 0.0f;
-
- return m_auraBaseMod[modGroup][modType];
-}
-
-float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
-{
- if(modGroup >= BASEMOD_END)
- {
- sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
- return 0.0f;
- }
-
- if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
- return 0.0f;
-
- return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
-}
-
-uint32 Player::GetShieldBlockValue() const
-{
- float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
-
- value = (value < 0) ? 0 : value;
-
- return uint32(value);
-}
-
-float Player::GetMeleeCritFromAgility()
-{
- uint8 level = getLevel();
- uint32 pclass = getClass();
-
- if (level > GT_MAX_LEVEL)
- level = GT_MAX_LEVEL;
-
- GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
- GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
- if (critBase == NULL || critRatio == NULL)
- return 0.0f;
-
- float crit = critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
- return crit*100.0f;
-}
-
-float Player::GetDodgeFromAgility()
-{
- // Table for base dodge values
- float dodge_base[MAX_CLASSES] = {
- 0.0075f, // Warrior
- 0.00652f, // Paladin
- -0.0545f, // Hunter
- -0.0059f, // Rogue
- 0.03183f, // Priest
- 0.0114f, // DK
- 0.0167f, // Shaman
- 0.034575f, // Mage
- 0.02011f, // Warlock
- 0.0f, // ??
- -0.0187f // Druid
- };
- // Crit/agility to dodge/agility coefficient multipliers
- float crit_to_dodge[MAX_CLASSES] = {
- 1.1f, // Warrior
- 1.0f, // Paladin
- 1.6f, // Hunter
- 2.0f, // Rogue
- 1.0f, // Priest
- 1.0f, // DK?
- 1.0f, // Shaman
- 1.0f, // Mage
- 1.0f, // Warlock
- 0.0f, // ??
- 1.7f // Druid
- };
-
- uint8 level = getLevel();
- uint32 pclass = getClass();
-
- if (level > GT_MAX_LEVEL)
- level = GT_MAX_LEVEL;
-
- // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
- GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
- if (dodgeRatio == NULL || pclass > MAX_CLASSES)
- return 0.0f;
-
- float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
- return dodge*100.0f;
-}
-
-float Player::GetSpellCritFromIntellect()
-{
- uint8 level = getLevel();
- uint32 pclass = getClass();
-
- if (level > GT_MAX_LEVEL)
- level = GT_MAX_LEVEL;
-
- GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
- GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
- if (critBase == NULL || critRatio == NULL)
- return 0.0f;
-
- float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
- return crit*100.0f;
-}
-
-float Player::GetRatingCoefficient(CombatRating cr) const
-{
- uint8 level = getLevel();
-
- if (level > GT_MAX_LEVEL)
- level = GT_MAX_LEVEL;
-
- GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
- if (Rating == NULL)
- return 1.0f; // By default use minimum coefficient (not must be called)
-
- return Rating->ratio;
-}
-
-float Player::GetRatingBonusValue(CombatRating cr) const
-{
- return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
-}
-
-float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
-{
- switch (attType)
- {
- case BASE_ATTACK:
- return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
- case OFF_ATTACK:
- return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
- default:
- break;
- }
- return 0.0f;
-}
-
-float Player::OCTRegenHPPerSpirit()
-{
- uint8 level = getLevel();
- uint32 pclass = getClass();
-
- if (level > GT_MAX_LEVEL)
- level = GT_MAX_LEVEL;
-
- GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
- GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
- if (baseRatio == NULL || moreRatio == NULL)
- return 0.0f;
-
- // Formula from PaperDollFrame script
- float spirit = GetStat(STAT_SPIRIT);
- float baseSpirit = spirit;
- if (baseSpirit > 50)
- baseSpirit = 50;
- float moreSpirit = spirit - baseSpirit;
- float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
- return regen;
-}
-
-float Player::OCTRegenMPPerSpirit()
-{
- uint8 level = getLevel();
- uint32 pclass = getClass();
-
- if (level > GT_MAX_LEVEL)
- level = GT_MAX_LEVEL;
-
-// GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
- GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
- if (moreRatio == NULL)
- return 0.0f;
-
- // Formula get from PaperDollFrame script
- float spirit = GetStat(STAT_SPIRIT);
- float regen = spirit * moreRatio->ratio;
- return regen;
-}
-
-void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
-{
- m_baseRatingValue[cr]+=(apply ? value : -value);
-
- // explicit affected values
- switch (cr)
- {
- case CR_HASTE_MELEE:
- {
- float RatingChange = value / GetRatingCoefficient(cr);
- ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
- ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
- break;
- }
- case CR_HASTE_RANGED:
- {
- float RatingChange = value / GetRatingCoefficient(cr);
- ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
- break;
- }
- case CR_HASTE_SPELL:
- {
- float RatingChange = value / GetRatingCoefficient(cr);
- ApplyCastTimePercentMod(RatingChange,apply);
- break;
- }
- }
-
- UpdateRating(cr);
-}
-
-void Player::UpdateRating(CombatRating cr)
-{
- int32 amount = m_baseRatingValue[cr];
- // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
- // stat used stored in miscValueB for this aura
- AuraEffectList const& modRatingFromStat = GetAuraEffectsByType(SPELL_AURA_MOD_RATING_FROM_STAT);
- for (AuraEffectList::const_iterator i = modRatingFromStat.begin(); i != modRatingFromStat.end(); ++i)
- if ((*i)->GetMiscValue() & (1<<cr))
- amount += int32(GetStat(Stats((*i)->GetMiscValueB())) * (*i)->GetAmount() / 100.0f);
- if (amount < 0)
- amount = 0;
- SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
-
- bool affectStats = CanModifyStats();
-
- switch (cr)
- {
- case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
- case CR_DEFENSE_SKILL:
- UpdateDefenseBonusesMod();
- break;
- case CR_DODGE:
- UpdateDodgePercentage();
- break;
- case CR_PARRY:
- UpdateParryPercentage();
- break;
- case CR_BLOCK:
- UpdateBlockPercentage();
- break;
- case CR_HIT_MELEE:
- UpdateMeleeHitChances();
- break;
- case CR_HIT_RANGED:
- UpdateRangedHitChances();
- break;
- case CR_HIT_SPELL:
- UpdateSpellHitChances();
- break;
- case CR_CRIT_MELEE:
- if(affectStats)
- {
- UpdateCritPercentage(BASE_ATTACK);
- UpdateCritPercentage(OFF_ATTACK);
- }
- break;
- case CR_CRIT_RANGED:
- if(affectStats)
- UpdateCritPercentage(RANGED_ATTACK);
- break;
- case CR_CRIT_SPELL:
- if(affectStats)
- UpdateAllSpellCritChances();
- break;
- case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
- case CR_HIT_TAKEN_RANGED:
- break;
- case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
- break;
- case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
- case CR_CRIT_TAKEN_RANGED:
- break;
- case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
- break;
- case CR_HASTE_MELEE: // Implemented in Player::ApplyRatingMod
- case CR_HASTE_RANGED:
- case CR_HASTE_SPELL:
- break;
- case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
- case CR_WEAPON_SKILL_OFFHAND:
- case CR_WEAPON_SKILL_RANGED:
- break;
- case CR_EXPERTISE:
- if(affectStats)
- {
- UpdateExpertise(BASE_ATTACK);
- UpdateExpertise(OFF_ATTACK);
- }
- break;
- case CR_ARMOR_PENETRATION:
- if(affectStats)
- UpdateArmorPenetration(amount);
- break;
- }
-}
-
-void Player::UpdateAllRatings()
-{
- for(int cr = 0; cr < MAX_COMBAT_RATING; ++cr)
- UpdateRating(CombatRating(cr));
-}
-
-void Player::SetRegularAttackTime()
-{
- for (uint8 i = 0; i < MAX_ATTACK; ++i)
- {
- Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
- if(tmpitem && !tmpitem->IsBroken())
- {
- ItemPrototype const *proto = tmpitem->GetProto();
- if(proto->Delay)
- SetAttackTime(WeaponAttackType(i), proto->Delay);
- else
- SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
- }
- }
-}
-
-//skill+step, checking for max value
-bool Player::UpdateSkill(uint32 skill_id, uint32 step)
-{
- if(!skill_id)
- return false;
-
- if(skill_id == SKILL_FIST_WEAPONS)
- skill_id = SKILL_UNARMED;
-
- SkillStatusMap::iterator itr = mSkillStatus.find(skill_id);
- if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
- return false;
-
- uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
- uint32 data = GetUInt32Value(valueIndex);
- uint32 value = SKILL_VALUE(data);
- uint32 max = SKILL_MAX(data);
-
- if ((!max) || (!value) || (value >= max))
- return false;
-
- if (value < max)
- {
- uint32 new_value = value+step;
- if(new_value > max)
- new_value = max;
-
- SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,max));
- if(itr->second.uState != SKILL_NEW)
- itr->second.uState = SKILL_CHANGED;
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
- return true;
- }
-
- return false;
-}
-
-inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
-{
- if ( SkillValue >= GrayLevel )
- return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
- if ( SkillValue >= GreenLevel )
- return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
- if ( SkillValue >= YellowLevel )
- return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
- return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
-}
-
-bool Player::UpdateCraftSkill(uint32 spellid)
-{
- sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
-
- SkillLineAbilityMapBounds bounds = spellmgr.GetSkillLineAbilityMapBounds(spellid);
-
- for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
- {
- if (_spell_idx->second->skillId)
- {
- uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
-
- // Alchemy Discoveries here
- SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
- if (spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
- {
- if (uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
- learnSpell(discoveredSpell,false);
- }
-
- uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
-
- return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
- _spell_idx->second->max_value,
- (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
- _spell_idx->second->min_value),
- craft_skill_gain);
- }
- }
- return false;
-}
-
-bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
-{
- sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
-
- uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
-
- // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
- switch (SkillId)
- {
- case SKILL_HERBALISM:
- case SKILL_LOCKPICKING:
- case SKILL_JEWELCRAFTING:
- case SKILL_INSCRIPTION:
- return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
- case SKILL_SKINNING:
- if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
- return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
- else
- return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
- case SKILL_MINING:
- if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
- return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
- else
- return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
- }
- return false;
-}
-
-bool Player::UpdateFishingSkill()
-{
- sLog.outDebug("UpdateFishingSkill");
-
- uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
-
- int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
-
- uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
-
- return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
-}
-
-// levels sync. with spell requirement for skill levels to learn
-// bonus abilities in sSkillLineAbilityStore
-// Used only to avoid scan DBC at each skill grow
-static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
-
-bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
-{
- sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
- if ( !SkillId )
- return false;
-
- if(Chance <= 0) // speedup in 0 chance case
- {
- sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
- return false;
- }
-
- SkillStatusMap::iterator itr = mSkillStatus.find(SkillId);
- if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
- return false;
-
- uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
-
- uint32 data = GetUInt32Value(valueIndex);
- uint16 SkillValue = SKILL_VALUE(data);
- uint16 MaxValue = SKILL_MAX(data);
-
- if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
- return false;
-
- int32 Roll = irand(1,1000);
-
- if ( Roll <= Chance )
- {
- uint32 new_value = SkillValue+step;
- if(new_value > MaxValue)
- new_value = MaxValue;
-
- SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,MaxValue));
- if(itr->second.uState != SKILL_NEW)
- itr->second.uState = SKILL_CHANGED;
- for (uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
- {
- if((SkillValue < *bsl && new_value >= *bsl))
- {
- learnSkillRewardedSpells( SkillId, new_value);
- break;
- }
- }
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
- sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
- return true;
- }
-
- sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
- return false;
-}
-
-void Player::UpdateWeaponSkill (WeaponAttackType attType)
-{
- // no skill gain in pvp
- Unit *pVictim = getVictim();
- if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
- return;
-
- if(IsInFeralForm())
- return; // always maximized SKILL_FERAL_COMBAT in fact
-
- if(m_form == FORM_TREE)
- return; // use weapon but not skill up
-
- if(pVictim && pVictim->GetTypeId() == TYPEID_UNIT && (((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_SKILLGAIN))
- return;
-
- uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
-
- switch(attType)
- {
- case BASE_ATTACK:
- {
- Item *tmpitem = GetWeaponForAttack(attType,true);
-
- if (!tmpitem)
- UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
- else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
- UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
- break;
- }
- case OFF_ATTACK:
- case RANGED_ATTACK:
- {
- Item *tmpitem = GetWeaponForAttack(attType,true);
- if (tmpitem)
- UpdateSkill(tmpitem->GetSkill(), weapon_skill_gain);
- break;
- }
- }
- UpdateAllCritPercentages();
-}
-
-void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
-{
- uint8 plevel = getLevel(); // if defense than pVictim == attacker
- uint8 greylevel = Trinity::XP::GetGrayLevel(plevel);
- uint8 moblevel = pVictim->getLevelForTarget(this);
- if(moblevel < greylevel)
- return;
-
- if (moblevel > plevel + 5)
- moblevel = plevel + 5;
-
- uint8 lvldif = moblevel - greylevel;
- if (lvldif < 3)
- lvldif = 3;
-
- uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
- if (skilldif <= 0)
- return;
-
- float chance = float(3 * lvldif * skilldif) / plevel;
- if (!defence)
- if (getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
- chance += chance * 0.02f * GetStat(STAT_INTELLECT);
-
- chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
-
- if (roll_chance_f(chance))
- {
- if (defence)
- UpdateDefense();
- else
- UpdateWeaponSkill(attType);
- }
- else
- return;
-}
-
-void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
-{
- SkillStatusMap::const_iterator itr = mSkillStatus.find(skillid);
- if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
- return;
-
- uint32 bonusIndex = PLAYER_SKILL_BONUS_INDEX(itr->second.pos);
-
- uint32 bonus_val = GetUInt32Value(bonusIndex);
- int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
- int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
-
- if(talent) // permanent bonus stored in high part
- SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
- else // temporary/item bonus stored in low part
- SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
-}
-
-void Player::UpdateSkillsForLevel()
-{
- uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
- uint32 maxSkill = GetMaxSkillValueForLevel();
-
- bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
-
- for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
- {
- if(itr->second.uState == SKILL_DELETED)
- continue;
-
- uint32 pskill = itr->first;
- SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
- if (!pSkill)
- continue;
-
- if (GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
- continue;
-
- uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
- uint32 data = GetUInt32Value(valueIndex);
- uint32 max = SKILL_MAX(data);
- uint32 val = SKILL_VALUE(data);
-
- /// update only level dependent max skill values
- if (max != 1)
- {
- /// maximize skill always
- if (alwaysMaxSkill)
- {
- SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(maxSkill,maxSkill));
- if(itr->second.uState != SKILL_NEW)
- itr->second.uState = SKILL_CHANGED;
- }
- else if(max != maxconfskill) /// update max skill value if current max skill not maximized
- {
- SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(val,maxSkill));
- if(itr->second.uState != SKILL_NEW)
- itr->second.uState = SKILL_CHANGED;
- }
- }
- }
-}
-
-void Player::UpdateSkillsToMaxSkillsForLevel()
-{
- for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
- {
- if(itr->second.uState == SKILL_DELETED)
- continue;
-
- uint32 pskill = itr->first;
- if (IsProfessionOrRidingSkill(pskill))
- continue;
- uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
- uint32 data = GetUInt32Value(valueIndex);
- uint32 max = SKILL_MAX(data);
-
- if (max > 1)
- {
- SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(max,max));
- if(itr->second.uState != SKILL_NEW)
- itr->second.uState = SKILL_CHANGED;
- }
- if (pskill == SKILL_DEFENSE)
- UpdateDefenseBonusesMod();
- }
-}
-
-// This functions sets a skill line value (and adds if doesn't exist yet)
-// To "remove" a skill line, set it's values to zero
-void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
-{
- if (!id)
- return;
-
- SkillStatusMap::iterator itr = mSkillStatus.find(id);
-
- //has skill
- if(itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED)
- {
- if (currVal)
- {
- SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos),MAKE_SKILL_VALUE(currVal,maxVal));
- if(itr->second.uState != SKILL_NEW)
- itr->second.uState = SKILL_CHANGED;
- learnSkillRewardedSpells(id, currVal);
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
- }
- else //remove
- {
- // clear skill fields
- SetUInt32Value(PLAYER_SKILL_INDEX(itr->second.pos),0);
- SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos),0);
- SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos),0);
-
- // mark as deleted or simply remove from map if not saved yet
- if(itr->second.uState != SKILL_NEW)
- itr->second.uState = SKILL_DELETED;
- else
- mSkillStatus.erase(itr);
-
- // remove all spells that related to this skill
- for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j)
- if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
- if (pAbility->skillId == id)
- removeSpell(spellmgr.GetFirstSpellInChain(pAbility->spellId));
- }
- }
- else if (currVal) //add
- {
- for (int i=0; i < PLAYER_MAX_SKILLS; ++i)
- if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
- {
- SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
- if (!pSkill)
- {
- sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
- return;
- }
- // enable unlearn button for primary professions only
- if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
- SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
- else
- SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
- SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
-
- // insert new entry or update if not deleted old entry yet
- if(itr != mSkillStatus.end())
- {
- itr->second.pos = i;
- itr->second.uState = SKILL_CHANGED;
- }
- else
- mSkillStatus.insert(SkillStatusMap::value_type(id, SkillStatusData(i, SKILL_NEW)));
-
- // apply skill bonuses
- SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
-
- // temporary bonuses
- AuraEffectList const& mModSkill = GetAuraEffectsByType(SPELL_AURA_MOD_SKILL);
- for (AuraEffectList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
- if ((*j)->GetMiscValue() == int32(id))
- (*j)->HandleEffect(this, 0, true);
-
- // permanent bonuses
- AuraEffectList const& mModSkillTalent = GetAuraEffectsByType(SPELL_AURA_MOD_SKILL_TALENT);
- for (AuraEffectList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
- if ((*j)->GetMiscValue() == int32(id))
- (*j)->HandleEffect(this, 0, true);
-
- // Learn all spells for skill
- learnSkillRewardedSpells(id, currVal);
- return;
- }
- }
-}
-
-bool Player::HasSkill(uint32 skill) const
-{
- if(!skill)
- return false;
-
- SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
- return (itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED);
-}
-
-uint16 Player::GetSkillValue(uint32 skill) const
-{
- if (!skill)
- return 0;
-
- SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
- if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
- return 0;
-
- uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
-
- int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
- result += SKILL_TEMP_BONUS(bonus);
- result += SKILL_PERM_BONUS(bonus);
- return result < 0 ? 0 : result;
-}
-
-uint16 Player::GetMaxSkillValue(uint32 skill) const
-{
- if (!skill)
- return 0;
-
- SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
- if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
- return 0;
-
- uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
-
- int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
- result += SKILL_TEMP_BONUS(bonus);
- result += SKILL_PERM_BONUS(bonus);
- return result < 0 ? 0 : result;
-}
-
-uint16 Player::GetPureMaxSkillValue(uint32 skill) const
-{
- if(!skill)
- return 0;
-
- SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
- if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
- return 0;
-
- return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
-}
-
-uint16 Player::GetBaseSkillValue(uint32 skill) const
-{
- if(!skill)
- return 0;
-
- SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
- if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
- return 0;
-
- int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
- result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
- return result < 0 ? 0 : result;
-}
-
-uint16 Player::GetPureSkillValue(uint32 skill) const
-{
- if(!skill)
- return 0;
-
- SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
- if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
- return 0;
-
- return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
-}
-
-int16 Player::GetSkillPermBonusValue(uint32 skill) const
-{
- if (!skill)
- return 0;
-
- SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
- if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
- return 0;
-
- return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
-}
-
-int16 Player::GetSkillTempBonusValue(uint32 skill) const
-{
- if (!skill)
- return 0;
-
- SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
- if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
- return 0;
-
-return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
-}
-
-void Player::SendActionButtons(uint32 state) const
-{
- sLog.outDetail( "Sending Action Buttons for '%u' spec '%u'", GetGUIDLow(), m_activeSpec);
-
- WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
- data << uint8(state); // can be 0, 1, 2
- if (state != 2)
- {
- for (uint16 button = 0; button < MAX_ACTION_BUTTONS; ++button)
- {
- ActionButtonList::const_iterator itr = m_actionButtons.find(button);
- if (itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
- data << uint32(itr->second.packedData);
- else
- data << uint32(0);
- }
- }
-
- GetSession()->SendPacket(&data);
- sLog.outDetail("Action Buttons for '%u' spec '%u' Sent", GetGUIDLow(), m_activeSpec);
-}
-
-ActionButton* Player::addActionButton(uint8 button, uint32 action, uint8 type)
-{
- if(button >= MAX_ACTION_BUTTONS)
- {
- sLog.outError( "Action %u not added into button %u for player %s: button must be < 144", action, button, GetName() );
- return NULL;
- }
-
- if(action >= MAX_ACTION_BUTTON_ACTION_VALUE)
- {
- sLog.outError( "Action %u not added into button %u for player %s: action must be < %u", action, button, GetName(), MAX_ACTION_BUTTON_ACTION_VALUE );
- return NULL;
- }
-
- switch (type)
- {
- case ACTION_BUTTON_SPELL:
- if (!sSpellStore.LookupEntry(action))
- {
- sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
- return NULL;
- }
-
- if (!HasSpell(action))
- {
- sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
- return NULL;
- }
- break;
- case ACTION_BUTTON_ITEM:
- if (!objmgr.GetItemPrototype(action))
- {
- sLog.outError( "Action %u not added into button %u for player %s: item not exist", action, button, GetName() );
- return NULL;
- }
- break;
- default:
- break; // pther cases not checked at this moment
- }
-
- // it create new button (NEW state) if need or return existed
- ActionButton& ab = m_actionButtons[button];
-
- // set data and update to CHANGED if not NEW
- ab.SetActionAndType(action,ActionButtonType(type));
-
- sLog.outDetail("Player '%u' Added Action '%u' (type %u) to Button '%u'", GetGUIDLow(), action, type, button);
- return &ab;
-}
-
-void Player::removeActionButton(uint8 button)
-{
- ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
- if (buttonItr == m_actionButtons.end())
- return;
-
- if (!buttonItr->second.canRemoveByClient)
- {
- buttonItr->second.canRemoveByClient = true;
- return;
- }
- if(buttonItr->second.uState==ACTIONBUTTON_NEW)
- m_actionButtons.erase(buttonItr); // new and not saved
- else
- buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
-
- sLog.outDetail("Action Button '%u' Removed from Player '%u'", button, GetGUIDLow());
-}
-
-bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
-{
- if (!Unit::SetPosition(x, y, z, orientation, teleport))
- return false;
-
- //if(movementInfo.flags & MOVEMENTFLAG_MOVING)
- // mover->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE);
- //if(movementInfo.flags & MOVEMENTFLAG_TURNING)
- // mover->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
- //AURA_INTERRUPT_FLAG_JUMP not sure
-
- // group update
- if (GetGroup())
- SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
-
- // code block for underwater state update
- UpdateUnderwaterState(GetMap(), x, y, z);
-
- if(GetTrader() && !IsWithinDistInMap(GetTrader(), INTERACTION_DISTANCE))
- GetSession()->SendCancelTrade();
-
- CheckExploreSystem();
-
- return true;
-}
-
-void Player::SaveRecallPosition()
-{
- m_recallMap = GetMapId();
- m_recallX = GetPositionX();
- m_recallY = GetPositionY();
- m_recallZ = GetPositionZ();
- m_recallO = GetOrientation();
-}
-
-void Player::SendMessageToSet(WorldPacket *data, bool self)
-{
- if (self)
- GetSession()->SendPacket(data);
-
- // we use World::GetMaxVisibleDistance() because i cannot see why not use a distance
- // update: replaced by GetMap()->GetVisibilityDistance()
- Trinity::MessageDistDeliverer notifier(this, data, GetMap()->GetVisibilityDistance());
- VisitNearbyWorldObject(GetMap()->GetVisibilityDistance(), notifier);
-}
-
-void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
-{
- if (self)
- GetSession()->SendPacket(data);
-
- Trinity::MessageDistDeliverer notifier(this, data, dist);
- VisitNearbyWorldObject(dist, notifier);
-}
-
-void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
-{
- if (self)
- GetSession()->SendPacket(data);
-
- Trinity::MessageDistDeliverer notifier(this, data, dist, own_team_only);
- VisitNearbyWorldObject(dist, notifier);
-}
-
-void Player::SendDirectMessage(WorldPacket *data)
-{
- if (m_session)
- m_session->SendPacket(data);
-}
-
-void Player::SendCinematicStart(uint32 CinematicSequenceId)
-{
- WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
- data << uint32(CinematicSequenceId);
- SendDirectMessage(&data);
-}
-
-void Player::SendMovieStart(uint32 MovieId)
-{
- WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
- data << uint32(MovieId);
- SendDirectMessage(&data);
-}
-
-void Player::CheckExploreSystem()
-{
- if (!isAlive())
- return;
-
- if (isInFlight())
- return;
-
- if(!m_AreaID)
- m_AreaID = GetAreaId();
- if(m_AreaID != GetAreaId())
- {
- m_AreaID = GetAreaId();
- GetSession()->HandleOnAreaChange(GetAreaEntryByAreaID(m_AreaID));
- }
-
- uint16 areaFlag = GetBaseMap()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
- if(areaFlag==0xffff)
- return;
- int offset = areaFlag / 32;
-
- if(offset >= 128)
- {
- 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);
- return;
- }
-
- uint32 val = (uint32)(1 << (areaFlag % 32));
- uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
-
- if( !(currFields & val) )
- {
- SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
-
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
-
- AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
- if(!p)
- {
- sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
- }
- else if(p->area_level > 0)
- {
- uint32 area = p->ID;
- if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
- {
- SendExplorationExperience(area,0);
- }
- else
- {
- int32 diff = int32(getLevel()) - p->area_level;
- uint32 XP = 0;
- if (diff < -5)
- {
- XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
- }
- else if (diff > 5)
- {
- int32 exploration_percent = (100-((diff-5)*5));
- if (exploration_percent > 100)
- exploration_percent = 100;
- else if (exploration_percent < 0)
- exploration_percent = 0;
-
- XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
- }
- else
- {
- XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
- }
-
- GiveXP( XP, NULL );
- SendExplorationExperience(area,XP);
- }
- sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
- }
- }
-}
-
-uint32 Player::TeamForRace(uint8 race)
-{
- ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
- if(!rEntry)
- {
- sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
- return ALLIANCE;
- }
-
- switch(rEntry->TeamID)
- {
- case 7: return ALLIANCE;
- case 1: return HORDE;
- }
-
- sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
- return ALLIANCE;
-}
-
-uint32 Player::getFactionForRace(uint8 race)
-{
- ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
- if(!rEntry)
- {
- sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
- return 0;
- }
-
- return rEntry->FactionID;
-}
-
-void Player::setFactionForRace(uint8 race)
-{
- m_team = TeamForRace(race);
- setFaction( getFactionForRace(race) );
-}
-
-ReputationRank Player::GetReputationRank(uint32 faction) const
-{
- FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
- return GetReputationMgr().GetRank(factionEntry);
-}
-
-//Calculate total reputation percent player gain with quest/creature level
-int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest)
-{
- float percent = 100.0f;
-
- float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL);
-
- if (rate != 1.0f && creatureOrQuestLevel <= Trinity::XP::GetGrayLevel(getLevel()))
- percent *= rate;
-
- float repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
-
- if (!for_quest)
- repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);
-
- percent += rep > 0 ? repMod : -repMod;
-
- if (percent <= 0.0f)
- return 0;
-
- return int32(rep*percent/100);
-}
-
-//Calculates how many reputation points player gains in victim's enemy factions
-void Player::RewardReputation(Unit *pVictim, float rate)
-{
- if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
- return;
-
- if(((Creature*)pVictim)->IsReputationGainDisabled())
- return;
-
- ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
-
- if(!Rep)
- return;
-
- uint32 ChampioningFaction = 0;
-
- if(GetChampioningFaction())
- {
- // support for: Championing - http://www.wowwiki.com/Championing
-
- Map const *pMap = GetMap();
- if(pMap && pMap->IsDungeon())
- {
- bool Heroic = ((InstanceMap*)pMap)->GetDifficulty() == DUNGEON_DIFFICULTY_HEROIC;
-
- InstanceTemplate const *pInstance = objmgr.GetInstanceTemplate(pMap->GetId());
- if(pInstance)
- {
- AccessRequirement const *pAccessRequirement = objmgr.GetAccessRequirement(pInstance->access_id);
- if(pAccessRequirement)
- {
- if(!pMap->IsRaid() && ((!Heroic && pAccessRequirement->levelMin == 80) || (Heroic && pAccessRequirement->heroicLevelMin == 80)))
- ChampioningFaction = GetChampioningFaction();
- }
- }
- }
- }
-
- // Favored reputation increase START
- uint32 zone = GetZoneId();
- uint32 team = GetTeam();
- float favored_rep_mult = 0;
-
- if( (HasAura(32096) || HasAura(32098)) && (zone == 3483 || zone == 3562 || zone == 3836 || zone == 3713 || zone == 3714) ) favored_rep_mult = 0.25; // Thrallmar's Favor and Honor Hold's Favor
- else if( HasAura(30754) && (Rep->repfaction1 == 609 || Rep->repfaction2 == 609) && !ChampioningFaction ) favored_rep_mult = 0.25; // Cenarion Favor
-
- if(favored_rep_mult > 0) favored_rep_mult *= 2; // Multiplied by 2 because the reputation is divided by 2 for some reason (See "donerep1 / 2" and "donerep2 / 2") -- if you know why this is done, please update/explain :)
- // Favored reputation increase END
-
- if(Rep->repfaction1 && (!Rep->team_dependent || team == ALLIANCE))
- {
- int32 donerep1 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue1, ChampioningFaction ? ChampioningFaction : Rep->repfaction1, false);
- donerep1 = int32(donerep1*(rate + favored_rep_mult));
- FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(ChampioningFaction ? ChampioningFaction : Rep->repfaction1);
- uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
- if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
- GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
-
- // Wiki: Team factions value divided by 2 -- Deprecated, see ModifyReputation
- /*if (factionEntry1 && Rep->is_teamaward1)
- {
- FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
- if(team1_factionEntry)
- GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
- }*/
- }
-
- if(Rep->repfaction2 && (!Rep->team_dependent || team == HORDE))
- {
- int32 donerep2 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue2, ChampioningFaction ? ChampioningFaction : Rep->repfaction2, false);
- donerep2 = int32(donerep2*(rate + favored_rep_mult));
- FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(ChampioningFaction ? ChampioningFaction : Rep->repfaction2);
- uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
- if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
- GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
-
- // Wiki: Team factions value divided by 2 -- Deprecated, see ModifyReputation
- /*if (factionEntry2 && Rep->is_teamaward2)
- {
- FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
- if(team2_factionEntry)
- GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
- }*/
- }
-}
-
-//Calculate how many reputation points player gain with the quest
-void Player::RewardReputation(Quest const *pQuest)
-{
- // quest reputation reward/loss
- for (uint8 i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
- {
- if (!pQuest->RewRepFaction[i])
- continue;
- if (pQuest->RewRepValue[i])
- {
- int32 rep = CalculateReputationGain(GetQuestLevel(pQuest), pQuest->RewRepValue[i], pQuest->RewRepFaction[i], true);
- if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]))
- GetReputationMgr().ModifyReputation(factionEntry, rep);
- }
- else
- {
- uint32 row = 1;
- int32 field = 0;
-
- if (pQuest->RewRepValueId[i] < 0)
- {
- ++row;
- field = abs(pQuest->RewRepValueId[i]);
- }
- else
- field = pQuest->RewRepValueId[i];
- if (const QuestFactionRewEntry *pRow = sQuestFactionRewardStore.LookupEntry(row))
- {
- int32 repPoints = pRow->QuestRewFactionValue[field];
-
- if (!repPoints)
- continue;
-
- repPoints = CalculateReputationGain(GetQuestLevel(pQuest), repPoints, pQuest->RewRepFaction[i], true);
- if (const FactionEntry* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]))
- GetReputationMgr().ModifyReputation(factionEntry, repPoints);
- }
- }
- }
-
- // TODO: implement reputation spillover
-}
-
-void Player::UpdateHonorFields()
-{
- /// called when rewarding honor and at each save
- uint64 now = time(NULL);
- uint64 today = uint64(time(NULL) / DAY) * DAY;
-
- if(m_lastHonorUpdateTime < today)
- {
- uint64 yesterday = today - DAY;
-
- uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
-
- // update yesterday's contribution
- if(m_lastHonorUpdateTime >= yesterday )
- {
- SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
-
- // this is the first update today, reset today's contribution
- SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
- SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
- }
- else
- {
- // no honor/kills yesterday or today, reset
- SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
- SetUInt32Value(PLAYER_FIELD_KILLS, 0);
- }
- }
-
- m_lastHonorUpdateTime = now;
-}
-
-///Calculate the amount of honor gained based on the victim
-///and the size of the group for which the honor is divided
-///An exact honor value can also be given (overriding the calcs)
-bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor, bool pvptoken)
-{
- // do not reward honor in arenas, but enable onkill spellproc
- if(InArena())
- {
- if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
- return false;
-
- if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
- return false;
-
- return true;
- }
-
- // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
- if(HasAura(SPELL_AURA_PLAYER_INACTIVE))
- return false;
-
- uint64 victim_guid = 0;
- uint32 victim_rank = 0;
- uint32 rank_diff = 0;
- time_t now = time(NULL);
-
- // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
- UpdateHonorFields();
-
- // do not reward honor in arenas, but return true to enable onkill spellproc
- if(InBattleGround() && GetBattleGround() && GetBattleGround()->isArena())
- return true;
-
- if(honor <= 0)
- {
- if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
- return false;
-
- victim_guid = uVictim->GetGUID();
-
- if( uVictim->GetTypeId() == TYPEID_PLAYER )
- {
- Player *pVictim = (Player *)uVictim;
-
- if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
- return false;
-
- float f = 1; //need for total kills (?? need more info)
- uint32 k_grey = 0;
- uint32 k_level = getLevel();
- uint32 v_level = pVictim->getLevel();
-
- {
- // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
- // [0] Just name
- // [1..14] Alliance honor titles and player name
- // [15..28] Horde honor titles and player name
- // [29..38] Other title and player name
- // [39+] Nothing
- uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
- // Get Killer titles, CharTitlesEntry::bit_index
- // Ranks:
- // title[1..14] -> rank[5..18]
- // title[15..28] -> rank[5..18]
- // title[other] -> 0
- if (victim_title == 0)
- victim_guid = 0; // Don't show HK: <rank> message, only log.
- else if (victim_title < 15)
- victim_rank = victim_title + 4;
- else if (victim_title < 29)
- victim_rank = victim_title - 14 + 4;
- else
- victim_guid = 0; // Don't show HK: <rank> message, only log.
- }
-
- k_grey = Trinity::XP::GetGrayLevel(k_level);
-
- if(v_level<=k_grey)
- return false;
-
- float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
-
- int32 v_rank =1; //need more info
-
- honor = ((f * diff_level * (190 + v_rank*10))/6);
- honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
-
- // count the number of playerkills in one day
- ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
- // and those in a lifetime
- ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS, 1, true);
- UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
- UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
- UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
- }
- else
- {
- Creature *cVictim = (Creature *)uVictim;
-
- if (!cVictim->isRacialLeader())
- return false;
-
- honor = 100; // ??? need more info
- victim_rank = 19; // HK: Leader
- }
- }
-
- if (uVictim != NULL)
- {
- honor *= sWorld.getRate(RATE_HONOR);
-
- if(groupsize > 1)
- honor /= groupsize;
-
- // apply honor multiplier from aura (not stacking-get highest)
- honor = int32(float(honor) * (float(GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN_PCT))+100.0f)/100.0f);
- honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
- }
-
- // honor - for show honor points in log
- // victim_guid - for show victim name in log
- // victim_rank [1..4] HK: <dishonored rank>
- // victim_rank [5..19] HK: <alliance\horde rank>
- // victim_rank [0,20+] HK: <>
- WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
- data << (uint32) honor;
- data << (uint64) victim_guid;
- data << (uint32) victim_rank;
-
- GetSession()->SendPacket(&data);
-
- // add honor points
- ModifyHonorPoints(int32(honor));
-
- ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
-
- if( sWorld.getConfig(CONFIG_PVP_TOKEN_ENABLE) && pvptoken )
- {
- if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
- return true;
-
- if(uVictim->GetTypeId() == TYPEID_PLAYER)
- {
- // Check if allowed to receive it in current map
- uint8 MapType = sWorld.getConfig(CONFIG_PVP_TOKEN_MAP_TYPE);
- if( (MapType == 1 && !InBattleGround() && !HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
- || (MapType == 2 && !HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
- || (MapType == 3 && !InBattleGround()) )
- return true;
-
- uint32 noSpaceForCount = 0;
- uint32 itemId = sWorld.getConfig(CONFIG_PVP_TOKEN_ID);
- int32 count = sWorld.getConfig(CONFIG_PVP_TOKEN_COUNT);
-
- // check space and find places
- ItemPosCountVec dest;
- uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, count, &noSpaceForCount );
- if( msg != EQUIP_ERR_OK ) // convert to possible store amount
- count = noSpaceForCount;
-
- if( count == 0 || dest.empty()) // can't add any
- {
- // -- TODO: Send to mailbox if no space
- ChatHandler(this).PSendSysMessage("You don't have any space in your bags for a token.");
- return true;
- }
-
- Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
- SendNewItem(item,count,true,false);
- ChatHandler(this).PSendSysMessage("You have been awarded a token for slaying another player.");
- }
- }
-
- return true;
-}
-
-void Player::ModifyHonorPoints(int32 value)
-{
- if(value < 0)
- {
- if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
- SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
- else
- SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
- }
- else
- SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
-}
-
-void Player::ModifyArenaPoints(int32 value)
-{
- if(value < 0)
- {
- if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
- SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
- else
- SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
- }
- else
- SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
-}
-
-uint32 Player::GetGuildIdFromDB(uint64 guid)
-{
- QueryResult_AutoPtr result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
- if(!result)
- return 0;
-
- uint32 id = result->Fetch()[0].GetUInt32();
- return id;
-}
-
-uint32 Player::GetRankFromDB(uint64 guid)
-{
- QueryResult_AutoPtr result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
- if( result )
- {
- uint32 v = result->Fetch()[0].GetUInt32();
- return v;
- }
- else
- return 0;
-}
-
-uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
-{
- QueryResult_AutoPtr 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);
- if(!result)
- return 0;
-
- uint32 id = (*result)[0].GetUInt32();
- return id;
-}
-
-uint32 Player::GetZoneIdFromDB(uint64 guid)
-{
- uint32 guidLow = GUID_LOPART(guid);
- QueryResult_AutoPtr result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
- if (!result)
- return 0;
- Field* fields = result->Fetch();
- uint32 zone = fields[0].GetUInt32();
-
- if (!zone)
- {
- // stored zone is zero, use generic and slow zone detection
- result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
- if( !result )
- return 0;
- fields = result->Fetch();
- uint32 map = fields[0].GetUInt32();
- float posx = fields[1].GetFloat();
- float posy = fields[2].GetFloat();
- float posz = fields[3].GetFloat();
-
- zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
-
- if (zone > 0)
- CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
- }
-
- return zone;
-}
-
-uint32 Player::GetLevelFromDB(uint64 guid)
-{
- QueryResult_AutoPtr result = CharacterDatabase.PQuery("SELECT level FROM characters WHERE guid='%u'", GUID_LOPART(guid));
- if (!result)
- return 0;
-
- Field* fields = result->Fetch();
- uint8 level = fields[0].GetUInt8();
-
- return level;
-}
-
-void Player::UpdateArea(uint32 newArea)
-{
- // FFA_PVP flags are area and not zone id dependent
- // so apply them accordingly
- m_areaUpdateId = newArea;
-
- AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
- pvpInfo.inFFAPvPArea = area && (area->flags & AREA_FLAG_ARENA);
- UpdatePvPState(true);
-
- UpdateAreaDependentAuras(newArea);
-}
-
-void Player::UpdateZone(uint32 newZone, uint32 newArea)
-{
- if (m_zoneUpdateId != newZone)
- {
- sOutdoorPvPMgr.HandlePlayerLeaveZone(this, m_zoneUpdateId);
- sOutdoorPvPMgr.HandlePlayerEnterZone(this, newZone);
- SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
- }
-
- m_zoneUpdateId = newZone;
- m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
-
- // zone changed, so area changed as well, update it
- UpdateArea(newArea);
-
- AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
- if (!zone)
- return;
-
- if (sWorld.getConfig(CONFIG_WEATHER))
- {
- Weather *wth = sWorld.FindWeather(zone->ID);
- if (wth)
- wth->SendWeatherUpdateToPlayer(this);
- else
- {
- if (!sWorld.AddWeather(zone->ID))
- {
- // send fine weather packet to remove old zone's weather
- Weather::SendFineWeatherUpdateToPlayer(this);
- }
- }
- }
-
- // in PvP, any not controlled zone (except zone->team == 6, default case)
- // in PvE, only opposition team capital
- switch (zone->team)
- {
- case AREATEAM_ALLY:
- pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
- break;
- case AREATEAM_HORDE:
- pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
- break;
- case AREATEAM_NONE:
- // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
- pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround() || zone->flags & AREA_FLAG_OUTDOOR_PVP;
- break;
- default: // 6 in fact
- pvpInfo.inHostileArea = false;
- break;
- }
-
- pvpInfo.inNoPvPArea = false;
- if(zone->IsSanctuary()) // in sanctuary
- {
- SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
- pvpInfo.inNoPvPArea = true;
- CombatStopWithPets();
- }
- else
- RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
-
- if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
- {
- SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
- SetRestType(REST_TYPE_IN_CITY);
- InnEnter(time(0),GetMapId(),0,0,0);
- pvpInfo.inNoPvPArea = true;
- }
- else // anywhere else
- {
- if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
- {
- if(GetRestType() == REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
- {
- if(GetMapId() != GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
- {
- RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
- SetRestType(REST_TYPE_NO);
- }
- }
- else // not in tavern (leave city then)
- {
- RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
- SetRestType(REST_TYPE_NO);
- }
- }
- }
-
- UpdatePvPState();
-
- // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
- // if player resurrected at teleport this will be applied in resurrect code
- if (isAlive())
- DestroyZoneLimitedItem(true, newZone);
-
- // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
- AutoUnequipOffhandIfNeed();
-
- // recent client version not send leave/join channel packets for built-in local channels
- UpdateLocalChannels(newZone);
-
- // group update
- if (GetGroup())
- SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
-
- UpdateZoneDependentAuras(newZone);
-}
-
-//If players are too far way of duel flag... then player loose the duel
-void Player::CheckDuelDistance(time_t currTime)
-{
- if (!duel)
- return;
-
- uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
- GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
- if (!obj)
- return;
-
- if (duel->outOfBound == 0)
- {
- if (!IsWithinDistInMap(obj, 50))
- {
- duel->outOfBound = currTime;
-
- WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
- GetSession()->SendPacket(&data);
- }
- }
- else
- {
- if (IsWithinDistInMap(obj, 40))
- {
- duel->outOfBound = 0;
-
- WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
- GetSession()->SendPacket(&data);
- }
- else if (currTime >= (duel->outOfBound+10))
- DuelComplete(DUEL_FLED);
- }
-}
-
-bool Player::IsOutdoorPvPActive()
-{
- return isAlive() && !HasInvisibilityAura() && !HasStealthAura() && (IsPvP() || sWorld.IsPvPRealm()) && !HasUnitMovementFlag(MOVEMENTFLAG_FLYING) && !isInFlight();
-}
-
-void Player::DuelComplete(DuelCompleteType type)
-{
- // duel not requested
- if (!duel)
- return;
-
- sLog.outDebug("Duel Complete %s %s", GetName(), duel->opponent->GetName());
-
- WorldPacket data(SMSG_DUEL_COMPLETE, (1));
- data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
- GetSession()->SendPacket(&data);
- duel->opponent->GetSession()->SendPacket(&data);
-
- if (type != DUEL_INTERUPTED)
- {
- data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
- data << uint8(type == DUEL_WON ? 0 : 1); // 0 = just won; 1 = fled
- data << duel->opponent->GetName();
- data << GetName();
- SendMessageToSet(&data,true);
- }
-
- switch (type)
- {
- case DUEL_FLED:
- // if initiator and opponent are on the same team
- // or initiator and opponent are not PvP enabled, forcibly stop attacking
- if (duel->initiator->GetTeam() == duel->opponent->GetTeam())
- {
- duel->initiator->AttackStop();
- duel->opponent->AttackStop();
- }
- else
- {
- if (!duel->initiator->IsPvP())
- duel->initiator->AttackStop();
- if (!duel->opponent->IsPvP())
- duel->opponent->AttackStop();
- }
- break;
- case DUEL_WON:
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
- if (duel->opponent)
- {
- duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
-
- //Credit for quest Death's Challenge
- if (getClass() == CLASS_DEATH_KNIGHT && duel->opponent->GetQuestStatus(12733) == QUEST_STATUS_INCOMPLETE)
- duel->opponent->CastSpell(duel->opponent, 52994, true);
- }
- break;
- }
-
- //Remove Duel Flag object
- GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
- if(obj)
- duel->initiator->RemoveGameObject(obj,true);
-
- /* remove auras */
- AuraApplicationMap &itsAuras = duel->opponent->GetAppliedAuras();
- for (AuraApplicationMap::iterator i = itsAuras.begin(); i != itsAuras.end();)
- {
- Aura const * aura = i->second->GetBase();
- if (!i->second->IsPositive() && aura->GetCasterGUID() == GetGUID() && aura->GetApplyTime() >= duel->startTime)
- duel->opponent->RemoveAura(i);
- else
- ++i;
- }
-
- AuraApplicationMap &myAuras = GetAppliedAuras();
- for (AuraApplicationMap::iterator i = myAuras.begin(); i != myAuras.end();)
- {
- Aura const * aura = i->second->GetBase();
- if (!i->second->IsPositive() && aura->GetCasterGUID() == duel->opponent->GetGUID() && aura->GetApplyTime() >= duel->startTime)
- RemoveAura(i);
- else
- ++i;
- }
-
- // cleanup combo points
- if(GetComboTarget()==duel->opponent->GetGUID())
- ClearComboPoints();
- else if(GetComboTarget()==duel->opponent->GetPetGUID())
- ClearComboPoints();
-
- if(duel->opponent->GetComboTarget()==GetGUID())
- duel->opponent->ClearComboPoints();
- else if(duel->opponent->GetComboTarget()==GetPetGUID())
- duel->opponent->ClearComboPoints();
-
- // Honor points after duel (the winner) - ImpConfig
- if(uint32 amount = sWorld.getConfig(CONFIG_HONOR_AFTER_DUEL))
- duel->opponent->RewardHonor(NULL,1,amount);
-
- //cleanups
- SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
- SetUInt32Value(PLAYER_DUEL_TEAM, 0);
- duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
- duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
-
- delete duel->opponent->duel;
- duel->opponent->duel = NULL;
- delete duel;
- duel = NULL;
-}
-
-//---------------------------------------------------------//
-
-void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
-{
- if(slot >= INVENTORY_SLOT_BAG_END || !item)
- return;
-
- ItemPrototype const *proto = item->GetProto();
-
- if (!proto)
- return;
-
- if (proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
- CorrectMetaGemEnchants(slot, apply);
-
- // not apply/remove mods for broken item
- if (item->IsBroken())
- return;
-
- sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
-
- uint8 attacktype = Player::GetAttackBySlot(slot);
-
- // check disarm only on mod apply to allow remove item mods
- if (!CanUseAttackType(attacktype) )
- return;
-
- if (attacktype < MAX_ATTACK)
- _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
-
- _ApplyItemBonuses(proto,slot,apply);
-
- if (slot==EQUIPMENT_SLOT_RANGED)
- _ApplyAmmoBonuses();
-
- ApplyItemEquipSpell(item,apply);
- ApplyEnchantment(item, apply);
-
- sLog.outDebug("_ApplyItemMods complete.");
-}
-
-void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply, bool only_level_scale /*= false*/)
-{
- if (slot >= INVENTORY_SLOT_BAG_END || !proto)
- return;
-
- ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : NULL;
- if (only_level_scale && !ssd)
- return;
-
- // req. check at equip, but allow use for extended range if range limit max level, set proper level
- uint32 ssd_level = getLevel();
- if (ssd && ssd_level > ssd->MaxLevel)
- ssd_level = ssd->MaxLevel;
-
- ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(ssd_level) : NULL;
- if (only_level_scale && !ssv)
- return;
-
- for (uint8 i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
- {
- uint32 statType = 0;
- int32 val = 0;
- // If set ScalingStatDistribution need get stats and values from it
- if (ssd && ssv)
- {
- if (ssd->StatMod[i] < 0)
- continue;
- statType = ssd->StatMod[i];
- val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[i]) / 10000;
- }
- else
- {
- if (i >= proto->StatsCount)
- continue;
- statType = proto->ItemStat[i].ItemStatType;
- val = proto->ItemStat[i].ItemStatValue;
- }
-
- if(val == 0)
- continue;
-
- switch (statType)
- {
- case ITEM_MOD_MANA:
- HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
- break;
- case ITEM_MOD_HEALTH: // modify HP
- HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
- break;
- case ITEM_MOD_AGILITY: // modify agility
- HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
- ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
- break;
- case ITEM_MOD_STRENGTH: //modify strength
- HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
- ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
- break;
- case ITEM_MOD_INTELLECT: //modify intellect
- HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
- ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
- break;
- case ITEM_MOD_SPIRIT: //modify spirit
- HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
- ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
- break;
- case ITEM_MOD_STAMINA: //modify stamina
- HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
- ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
- break;
- case ITEM_MOD_DEFENSE_SKILL_RATING:
- ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
- break;
- case ITEM_MOD_DODGE_RATING:
- ApplyRatingMod(CR_DODGE, int32(val), apply);
- break;
- case ITEM_MOD_PARRY_RATING:
- ApplyRatingMod(CR_PARRY, int32(val), apply);
- break;
- case ITEM_MOD_BLOCK_RATING:
- ApplyRatingMod(CR_BLOCK, int32(val), apply);
- break;
- case ITEM_MOD_HIT_MELEE_RATING:
- ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
- break;
- case ITEM_MOD_HIT_RANGED_RATING:
- ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
- break;
- case ITEM_MOD_HIT_SPELL_RATING:
- ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
- break;
- case ITEM_MOD_CRIT_MELEE_RATING:
- ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
- break;
- case ITEM_MOD_CRIT_RANGED_RATING:
- ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
- break;
- case ITEM_MOD_CRIT_SPELL_RATING:
- ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
- break;
- case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
- ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
- break;
- case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
- ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
- break;
- case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
- ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
- break;
- case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
- ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
- break;
- case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
- ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
- break;
- case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
- ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
- break;
- case ITEM_MOD_HASTE_MELEE_RATING:
- ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
- break;
- case ITEM_MOD_HASTE_RANGED_RATING:
- ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
- break;
- case ITEM_MOD_HASTE_SPELL_RATING:
- ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
- break;
- case ITEM_MOD_HIT_RATING:
- ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
- ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
- ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
- break;
- case ITEM_MOD_CRIT_RATING:
- ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
- ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
- ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
- break;
- case ITEM_MOD_HIT_TAKEN_RATING:
- ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
- ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
- ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
- break;
- case ITEM_MOD_CRIT_TAKEN_RATING:
- ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
- ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
- ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
- break;
- case ITEM_MOD_RESILIENCE_RATING:
- ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
- ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
- ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
- break;
- case ITEM_MOD_HASTE_RATING:
- ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
- ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
- ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
- break;
- case ITEM_MOD_EXPERTISE_RATING:
- ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
- break;
- case ITEM_MOD_ATTACK_POWER:
- HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
- HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
- break;
- case ITEM_MOD_RANGED_ATTACK_POWER:
- HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
- break;
-// case ITEM_MOD_FERAL_ATTACK_POWER:
-// ApplyFeralAPBonus(int32(val), apply);
-// break;
- case ITEM_MOD_MANA_REGENERATION:
- ApplyManaRegenBonus(int32(val), apply);
- break;
- case ITEM_MOD_ARMOR_PENETRATION_RATING:
- ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
- break;
- case ITEM_MOD_SPELL_POWER:
- ApplySpellPowerBonus(int32(val), apply);
- break;
- case ITEM_MOD_HEALTH_REGEN:
- ApplyHealthRegenBonus(int32(val), apply);
- break;
- // depricated item mods
- case ITEM_MOD_SPELL_HEALING_DONE:
- case ITEM_MOD_SPELL_DAMAGE_DONE:
- break;
- }
- }
-
- // Apply Spell Power from ScalingStatValue if set
- if(ssv)
- {
- if (int32 spellbonus = ssv->getSpellBonus(proto->ScalingStatValue))
- ApplySpellPowerBonus(spellbonus, apply);
- }
-
- // If set ScalingStatValue armor get it or use item armor
- uint32 armor = proto->Armor;
- if (ssv)
- {
- if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue))
- armor = ssvarmor;
- }
-
- if (armor)
- {
- UnitModifierType modType = TOTAL_VALUE;
- if (proto->Class == ITEM_CLASS_ARMOR)
- {
- switch (proto->SubClass)
- {
- case ITEM_SUBCLASS_ARMOR_CLOTH:
- case ITEM_SUBCLASS_ARMOR_LEATHER:
- case ITEM_SUBCLASS_ARMOR_MAIL:
- case ITEM_SUBCLASS_ARMOR_PLATE:
- case ITEM_SUBCLASS_ARMOR_SHIELD:
- modType = BASE_VALUE;
- break;
- }
- }
- HandleStatModifier(UNIT_MOD_ARMOR, modType, float(armor), apply);
- }
-
- // Add armor bonus from ArmorDamageModifier if > 0
- if (proto->ArmorDamageModifier > 0)
- HandleStatModifier(UNIT_MOD_ARMOR, TOTAL_VALUE, float(proto->ArmorDamageModifier), apply);
-
- if (proto->Block)
- HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
-
- if (proto->HolyRes)
- HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
-
- if (proto->FireRes)
- HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
-
- if (proto->NatureRes)
- HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
-
- if (proto->FrostRes)
- HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
-
- if (proto->ShadowRes)
- HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
-
- if (proto->ArcaneRes)
- HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
-
- WeaponAttackType attType = BASE_ATTACK;
- float damage = 0.0f;
-
- if( slot == EQUIPMENT_SLOT_RANGED && (
- proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
- proto->InventoryType == INVTYPE_RANGEDRIGHT ))
- {
- attType = RANGED_ATTACK;
- }
- else if(slot==EQUIPMENT_SLOT_OFFHAND)
- {
- attType = OFF_ATTACK;
- }
-
- float minDamage = proto->Damage[0].DamageMin;
- float maxDamage = proto->Damage[0].DamageMax;
- int32 extraDPS = 0;
- // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
- if (ssv)
- {
- if ((extraDPS = ssv->getDPSMod(proto->ScalingStatValue)))
- {
- float average = extraDPS * proto->Delay / 1000.0f;
- minDamage = 0.7f * average;
- maxDamage = 1.3f * average;
- }
- }
- if (minDamage > 0 )
- {
- damage = apply ? minDamage : BASE_MINDAMAGE;
- SetBaseWeaponDamage(attType, MINDAMAGE, damage);
- //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
- }
-
- if (maxDamage > 0 )
- {
- damage = apply ? maxDamage : BASE_MAXDAMAGE;
- SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
- }
-
- // Apply feral bonus from ScalingStatValue if set
- if (ssv)
- {
- if (int32 feral_bonus = ssv->getFeralBonus(proto->ScalingStatValue))
- ApplyFeralAPBonus(feral_bonus, apply);
- }
- // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
- if(getClass() == CLASS_DRUID)
- {
- int32 feral_bonus = proto->getFeralBonus(extraDPS);
- if (feral_bonus > 0)
- ApplyFeralAPBonus(feral_bonus, apply);
- }
-
- if(IsInFeralForm() || !CanUseAttackType(attType))
- return;
-
- if (proto->Delay)
- {
- if(slot == EQUIPMENT_SLOT_RANGED)
- SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
- else if(slot==EQUIPMENT_SLOT_MAINHAND)
- SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
- else if(slot==EQUIPMENT_SLOT_OFFHAND)
- SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
- }
-
- if(CanModifyStats() && (damage || proto->Delay))
- UpdateDamagePhysical(attType);
-}
-
-void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
-{
- AuraEffectList const& auraCritList = GetAuraEffectsByType(SPELL_AURA_MOD_WEAPON_CRIT_PERCENT);
- for (AuraEffectList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end(); ++itr)
- _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
-
- AuraEffectList const& auraDamageFlatList = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE);
- for (AuraEffectList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end(); ++itr)
- _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
-
- AuraEffectList const& auraDamagePCTList = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
- for (AuraEffectList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end(); ++itr)
- _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
-}
-
-void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, AuraEffect const* aura, bool apply)
-{
- // generic not weapon specific case processes in aura code
- if (aura->GetSpellProto()->EquippedItemClass == -1)
- return;
-
- BaseModGroup mod = BASEMOD_END;
- switch (attackType)
- {
- case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
- case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
- case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
- default: return;
- }
-
- if (!item->IsBroken()&&item->IsFitToSpellRequirements(aura->GetSpellProto()))
- HandleBaseModValue(mod, FLAT_MOD, float (aura->GetAmount()), apply);
-}
-
-void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, AuraEffect const* aura, bool apply)
-{
- //don't apply mod if item is broken
- if (item->IsBroken())
- return;
-
- // ignore spell mods for not wands
- if ((aura->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL) == 0 && (getClassMask() & CLASSMASK_WAND_USERS) == 0)
- return;
-
- // generic not weapon specific case processes in aura code
- if (aura->GetSpellProto()->EquippedItemClass == -1)
- return;
-
- UnitMods unitMod = UNIT_MOD_END;
- switch (attackType)
- {
- case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
- case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
- case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
- default: return;
- }
-
- UnitModifierType unitModType = TOTAL_VALUE;
- switch (aura->GetAuraType())
- {
- case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
- case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
- default: return;
- }
-
- if (!item->IsBroken()&&item->IsFitToSpellRequirements(aura->GetSpellProto()))
- {
- HandleStatModifier(unitMod, unitModType, float(aura->GetAmount()),apply);
-
- if (unitModType == TOTAL_PCT)
- ApplyModSignedFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT,aura->GetAmount()/100.0f,apply);
- else
- ApplyModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS,aura->GetAmount(),apply);
- }
-}
-
-void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
-{
- if(!item)
- return;
-
- ItemPrototype const *proto = item->GetProto();
- if(!proto)
- return;
-
- for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
- {
- _Spell const& spellData = proto->Spells[i];
-
- // no spell
- if (!spellData.SpellId)
- continue;
-
- // wrong triggering type
- if (apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
- continue;
-
- // check if it is valid spell
- SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
- if (!spellproto)
- continue;
-
- ApplyEquipSpell(spellproto,item,apply,form_change);
- }
-}
-
-void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
-{
- if (apply)
- {
- // Cannot be used in this stance/form
- if (GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
- return;
-
- if (form_change) // check aura active state from other form
- {
- AuraApplicationMap const& auras = GetAppliedAuras();
- for (AuraApplicationMap::const_iterator itr = auras.lower_bound(spellInfo->Id); itr != auras.upper_bound(spellInfo->Id); ++itr)
- if (!item || itr->second->GetBase()->GetCastItemGUID() == item->GetGUID())
- return;
- }
-
- DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
-
- CastSpell(this,spellInfo,true,item);
- }
- else
- {
- if(form_change) // check aura compatibility
- {
- // Cannot be used in this stance/form
- if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
- return; // and remove only not compatible at form change
- }
-
- if (item)
- RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells, not only at-equipped
- else
- RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
- }
-}
-
-void Player::UpdateEquipSpellsAtFormChange()
-{
- for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
- {
- if(m_items[i] && !m_items[i]->IsBroken())
- {
- ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
- ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
- }
- }
-
- // item set bonuses not dependent from item broken state
- for (size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
- {
- ItemSetEffect* eff = ItemSetEff[setindex];
- if(!eff)
- continue;
-
- for (uint32 y=0; y<8; ++y)
- {
- SpellEntry const* spellInfo = eff->spells[y];
- if(!spellInfo)
- continue;
-
- ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
- ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
- }
- }
-}
-void Player::CastItemCombatSpell(Unit *target, WeaponAttackType attType, uint32 procVictim, uint32 procEx)
-{
- if (!target || !target->isAlive() || target == this)
- return;
-
- for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
- {
- // If usable, try to cast item spell
- if (Item * item = GetItemByPos(INVENTORY_SLOT_BAG_0,i))
- if (!item->IsBroken())
- if (ItemPrototype const *proto = item->GetProto())
- {
- // Additional check for weapons
- if (proto->Class == ITEM_CLASS_WEAPON)
- {
- // offhand item cannot proc from main hand hit etc
- EquipmentSlots slot;
- switch (attType)
- {
- case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
- case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
- case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
- default: slot = EQUIPMENT_SLOT_END; break;
- }
- if (slot != i)
- continue;
- // Check if item is useable (forms or disarm)
- if (attType == BASE_ATTACK)
- if (!IsUseEquipedWeapon(true))
- continue;
- }
- CastItemCombatSpell(target, attType, procVictim, procEx, item, proto);
- }
- }
-}
-
-void Player::CastItemCombatSpell(Unit *target, WeaponAttackType attType, uint32 procVictim, uint32 procEx, Item *item, ItemPrototype const * proto)
-{
- // Can do effect if any damage done to target
- if (procVictim & PROC_FLAG_TAKEN_ANY_DAMAGE)
- //if (damageInfo->procVictim & PROC_FLAG_TAKEN_ANY_DAMAGE)
- {
- for (uint8 i = 0; i < 5; ++i)
- {
- _Spell const& spellData = proto->Spells[i];
-
- // no spell
- if (!spellData.SpellId)
- continue;
-
- // wrong triggering type
- if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
- continue;
-
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
- if (!spellInfo)
- {
- sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
- continue;
- }
-
- // not allow proc extra attack spell at extra attack
- if (m_extraAttacks && IsSpellHaveEffect(spellInfo, SPELL_EFFECT_ADD_EXTRA_ATTACKS))
- return;
-
- float chance = spellInfo->procChance;
-
- if (spellData.SpellPPMRate)
- {
- if (spellData.SpellId == 52781) // Persuasive Strike
- {
- switch (target->GetEntry())
- {
- default:
- return;
- case 28939:
- case 28940:
- case 28610:
- break;
- }
- }
- uint32 WeaponSpeed = GetAttackTime(attType);
- chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate, spellInfo);
- }
- else if (chance > 100.0f)
- {
- chance = GetWeaponProcChance();
- }
-
- if (roll_chance_f(chance))
- CastSpell(target, spellInfo->Id, true, item);
- }
- }
-
- // item combat enchantments
- for (uint8 e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
- {
- uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
- SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
- if(!pEnchant) continue;
- for (uint8 s = 0; s < 3; ++s)
- {
- if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
- continue;
-
- SpellEnchantProcEntry const* entry = spellmgr.GetSpellEnchantProcEvent(enchant_id);
-
- if (entry && entry->procEx)
- {
- // Check hit/crit/dodge/parry requirement
- if((entry->procEx & procEx) == 0)
- continue;
- }
- else
- {
- // Can do effect if any damage done to target
- if (!(procVictim & PROC_FLAG_TAKEN_ANY_DAMAGE))
- //if (!(damageInfo->procVictim & PROC_FLAG_TAKEN_ANY_DAMAGE))
- continue;
- }
-
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
- if (!spellInfo)
- {
- sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
- continue;
- }
-
- float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
-
- if (entry)
- {
- if(entry->PPMChance)
- chance = GetPPMProcChance(proto->Delay, entry->PPMChance, spellInfo);
- else if(entry->customChance)
- chance = entry->customChance;
- }
-
- // Apply spell mods
- ApplySpellMod(pEnchant->spellid[s],SPELLMOD_CHANCE_OF_SUCCESS,chance);
-
- if (roll_chance_f(chance))
- {
- if(IsPositiveSpell(pEnchant->spellid[s]))
- CastSpell(this, pEnchant->spellid[s], true, item);
- else
- CastSpell(target, pEnchant->spellid[s], true, item);
- }
- }
- }
-}
-
-void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
-{
- ItemPrototype const* proto = item->GetProto();
- // special learning case
- if (proto->Spells[0].SpellId == 483 || proto->Spells[0].SpellId == 55884)
- {
- uint32 learn_spell_id = proto->Spells[0].SpellId;
- uint32 learning_spell_id = proto->Spells[1].SpellId;
-
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
- if (!spellInfo)
- {
- sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
- SendEquipError(EQUIP_ERR_NONE,item,NULL);
- return;
- }
-
- Spell *spell = new Spell(this, spellInfo,false);
- spell->m_CastItem = item;
- spell->m_cast_count = cast_count; //set count of casts
- spell->m_currentBasePoints[0] = learning_spell_id;
- spell->prepare(&targets);
- return;
- }
-
- // use triggered flag only for items with many spell casts and for not first cast
- uint8 count = 0;
-
- // item spells casted at use
- for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
- {
- _Spell const& spellData = proto->Spells[i];
-
- // no spell
- if (!spellData.SpellId)
- continue;
-
- // wrong triggering type
- if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
- continue;
-
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
- if(!spellInfo)
- {
- sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
- continue;
- }
-
- Spell *spell = new Spell(this, spellInfo, (count > 0));
- spell->m_CastItem = item;
- spell->m_cast_count = cast_count; // set count of casts
- spell->m_glyphIndex = glyphIndex; // glyph index
- spell->prepare(&targets);
-
- ++count;
- }
-
- // Item enchantments spells casted at use
- for (uint8 e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
- {
- uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
- SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
- if (!pEnchant)
- continue;
- for (uint8 s = 0; s < 3; ++s)
- {
- if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
- continue;
-
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
- if (!spellInfo)
- {
- sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
- continue;
- }
-
- Spell *spell = new Spell(this, spellInfo, (count > 0));
- spell->m_CastItem = item;
- spell->m_cast_count = cast_count; // set count of casts
- spell->m_glyphIndex = glyphIndex; // glyph index
- spell->prepare(&targets);
-
- ++count;
- }
- }
-}
-
-void Player::_RemoveAllItemMods()
-{
- sLog.outDebug("_RemoveAllItemMods start.");
-
- for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
- {
- if (m_items[i])
- {
- ItemPrototype const *proto = m_items[i]->GetProto();
- if (!proto)
- continue;
-
- // item set bonuses not dependent from item broken state
- if (proto->ItemSet)
- RemoveItemsSetItem(this,proto);
-
- if (m_items[i]->IsBroken())
- continue;
-
- ApplyItemEquipSpell(m_items[i], false);
- ApplyEnchantment(m_items[i], false);
- }
- }
-
- for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
- {
- if (m_items[i])
- {
- if (m_items[i]->IsBroken())
- continue;
- ItemPrototype const *proto = m_items[i]->GetProto();
- if (!proto)
- continue;
-
- uint32 attacktype = Player::GetAttackBySlot(i);
- if (attacktype < MAX_ATTACK)
- _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
-
- _ApplyItemBonuses(proto,i, false);
-
- if (i == EQUIPMENT_SLOT_RANGED)
- _ApplyAmmoBonuses();
- }
- }
-
- sLog.outDebug("_RemoveAllItemMods complete.");
-}
-
-void Player::_ApplyAllItemMods()
-{
- sLog.outDebug("_ApplyAllItemMods start.");
-
- for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
- {
- if (m_items[i])
- {
- if (m_items[i]->IsBroken())
- continue;
-
- ItemPrototype const *proto = m_items[i]->GetProto();
- if (!proto)
- continue;
-
- uint32 attacktype = Player::GetAttackBySlot(i);
- if (attacktype < MAX_ATTACK)
- _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
-
- _ApplyItemBonuses(proto,i, true);
-
- if (i == EQUIPMENT_SLOT_RANGED)
- _ApplyAmmoBonuses();
- }
- }
-
- for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
- {
- if (m_items[i])
- {
- ItemPrototype const *proto = m_items[i]->GetProto();
- if (!proto)
- continue;
-
- // item set bonuses not dependent from item broken state
- if (proto->ItemSet)
- AddItemsSetItem(this,m_items[i]);
-
- if (m_items[i]->IsBroken())
- continue;
-
- ApplyItemEquipSpell(m_items[i],true);
- ApplyEnchantment(m_items[i], true);
- }
- }
-
- sLog.outDebug("_ApplyAllItemMods complete.");
-}
-
-void Player::_ApplyAllLevelScaleItemMods(bool apply)
-{
- for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
- {
- if (m_items[i])
- {
- if (m_items[i]->IsBroken())
- continue;
-
- ItemPrototype const *proto = m_items[i]->GetProto();
- if (!proto)
- continue;
-
- _ApplyItemBonuses(proto,i, apply, true);
- }
- }
-}
-
-void Player::_ApplyAmmoBonuses()
-{
- // check ammo
- uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
- if (!ammo_id)
- return;
-
- float currentAmmoDPS;
-
- ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
- if (!ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
- currentAmmoDPS = 0.0f;
- else
- currentAmmoDPS = (ammo_proto->Damage[0].DamageMin + ammo_proto->Damage[0].DamageMax) / 2;
-
- if (currentAmmoDPS == GetAmmoDPS())
- return;
-
- m_ammoDPS = currentAmmoDPS;
-
- if (CanModifyStats())
- UpdateDamagePhysical(RANGED_ATTACK);
-}
-
-bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
-{
- if (!ammo_proto)
- return false;
-
- // check ranged weapon
- Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
- if (!weapon || weapon->IsBroken())
- return false;
-
- ItemPrototype const* weapon_proto = weapon->GetProto();
- if (!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
- return false;
-
- // check ammo ws. weapon compatibility
- switch (weapon_proto->SubClass)
- {
- case ITEM_SUBCLASS_WEAPON_BOW:
- case ITEM_SUBCLASS_WEAPON_CROSSBOW:
- if (ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
- return false;
- break;
- case ITEM_SUBCLASS_WEAPON_GUN:
- if (ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
- return false;
- break;
- default:
- return false;
- }
-
- return true;
-}
-
-/* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
- Called by remove insignia spell effect */
-void Player::RemovedInsignia(Player* looterPlr)
-{
- if (!GetBattleGroundId())
- return;
-
- // If not released spirit, do it !
- if (m_deathTimer > 0)
- {
- m_deathTimer = 0;
- BuildPlayerRepop();
- RepopAtGraveyard();
- }
-
- Corpse *corpse = GetCorpse();
- if (!corpse)
- return;
-
- // We have to convert player corpse to bones, not to be able to resurrect there
- // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
- Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
- if (!bones)
- return;
-
- // Now we must make bones lootable, and send player loot
- bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
-
- // We store the level of our player in the gold field
- // We retrieve this information at Player::SendLoot()
- bones->loot.gold = getLevel();
- bones->lootRecipient = looterPlr;
- looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
-}
-
-void Player::SendLootRelease( uint64 guid )
-{
- WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
- data << uint64(guid) << uint8(1);
- SendDirectMessage( &data );
-}
-
-void Player::SendLoot(uint64 guid, LootType loot_type)
-{
- if (uint64 lguid = GetLootGUID())
- m_session->DoLootRelease(lguid);
-
- Loot *loot = 0;
- PermissionTypes permission = ALL_PERMISSION;
-
- sLog.outDebug("Player::SendLoot");
- if (IS_GAMEOBJECT_GUID(guid))
- {
- sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
- GameObject *go = GetMap()->GetGameObject(guid);
-
- // not check distance for GO in case owned GO (fishing bobber case, for example)
- // And permit out of range GO with no owner in case fishing hole
- if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
- {
- SendLootRelease(guid);
- return;
- }
-
- loot = &go->loot;
-
- if (go->getLootState() == GO_READY)
- {
- uint32 lootid = go->GetGOInfo()->GetLootId();
-
- //TODO: fix this big hack
- if((go->GetEntry() == BG_AV_OBJECTID_MINE_N || go->GetEntry() == BG_AV_OBJECTID_MINE_S))
- if( BattleGround *bg = GetBattleGround())
- if(bg->GetTypeID() == BATTLEGROUND_AV)
- if(!(((BattleGroundAV*)bg)->PlayerCanDoMineQuest(go->GetEntry(),GetTeam())))
- {
- SendLootRelease(guid);
- return;
- }
-
- if (lootid)
- {
- sLog.outDebug(" if(lootid)");
- loot->clear();
- loot->FillLoot(lootid, LootTemplates_Gameobject, this, false, false, go->GetLootMode());
- }
-
- if (loot_type == LOOT_FISHING)
- go->getFishLoot(loot,this);
-
- go->SetLootState(GO_ACTIVATED);
- }
- }
- else if (IS_ITEM_GUID(guid))
- {
- Item *item = GetItemByGuid(guid);
-
- if (!item)
- {
- SendLootRelease(guid);
- return;
- }
-
- loot = &item->loot;
-
- if (!item->m_lootGenerated)
- {
- item->m_lootGenerated = true;
- loot->clear();
-
- switch (loot_type)
- {
- case LOOT_DISENCHANTING:
- loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
- break;
- case LOOT_PROSPECTING:
- loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
- break;
- case LOOT_MILLING:
- loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
- break;
- default:
- loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
- loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
- break;
- }
- }
- }
- else if (IS_CORPSE_GUID(guid)) // remove insignia
- {
- Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
-
- if (!bones || !(loot_type == LOOT_CORPSE || loot_type == LOOT_INSIGNIA) || bones->GetType() != CORPSE_BONES)
- {
- SendLootRelease(guid);
- return;
- }
-
- loot = &bones->loot;
-
- if (!bones->lootForBody)
- {
- bones->lootForBody = true;
- uint32 pLevel = bones->loot.gold;
- bones->loot.clear();
- if (BattleGround *bg = GetBattleGround())
- if (bg->GetTypeID() == BATTLEGROUND_AV)
- loot->FillLoot(1, LootTemplates_Creature, this, true);
- // It may need a better formula
- // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
- bones->loot.gold = uint32(urand(50, 150) * 0.016f * pow(float(pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY));
- }
-
- if (bones->lootRecipient != this)
- permission = NONE_PERMISSION;
- }
- else
- {
- Creature *creature = GetMap()->GetCreature(guid);
-
- // must be in range and creature must be alive for pickpocket and must be dead for another loot
- if (!creature || creature->isAlive() != (loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
- {
- SendLootRelease(guid);
- return;
- }
-
- if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
- {
- SendLootRelease(guid);
- return;
- }
-
- loot = &creature->loot;
-
- if (loot_type == LOOT_PICKPOCKETING)
- {
- if (!creature->lootForPickPocketed)
- {
- creature->lootForPickPocketed = true;
- loot->clear();
-
- if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
- loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
-
- // Generate extra money for pick pocket loot
- const uint32 a = urand(0, creature->getLevel()/2);
- const uint32 b = urand(0, getLevel()/2);
- loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
- }
- }
- else
- {
- // the player whose group may loot the corpse
- Player *recipient = creature->GetLootRecipient();
- if (!recipient)
- {
- creature->SetLootRecipient(this);
- recipient = this;
- }
-
- if (creature->lootForPickPocketed)
- {
- creature->lootForPickPocketed = false;
- loot->clear();
- }
-
- if (!creature->lootForBody)
- {
- creature->lootForBody = true;
- loot->clear();
-
- if (uint32 lootid = creature->GetCreatureInfo()->lootid)
- loot->FillLoot(lootid, LootTemplates_Creature, recipient, false, false, creature->GetLootMode());
-
- loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
-
- if (Group* group = recipient->GetGroup())
- {
- group->UpdateLooterGuid(creature,true);
-
- switch (group->GetLootMethod())
- {
- case GROUP_LOOT:
- // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
- group->GroupLoot(recipient->GetGUID(), loot, creature);
- break;
- case NEED_BEFORE_GREED:
- group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
- break;
- case MASTER_LOOT:
- group->MasterLoot(recipient->GetGUID(), loot, creature);
- break;
- default:
- break;
- }
- }
- }
-
- // possible only if creature->lootForBody && loot->empty() at spell cast check
- if (loot_type == LOOT_SKINNING)
- {
- loot->clear();
- loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
- }
- // set group rights only for loot_type != LOOT_SKINNING
- else
- {
- if(Group* group = GetGroup())
- {
- if (group == recipient->GetGroup())
- {
- if (group->GetLootMethod() == FREE_FOR_ALL)
- permission = ALL_PERMISSION;
- else if (group->GetLooterGuid() == GetGUID())
- {
- if (group->GetLootMethod() == MASTER_LOOT)
- permission = MASTER_PERMISSION;
- else
- permission = ALL_PERMISSION;
- }
- else
- permission = GROUP_PERMISSION;
- }
- else
- permission = NONE_PERMISSION;
- }
- else if (recipient == this)
- permission = ALL_PERMISSION;
- else
- permission = NONE_PERMISSION;
- }
- }
- }
-
- SetLootGUID(guid);
-
- // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
- switch (loot_type)
- {
- case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
- case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
- default: break;
- }
-
- // need know merged fishing/corpse loot type for achievements
- loot->loot_type = loot_type;
-
- WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
-
- data << uint64(guid);
- data << uint8(loot_type);
- data << LootView(*loot, this, permission);
-
- SendDirectMessage(&data);
-
- // add 'this' player as one of the players that are looting 'loot'
- if (permission != NONE_PERMISSION)
- loot->AddLooter(GetGUID());
-
- if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
- SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
-}
-
-void Player::SendNotifyLootMoneyRemoved()
-{
- WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
- GetSession()->SendPacket( &data );
-}
-
-void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
-{
- WorldPacket data(SMSG_LOOT_REMOVED, 1);
- data << uint8(lootSlot);
- GetSession()->SendPacket( &data );
-}
-
-void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
-{
- WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
- data << Field;
- data << Value;
- GetSession()->SendPacket(&data);
-}
-
-void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
-{
- // data depends on zoneid/mapid...
- BattleGround* bg = GetBattleGround();
- uint16 NumberOfFields = 0;
- uint32 mapid = GetMapId();
- OutdoorPvP * pvp = sOutdoorPvPMgr.GetOutdoorPvPToZoneId(zoneid);
-
- sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map: %u, Zone: %u", mapid, zoneid);
-
- // may be exist better way to do this...
- switch (zoneid)
- {
- case 0:
- case 1:
- case 4:
- case 8:
- case 10:
- case 11:
- case 12:
- case 36:
- case 38:
- case 40:
- case 41:
- case 51:
- case 267:
- case 1519:
- case 1537:
- case 2257:
- case 2918:
- NumberOfFields = 8;
- break;
- case 139:
- NumberOfFields = 41;
- break;
- case 1377:
- NumberOfFields = 15;
- break;
- case 2597:
- NumberOfFields = 83;
- break;
- case 3277:
- NumberOfFields = 16;
- break;
- case 3358:
- case 3820:
- NumberOfFields = 40;
- break;
- case 3483:
- NumberOfFields = 27;
- break;
- case 3518:
- NumberOfFields = 39;
- break;
- case 3519:
- NumberOfFields = 38;
- break;
- case 3521:
- NumberOfFields = 37;
- break;
- case 3698:
- case 3702:
- case 3968:
- NumberOfFields = 11;
- break;
- case 4378:
- NumberOfFields = 11;
- break;
- case 3703:
- NumberOfFields = 11;
- break;
- case 4384:
- NumberOfFields = 30;
- break;
- default:
- NumberOfFields = 12;
- break;
- }
-
- WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
- data << uint32(mapid); // mapid
- data << uint32(zoneid); // zone id
- data << uint32(areaid); // area id, new 2.1.0
- data << uint16(NumberOfFields); // count of uint64 blocks
- data << uint32(0x8d8) << uint32(0x0); // 1
- data << uint32(0x8d7) << uint32(0x0); // 2
- data << uint32(0x8d6) << uint32(0x0); // 3
- data << uint32(0x8d5) << uint32(0x0); // 4
- data << uint32(0x8d4) << uint32(0x0); // 5
- data << uint32(0x8d3) << uint32(0x0); // 6
- // 7 1 - Arena season in progress, 0 - end of season
- data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
- // 8 Arena season id
- data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
-
- if(mapid == 530) // Outland
- {
- data << uint32(0x9bf) << uint32(0x0); // 7
- data << uint32(0x9bd) << uint32(0xF); // 8
- data << uint32(0x9bb) << uint32(0xF); // 9
- }
- switch(zoneid)
- {
- case 1:
- case 11:
- case 12:
- case 38:
- case 40:
- case 51:
- case 1519:
- case 1537:
- case 2257:
- break;
- case 139: // EPL
- {
- if(pvp && pvp->GetTypeId() == OUTDOOR_PVP_EP)
- pvp->FillInitialWorldStates(data);
- else
- {
- data << uint32(0x97a) << uint32(0x0); // 10 2426
- data << uint32(0x917) << uint32(0x0); // 11 2327
- data << uint32(0x918) << uint32(0x0); // 12 2328
- data << uint32(0x97b) << uint32(0x32); // 13 2427
- data << uint32(0x97c) << uint32(0x32); // 14 2428
- data << uint32(0x933) << uint32(0x1); // 15 2355
- data << uint32(0x946) << uint32(0x0); // 16 2374
- data << uint32(0x947) << uint32(0x0); // 17 2375
- data << uint32(0x948) << uint32(0x0); // 18 2376
- data << uint32(0x949) << uint32(0x0); // 19 2377
- data << uint32(0x94a) << uint32(0x0); // 20 2378
- data << uint32(0x94b) << uint32(0x0); // 21 2379
- data << uint32(0x932) << uint32(0x0); // 22 2354
- data << uint32(0x934) << uint32(0x0); // 23 2356
- data << uint32(0x935) << uint32(0x0); // 24 2357
- data << uint32(0x936) << uint32(0x0); // 25 2358
- data << uint32(0x937) << uint32(0x0); // 26 2359
- data << uint32(0x938) << uint32(0x0); // 27 2360
- data << uint32(0x939) << uint32(0x1); // 28 2361
- data << uint32(0x930) << uint32(0x1); // 29 2352
- data << uint32(0x93a) << uint32(0x0); // 30 2362
- data << uint32(0x93b) << uint32(0x0); // 31 2363
- data << uint32(0x93c) << uint32(0x0); // 32 2364
- data << uint32(0x93d) << uint32(0x0); // 33 2365
- data << uint32(0x944) << uint32(0x0); // 34 2372
- data << uint32(0x945) << uint32(0x0); // 35 2373
- data << uint32(0x931) << uint32(0x1); // 36 2353
- data << uint32(0x93e) << uint32(0x0); // 37 2366
- data << uint32(0x931) << uint32(0x1); // 38 2367 ?? grey horde not in dbc! send for consistency's sake, and to match field count
- data << uint32(0x940) << uint32(0x0); // 39 2368
- data << uint32(0x941) << uint32(0x0); // 7 2369
- data << uint32(0x942) << uint32(0x0); // 8 2370
- data << uint32(0x943) << uint32(0x0); // 9 2371
- }
- }
- break;
- case 1377: // Silithus
- {
- if (pvp && pvp->GetTypeId() == OUTDOOR_PVP_SI)
- pvp->FillInitialWorldStates(data);
- else
- {
- // states are always shown
- data << uint32(2313) << uint32(0x0); // 7 ally silityst gathered
- data << uint32(2314) << uint32(0x0); // 8 horde silityst gathered
- data << uint32(2317) << uint32(0x0); // 9 max silithyst
- }
- // dunno about these... aq opening event maybe?
- data << uint32(2322) << uint32(0x0); // 10 sandworm N
- data << uint32(2323) << uint32(0x0); // 11 sandworm S
- data << uint32(2324) << uint32(0x0); // 12 sandworm SW
- data << uint32(2325) << uint32(0x0); // 13 sandworm E
- }
- break;
- case 2597: // AV
- if (bg && bg->GetTypeID() == BATTLEGROUND_AV)
- bg->FillInitialWorldStates(data);
- else
- {
- data << uint32(0x7ae) << uint32(0x1); // 7 snowfall n
- data << uint32(0x532) << uint32(0x1); // 8 frostwolfhut hc
- data << uint32(0x531) << uint32(0x0); // 9 frostwolfhut ac
- data << uint32(0x52e) << uint32(0x0); // 10 stormpike firstaid a_a
- data << uint32(0x571) << uint32(0x0); // 11 east frostwolf tower horde assaulted -unused
- data << uint32(0x570) << uint32(0x0); // 12 west frostwolf tower horde assaulted - unused
- data << uint32(0x567) << uint32(0x1); // 13 frostwolfe c
- data << uint32(0x566) << uint32(0x1); // 14 frostwolfw c
- data << uint32(0x550) << uint32(0x1); // 15 irondeep (N) ally
- data << uint32(0x544) << uint32(0x0); // 16 ice grave a_a
- data << uint32(0x536) << uint32(0x0); // 17 stormpike grave h_c
- data << uint32(0x535) << uint32(0x1); // 18 stormpike grave a_c
- data << uint32(0x518) << uint32(0x0); // 19 stoneheart grave a_a
- data << uint32(0x517) << uint32(0x0); // 20 stoneheart grave h_a
- data << uint32(0x574) << uint32(0x0); // 21 1396 unk
- data << uint32(0x573) << uint32(0x0); // 22 iceblood tower horde assaulted -unused
- data << uint32(0x572) << uint32(0x0); // 23 towerpoint horde assaulted - unused
- data << uint32(0x56f) << uint32(0x0); // 24 1391 unk
- data << uint32(0x56e) << uint32(0x0); // 25 iceblood a
- data << uint32(0x56d) << uint32(0x0); // 26 towerp a
- data << uint32(0x56c) << uint32(0x0); // 27 frostwolfe a
- data << uint32(0x56b) << uint32(0x0); // 28 froswolfw a
- data << uint32(0x56a) << uint32(0x1); // 29 1386 unk
- data << uint32(0x569) << uint32(0x1); // 30 iceblood c
- data << uint32(0x568) << uint32(0x1); // 31 towerp c
- data << uint32(0x565) << uint32(0x0); // 32 stoneh tower a
- data << uint32(0x564) << uint32(0x0); // 33 icewing tower a
- data << uint32(0x563) << uint32(0x0); // 34 dunn a
- data << uint32(0x562) << uint32(0x0); // 35 duns a
- data << uint32(0x561) << uint32(0x0); // 36 stoneheart bunker alliance assaulted - unused
- data << uint32(0x560) << uint32(0x0); // 37 icewing bunker alliance assaulted - unused
- data << uint32(0x55f) << uint32(0x0); // 38 dunbaldar south alliance assaulted - unused
- data << uint32(0x55e) << uint32(0x0); // 39 dunbaldar north alliance assaulted - unused
- data << uint32(0x55d) << uint32(0x0); // 40 stone tower d
- data << uint32(0x3c6) << uint32(0x0); // 41 966 unk
- data << uint32(0x3c4) << uint32(0x0); // 42 964 unk
- data << uint32(0x3c2) << uint32(0x0); // 43 962 unk
- data << uint32(0x516) << uint32(0x1); // 44 stoneheart grave a_c
- data << uint32(0x515) << uint32(0x0); // 45 stonheart grave h_c
- data << uint32(0x3b6) << uint32(0x0); // 46 950 unk
- data << uint32(0x55c) << uint32(0x0); // 47 icewing tower d
- data << uint32(0x55b) << uint32(0x0); // 48 dunn d
- data << uint32(0x55a) << uint32(0x0); // 49 duns d
- data << uint32(0x559) << uint32(0x0); // 50 1369 unk
- data << uint32(0x558) << uint32(0x0); // 51 iceblood d
- data << uint32(0x557) << uint32(0x0); // 52 towerp d
- data << uint32(0x556) << uint32(0x0); // 53 frostwolfe d
- data << uint32(0x555) << uint32(0x0); // 54 frostwolfw d
- data << uint32(0x554) << uint32(0x1); // 55 stoneh tower c
- data << uint32(0x553) << uint32(0x1); // 56 icewing tower c
- data << uint32(0x552) << uint32(0x1); // 57 dunn c
- data << uint32(0x551) << uint32(0x1); // 58 duns c
- data << uint32(0x54f) << uint32(0x0); // 59 irondeep (N) horde
- data << uint32(0x54e) << uint32(0x0); // 60 irondeep (N) ally
- data << uint32(0x54d) << uint32(0x1); // 61 mine (S) neutral
- data << uint32(0x54c) << uint32(0x0); // 62 mine (S) horde
- data << uint32(0x54b) << uint32(0x0); // 63 mine (S) ally
- data << uint32(0x545) << uint32(0x0); // 64 iceblood h_a
- data << uint32(0x543) << uint32(0x1); // 65 iceblod h_c
- data << uint32(0x542) << uint32(0x0); // 66 iceblood a_c
- data << uint32(0x540) << uint32(0x0); // 67 snowfall h_a
- data << uint32(0x53f) << uint32(0x0); // 68 snowfall a_a
- data << uint32(0x53e) << uint32(0x0); // 69 snowfall h_c
- data << uint32(0x53d) << uint32(0x0); // 70 snowfall a_c
- data << uint32(0x53c) << uint32(0x0); // 71 frostwolf g h_a
- data << uint32(0x53b) << uint32(0x0); // 72 frostwolf g a_a
- data << uint32(0x53a) << uint32(0x1); // 73 frostwolf g h_c
- data << uint32(0x539) << uint32(0x0); // 74 frostwolf g a_c
- data << uint32(0x538) << uint32(0x0); // 75 stormpike grave h_a
- data << uint32(0x537) << uint32(0x0); // 76 stormpike grave a_a
- data << uint32(0x534) << uint32(0x0); // 77 frostwolf hut h_a
- data << uint32(0x533) << uint32(0x0); // 78 frostwolf hut a_a
- data << uint32(0x530) << uint32(0x0); // 79 stormpike first aid h_a
- data << uint32(0x52f) << uint32(0x0); // 80 stormpike first aid h_c
- data << uint32(0x52d) << uint32(0x1); // 81 stormpike first aid a_c
- }
- break;
- case 3277: // WS
- if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
- bg->FillInitialWorldStates(data);
- else
- {
- data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
- data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
- data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
- data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
- data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
- data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
- data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
- data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
- }
- break;
- case 3358: // AB
- if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
- bg->FillInitialWorldStates(data);
- else
- {
- data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
- data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
- data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
- data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
- data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
- data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
- data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
- data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
- data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
- data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
- data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
- data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
- data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
- data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
- data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
- data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
- data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
- data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
- data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
- data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
- data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
- data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
- data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
- data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
- data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
- data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
- data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
- data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
- data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
- data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
- data << uint32(0x745) << uint32(0x2); // 37 1861 unk
- data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
- }
- break;
- case 3820: // EY
- if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
- bg->FillInitialWorldStates(data);
- else
- {
- data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
- data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
- data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
- data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
- data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
- data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
- data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
- data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
- data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
- data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
- data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
- data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
- data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
- data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
- data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
- data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
- data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
- data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
- data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
- data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
- data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
- data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
- data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
- data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
- data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
- data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
- data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
- data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
- data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
- data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
- data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
- data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
- // and some more ... unknown
- }
- break;
- // any of these needs change! the client remembers the prev setting!
- // ON EVERY ZONE LEAVE, RESET THE OLD ZONE'S WORLD STATE, BUT AT LEAST THE UI STUFF!
- case 3483: // Hellfire Peninsula
- {
- if(pvp && pvp->GetTypeId() == OUTDOOR_PVP_HP)
- pvp->FillInitialWorldStates(data);
- else
- {
- data << uint32(0x9ba) << uint32(0x1); // 10 // add ally tower main gui icon // maybe should be sent only on login?
- data << uint32(0x9b9) << uint32(0x1); // 11 // add horde tower main gui icon // maybe should be sent only on login?
- data << uint32(0x9b5) << uint32(0x0); // 12 // show neutral broken hill icon // 2485
- data << uint32(0x9b4) << uint32(0x1); // 13 // show icon above broken hill // 2484
- data << uint32(0x9b3) << uint32(0x0); // 14 // show ally broken hill icon // 2483
- data << uint32(0x9b2) << uint32(0x0); // 15 // show neutral overlook icon // 2482
- data << uint32(0x9b1) << uint32(0x1); // 16 // show the overlook arrow // 2481
- data << uint32(0x9b0) << uint32(0x0); // 17 // show ally overlook icon // 2480
- data << uint32(0x9ae) << uint32(0x0); // 18 // horde pvp objectives captured // 2478
- data << uint32(0x9ac) << uint32(0x0); // 19 // ally pvp objectives captured // 2476
- data << uint32(2475) << uint32(100); //: ally / horde slider grey area // show only in direct vicinity!
- data << uint32(2474) << uint32(50); //: ally / horde slider percentage, 100 for ally, 0 for horde // show only in direct vicinity!
- data << uint32(2473) << uint32(0); //: ally / horde slider display // show only in direct vicinity!
- data << uint32(0x9a8) << uint32(0x0); // 20 // show the neutral stadium icon // 2472
- data << uint32(0x9a7) << uint32(0x0); // 21 // show the ally stadium icon // 2471
- data << uint32(0x9a6) << uint32(0x1); // 22 // show the horde stadium icon // 2470
- }
- }
- break;
- case 3518:
- {
- if(pvp && pvp->GetTypeId() == OUTDOOR_PVP_NA)
- pvp->FillInitialWorldStates(data);
- else
- {
- data << uint32(2503) << uint32(0x0); // 10
- data << uint32(2502) << uint32(0x0); // 11
- data << uint32(2493) << uint32(0x0); // 12
- data << uint32(2491) << uint32(0x0); // 13
-
- data << uint32(2495) << uint32(0x0); // 14
- data << uint32(2494) << uint32(0x0); // 15
- data << uint32(2497) << uint32(0x0); // 16
-
- data << uint32(2762) << uint32(0x0); // 17
- data << uint32(2662) << uint32(0x0); // 18
- data << uint32(2663) << uint32(0x0); // 19
- data << uint32(2664) << uint32(0x0); // 20
-
- data << uint32(2760) << uint32(0x0); // 21
- data << uint32(2670) << uint32(0x0); // 22
- data << uint32(2668) << uint32(0x0); // 23
- data << uint32(2669) << uint32(0x0); // 24
-
- data << uint32(2761) << uint32(0x0); // 25
- data << uint32(2667) << uint32(0x0); // 26
- data << uint32(2665) << uint32(0x0); // 27
- data << uint32(2666) << uint32(0x0); // 28
-
- data << uint32(2763) << uint32(0x0); // 29
- data << uint32(2659) << uint32(0x0); // 30
- data << uint32(2660) << uint32(0x0); // 31
- data << uint32(2661) << uint32(0x0); // 32
-
- data << uint32(2671) << uint32(0x0); // 33
- data << uint32(2676) << uint32(0x0); // 34
- data << uint32(2677) << uint32(0x0); // 35
- data << uint32(2672) << uint32(0x0); // 36
- data << uint32(2673) << uint32(0x0); // 37
- }
- }
- break;
- case 3519: // Terokkar Forest
- {
- if(pvp && pvp->GetTypeId() == OUTDOOR_PVP_TF)
- pvp->FillInitialWorldStates(data);
- else
- {
- data << uint32(0xa41) << uint32(0x0); // 10 // 2625 capture bar pos
- data << uint32(0xa40) << uint32(0x14); // 11 // 2624 capture bar neutral
- data << uint32(0xa3f) << uint32(0x0); // 12 // 2623 show capture bar
- data << uint32(0xa3e) << uint32(0x0); // 13 // 2622 horde towers controlled
- data << uint32(0xa3d) << uint32(0x5); // 14 // 2621 ally towers controlled
- data << uint32(0xa3c) << uint32(0x0); // 15 // 2620 show towers controlled
- data << uint32(0xa88) << uint32(0x0); // 16 // 2696 SE Neu
- data << uint32(0xa87) << uint32(0x0); // 17 // SE Horde
- data << uint32(0xa86) << uint32(0x0); // 18 // SE Ally
- data << uint32(0xa85) << uint32(0x0); // 19 //S Neu
- data << uint32(0xa84) << uint32(0x0); // 20 S Horde
- data << uint32(0xa83) << uint32(0x0); // 21 S Ally
- data << uint32(0xa82) << uint32(0x0); // 22 NE Neu
- data << uint32(0xa81) << uint32(0x0); // 23 NE Horde
- data << uint32(0xa80) << uint32(0x0); // 24 NE Ally
- data << uint32(0xa7e) << uint32(0x0); // 25 // 2686 N Neu
- data << uint32(0xa7d) << uint32(0x0); // 26 N Horde
- data << uint32(0xa7c) << uint32(0x0); // 27 N Ally
- data << uint32(0xa7b) << uint32(0x0); // 28 NW Ally
- data << uint32(0xa7a) << uint32(0x0); // 29 NW Horde
- data << uint32(0xa79) << uint32(0x0); // 30 NW Neutral
- data << uint32(0x9d0) << uint32(0x5); // 31 // 2512 locked time remaining seconds first digit
- data << uint32(0x9ce) << uint32(0x0); // 32 // 2510 locked time remaining seconds second digit
- data << uint32(0x9cd) << uint32(0x0); // 33 // 2509 locked time remaining minutes
- data << uint32(0x9cc) << uint32(0x0); // 34 // 2508 neutral locked time show
- data << uint32(0xad0) << uint32(0x0); // 35 // 2768 horde locked time show
- data << uint32(0xacf) << uint32(0x1); // 36 // 2767 ally locked time show
- }
- }
- break;
- case 3521: // Zangarmarsh
- {
- if(pvp && pvp->GetTypeId() == OUTDOOR_PVP_ZM)
- pvp->FillInitialWorldStates(data);
- else
- {
- data << uint32(0x9e1) << uint32(0x0); // 10 //2529
- data << uint32(0x9e0) << uint32(0x0); // 11
- data << uint32(0x9df) << uint32(0x0); // 12
- data << uint32(0xa5d) << uint32(0x1); // 13 //2653
- data << uint32(0xa5c) << uint32(0x0); // 14 //2652 east beacon neutral
- data << uint32(0xa5b) << uint32(0x1); // 15 horde
- data << uint32(0xa5a) << uint32(0x0); // 16 ally
- data << uint32(0xa59) << uint32(0x1); // 17 // 2649 Twin spire graveyard horde 12???
- data << uint32(0xa58) << uint32(0x0); // 18 ally 14 ???
- data << uint32(0xa57) << uint32(0x0); // 19 neutral 7???
- data << uint32(0xa56) << uint32(0x0); // 20 // 2646 west beacon neutral
- data << uint32(0xa55) << uint32(0x1); // 21 horde
- data << uint32(0xa54) << uint32(0x0); // 22 ally
- data << uint32(0x9e7) << uint32(0x0); // 23 // 2535
- data << uint32(0x9e6) << uint32(0x0); // 24
- data << uint32(0x9e5) << uint32(0x0); // 25
- data << uint32(0xa00) << uint32(0x0); // 26 // 2560
- data << uint32(0x9ff) << uint32(0x1); // 27
- data << uint32(0x9fe) << uint32(0x0); // 28
- data << uint32(0x9fd) << uint32(0x0); // 29
- data << uint32(0x9fc) << uint32(0x1); // 30
- data << uint32(0x9fb) << uint32(0x0); // 31
- data << uint32(0xa62) << uint32(0x0); // 32 // 2658
- data << uint32(0xa61) << uint32(0x1); // 33
- data << uint32(0xa60) << uint32(0x1); // 34
- data << uint32(0xa5f) << uint32(0x0); // 35
- }
- }
- break;
- case 3698: // Nagrand Arena
- if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
- bg->FillInitialWorldStates(data);
- else
- {
- data << uint32(0xa0f) << uint32(0x0); // 7
- data << uint32(0xa10) << uint32(0x0); // 8
- data << uint32(0xa11) << uint32(0x0); // 9 show
- }
- break;
- case 3702: // Blade's Edge Arena
- if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
- bg->FillInitialWorldStates(data);
- else
- {
- data << uint32(0x9f0) << uint32(0x0); // 7 gold
- data << uint32(0x9f1) << uint32(0x0); // 8 green
- data << uint32(0x9f3) << uint32(0x0); // 9 show
- }
- break;
- case 3968: // Ruins of Lordaeron
- if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
- bg->FillInitialWorldStates(data);
- else
- {
- data << uint32(0xbb8) << uint32(0x0); // 7 gold
- data << uint32(0xbb9) << uint32(0x0); // 8 green
- data << uint32(0xbba) << uint32(0x0); // 9 show
- }
- break;
- case 4378: // Dalaran Sewers
- if (bg && bg->GetTypeID() == BATTLEGROUND_DS)
- bg->FillInitialWorldStates(data);
- else
- {
- data << uint32(3601) << uint32(0x0); // 7 gold
- data << uint32(3600) << uint32(0x0); // 8 green
- data << uint32(3610) << uint32(0x0); // 9 show
- }
- break;
- case 3703: // Shattrath City
- case 4384: // SA
- if (bg && bg->GetTypeID() == BATTLEGROUND_SA)
- bg->FillInitialWorldStates(data);
- else
- {
- // 1-3 A defend, 4-6 H defend, 7-9 unk defend, 1 - ok, 2 - half destroyed, 3 - destroyed
- data << uint32(0xf09) << uint32(0x0); // 7 3849 Gate of Temple
- data << uint32(0xe36) << uint32(0x0); // 8 3638 Gate of Yellow Moon
- data << uint32(0xe27) << uint32(0x0); // 9 3623 Gate of Green Emerald
- data << uint32(0xe24) << uint32(0x0); // 10 3620 Gate of Blue Sapphire
- data << uint32(0xe21) << uint32(0x0); // 11 3617 Gate of Red Sun
- data << uint32(0xe1e) << uint32(0x0); // 12 3614 Gate of Purple Ametyst
-
- data << uint32(0xdf3) << uint32(0x0); // 13 3571 bonus timer (1 - on, 0 - off)
- data << uint32(0xded) << uint32(0x0); // 14 3565 Horde Attacker
- data << uint32(0xdec) << uint32(0x0); // 15 3564 Alliance Attacker
- // End Round (timer), better explain this by example, eg. ends in 19:59 -> A:BC
- data << uint32(0xde9) << uint32(0x0); // 16 3561 C
- data << uint32(0xde8) << uint32(0x0); // 17 3560 B
- data << uint32(0xde7) << uint32(0x0); // 18 3559 A
- data << uint32(0xe35) << uint32(0x0); // 19 3637 East g - Horde control
- data << uint32(0xe34) << uint32(0x0); // 20 3636 West g - Horde control
- data << uint32(0xe33) << uint32(0x0); // 21 3635 South g - Horde control
- data << uint32(0xe32) << uint32(0x0); // 22 3634 East g - Alliance control
- data << uint32(0xe31) << uint32(0x0); // 23 3633 West g - Alliance control
- data << uint32(0xe30) << uint32(0x0); // 24 3632 South g - Alliance control
- data << uint32(0xe2f) << uint32(0x0); // 25 3631 Chamber of Ancients - Horde control
- data << uint32(0xe2e) << uint32(0x0); // 26 3630 Chamber of Ancients - Alliance control
- data << uint32(0xe2d) << uint32(0x0); // 27 3629 Beach1 - Horde control
- data << uint32(0xe2c) << uint32(0x0); // 28 3628 Beach2 - Horde control
- data << uint32(0xe2b) << uint32(0x0); // 29 3627 Beach1 - Alliance control
- data << uint32(0xe2a) << uint32(0x0); // 30 3626 Beach2 - Alliance control
- // and many unks...
- }
- break;
- case 4406: // Ring of Valor
- if (bg && bg->GetTypeID() == BATTLEGROUND_RV)
- bg->FillInitialWorldStates(data);
- else
- {
- data << uint32(0xe10) << uint32(0x0); // 7 gold
- data << uint32(0xe11) << uint32(0x0); // 8 green
- data << uint32(0xe1a) << uint32(0x0); // 9 show
- }
- break;
- default:
- data << uint32(0x914) << uint32(0x0); // 7
- data << uint32(0x913) << uint32(0x0); // 8
- data << uint32(0x912) << uint32(0x0); // 9
- data << uint32(0x915) << uint32(0x0); // 10
- break;
- }
- GetSession()->SendPacket(&data);
-}
-
-uint32 Player::GetXPRestBonus(uint32 xp)
-{
- uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
-
- if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
- rested_bonus = xp;
-
- SetRestBonus( GetRestBonus() - rested_bonus);
-
- sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
- return rested_bonus;
-}
-
-void Player::SetBindPoint(uint64 guid)
-{
- WorldPacket data(SMSG_BINDER_CONFIRM, 8);
- data << uint64(guid);
- GetSession()->SendPacket( &data );
-}
-
-void Player::SendTalentWipeConfirm(uint64 guid)
-{
- WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
- data << uint64(guid);
- uint32 cost = sWorld.getConfig(CONFIG_NO_RESET_TALENT_COST) ? 0 : resetTalentsCost();
- data << cost;
- GetSession()->SendPacket( &data );
-}
-
-void Player::SendPetSkillWipeConfirm()
-{
- Pet* pet = GetPet();
- if (!pet)
- return;
- WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
- data << pet->GetGUID();
- data << uint32(pet->resetTalentsCost());
- GetSession()->SendPacket( &data );
-}
-
-/*********************************************************/
-/*** STORAGE SYSTEM ***/
-/*********************************************************/
-
-void Player::SetVirtualItemSlot( uint8 i, Item* item)
-{
- assert(i < 3);
- if (i < 2 && item)
- {
- if (!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
- return;
- uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
- if (charges == 0)
- return;
- if (charges > 1)
- item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
- else if (charges <= 1)
- {
- ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
- item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
- }
- }
-}
-
-void Player::SetSheath( SheathState sheathed )
-{
- switch (sheathed)
- {
- case SHEATH_STATE_UNARMED: // no prepared weapon
- SetVirtualItemSlot(0,NULL);
- SetVirtualItemSlot(1,NULL);
- SetVirtualItemSlot(2,NULL);
- break;
- case SHEATH_STATE_MELEE: // prepared melee weapon
- {
- SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
- SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
- SetVirtualItemSlot(2,NULL);
- }; break;
- case SHEATH_STATE_RANGED: // prepared ranged weapon
- SetVirtualItemSlot(0,NULL);
- SetVirtualItemSlot(1,NULL);
- SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
- break;
- default:
- SetVirtualItemSlot(0,NULL);
- SetVirtualItemSlot(1,NULL);
- SetVirtualItemSlot(2,NULL);
- break;
- }
- Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
-}
-
-uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
-{
- uint8 pClass = getClass();
-
- uint8 slots[4];
- slots[0] = NULL_SLOT;
- slots[1] = NULL_SLOT;
- slots[2] = NULL_SLOT;
- slots[3] = NULL_SLOT;
- switch (proto->InventoryType)
- {
- case INVTYPE_HEAD:
- slots[0] = EQUIPMENT_SLOT_HEAD;
- break;
- case INVTYPE_NECK:
- slots[0] = EQUIPMENT_SLOT_NECK;
- break;
- case INVTYPE_SHOULDERS:
- slots[0] = EQUIPMENT_SLOT_SHOULDERS;
- break;
- case INVTYPE_BODY:
- slots[0] = EQUIPMENT_SLOT_BODY;
- break;
- case INVTYPE_CHEST:
- slots[0] = EQUIPMENT_SLOT_CHEST;
- break;
- case INVTYPE_ROBE:
- slots[0] = EQUIPMENT_SLOT_CHEST;
- break;
- case INVTYPE_WAIST:
- slots[0] = EQUIPMENT_SLOT_WAIST;
- break;
- case INVTYPE_LEGS:
- slots[0] = EQUIPMENT_SLOT_LEGS;
- break;
- case INVTYPE_FEET:
- slots[0] = EQUIPMENT_SLOT_FEET;
- break;
- case INVTYPE_WRISTS:
- slots[0] = EQUIPMENT_SLOT_WRISTS;
- break;
- case INVTYPE_HANDS:
- slots[0] = EQUIPMENT_SLOT_HANDS;
- break;
- case INVTYPE_FINGER:
- slots[0] = EQUIPMENT_SLOT_FINGER1;
- slots[1] = EQUIPMENT_SLOT_FINGER2;
- break;
- case INVTYPE_TRINKET:
- slots[0] = EQUIPMENT_SLOT_TRINKET1;
- slots[1] = EQUIPMENT_SLOT_TRINKET2;
- break;
- case INVTYPE_CLOAK:
- slots[0] = EQUIPMENT_SLOT_BACK;
- break;
- case INVTYPE_WEAPON:
- {
- slots[0] = EQUIPMENT_SLOT_MAINHAND;
-
- // suggest offhand slot only if know dual wielding
- // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
- if (CanDualWield())
- slots[1] = EQUIPMENT_SLOT_OFFHAND;
- break;
- };
- case INVTYPE_SHIELD:
- slots[0] = EQUIPMENT_SLOT_OFFHAND;
- break;
- case INVTYPE_RANGED:
- slots[0] = EQUIPMENT_SLOT_RANGED;
- break;
- case INVTYPE_2HWEAPON:
- slots[0] = EQUIPMENT_SLOT_MAINHAND;
- if (Item *mhWeapon = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND))
- if (ItemPrototype const *mhWeaponProto = mhWeapon->GetProto())
- if (mhWeaponProto->SubClass == ITEM_SUBCLASS_WEAPON_POLEARM || mhWeaponProto->SubClass == ITEM_SUBCLASS_WEAPON_STAFF)
- {
- const_cast<Player *>(this)->AutoUnequipOffhandIfNeed(true);
- break;
- }
- if (CanDualWield() && CanTitanGrip() && proto->SubClass != ITEM_SUBCLASS_WEAPON_POLEARM && proto->SubClass != ITEM_SUBCLASS_WEAPON_STAFF)
- slots[1] = EQUIPMENT_SLOT_OFFHAND;
- break;
- case INVTYPE_TABARD:
- slots[0] = EQUIPMENT_SLOT_TABARD;
- break;
- case INVTYPE_WEAPONMAINHAND:
- slots[0] = EQUIPMENT_SLOT_MAINHAND;
- break;
- case INVTYPE_WEAPONOFFHAND:
- slots[0] = EQUIPMENT_SLOT_OFFHAND;
- break;
- case INVTYPE_HOLDABLE:
- slots[0] = EQUIPMENT_SLOT_OFFHAND;
- break;
- case INVTYPE_THROWN:
- slots[0] = EQUIPMENT_SLOT_RANGED;
- break;
- case INVTYPE_RANGEDRIGHT:
- slots[0] = EQUIPMENT_SLOT_RANGED;
- break;
- case INVTYPE_BAG:
- slots[0] = INVENTORY_SLOT_BAG_START + 0;
- slots[1] = INVENTORY_SLOT_BAG_START + 1;
- slots[2] = INVENTORY_SLOT_BAG_START + 2;
- slots[3] = INVENTORY_SLOT_BAG_START + 3;
- break;
- case INVTYPE_RELIC:
- {
- switch(proto->SubClass)
- {
- case ITEM_SUBCLASS_ARMOR_LIBRAM:
- if (pClass == CLASS_PALADIN)
- slots[0] = EQUIPMENT_SLOT_RANGED;
- break;
- case ITEM_SUBCLASS_ARMOR_IDOL:
- if (pClass == CLASS_DRUID)
- slots[0] = EQUIPMENT_SLOT_RANGED;
- break;
- case ITEM_SUBCLASS_ARMOR_TOTEM:
- if (pClass == CLASS_SHAMAN)
- slots[0] = EQUIPMENT_SLOT_RANGED;
- break;
- case ITEM_SUBCLASS_ARMOR_MISC:
- if (pClass == CLASS_WARLOCK)
- slots[0] = EQUIPMENT_SLOT_RANGED;
- break;
- case ITEM_SUBCLASS_ARMOR_SIGIL:
- if (pClass == CLASS_DEATH_KNIGHT)
- slots[0] = EQUIPMENT_SLOT_RANGED;
- break;
- }
- break;
- }
- default:
- return NULL_SLOT;
- }
-
- if (slot != NULL_SLOT)
- {
- if (swap || !GetItemByPos(INVENTORY_SLOT_BAG_0, slot))
- for (uint8 i = 0; i < 4; ++i)
- if (slots[i] == slot)
- return slot;
- }
- else
- {
- // search free slot at first
- for (uint8 i = 0; i < 4; ++i)
- if (slots[i] != NULL_SLOT && !GetItemByPos(INVENTORY_SLOT_BAG_0, slots[i]))
- // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
- if(slots[i] != EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
- return slots[i];
-
- // if not found free and can swap return first appropriate from used
- for (uint8 i = 0; i < 4; ++i)
- if (slots[i] != NULL_SLOT && swap)
- return slots[i];
- }
-
- // no free position
- return NULL_SLOT;
-}
-
-uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
-{
- uint32 tempcount = 0;
-
- uint8 res = EQUIP_ERR_OK;
-
- for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
- if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- if (pItem->GetEntry() == item)
- {
- uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
- if (ires == EQUIP_ERR_OK)
- {
- tempcount += pItem->GetCount();
- if (tempcount >= count)
- return EQUIP_ERR_OK;
- }
- else
- res = ires;
- }
-
- for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
- if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i))
- if (pItem->GetEntry() == item)
- {
- tempcount += pItem->GetCount();
- if (tempcount >= count)
- return EQUIP_ERR_OK;
- }
-
- for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
- if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i))
- if (pItem->GetEntry() == item)
- {
- tempcount += pItem->GetCount();
- if(tempcount >= count)
- return EQUIP_ERR_OK;
- }
-
- for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
- if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i))
- for (uint32 j = 0; j < pBag->GetBagSize(); ++j)
- if (Item *pItem = GetItemByPos(i, j))
- if (pItem->GetEntry() == item)
- {
- tempcount += pItem->GetCount();
- if (tempcount >= count)
- return EQUIP_ERR_OK;
- }
-
- // not found req. item count and have unequippable items
- return res;
-}
-
-uint32 Player::GetItemCount(uint32 item, bool inBankAlso, Item* skipItem) const
-{
- uint32 count = 0;
- for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
- if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i))
- if (pItem != skipItem && pItem->GetEntry() == item)
- count += pItem->GetCount();
-
- for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
- if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i))
- if (pItem != skipItem && pItem->GetEntry() == item)
- count += pItem->GetCount();
-
- for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
- if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- count += pBag->GetItemCount(item,skipItem);
-
- if(skipItem && skipItem->GetProto()->GemProperties)
- for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
- if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i))
- if (pItem != skipItem && pItem->GetProto()->Socket[0].Color)
- count += pItem->GetGemCountWithID(item);
-
- if (inBankAlso)
- {
- for (uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
- if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i))
- if (pItem != skipItem && pItem->GetEntry() == item)
- count += pItem->GetCount();
-
- for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
- if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i))
- count += pBag->GetItemCount(item,skipItem);
-
- if (skipItem && skipItem->GetProto()->GemProperties)
- for (uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
- if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- if (pItem != skipItem && pItem->GetProto()->Socket[0].Color)
- count += pItem->GetGemCountWithID(item);
- }
-
- return count;
-}
-
-Item* Player::GetItemByGuid( uint64 guid ) const
-{
- for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
- if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- if (pItem->GetGUID() == guid)
- return pItem;
-
- for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
- if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i))
- if (pItem->GetGUID() == guid)
- return pItem;
-
- for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
- if (Bag *pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- for (uint32 j = 0; j < pBag->GetBagSize(); ++j)
- if (Item* pItem = pBag->GetItemByPos(j))
- if (pItem->GetGUID() == guid)
- return pItem;
-
- for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
- if (Bag *pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- for (uint32 j = 0; j < pBag->GetBagSize(); ++j)
- if (Item* pItem = pBag->GetItemByPos(j))
- if (pItem->GetGUID() == guid)
- return pItem;
-
- return NULL;
-}
-
-Item* Player::GetItemByPos( uint16 pos ) const
-{
- uint8 bag = pos >> 8;
- uint8 slot = pos & 255;
- return GetItemByPos( bag, slot );
-}
-
-Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
-{
- if (bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || (slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END) ))
- return m_items[slot];
- else if ((bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
- || (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END))
- {
- if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag))
- return pBag->GetItemByPos(slot);
- }
- return NULL;
-}
-
-Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable /*= false*/) const
-{
- uint16 slot;
- switch (attackType)
- {
- case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
- case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
- case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
- default: return NULL;
- }
-
- Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, slot);
- if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
- return NULL;
-
- if (!useable)
- return item;
-
- if (item->IsBroken() || IsInFeralForm())
- return NULL;
-
- return item;
-}
-
-Item* Player::GetShield(bool useable) const
-{
- Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
- if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
- return NULL;
-
- if (!useable)
- return item;
-
- if (item->IsBroken())
- return NULL;
-
- return item;
-}
-
-uint8 Player::GetAttackBySlot( uint8 slot )
-{
- switch(slot)
- {
- case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
- case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
- case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
- default: return MAX_ATTACK;
- }
-}
-
-bool Player::IsInventoryPos( uint8 bag, uint8 slot )
-{
- if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
- return true;
- if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
- return true;
- if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
- return true;
- if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
- return true;
- return false;
-}
-
-bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
-{
- if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
- return true;
- if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
- return true;
- return false;
-}
-
-bool Player::IsBankPos( uint8 bag, uint8 slot )
-{
- if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
- return true;
- if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
- return true;
- if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
- return true;
- return false;
-}
-
-bool Player::IsBagPos( uint16 pos )
-{
- uint8 bag = pos >> 8;
- uint8 slot = pos & 255;
- if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
- return true;
- if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
- return true;
- return false;
-}
-
-bool Player::IsValidPos( uint8 bag, uint8 slot )
-{
- // post selected
- if(bag == NULL_BAG)
- return true;
-
- if (bag == INVENTORY_SLOT_BAG_0)
- {
- // any post selected
- if (slot == NULL_SLOT)
- return true;
-
- // equipment
- if (slot < EQUIPMENT_SLOT_END)
- return true;
-
- // bag equip slots
- if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
- return true;
-
- // backpack slots
- if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
- return true;
-
- // keyring slots
- if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
- return true;
-
- // bank main slots
- if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
- return true;
-
- // bank bag slots
- if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
- return true;
-
- return false;
- }
-
- // bag content slots
- if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
- {
- Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
- if(!pBag)
- return false;
-
- // any post selected
- if (slot == NULL_SLOT)
- return true;
-
- return slot < pBag->GetBagSize();
- }
-
- // bank bag content slots
- if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
- {
- Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
- if(!pBag)
- return false;
-
- // any post selected
- if (slot == NULL_SLOT)
- return true;
-
- return slot < pBag->GetBagSize();
- }
-
- // where this?
- return false;
-}
-
-bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
-{
- uint32 tempcount = 0;
- for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
- {
- Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
- if( pItem && pItem->GetEntry() == item )
- {
- tempcount += pItem->GetCount();
- if( tempcount >= count )
- return true;
- }
- }
- for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
- {
- Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
- if( pItem && pItem->GetEntry() == item )
- {
- tempcount += pItem->GetCount();
- if( tempcount >= count )
- return true;
- }
- }
- for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
- {
- if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- {
- for (uint32 j = 0; j < pBag->GetBagSize(); j++)
- {
- Item* pItem = GetItemByPos( i, j );
- if( pItem && pItem->GetEntry() == item )
- {
- tempcount += pItem->GetCount();
- if( tempcount >= count )
- return true;
- }
- }
- }
- }
-
- if(inBankAlso)
- {
- for (uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
- {
- Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
- if( pItem && pItem->GetEntry() == item )
- {
- tempcount += pItem->GetCount();
- if( tempcount >= count )
- return true;
- }
- }
- for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
- {
- if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- {
- for (uint32 j = 0; j < pBag->GetBagSize(); j++)
- {
- Item* pItem = GetItemByPos( i, j );
- if( pItem && pItem->GetEntry() == item )
- {
- tempcount += pItem->GetCount();
- if( tempcount >= count )
- return true;
- }
- }
- }
- }
- }
-
- return false;
-}
-
-bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
-{
- uint32 tempcount = 0;
- for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
- {
- if(i == except_slot)
- continue;
-
- Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
- if( pItem && pItem->GetEntry() == item)
- {
- tempcount += pItem->GetCount();
- if( tempcount >= count )
- return true;
- }
- }
-
- ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
- if (pProto && pProto->GemProperties)
- {
- for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
- {
- if(i == except_slot)
- continue;
-
- Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
- if( pItem && pItem->GetProto()->Socket[0].Color)
- {
- tempcount += pItem->GetGemCountWithID(item);
- if( tempcount >= count )
- return true;
- }
- }
- }
-
- return false;
-}
-
-bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
-{
- uint32 tempcount = 0;
- for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
- {
- if(i == except_slot)
- continue;
-
- Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
- if (!pItem)
- continue;
-
- ItemPrototype const *pProto = pItem->GetProto();
- if (!pProto)
- continue;
-
- if (pProto->ItemLimitCategory == limitCategory)
- {
- tempcount += pItem->GetCount();
- if( tempcount >= count )
- return true;
- }
-
- if( pProto->Socket[0].Color)
- {
- tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
- if( tempcount >= count )
- return true;
- }
- }
-
- return false;
-}
-
-uint8 Player::CountItemWithLimitCategory(uint32 limitCategory, Item* skipItem) const
-{
- uint8 tempcount = 0;
- for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
- {
- Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
- if (!pItem)
- continue;
-
- if (pItem == skipItem)
- continue;
-
- ItemPrototype const *pProto = pItem->GetProto();
- if (pProto && pProto->ItemLimitCategory == limitCategory)
- tempcount += pItem->GetCount();
- }
-
- for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
- {
- Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
- if (!pItem)
- continue;
-
- if (pItem == skipItem)
- continue;
-
- ItemPrototype const *pProto = pItem->GetProto();
- if (pProto && pProto->ItemLimitCategory == limitCategory)
- tempcount += pItem->GetCount();
- }
-
- for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
- {
- Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
- if (!pBag)
- continue;
-
- for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
- {
- Item *pItem = GetItemByPos( i, j );
-
- if (!pItem)
- continue;
-
- if (pItem == skipItem)
- continue;
-
- if (pItem->GetProto()->ItemLimitCategory == limitCategory)
- tempcount += pItem->GetCount();
- }
- }
-
- for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
- {
- Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
- if (!pItem)
- continue;
-
- if (pItem == skipItem)
- continue;
-
- ItemPrototype const *pProto = pItem->GetProto();
- if (pProto && pProto->ItemLimitCategory == limitCategory)
- tempcount += pItem->GetCount();
- }
-
- for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
- {
- Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
- if (!pBag)
- continue;
-
- for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
- {
- Item *pItem = GetItemByPos( i, j );
-
- if(!pItem)
- continue;
-
- if(pItem == skipItem)
- continue;
-
- if(pItem->GetProto()->ItemLimitCategory == limitCategory)
- tempcount += pItem->GetCount();
- }
- }
-
- return tempcount;
-}
-
-uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
-{
- ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
- if (!pProto)
- {
- if(no_space_count)
- *no_space_count = count;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
- }
-
- if (pItem && pItem->m_lootGenerated)
- return EQUIP_ERR_ALREADY_LOOTED;
-
- // no maximum
- if (pProto->MaxCount <= 0 && pProto->ItemLimitCategory == 0 || pProto->MaxCount == 2147483647)
- return EQUIP_ERR_OK;
-
- uint32 curcount;
- if (pProto->ItemLimitCategory)
- curcount = CountItemWithLimitCategory(pProto->ItemLimitCategory,pItem);
- else
- curcount = GetItemCount(pProto->ItemId,true,pItem);
-
- if ((curcount + count > uint32(pProto->MaxCount)) && !(pProto->ItemLimitCategory))
- {
- if (no_space_count)
- *no_space_count = count +curcount - pProto->MaxCount;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
- }
-
- if (pProto->ItemLimitCategory && pProto->Class!=ITEM_CLASS_GEM) // gem have equip check (maybe sort by bonding?)
- {
- ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(pProto->ItemLimitCategory);
- if (!limitEntry)
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
-
- if (curcount + count > limitEntry->maxCount)
- {
- if (no_space_count)
- *no_space_count = count + curcount - limitEntry->maxCount;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; // attempt add too many limit category items
- }
- }
-
- return EQUIP_ERR_OK;
-}
-
-bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
-{
- Item *pItem;
- for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
- {
- pItem = GetUseableItemByPos( INVENTORY_SLOT_BAG_0, i );
- if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
- return true;
- }
- for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
- {
- pItem = GetUseableItemByPos( INVENTORY_SLOT_BAG_0, i );
- if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
- return true;
- }
- for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
- {
- if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- {
- for (uint32 j = 0; j < pBag->GetBagSize(); ++j)
- {
- pItem = GetUseableItemByPos( i, j );
- if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
- return true;
- }
- }
- }
- return false;
-}
-
-uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
-{
- Item* pItem2 = GetItemByPos( bag, slot );
-
- // ignore move item (this slot will be empty at move)
- if (pItem2==pSrcItem)
- pItem2 = NULL;
-
- uint32 need_space;
-
- // empty specific slot - check item fit to slot
- if (!pItem2 || swap)
- {
- if (bag == INVENTORY_SLOT_BAG_0)
- {
- // keyring case
- if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
- return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
-
- // currencytoken case
- if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
- return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
-
- // prevent cheating
- if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
- return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
- }
- else
- {
- Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
- if (!pBag)
- return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
-
- ItemPrototype const* pBagProto = pBag->GetProto();
- if (!pBagProto)
- return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
-
- if (slot >= pBagProto->ContainerSlots)
- return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
-
- if (!ItemCanGoIntoBag(pProto,pBagProto))
- return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
- }
-
- // non empty stack with space
- need_space = pProto->GetMaxStackSize();
- }
- // non empty slot, check item type
- else
- {
- // check item type
- if (pItem2->GetEntry() != pProto->ItemId)
- return EQUIP_ERR_ITEM_CANT_STACK;
-
- // check free space
- if (pItem2->GetCount() >= pProto->GetMaxStackSize())
- return EQUIP_ERR_ITEM_CANT_STACK;
-
- // free stack space or infinity
- need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
- }
-
- if (need_space > count)
- need_space = count;
-
- ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
- if (!newPosition.isContainedIn(dest))
- {
- dest.push_back(newPosition);
- count -= need_space;
- }
- return EQUIP_ERR_OK;
-}
-
-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
-{
- // skip specific bag already processed in first called _CanStoreItem_InBag
- if (bag==skip_bag)
- return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
-
- Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
- if (!pBag)
- return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
-
- ItemPrototype const* pBagProto = pBag->GetProto();
- if (!pBagProto)
- return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
-
- // specialized bag mode or non-specilized
- if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER))
- return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
-
- if (!ItemCanGoIntoBag(pProto,pBagProto))
- return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
-
- for (uint32 j = 0; j < pBag->GetBagSize(); j++)
- {
- // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
- if (j==skip_slot)
- continue;
-
- Item* pItem2 = GetItemByPos( bag, j );
-
- // ignore move item (this slot will be empty at move)
- if (pItem2==pSrcItem)
- pItem2 = NULL;
-
- // if merge skip empty, if !merge skip non-empty
- if ((pItem2!=NULL)!=merge)
- continue;
-
- if (pItem2)
- {
- if (pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
- {
- uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
- if(need_space > count)
- need_space = count;
-
- ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
- if (!newPosition.isContainedIn(dest))
- {
- dest.push_back(newPosition);
- count -= need_space;
-
- if (count==0)
- return EQUIP_ERR_OK;
- }
- }
- }
- else
- {
- uint32 need_space = pProto->GetMaxStackSize();
- if (need_space > count)
- need_space = count;
-
- ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
- if (!newPosition.isContainedIn(dest))
- {
- dest.push_back(newPosition);
- count -= need_space;
-
- if (count==0)
- return EQUIP_ERR_OK;
- }
- }
- }
- return EQUIP_ERR_OK;
-}
-
-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
-{
- for (uint32 j = slot_begin; j < slot_end; j++)
- {
- // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
- if (INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
- continue;
-
- Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
-
- // ignore move item (this slot will be empty at move)
- if (pItem2==pSrcItem)
- pItem2 = NULL;
-
- // if merge skip empty, if !merge skip non-empty
- if ((pItem2!=NULL)!=merge)
- continue;
-
- if (pItem2)
- {
- if (pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
- {
- uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
- if (need_space > count)
- need_space = count;
- ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
- if (!newPosition.isContainedIn(dest))
- {
- dest.push_back(newPosition);
- count -= need_space;
-
- if (count==0)
- return EQUIP_ERR_OK;
- }
- }
- }
- else
- {
- uint32 need_space = pProto->GetMaxStackSize();
- if (need_space > count)
- need_space = count;
-
- ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
- if (!newPosition.isContainedIn(dest))
- {
- dest.push_back(newPosition);
- count -= need_space;
-
- if (count==0)
- return EQUIP_ERR_OK;
- }
- }
- }
- return EQUIP_ERR_OK;
-}
-
-uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
-{
- sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
-
- ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
- if (!pProto)
- {
- if (no_space_count)
- *no_space_count = count;
- return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
- }
-
- if (pItem && pItem->IsBindedNotWith(this))
- {
- if (no_space_count)
- *no_space_count = count;
- return EQUIP_ERR_DONT_OWN_THAT_ITEM;
- }
-
- // check count of items (skip for auto move for same player from bank)
- uint32 no_similar_count = 0; // can't store this amount similar items
- uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
- if (res!=EQUIP_ERR_OK)
- {
- if (count==no_similar_count)
- {
- if (no_space_count)
- *no_space_count = no_similar_count;
- return res;
- }
- count -= no_similar_count;
- }
-
- // in specific slot
- if (bag != NULL_BAG && slot != NULL_SLOT)
- {
- res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
- if (res!=EQUIP_ERR_OK)
- {
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return res;
- }
-
- if (count==0)
- {
- if (no_similar_count==0)
- return EQUIP_ERR_OK;
-
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
- }
- }
-
- // not specific slot or have space for partly store only in specific slot
-
- // in specific bag
- if (bag != NULL_BAG)
- {
- // search stack in bag for merge to
- if (pProto->Stackable != 1)
- {
- if (bag == INVENTORY_SLOT_BAG_0) // inventory
- {
- res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
- if (res!=EQUIP_ERR_OK)
- {
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return res;
- }
-
- if (count==0)
- {
- if (no_similar_count==0)
- return EQUIP_ERR_OK;
-
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
- }
-
- res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
- if (res!=EQUIP_ERR_OK)
- {
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return res;
- }
-
- if (count==0)
- {
- if (no_similar_count==0)
- return EQUIP_ERR_OK;
-
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
- }
- }
- else // equipped bag
- {
- // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
- res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
- if (res!=EQUIP_ERR_OK)
- res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
-
- if (res!=EQUIP_ERR_OK)
- {
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return res;
- }
-
- if (count==0)
- {
- if (no_similar_count==0)
- return EQUIP_ERR_OK;
-
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
- }
- }
- }
-
- // search free slot in bag for place to
- if(bag == INVENTORY_SLOT_BAG_0) // inventory
- {
- // search free slot - keyring case
- if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
- {
- uint32 keyringSize = GetMaxKeyringSize();
- res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
- if (res!=EQUIP_ERR_OK)
- {
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return res;
- }
-
- if (count==0)
- {
- if (no_similar_count==0)
- return EQUIP_ERR_OK;
-
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
- }
-
- res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
- if (res!=EQUIP_ERR_OK)
- {
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return res;
- }
-
- if (count==0)
- {
- if (no_similar_count==0)
- return EQUIP_ERR_OK;
-
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
- }
- }
- else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
- {
- res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
- if (res!=EQUIP_ERR_OK)
- {
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return res;
- }
-
- if (count==0)
- {
- if (no_similar_count==0)
- return EQUIP_ERR_OK;
-
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
- }
- }
-
- res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
- if (res!=EQUIP_ERR_OK)
- {
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return res;
- }
-
- if (count==0)
- {
- if (no_similar_count==0)
- return EQUIP_ERR_OK;
-
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
- }
- }
- else // equipped bag
- {
- res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
- if (res!=EQUIP_ERR_OK)
- res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
-
- if (res!=EQUIP_ERR_OK)
- {
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return res;
- }
-
- if (count==0)
- {
- if (no_similar_count==0)
- return EQUIP_ERR_OK;
-
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
- }
- }
- }
-
- // not specific bag or have space for partly store only in specific bag
-
- // search stack for merge to
- if (pProto->Stackable != 1)
- {
- res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
- if (res!=EQUIP_ERR_OK)
- {
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return res;
- }
-
- if (count==0)
- {
- if (no_similar_count==0)
- return EQUIP_ERR_OK;
-
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
- }
-
- res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
- if (res!=EQUIP_ERR_OK)
- {
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return res;
- }
-
- if (count==0)
- {
- if (no_similar_count==0)
- return EQUIP_ERR_OK;
-
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
- }
-
- if (pProto->BagFamily)
- {
- for (uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
- {
- res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
- if (res!=EQUIP_ERR_OK)
- continue;
-
- if (count==0)
- {
- if (no_similar_count==0)
- return EQUIP_ERR_OK;
-
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
- }
- }
- }
-
- for (uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
- {
- res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
- if (res!=EQUIP_ERR_OK)
- continue;
-
- if (count==0)
- {
- if (no_similar_count==0)
- return EQUIP_ERR_OK;
-
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
- }
- }
- }
-
- // search free slot - special bag case
- if (pProto->BagFamily)
- {
- if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
- {
- uint32 keyringSize = GetMaxKeyringSize();
- res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
- if (res!=EQUIP_ERR_OK)
- {
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return res;
- }
-
- if (count==0)
- {
- if (no_similar_count==0)
- return EQUIP_ERR_OK;
-
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
- }
- }
- else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
- {
- res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
- if (res!=EQUIP_ERR_OK)
- {
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return res;
- }
-
- if (count==0)
- {
- if (no_similar_count==0)
- return EQUIP_ERR_OK;
-
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
- }
- }
-
- for (uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
- {
- res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
- if (res!=EQUIP_ERR_OK)
- continue;
-
- if (count==0)
- {
- if (no_similar_count==0)
- return EQUIP_ERR_OK;
-
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
- }
- }
- }
-
- // search free slot
- res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
- if (res!=EQUIP_ERR_OK)
- {
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return res;
- }
-
- if (count==0)
- {
- if (no_similar_count==0)
- return EQUIP_ERR_OK;
-
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
- }
-
- for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
- {
- res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
- if (res!=EQUIP_ERR_OK)
- continue;
-
- if (count==0)
- {
- if (no_similar_count==0)
- return EQUIP_ERR_OK;
-
- if (no_space_count)
- *no_space_count = count + no_similar_count;
- return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
- }
- }
-
- if (no_space_count)
- *no_space_count = count + no_similar_count;
-
- return EQUIP_ERR_INVENTORY_FULL;
-}
-
-//////////////////////////////////////////////////////////////////////////
-uint8 Player::CanStoreItems( Item **pItems,int count) const
-{
- Item *pItem2;
-
- // fill space table
- int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
- int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
- int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
- int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
-
- memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
- memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
- memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
- memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
-
- for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
- {
- pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
-
- if (pItem2 && !pItem2->IsInTrade())
- {
- inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
- }
- }
-
- for (uint8 i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
- {
- pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
-
- if (pItem2 && !pItem2->IsInTrade())
- {
- inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
- }
- }
-
- for (uint8 i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; i++)
- {
- pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
-
- if (pItem2 && !pItem2->IsInTrade())
- {
- inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
- }
- }
-
- for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
- {
- if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- {
- for (uint32 j = 0; j < pBag->GetBagSize(); j++)
- {
- pItem2 = GetItemByPos( i, j );
- if (pItem2 && !pItem2->IsInTrade())
- {
- inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
- }
- }
- }
- }
-
- // check free space for all items
- for (int k = 0; k < count; ++k)
- {
- Item *pItem = pItems[k];
-
- // no item
- if (!pItem) continue;
-
- sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
- ItemPrototype const *pProto = pItem->GetProto();
-
- // strange item
- if( !pProto )
- return EQUIP_ERR_ITEM_NOT_FOUND;
-
- // item it 'bind'
- if(pItem->IsBindedNotWith(this))
- return EQUIP_ERR_DONT_OWN_THAT_ITEM;
-
- Bag *pBag;
- ItemPrototype const *pBagProto;
-
- // item is 'one item only'
- uint8 res = CanTakeMoreSimilarItems(pItem);
- if(res != EQUIP_ERR_OK)
- return res;
-
- // search stack for merge to
- if( pProto->Stackable != 1 )
- {
- bool b_found = false;
-
- for (int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
- {
- pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
- if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
- {
- inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
- b_found = true;
- break;
- }
- }
- if (b_found) continue;
-
- for (int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
- {
- pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
- if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
- {
- inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
- b_found = true;
- break;
- }
- }
- if (b_found) continue;
-
- for (int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
- {
- pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
- if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
- {
- inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
- b_found = true;
- break;
- }
- }
- if (b_found) continue;
-
- for (int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
- {
- pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
- if( pBag && ItemCanGoIntoBag(pItem->GetProto(), pBag->GetProto()))
- {
- for (uint32 j = 0; j < pBag->GetBagSize(); j++)
- {
- pItem2 = GetItemByPos( t, j );
- if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
- {
- inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
- b_found = true;
- break;
- }
- }
- }
- }
- if (b_found) continue;
- }
-
- // special bag case
- if( pProto->BagFamily )
- {
- bool b_found = false;
- if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
- {
- uint32 keyringSize = GetMaxKeyringSize();
- for (uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
- {
- if( inv_keys[t-KEYRING_SLOT_START] == 0 )
- {
- inv_keys[t-KEYRING_SLOT_START] = 1;
- b_found = true;
- break;
- }
- }
- }
-
- if (b_found) continue;
-
- if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
- {
- for (uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
- {
- if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
- {
- inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
- b_found = true;
- break;
- }
- }
- }
-
- if (b_found) continue;
-
- for (int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
- {
- pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
- if( pBag )
- {
- pBagProto = pBag->GetProto();
-
- // not plain container check
- if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
- ItemCanGoIntoBag(pProto,pBagProto) )
- {
- for (uint32 j = 0; j < pBag->GetBagSize(); j++)
- {
- if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
- {
- inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
- b_found = true;
- break;
- }
- }
- }
- }
- }
- if (b_found) continue;
- }
-
- // search free slot
- bool b_found = false;
- for (int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
- {
- if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
- {
- inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
- b_found = true;
- break;
- }
- }
- if (b_found) continue;
-
- // search free slot in bags
- for (int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
- {
- pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
- if( pBag )
- {
- pBagProto = pBag->GetProto();
-
- // special bag already checked
- if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
- continue;
-
- for (uint32 j = 0; j < pBag->GetBagSize(); j++)
- {
- if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
- {
- inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
- b_found = true;
- break;
- }
- }
- }
- }
-
- // no free slot found?
- if (!b_found)
- return EQUIP_ERR_INVENTORY_FULL;
- }
-
- return EQUIP_ERR_OK;
-}
-
-//////////////////////////////////////////////////////////////////////////
-uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
-{
- dest = 0;
- Item *pItem = Item::CreateItem( item, 1, this );
- if( pItem )
- {
- uint8 result = CanEquipItem(slot, dest, pItem, swap );
- delete pItem;
- return result;
- }
-
- return EQUIP_ERR_ITEM_NOT_FOUND;
-}
-
-uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
-{
- dest = 0;
- if( pItem )
- {
- sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
- ItemPrototype const *pProto = pItem->GetProto();
- if( pProto )
- {
- if(pItem->IsBindedNotWith(this))
- return EQUIP_ERR_DONT_OWN_THAT_ITEM;
-
- // check count of items (skip for auto move for same player from bank)
- uint8 res = CanTakeMoreSimilarItems(pItem);
- if(res != EQUIP_ERR_OK)
- return res;
-
- // check this only in game
- if(not_loading)
- {
- // May be here should be more stronger checks; STUNNED checked
- // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
- if (hasUnitState(UNIT_STAT_STUNNED))
- return EQUIP_ERR_YOU_ARE_STUNNED;
-
- // do not allow equipping gear except weapons, offhands, projectiles, relics in
- // - combat
- // - in-progress arenas
- if( !pProto->CanChangeEquipStateInCombat() )
- {
- if( isInCombat() )
- return EQUIP_ERR_NOT_IN_COMBAT;
-
- if(BattleGround* bg = GetBattleGround())
- if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
- return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
- }
-
- if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
- return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
-
- if(IsNonMeleeSpellCasted(false))
- return EQUIP_ERR_CANT_DO_RIGHT_NOW;
- }
-
- ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0;
- // 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)
- if (ssd && ssd->MaxLevel < DEFAULT_MAX_LEVEL && ssd->MaxLevel < getLevel())
- return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
-
- uint8 eslot = FindEquipSlot( pProto, slot, swap );
- if (eslot == NULL_SLOT)
- return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
-
- uint8 msg = CanUseItem(pItem , not_loading);
- if (msg != EQUIP_ERR_OK)
- return msg;
- if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
- return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
-
- // if swap ignore item (equipped also)
- if (uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
- return res2;
-
- // check unique-equipped special item classes
- if (pProto->Class == ITEM_CLASS_QUIVER)
- {
- for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
- {
- if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- {
- if (pBag != pItem)
- {
- if (ItemPrototype const* pBagProto = pBag->GetProto())
- {
- if (pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot))
- return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
- ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
- : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
- }
- }
- }
- }
- }
-
- uint32 type = pProto->InventoryType;
-
- if (eslot == EQUIPMENT_SLOT_OFFHAND)
- {
- if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
- {
- if (!CanDualWield())
- return EQUIP_ERR_CANT_DUAL_WIELD;
- }
- else if (type == INVTYPE_2HWEAPON)
- {
- if (!CanDualWield() || !CanTitanGrip())
- return EQUIP_ERR_CANT_DUAL_WIELD;
- }
-
- if (IsTwoHandUsed())
- return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
- }
-
- // equip two-hand weapon case (with possible unequip 2 items)
- if (type == INVTYPE_2HWEAPON)
- {
- if (eslot == EQUIPMENT_SLOT_OFFHAND)
- {
- if (!CanTitanGrip())
- return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
- }
- else if (eslot != EQUIPMENT_SLOT_MAINHAND)
- return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
-
- if (!CanTitanGrip())
- {
- // offhand item must can be stored in inventory for offhand item and it also must be unequipped
- Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
- ItemPosCountVec off_dest;
- if (offItem && (!not_loading ||
- CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
- CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ))
- return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
- }
- }
- dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
- return EQUIP_ERR_OK;
- }
- }
-
- return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
-}
-
-uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
-{
- // Applied only to equipped items and bank bags
- if(!IsEquipmentPos(pos) && !IsBagPos(pos))
- return EQUIP_ERR_OK;
-
- Item* pItem = GetItemByPos(pos);
-
- // Applied only to existed equipped item
- if( !pItem )
- return EQUIP_ERR_OK;
-
- sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
-
- ItemPrototype const *pProto = pItem->GetProto();
- if( !pProto )
- return EQUIP_ERR_ITEM_NOT_FOUND;
-
- // do not allow unequipping gear except weapons, offhands, projectiles, relics in
- // - combat
- // - in-progress arenas
- if( !pProto->CanChangeEquipStateInCombat() )
- {
- if( isInCombat() )
- return EQUIP_ERR_NOT_IN_COMBAT;
-
- if(BattleGround* bg = GetBattleGround())
- if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
- return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
- }
-
- if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
- return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
-
- return EQUIP_ERR_OK;
-}
-
-uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
-{
- if (!pItem)
- return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
-
- if (pItem->m_lootGenerated)
- {
- GetSession()->DoLootRelease(GetLootGUID());
- return EQUIP_ERR_OK;
- }
-
- uint32 count = pItem->GetCount();
-
- sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
- ItemPrototype const *pProto = pItem->GetProto();
- if (!pProto)
- return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
-
- if (pItem->IsBindedNotWith(this))
- return EQUIP_ERR_DONT_OWN_THAT_ITEM;
-
- // check count of items (skip for auto move for same player from bank)
- uint8 res = CanTakeMoreSimilarItems(pItem);
- if (res != EQUIP_ERR_OK)
- return res;
-
- // in specific slot
- if (bag != NULL_BAG && slot != NULL_SLOT)
- {
- if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
- {
- if (!pItem->IsBag())
- return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
-
- if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
- return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
-
- if (uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK)
- return cantuse;
- }
-
- res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
- if (res!=EQUIP_ERR_OK)
- return res;
-
- if (count==0)
- return EQUIP_ERR_OK;
- }
-
- // not specific slot or have space for partly store only in specific slot
-
- // in specific bag
- if( bag != NULL_BAG )
- {
- if( pProto->InventoryType == INVTYPE_BAG )
- {
- Bag *pBag = (Bag*)pItem;
- if( pBag && !pBag->IsEmpty() )
- return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
- }
-
- // search stack in bag for merge to
- if( pProto->Stackable != 1 )
- {
- if( bag == INVENTORY_SLOT_BAG_0 )
- {
- res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
- if(res!=EQUIP_ERR_OK)
- return res;
-
- if(count==0)
- return EQUIP_ERR_OK;
- }
- else
- {
- res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
- if(res!=EQUIP_ERR_OK)
- res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
-
- if(res!=EQUIP_ERR_OK)
- return res;
-
- if(count==0)
- return EQUIP_ERR_OK;
- }
- }
-
- // search free slot in bag
- if( bag == INVENTORY_SLOT_BAG_0 )
- {
- res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
- if(res!=EQUIP_ERR_OK)
- return res;
-
- if(count==0)
- return EQUIP_ERR_OK;
- }
- else
- {
- res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
- if(res != EQUIP_ERR_OK)
- res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
-
- if(res != EQUIP_ERR_OK)
- return res;
-
- if(count == 0)
- return EQUIP_ERR_OK;
- }
- }
-
- // not specific bag or have space for partly store only in specific bag
-
- // search stack for merge to
- if( pProto->Stackable != 1 )
- {
- // in slots
- res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
- if(res != EQUIP_ERR_OK)
- return res;
-
- if(count == 0)
- return EQUIP_ERR_OK;
-
- // in special bags
- if( pProto->BagFamily )
- {
- for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
- {
- res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
- if(res!=EQUIP_ERR_OK)
- continue;
-
- if(count==0)
- return EQUIP_ERR_OK;
- }
- }
-
- for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
- {
- res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
- if(res!=EQUIP_ERR_OK)
- continue;
-
- if(count==0)
- return EQUIP_ERR_OK;
- }
- }
-
- // search free place in special bag
- if( pProto->BagFamily )
- {
- for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
- {
- res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
- if(res!=EQUIP_ERR_OK)
- continue;
-
- if(count==0)
- return EQUIP_ERR_OK;
- }
- }
-
- // search free space
- res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
- if(res!=EQUIP_ERR_OK)
- return res;
-
- if(count==0)
- return EQUIP_ERR_OK;
-
- for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
- {
- res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
- if(res!=EQUIP_ERR_OK)
- continue;
-
- if(count==0)
- return EQUIP_ERR_OK;
- }
- return EQUIP_ERR_BANK_FULL;
-}
-
-uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
-{
- if (pItem)
- {
- sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
-
- if (!isAlive() && not_loading)
- return EQUIP_ERR_YOU_ARE_DEAD;
-
- //if (isStunned())
- // return EQUIP_ERR_YOU_ARE_STUNNED;
-
- ItemPrototype const *pProto = pItem->GetProto();
- if (pProto)
- {
- if (pItem->IsBindedNotWith(this))
- return EQUIP_ERR_DONT_OWN_THAT_ITEM;
-
- if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0)
- return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
-
- if (pItem->GetSkill() != 0)
- {
- bool allowEquip = false;
- uint32 itemSkill = pItem->GetSkill();
- // Armor that is binded to account can "morph" from plate to mail, etc. if skill is not learned yet.
- if (pProto->Quality == ITEM_QUALITY_HEIRLOOM && pProto->Class == ITEM_CLASS_ARMOR && !HasSkill(itemSkill))
- {
- // TODO: when you right-click already equipped item it throws EQUIP_ERR_NO_REQUIRED_PROFICIENCY.
-
- // In fact it's a visual bug, everything works properly... I need sniffs of operations with
- // binded to account items from off server.
-
- switch (this->getClass())
- {
- case CLASS_HUNTER:
- case CLASS_SHAMAN:
- allowEquip = (itemSkill == SKILL_MAIL);
- break;
- case CLASS_PALADIN:
- allowEquip = (itemSkill == SKILL_PLATE_MAIL);
- break;
- }
- }
- if (!allowEquip && GetSkillValue(itemSkill) == 0)
- return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
- }
-
- if (pProto->RequiredSkill != 0)
- {
- if (GetSkillValue( pProto->RequiredSkill ) == 0)
- return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
-
- if (GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank)
- return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
- }
-
- if (pProto->RequiredSpell != 0 && !HasSpell(pProto->RequiredSpell))
- return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
-
- if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
- return EQUIP_ERR_CANT_EQUIP_REPUTATION;
-
- if (getLevel() < pProto->RequiredLevel)
- return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
-
- return EQUIP_ERR_OK;
- }
- }
- return EQUIP_ERR_ITEM_NOT_FOUND;
-}
-
-bool Player::CanUseItem( ItemPrototype const *pProto )
-{
- // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
-
- if( pProto )
- {
- if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
- return false;
- if( pProto->RequiredSkill != 0 )
- {
- if( GetSkillValue( pProto->RequiredSkill ) == 0 )
- return false;
- else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
- return false;
- }
- if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
- return false;
- if( getLevel() < pProto->RequiredLevel )
- return false;
- return true;
- }
- return false;
-}
-
-uint8 Player::CanUseAmmo( uint32 item ) const
-{
- sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
- if( !isAlive() )
- return EQUIP_ERR_YOU_ARE_DEAD;
- //if( isStunned() )
- // return EQUIP_ERR_YOU_ARE_STUNNED;
- ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
- if( pProto )
- {
- if( pProto->InventoryType!= INVTYPE_AMMO )
- return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
- if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
- return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
- if( pProto->RequiredSkill != 0 )
- {
- if( GetSkillValue( pProto->RequiredSkill ) == 0 )
- return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
- else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
- return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
- }
- if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
- return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
- /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
- return EQUIP_ERR_CANT_EQUIP_REPUTATION;
- */
- if( getLevel() < pProto->RequiredLevel )
- return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
-
- // Requires No Ammo
- if(HasAura(46699))
- return EQUIP_ERR_BAG_FULL6;
-
- return EQUIP_ERR_OK;
- }
- return EQUIP_ERR_ITEM_NOT_FOUND;
-}
-
-void Player::SetAmmo( uint32 item )
-{
- if(!item)
- return;
-
- // already set
- if( GetUInt32Value(PLAYER_AMMO_ID) == item )
- return;
-
- // check ammo
- if(item)
- {
- uint8 msg = CanUseAmmo( item );
- if( msg != EQUIP_ERR_OK )
- {
- SendEquipError( msg, NULL, NULL );
- return;
- }
- }
-
- SetUInt32Value(PLAYER_AMMO_ID, item);
-
- _ApplyAmmoBonuses();
-}
-
-void Player::RemoveAmmo()
-{
- SetUInt32Value(PLAYER_AMMO_ID, 0);
-
- m_ammoDPS = 0.0f;
-
- if(CanModifyStats())
- UpdateDamagePhysical(RANGED_ATTACK);
-}
-
-// Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
-Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
-{
- uint32 count = 0;
- for (ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
- count += itr->count;
-
- Item *pItem = Item::CreateItem( item, count, this );
- if( pItem )
- {
- ItemAddedQuestCheck( item, count );
- if(randomPropertyId)
- pItem->SetItemRandomProperties(randomPropertyId);
- pItem = StoreItem( dest, pItem, update );
- }
- return pItem;
-}
-
-Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
-{
- if( !pItem )
- return NULL;
-
- Item* lastItem = pItem;
- uint32 entry = pItem->GetEntry();
- for (ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end();)
- {
- uint16 pos = itr->pos;
- uint32 count = itr->count;
-
- ++itr;
-
- if(itr == dest.end())
- {
- lastItem = _StoreItem(pos,pItem,count,false,update);
- break;
- }
-
- lastItem = _StoreItem(pos,pItem,count,true,update);
- }
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
- return lastItem;
-}
-
-// Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
-Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
-{
- if( !pItem )
- return NULL;
-
- uint8 bag = pos >> 8;
- uint8 slot = pos & 255;
-
- sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u, guid = %u", bag, slot, pItem->GetEntry(), count, pItem->GetGUIDLow());
-
- Item *pItem2 = GetItemByPos( bag, slot );
-
- if (!pItem2)
- {
- if (clone)
- pItem = pItem->CloneItem(count, this);
- else
- pItem->SetCount(count);
-
- if (!pItem)
- return NULL;
-
- if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
- pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
- (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
- pItem->SetBinding( true );
-
- if (bag == INVENTORY_SLOT_BAG_0)
- {
- m_items[slot] = pItem;
- SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
- pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
- pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
-
- pItem->SetSlot( slot );
- pItem->SetContainer( NULL );
-
- // need update known currency
- if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
- UpdateKnownCurrencies(pItem->GetEntry(), true);
-
- if (IsInWorld() && update)
- {
- pItem->AddToWorld();
- pItem->SendUpdateToPlayer( this );
- }
-
- pItem->SetState(ITEM_CHANGED, this);
- }
- else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
- {
- pBag->StoreItem( slot, pItem, update );
- if( IsInWorld() && update )
- {
- pItem->AddToWorld();
- pItem->SendUpdateToPlayer( this );
- }
- pItem->SetState(ITEM_CHANGED, this);
- pBag->SetState(ITEM_CHANGED, this);
- }
-
- AddEnchantmentDurations(pItem);
- AddItemDurations(pItem);
-
- return pItem;
- }
- else
- {
- if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
- pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
- (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
- pItem2->SetBinding( true );
-
- pItem2->SetCount( pItem2->GetCount() + count );
- if (IsInWorld() && update)
- pItem2->SendUpdateToPlayer( this );
-
- if (!clone)
- {
- // delete item (it not in any slot currently)
- if (IsInWorld() && update)
- {
- pItem->RemoveFromWorld();
- pItem->DestroyForPlayer( this );
- }
-
- RemoveEnchantmentDurations(pItem);
- RemoveItemDurations(pItem);
-
- pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
- pItem->SetState(ITEM_REMOVED, this);
- }
-
- // AddItemDurations(pItem2); - pItem2 already have duration listed for player
- AddEnchantmentDurations(pItem2);
-
- pItem2->SetState(ITEM_CHANGED, this);
-
- return pItem2;
- }
-}
-
-Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
-{
- if (Item *pItem = Item::CreateItem( item, 1, this ))
- {
- ItemAddedQuestCheck( item, 1 );
- return EquipItem( pos, pItem, update );
- }
-
- return NULL;
-}
-
-Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
-{
- AddEnchantmentDurations(pItem);
- AddItemDurations(pItem);
-
- uint8 bag = pos >> 8;
- uint8 slot = pos & 255;
-
- Item *pItem2 = GetItemByPos( bag, slot );
-
- if( !pItem2 )
- {
- VisualizeItem( slot, pItem);
-
- if(isAlive())
- {
- ItemPrototype const *pProto = pItem->GetProto();
-
- // item set bonuses applied only at equip and removed at unequip, and still active for broken items
- if(pProto && pProto->ItemSet)
- AddItemsSetItem(this, pItem);
-
- _ApplyItemMods(pItem, slot, true);
-
- if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
- {
- uint32 cooldownSpell = 6119;
-
- if (getClass() == CLASS_ROGUE)
- cooldownSpell = 6123;
-
- SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
-
- if (!spellProto)
- sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
- else
- {
- m_weaponChangeTimer = spellProto->StartRecoveryTime;
-
- WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
- data << uint64(GetGUID());
- data << uint8(1);
- data << uint32(cooldownSpell);
- data << uint32(0);
- GetSession()->SendPacket(&data);
- }
- }
- }
-
- if( IsInWorld() && update )
- {
- pItem->AddToWorld();
- pItem->SendUpdateToPlayer( this );
- }
-
- ApplyEquipCooldown(pItem);
-
- // update expertise and armor penetration - passive auras may need it
-
- if( slot == EQUIPMENT_SLOT_MAINHAND )
- UpdateExpertise(BASE_ATTACK);
-
- else if( slot == EQUIPMENT_SLOT_OFFHAND )
- UpdateExpertise(OFF_ATTACK);
-
- switch(slot)
- {
- case EQUIPMENT_SLOT_MAINHAND:
- case EQUIPMENT_SLOT_OFFHAND:
- case EQUIPMENT_SLOT_RANGED:
- RecalculateRating(CR_ARMOR_PENETRATION);
- default:
- break;
- }
- }
- else
- {
- pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
- if( IsInWorld() && update )
- pItem2->SendUpdateToPlayer( this );
-
- // delete item (it not in any slot currently)
- //pItem->DeleteFromDB();
- if( IsInWorld() && update )
- {
- pItem->RemoveFromWorld();
- pItem->DestroyForPlayer( this );
- }
-
- RemoveEnchantmentDurations(pItem);
- RemoveItemDurations(pItem);
-
- pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
- pItem->SetState(ITEM_REMOVED, this);
- pItem2->SetState(ITEM_CHANGED, this);
-
- ApplyEquipCooldown(pItem2);
-
- return pItem2;
- }
-
- // only for full equip instead adding to stack
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, pItem->GetEntry(), slot);
-
- return pItem;
-}
-
-void Player::QuickEquipItem( uint16 pos, Item *pItem)
-{
- if( pItem )
- {
- AddEnchantmentDurations(pItem);
- AddItemDurations(pItem);
-
- uint8 slot = pos & 255;
- VisualizeItem( slot, pItem);
-
- if( IsInWorld() )
- {
- pItem->AddToWorld();
- pItem->SendUpdateToPlayer( this );
- }
-
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, pItem->GetEntry(), slot);
- }
-}
-
-void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
-{
- if(pItem)
- {
- SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
- SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
- SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT));
- }
- else
- {
- SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
- SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
- }
-}
-
-void Player::VisualizeItem( uint8 slot, Item *pItem)
-{
- if(!pItem)
- return;
-
- // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
- if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
- pItem->SetBinding( true );
-
- sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
-
- m_items[slot] = pItem;
- SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
- pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
- pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
- pItem->SetSlot( slot );
- pItem->SetContainer( NULL );
-
- if( slot < EQUIPMENT_SLOT_END )
- SetVisibleItemSlot(slot, pItem);
-
- pItem->SetState(ITEM_CHANGED, this);
-}
-
-void Player::RemoveItem(uint8 bag, uint8 slot, bool update)
-{
- // note: removeitem does not actually change the item
- // it only takes the item out of storage temporarily
- // note2: if removeitem is to be used for delinking
- // the item must be removed from the player's updatequeue
-
- Item *pItem = GetItemByPos(bag, slot);
- if (pItem)
- {
- sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
-
- RemoveEnchantmentDurations(pItem);
- RemoveItemDurations(pItem);
-
- if (bag == INVENTORY_SLOT_BAG_0)
- {
- if (slot < INVENTORY_SLOT_BAG_END)
- {
- ItemPrototype const *pProto = pItem->GetProto();
- // item set bonuses applied only at equip and removed at unequip, and still active for broken items
-
- if(pProto && pProto->ItemSet)
- RemoveItemsSetItem(this, pProto);
-
- _ApplyItemMods(pItem, slot, false);
-
- // remove item dependent auras and casts (only weapon and armor slots)
- if(slot < EQUIPMENT_SLOT_END)
- {
- RemoveItemDependentAurasAndCasts(pItem);
-
- // remove held enchantments, update expertise
- if (slot == EQUIPMENT_SLOT_MAINHAND)
- {
- if (pItem->GetItemSuffixFactor())
- {
- pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
- pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
- }
- else
- {
- pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
- pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
- }
-
- UpdateExpertise(BASE_ATTACK);
- }
- else if (slot == EQUIPMENT_SLOT_OFFHAND)
- UpdateExpertise(OFF_ATTACK);
- // update armor penetration - passive auras may need it
- switch(slot)
- {
- case EQUIPMENT_SLOT_MAINHAND:
- case EQUIPMENT_SLOT_OFFHAND:
- case EQUIPMENT_SLOT_RANGED:
- RecalculateRating(CR_ARMOR_PENETRATION);
- default:
- break;
- }
- }
- }
- // need update known currency
- else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
- UpdateKnownCurrencies(pItem->GetEntry(), false);
-
- m_items[slot] = NULL;
- SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
-
- if (slot < EQUIPMENT_SLOT_END)
- SetVisibleItemSlot(slot, NULL);
- }
- else
- {
- if (Bag *pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, bag))
- pBag->RemoveItem(slot, update);
- }
- pItem->SetUInt64Value(ITEM_FIELD_CONTAINED, 0);
- // pItem->SetUInt64Value(ITEM_FIELD_OWNER, 0); not clear owner at remove (it will be set at store). This used in mail and auction code
- pItem->SetSlot(NULL_SLOT);
- if(IsInWorld() && update)
- pItem->SendUpdateToPlayer(this);
- }
-}
-
-// Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
-void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
-{
- if(Item* it = GetItemByPos(bag,slot))
- {
- ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
- RemoveItem(bag, slot, update);
- it->RemoveFromUpdateQueueOf(this);
- if(it->IsInWorld())
- {
- it->RemoveFromWorld();
- it->DestroyForPlayer(this);
- }
- }
-}
-
-// Common operation need to add item from inventory without delete in trade, guild bank, mail....
-void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
-{
- // update quest counters
- ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
-
- // store item
- Item* pLastItem = StoreItem(dest, pItem, update);
-
- // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
- if(pLastItem == pItem)
- {
- // update owner for last item (this can be original item with wrong owner
- if(pLastItem->GetOwnerGUID() != GetGUID())
- pLastItem->SetOwnerGUID(GetGUID());
-
- // if this original item then it need create record in inventory
- // in case trade we already have item in other player inventory
- pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
- }
-}
-
-void Player::DestroyItem(uint8 bag, uint8 slot, bool update)
-{
- Item *pItem = GetItemByPos(bag, slot);
- if(pItem)
- {
- sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
-
- // start from destroy contained items (only equipped bag can have its)
- if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
- {
- for (uint8 i = 0; i < MAX_BAG_SIZE; ++i)
- DestroyItem(slot, i, update);
- }
-
- if (pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
- CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
-
- RemoveEnchantmentDurations(pItem);
- RemoveItemDurations(pItem);
-
- ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
-
- if (bag == INVENTORY_SLOT_BAG_0)
- {
- SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
-
- // equipment and equipped bags can have applied bonuses
- if (slot < INVENTORY_SLOT_BAG_END)
- {
- ItemPrototype const *pProto = pItem->GetProto();
-
- // item set bonuses applied only at equip and removed at unequip, and still active for broken items
- if (pProto && pProto->ItemSet)
- RemoveItemsSetItem(this, pProto);
-
- _ApplyItemMods(pItem, slot, false);
- }
-
- if ( slot < EQUIPMENT_SLOT_END )
- {
- // remove item dependent auras and casts (only weapon and armor slots)
- RemoveItemDependentAurasAndCasts(pItem);
-
- // update expertise and armor penetration - passive auras may need it
- switch (slot)
- {
- case EQUIPMENT_SLOT_MAINHAND:
- case EQUIPMENT_SLOT_OFFHAND:
- case EQUIPMENT_SLOT_RANGED:
- RecalculateRating(CR_ARMOR_PENETRATION);
- default:
- break;
- }
-
- if (slot == EQUIPMENT_SLOT_MAINHAND)
- UpdateExpertise(BASE_ATTACK);
- else if (slot == EQUIPMENT_SLOT_OFFHAND)
- UpdateExpertise(OFF_ATTACK);
-
- // equipment visual show
- SetVisibleItemSlot(slot, NULL);
- }
- // need update known currency
- else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
- UpdateKnownCurrencies(pItem->GetEntry(), false);
-
- m_items[slot] = NULL;
- }
- else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
- pBag->RemoveItem(slot, update);
-
- if (IsInWorld() && update)
- {
- pItem->RemoveFromWorld();
- pItem->DestroyForPlayer(this);
- }
-
- //pItem->SetOwnerGUID(0);
- pItem->SetUInt64Value(ITEM_FIELD_CONTAINED, 0);
- pItem->SetSlot(NULL_SLOT);
- pItem->SetState(ITEM_REMOVED, this);
- }
-}
-
-void Player::DestroyItemCount(uint32 item, uint32 count, bool update, bool unequip_check)
-{
- sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
- uint32 remcount = 0;
-
- // in inventory
- for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
- {
- if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- {
- if (pItem->GetEntry() == item)
- {
- if (pItem->GetCount() + remcount <= count)
- {
- // all items in inventory can unequipped
- remcount += pItem->GetCount();
- DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
-
- if (remcount >= count)
- return;
- }
- else
- {
- ItemRemovedQuestCheck(pItem->GetEntry(), count - remcount);
- pItem->SetCount(pItem->GetCount() - count + remcount);
- if (IsInWorld() & update)
- pItem->SendUpdateToPlayer( this );
- pItem->SetState(ITEM_CHANGED, this);
- return;
- }
- }
- }
- }
-
- for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
- {
- if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- {
- if (pItem->GetEntry() == item)
- {
- if (pItem->GetCount() + remcount <= count)
- {
- // all keys can be unequipped
- remcount += pItem->GetCount();
- DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
-
- if (remcount >= count)
- return;
- }
- else
- {
- ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
- pItem->SetCount( pItem->GetCount() - count + remcount );
- if (IsInWorld() & update)
- pItem->SendUpdateToPlayer( this );
- pItem->SetState(ITEM_CHANGED, this);
- return;
- }
- }
- }
- }
-
- // in inventory bags
- for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
- {
- if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- {
- for (uint32 j = 0; j < pBag->GetBagSize(); j++)
- {
- if(Item* pItem = pBag->GetItemByPos(j))
- {
- if (pItem->GetEntry() == item)
- {
- // all items in bags can be unequipped
- if (pItem->GetCount() + remcount <= count)
- {
- remcount += pItem->GetCount();
- DestroyItem( i, j, update );
-
- if (remcount >= count)
- return;
- }
- else
- {
- ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
- pItem->SetCount( pItem->GetCount() - count + remcount );
- if (IsInWorld() && update)
- pItem->SendUpdateToPlayer( this );
- pItem->SetState(ITEM_CHANGED, this);
- return;
- }
- }
- }
- }
- }
- }
-
- // in equipment and bag list
- for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
- {
- if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- {
- if (pItem && pItem->GetEntry() == item)
- {
- if (pItem->GetCount() + remcount <= count)
- {
- if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
- {
- remcount += pItem->GetCount();
- DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
-
- if (remcount >= count)
- return;
- }
- }
- else
- {
- ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
- pItem->SetCount( pItem->GetCount() - count + remcount );
- if (IsInWorld() & update)
- pItem->SendUpdateToPlayer( this );
- pItem->SetState(ITEM_CHANGED, this);
- return;
- }
- }
- }
- }
-}
-
-void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
-{
- sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
-
- // in inventory
- for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
- if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
- DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
-
- for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
- if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
- DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
-
- // in inventory bags
- for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
- if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- for (uint32 j = 0; j < pBag->GetBagSize(); j++)
- if (Item* pItem = pBag->GetItemByPos(j))
- if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
- DestroyItem(i, j, update);
-
- // in equipment and bag list
- for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
- if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
- DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
-}
-
-void Player::DestroyConjuredItems( bool update )
-{
- // used when entering arena
- // destroys all conjured items
- sLog.outDebug( "STORAGE: DestroyConjuredItems" );
-
- // in inventory
- for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
- if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- if (pItem->IsConjuredConsumable())
- DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
-
- // in inventory bags
- for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
- if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- for (uint32 j = 0; j < pBag->GetBagSize(); j++)
- if (Item* pItem = pBag->GetItemByPos(j))
- if (pItem->IsConjuredConsumable())
- DestroyItem( i, j, update);
-
- // in equipment and bag list
- for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
- if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- if (pItem->IsConjuredConsumable())
- DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
-}
-
-Item* Player::GetItemByEntry(uint32 entry) const
-{
- // in inventory
- for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
- {
- if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- if (pItem->GetEntry() == entry)
- return pItem;
- }
-
-
- for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
- {
- if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- {
- for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
- {
- if (Item* pItem = pBag->GetItemByPos(j))
- if (pItem->GetEntry()==entry)
- return pItem;
- }
- }
- }
-
-
- for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
- {
- if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- if (pItem->GetEntry()==entry)
- return pItem;
- }
-
- return NULL;
-}
-
-void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
-{
- if(!pItem)
- return;
-
- sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
-
- if( pItem->GetCount() <= count )
- {
- count -= pItem->GetCount();
-
- DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
- }
- else
- {
- ItemRemovedQuestCheck( pItem->GetEntry(), count);
- pItem->SetCount( pItem->GetCount() - count );
- count = 0;
- if( IsInWorld() & update )
- pItem->SendUpdateToPlayer( this );
- pItem->SetState(ITEM_CHANGED, this);
- }
-}
-
-void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
-{
- uint8 srcbag = src >> 8;
- uint8 srcslot = src & 255;
-
- uint8 dstbag = dst >> 8;
- uint8 dstslot = dst & 255;
-
- Item *pSrcItem = GetItemByPos( srcbag, srcslot );
- if( !pSrcItem )
- {
- SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
- return;
- }
-
- // not let split all items (can be only at cheating)
- if(pSrcItem->GetCount() == count)
- {
- SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
- return;
- }
-
- // not let split more existed items (can be only at cheating)
- if(pSrcItem->GetCount() < count)
- {
- SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
- return;
- }
-
- if(pSrcItem->m_lootGenerated) // prevent split looting item (item
- {
- //best error message found for attempting to split while looting
- SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
- return;
- }
-
- sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
- Item *pNewItem = pSrcItem->CloneItem( count, this );
- if( !pNewItem )
- {
- SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
- return;
- }
-
- if( IsInventoryPos( dst ) )
- {
- // change item amount before check (for unique max count check)
- pSrcItem->SetCount( pSrcItem->GetCount() - count );
-
- ItemPosCountVec dest;
- uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
- if( msg != EQUIP_ERR_OK )
- {
- delete pNewItem;
- pSrcItem->SetCount( pSrcItem->GetCount() + count );
- SendEquipError( msg, pSrcItem, NULL );
- return;
- }
-
- if( IsInWorld() )
- pSrcItem->SendUpdateToPlayer( this );
- pSrcItem->SetState(ITEM_CHANGED, this);
- StoreItem( dest, pNewItem, true);
- }
- else if( IsBankPos ( dst ) )
- {
- // change item amount before check (for unique max count check)
- pSrcItem->SetCount( pSrcItem->GetCount() - count );
-
- ItemPosCountVec dest;
- uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
- if( msg != EQUIP_ERR_OK )
- {
- delete pNewItem;
- pSrcItem->SetCount( pSrcItem->GetCount() + count );
- SendEquipError( msg, pSrcItem, NULL );
- return;
- }
-
- if( IsInWorld() )
- pSrcItem->SendUpdateToPlayer( this );
- pSrcItem->SetState(ITEM_CHANGED, this);
- BankItem( dest, pNewItem, true);
- }
- else if( IsEquipmentPos ( dst ) )
- {
- // change item amount before check (for unique max count check), provide space for splitted items
- pSrcItem->SetCount( pSrcItem->GetCount() - count );
-
- uint16 dest;
- uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
- if( msg != EQUIP_ERR_OK )
- {
- delete pNewItem;
- pSrcItem->SetCount( pSrcItem->GetCount() + count );
- SendEquipError( msg, pSrcItem, NULL );
- return;
- }
-
- if( IsInWorld() )
- pSrcItem->SendUpdateToPlayer( this );
- pSrcItem->SetState(ITEM_CHANGED, this);
- EquipItem( dest, pNewItem, true);
- AutoUnequipOffhandIfNeed();
- }
-}
-
-void Player::SwapItem( uint16 src, uint16 dst )
-{
- uint8 srcbag = src >> 8;
- uint8 srcslot = src & 255;
-
- uint8 dstbag = dst >> 8;
- uint8 dstslot = dst & 255;
-
- Item *pSrcItem = GetItemByPos( srcbag, srcslot );
- Item *pDstItem = GetItemByPos( dstbag, dstslot );
-
- if( !pSrcItem )
- return;
-
- sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
-
- if(!isAlive() )
- {
- SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
- return;
- }
-
- // SRC checks
-
- if(pSrcItem->m_lootGenerated) // prevent swap looting item
- {
- //best error message found for attempting to swap while looting
- SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
- return;
- }
-
- // check unequip potability for equipped items and bank bags
- if(IsEquipmentPos ( src ) || IsBagPos ( src ))
- {
- // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
- uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || (pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty()));
- if(msg != EQUIP_ERR_OK)
- {
- SendEquipError( msg, pSrcItem, pDstItem );
- return;
- }
- }
-
- // prevent put equipped/bank bag in self
- if( IsBagPos ( src ) && srcslot == dstbag)
- {
- SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
- return;
- }
-
- // DST checks
-
- if (pDstItem)
- {
- if(pDstItem->m_lootGenerated) // prevent swap looting item
- {
- //best error message found for attempting to swap while looting
- SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
- return;
- }
-
- // check unequip potability for equipped items and bank bags
- if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
- {
- // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
- uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || (pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty()));
- if(msg != EQUIP_ERR_OK)
- {
- SendEquipError( msg, pSrcItem, pDstItem );
- return;
- }
- }
- }
-
- // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
- // or swap empty bag with another empty or not empty bag (with items exchange)
-
- // Move case
- if( !pDstItem )
- {
- if( IsInventoryPos( dst ) )
- {
- ItemPosCountVec dest;
- uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
- if( msg != EQUIP_ERR_OK )
- {
- SendEquipError( msg, pSrcItem, NULL );
- return;
- }
-
- RemoveItem(srcbag, srcslot, true);
- StoreItem( dest, pSrcItem, true);
- }
- else if( IsBankPos ( dst ) )
- {
- ItemPosCountVec dest;
- uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
- if( msg != EQUIP_ERR_OK )
- {
- SendEquipError( msg, pSrcItem, NULL );
- return;
- }
-
- RemoveItem(srcbag, srcslot, true);
- BankItem( dest, pSrcItem, true);
- }
- else if( IsEquipmentPos ( dst ) )
- {
- uint16 dest;
- uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
- if( msg != EQUIP_ERR_OK )
- {
- SendEquipError( msg, pSrcItem, NULL );
- return;
- }
-
- RemoveItem(srcbag, srcslot, true);
- EquipItem(dest, pSrcItem, true);
- AutoUnequipOffhandIfNeed();
- }
-
- return;
- }
-
- // attempt merge to / fill target item
- if(!pSrcItem->IsBag() && !pDstItem->IsBag())
- {
- uint8 msg;
- ItemPosCountVec sDest;
- uint16 eDest;
- if( IsInventoryPos( dst ) )
- msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
- else if( IsBankPos ( dst ) )
- msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
- else if( IsEquipmentPos ( dst ) )
- msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
- else
- return;
-
- // can be merge/fill
- if(msg == EQUIP_ERR_OK)
- {
- if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
- {
- RemoveItem(srcbag, srcslot, true);
-
- if( IsInventoryPos( dst ) )
- StoreItem( sDest, pSrcItem, true);
- else if( IsBankPos ( dst ) )
- BankItem( sDest, pSrcItem, true);
- else if( IsEquipmentPos ( dst ) )
- {
- EquipItem( eDest, pSrcItem, true);
- AutoUnequipOffhandIfNeed();
- }
- }
- else
- {
- pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
- pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
- pSrcItem->SetState(ITEM_CHANGED, this);
- pDstItem->SetState(ITEM_CHANGED, this);
- if( IsInWorld() )
- {
- pSrcItem->SendUpdateToPlayer( this );
- pDstItem->SendUpdateToPlayer( this );
- }
- }
- return;
- }
- }
-
- // impossible merge/fill, do real swap
- uint8 msg;
-
- // check src->dest move possibility
- ItemPosCountVec sDest;
- uint16 eDest = 0;
- if( IsInventoryPos( dst ) )
- msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
- else if( IsBankPos( dst ) )
- msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
- else if( IsEquipmentPos( dst ) )
- {
- msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
- if( msg == EQUIP_ERR_OK )
- msg = CanUnequipItem( eDest, true );
- }
-
- if( msg != EQUIP_ERR_OK )
- {
- SendEquipError( msg, pSrcItem, pDstItem );
- return;
- }
-
- // check dest->src move possibility
- ItemPosCountVec sDest2;
- uint16 eDest2 = 0;
- if( IsInventoryPos( src ) )
- msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
- else if( IsBankPos( src ) )
- msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
- else if( IsEquipmentPos( src ) )
- {
- msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
- if( msg == EQUIP_ERR_OK )
- msg = CanUnequipItem( eDest2, true);
- }
-
- if( msg != EQUIP_ERR_OK )
- {
- SendEquipError( msg, pDstItem, pSrcItem );
- return;
- }
-
- // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
- if(pSrcItem->IsBag() && pDstItem->IsBag())
- {
- Bag* emptyBag = NULL;
- Bag* fullBag = NULL;
- if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
- {
- emptyBag = (Bag*)pSrcItem;
- fullBag = (Bag*)pDstItem;
- }
- else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
- {
- emptyBag = (Bag*)pDstItem;
- fullBag = (Bag*)pSrcItem;
- }
-
- // bag swap (with items exchange) case
- if(emptyBag && fullBag)
- {
- ItemPrototype const* emptyProto = emptyBag->GetProto();
-
- uint32 count = 0;
-
- for (uint32 i=0; i < fullBag->GetBagSize(); ++i)
- {
- Item *bagItem = fullBag->GetItemByPos(i);
- if (!bagItem)
- continue;
-
- ItemPrototype const* bagItemProto = bagItem->GetProto();
- if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emptyProto))
- {
- // one from items not go to empty target bag
- SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
- return;
- }
-
- ++count;
- }
-
- if (count > emptyBag->GetBagSize())
- {
- // too small targeted bag
- SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
- return;
- }
-
- // Items swap
- count = 0; // will pos in new bag
- for (uint32 i = 0; i< fullBag->GetBagSize(); ++i)
- {
- Item *bagItem = fullBag->GetItemByPos(i);
- if (!bagItem)
- continue;
-
- fullBag->RemoveItem(i, true);
- emptyBag->StoreItem(count, bagItem, true);
- bagItem->SetState(ITEM_CHANGED, this);
-
- ++count;
- }
- }
- }
-
- // now do moves, remove...
- RemoveItem(dstbag, dstslot, false);
- RemoveItem(srcbag, srcslot, false);
-
- // add to dest
- if (IsInventoryPos(dst))
- StoreItem(sDest, pSrcItem, true);
- else if (IsBankPos(dst))
- BankItem(sDest, pSrcItem, true);
- else if (IsEquipmentPos(dst))
- EquipItem(eDest, pSrcItem, true);
-
- // add to src
- if (IsInventoryPos(src))
- StoreItem(sDest2, pDstItem, true);
- else if (IsBankPos(src))
- BankItem(sDest2, pDstItem, true);
- else if (IsEquipmentPos(src))
- EquipItem(eDest2, pDstItem, true);
-
- // if player is moving bags and is looting an item inside this bag
- // release the loot
- if (GetLootGUID())
- {
- bool released = false;
- if (IsBagPos(src))
- {
- Bag* bag = (Bag*)pSrcItem;
- for(int i=0; i < bag->GetBagSize(); ++i)
- {
- if (Item *bagItem = bag->GetItemByPos(i))
- {
- if (bagItem->m_lootGenerated)
- {
- m_session->DoLootRelease(GetLootGUID());
- released = true; // so we don't need to look at dstBag
- break;
- }
- }
- }
- }
-
- if (!released && IsBagPos(dst) && pDstItem)
- {
- Bag* bag = (Bag*)pDstItem;
- for(int i=0; i < bag->GetBagSize(); ++i)
- {
- if (Item *bagItem = bag->GetItemByPos(i))
- {
- if (bagItem->m_lootGenerated)
- {
- m_session->DoLootRelease(GetLootGUID());
- released = true; // not realy needed here
- break;
- }
- }
- }
- }
- }
-
- AutoUnequipOffhandIfNeed();
-}
-
-void Player::AddItemToBuyBackSlot( Item *pItem )
-{
- if (pItem)
- {
- uint32 slot = m_currentBuybackSlot;
- // if current back slot non-empty search oldest or free
- if (m_items[slot])
- {
- uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
- uint32 oldest_slot = BUYBACK_SLOT_START;
-
- for (uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
- {
- // found empty
- if (!m_items[i])
- {
- slot = i;
- break;
- }
-
- uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
-
- if (oldest_time > i_time)
- {
- oldest_time = i_time;
- oldest_slot = i;
- }
- }
-
- // find oldest
- slot = oldest_slot;
- }
-
- RemoveItemFromBuyBackSlot( slot, true );
- sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
-
- m_items[slot] = pItem;
- time_t base = time(NULL);
- uint32 etime = uint32(base - m_logintime + (30 * 3600));
- uint32 eslot = slot - BUYBACK_SLOT_START;
-
- SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID() );
- if (ItemPrototype const *pProto = pItem->GetProto())
- SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
- else
- SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
- SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
-
- // move to next (for non filled list is move most optimized choice)
- if (m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
- ++m_currentBuybackSlot;
- }
-}
-
-Item* Player::GetItemFromBuyBackSlot( uint32 slot )
-{
- sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
- if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
- return m_items[slot];
- return NULL;
-}
-
-void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
-{
- sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
- if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
- {
- Item *pItem = m_items[slot];
- if (pItem)
- {
- pItem->RemoveFromWorld();
- if(del)
- pItem->SetState(ITEM_REMOVED, this);
- }
-
- m_items[slot] = NULL;
-
- uint32 eslot = slot - BUYBACK_SLOT_START;
- SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0);
- SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0);
- SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0);
-
- // if current backslot is filled set to now free slot
- if(m_items[m_currentBuybackSlot])
- m_currentBuybackSlot = slot;
- }
-}
-
-void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
-{
- sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
- WorldPacket data(SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18));
- data << uint8(msg);
-
- if (msg != EQUIP_ERR_OK)
- {
- data << uint64(pItem ? pItem->GetGUID() : 0);
- data << uint64(pItem2 ? pItem2->GetGUID() : 0);
- data << uint8(0); // not 0 there...
-
- if (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
- {
- uint8 level = 0;
-
- if (pItem)
- if (ItemPrototype const* proto = pItem->GetProto())
- level = proto->RequiredLevel;
-
- data << uint32(level); // new 2.4.0
- }
- }
- GetSession()->SendPacket(&data);
-}
-
-void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
-{
- sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
- WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
- data << uint64(pCreature ? pCreature->GetGUID() : 0);
- data << uint32(item);
- if (param > 0)
- data << uint32(param);
- data << uint8(msg);
- GetSession()->SendPacket(&data);
-}
-
-void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
-{
- sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
- WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
- data << uint64(pCreature ? pCreature->GetGUID() : 0);
- data << uint64(guid);
- if (param > 0)
- data << uint32(param);
- data << uint8(msg);
- GetSession()->SendPacket(&data);
-}
-
-void Player::ClearTrade()
-{
- tradeGold = 0;
- acceptTrade = false;
- for (uint8 i = 0; i < TRADE_SLOT_COUNT; i++)
- tradeItems[i] = 0;
-}
-
-void Player::TradeCancel(bool sendback)
-{
- if (pTrader)
- {
- // send yellow "Trade canceled" message to both traders
- WorldSession* ws;
- ws = GetSession();
- if (sendback)
- ws->SendCancelTrade();
- ws = pTrader->GetSession();
- if (!ws->PlayerLogout())
- ws->SendCancelTrade();
-
- // cleanup
- ClearTrade();
- pTrader->ClearTrade();
- // prevent loss of reference
- pTrader->pTrader = NULL;
- pTrader = NULL;
- }
-}
-
-void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
-{
- if (m_itemDuration.empty())
- return;
-
- sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
-
- for (ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end();)
- {
- Item* item = *itr;
- ++itr; // current element can be erased in UpdateDuration
-
- if ((realtimeonly && item->GetProto()->Duration < 0) || !realtimeonly)
- item->UpdateDuration(this,time);
- }
-}
-
-void Player::UpdateEnchantTime(uint32 time)
-{
- for (EnchantDurationList::iterator itr = m_enchantDuration.begin(),next; itr != m_enchantDuration.end(); itr=next)
- {
- assert(itr->item);
- next = itr;
- if (!itr->item->GetEnchantmentId(itr->slot))
- {
- next = m_enchantDuration.erase(itr);
- }
- else if (itr->leftduration <= time)
- {
- ApplyEnchantment(itr->item, itr->slot, false, false);
- itr->item->ClearEnchantment(itr->slot);
- next = m_enchantDuration.erase(itr);
- }
- else if (itr->leftduration > time)
- {
- itr->leftduration -= time;
- ++next;
- }
- }
-}
-
-void Player::AddEnchantmentDurations(Item *item)
-{
- for (int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
- {
- if (!item->GetEnchantmentId(EnchantmentSlot(x)))
- continue;
-
- uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
- if (duration > 0)
- AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
- }
-}
-
-void Player::RemoveEnchantmentDurations(Item *item)
-{
- for (EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
- {
- if (itr->item == item)
- {
- // save duration in item
- item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
- itr = m_enchantDuration.erase(itr);
- }
- else
- ++itr;
- }
-}
-
-void Player::RemoveArenaEnchantments(EnchantmentSlot slot)
-{
- // remove enchantments from equipped items first to clean up the m_enchantDuration list
- for (EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
- {
- next = itr;
- if (itr->slot == slot)
- {
- if (itr->item && itr->item->GetEnchantmentId(slot))
- {
- // Poisons and DK runes are enchants which are allowed on arenas
- if (spellmgr.IsArenaAllowedEnchancment(itr->item->GetEnchantmentId(slot)))
- {
- ++next;
- continue;
- }
- // remove from stats
- ApplyEnchantment(itr->item, slot, false, false);
- // remove visual
- itr->item->ClearEnchantment(slot);
- }
- // remove from update list
- next = m_enchantDuration.erase(itr);
- }
- else
- ++next;
- }
-
- // remove enchants from inventory items
- // NOTE: no need to remove these from stats, since these aren't equipped
- // in inventory
- for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
- if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
- if (pItem->GetEnchantmentId(slot))
- pItem->ClearEnchantment(slot);
-
- // in inventory bags
- for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
- if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
- for (uint32 j = 0; j < pBag->GetBagSize(); j++)
- if (Item* pItem = pBag->GetItemByPos(j))
- if (pItem->GetEnchantmentId(slot))
- pItem->ClearEnchantment(slot);
-}
-
-// duration == 0 will remove item enchant
-void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
-{
- if (!item)
- return;
-
- if (slot >= MAX_ENCHANTMENT_SLOT)
- return;
-
- for (EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
- {
- if (itr->item == item && itr->slot == slot)
- {
- itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
- m_enchantDuration.erase(itr);
- break;
- }
- }
- if (item && duration > 0 )
- {
- GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
- m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
- }
-}
-
-void Player::ApplyEnchantment(Item *item,bool apply)
-{
- for (uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
- ApplyEnchantment(item, EnchantmentSlot(slot), apply);
-}
-
-void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
-{
- if (!item)
- return;
-
- if (!item->IsEquipped())
- return;
-
- if (!CanUseAttackType(Player::GetAttackBySlot(item->GetSlot())))
- return;
-
- if (slot >= MAX_ENCHANTMENT_SLOT)
- return;
-
- uint32 enchant_id = item->GetEnchantmentId(slot);
- if (!enchant_id)
- return;
-
- SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
- if (!pEnchant)
- return;
-
- if (!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
- return;
-
- if ((pEnchant->requiredLevel) > ((Player*)this)->getLevel())
- return;
-
- if ((pEnchant->requiredSkill) > 0)
- {
- if ((pEnchant->requiredSkillValue) > (((Player*)this)->GetSkillValue(pEnchant->requiredSkill)))
- return;
- }
-
- if (!item->IsBroken())
- {
- for (int s = 0; s < 3; ++s)
- {
- uint32 enchant_display_type = pEnchant->type[s];
- uint32 enchant_amount = pEnchant->amount[s];
- uint32 enchant_spell_id = pEnchant->spellid[s];
-
- switch(enchant_display_type)
- {
- case ITEM_ENCHANTMENT_TYPE_NONE:
- break;
- case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
- // processed in Player::CastItemCombatSpell
- break;
- case ITEM_ENCHANTMENT_TYPE_DAMAGE:
- if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
- HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
- else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
- HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
- else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
- HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
- break;
- case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
- if (enchant_spell_id)
- {
- if (apply)
- {
- int32 basepoints = 0;
- // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
- if (item->GetItemRandomPropertyId())
- {
- ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
- if (item_rand)
- {
- // Search enchant_amount
- for (int k = 0; k < 3; ++k)
- {
- if(item_rand->enchant_id[k] == enchant_id)
- {
- basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
- break;
- }
- }
- }
- }
- // Cast custom spell vs all equal basepoints getted from enchant_amount
- if (basepoints)
- CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
- else
- CastSpell(this, enchant_spell_id, true, item);
- }
- else
- RemoveAurasDueToItemSpell(item, enchant_spell_id);
- }
- break;
- case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
- if (!enchant_amount)
- {
- ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
- if(item_rand)
- {
- for (int k = 0; k < 3; ++k)
- {
- if(item_rand->enchant_id[k] == enchant_id)
- {
- enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
- break;
- }
- }
- }
- }
-
- HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
- break;
- case ITEM_ENCHANTMENT_TYPE_STAT:
- {
- if (!enchant_amount)
- {
- ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
- if(item_rand_suffix)
- {
- for (int k = 0; k < 3; ++k)
- {
- if(item_rand_suffix->enchant_id[k] == enchant_id)
- {
- enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
- break;
- }
- }
- }
- }
-
- sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
- switch (enchant_spell_id)
- {
- case ITEM_MOD_MANA:
- sLog.outDebug("+ %u MANA",enchant_amount);
- HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
- break;
- case ITEM_MOD_HEALTH:
- sLog.outDebug("+ %u HEALTH",enchant_amount);
- HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
- break;
- case ITEM_MOD_AGILITY:
- sLog.outDebug("+ %u AGILITY",enchant_amount);
- HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
- ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
- break;
- case ITEM_MOD_STRENGTH:
- sLog.outDebug("+ %u STRENGTH",enchant_amount);
- HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
- ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
- break;
- case ITEM_MOD_INTELLECT:
- sLog.outDebug("+ %u INTELLECT",enchant_amount);
- HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
- ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
- break;
- case ITEM_MOD_SPIRIT:
- sLog.outDebug("+ %u SPIRIT",enchant_amount);
- HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
- ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
- break;
- case ITEM_MOD_STAMINA:
- sLog.outDebug("+ %u STAMINA",enchant_amount);
- HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
- ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
- break;
- case ITEM_MOD_DEFENSE_SKILL_RATING:
- ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
- sLog.outDebug("+ %u DEFENCE", enchant_amount);
- break;
- case ITEM_MOD_DODGE_RATING:
- ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
- sLog.outDebug("+ %u DODGE", enchant_amount);
- break;
- case ITEM_MOD_PARRY_RATING:
- ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
- sLog.outDebug("+ %u PARRY", enchant_amount);
- break;
- case ITEM_MOD_BLOCK_RATING:
- ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
- sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
- break;
- case ITEM_MOD_HIT_MELEE_RATING:
- ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
- sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
- break;
- case ITEM_MOD_HIT_RANGED_RATING:
- ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
- sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
- break;
- case ITEM_MOD_HIT_SPELL_RATING:
- ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
- sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
- break;
- case ITEM_MOD_CRIT_MELEE_RATING:
- ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
- sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
- break;
- case ITEM_MOD_CRIT_RANGED_RATING:
- ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
- sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
- break;
- case ITEM_MOD_CRIT_SPELL_RATING:
- ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
- sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
- break;
-// Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
-// in Enchantments
-// case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
-// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
-// break;
-// case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
-// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
-// break;
-// case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
-// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
-// break;
-// case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
-// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
-// break;
-// case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
-// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
-// break;
-// case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
-// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
-// break;
-// case ITEM_MOD_HASTE_MELEE_RATING:
-// ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
-// break;
-// case ITEM_MOD_HASTE_RANGED_RATING:
-// ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
-// break;
- case ITEM_MOD_HASTE_SPELL_RATING:
- ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
- break;
- case ITEM_MOD_HIT_RATING:
- ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
- ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
- ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
- sLog.outDebug("+ %u HIT", enchant_amount);
- break;
- case ITEM_MOD_CRIT_RATING:
- ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
- ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
- ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
- sLog.outDebug("+ %u CRITICAL", enchant_amount);
- break;
-// Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
-// case ITEM_MOD_HIT_TAKEN_RATING:
-// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
-// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
-// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
-// break;
-// case ITEM_MOD_CRIT_TAKEN_RATING:
-// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
-// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
-// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
-// break;
- case ITEM_MOD_RESILIENCE_RATING:
- ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
- ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
- ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
- sLog.outDebug("+ %u RESILIENCE", enchant_amount);
- break;
- case ITEM_MOD_HASTE_RATING:
- ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
- ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
- ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
- sLog.outDebug("+ %u HASTE", enchant_amount);
- break;
- case ITEM_MOD_EXPERTISE_RATING:
- ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
- sLog.outDebug("+ %u EXPERTISE", enchant_amount);
- break;
- case ITEM_MOD_ATTACK_POWER:
- HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
- HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
- sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
- break;
- case ITEM_MOD_RANGED_ATTACK_POWER:
- HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
- sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
- break;
-// case ITEM_MOD_FERAL_ATTACK_POWER:
-// ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
- sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
- break;
- case ITEM_MOD_MANA_REGENERATION:
- ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
- sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
- break;
- case ITEM_MOD_ARMOR_PENETRATION_RATING:
- ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
- sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
- break;
- case ITEM_MOD_SPELL_POWER:
- ((Player*)this)->ApplySpellPowerBonus(enchant_amount, apply);
- sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
- break;
- case ITEM_MOD_HEALTH_REGEN:
- ((Player*)this)->ApplyHealthRegenBonus(enchant_amount, apply);
- sLog.outDebug("+ %u HEALTH_REGENERATION", enchant_amount);
- break;
- case ITEM_MOD_SPELL_HEALING_DONE: // deprecated
- case ITEM_MOD_SPELL_DAMAGE_DONE: // deprecated
- default:
- break;
- }
- break;
- }
- case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
- {
- if(getClass() == CLASS_SHAMAN)
- {
- float addValue = 0.0f;
- if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
- {
- addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
- HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
- }
- else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
- {
- addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
- HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
- }
- }
- break;
- }
- case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
- // processed in Player::CastItemUseSpell
- break;
- case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
- // nothing do..
- break;
- default:
- sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
- break;
- } /*switch(enchant_display_type)*/
- } /*for*/
- }
-
- // visualize enchantment at player and equipped items
- if(slot == PERM_ENCHANTMENT_SLOT)
- SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
-
- if(slot == TEMP_ENCHANTMENT_SLOT)
- SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
-
- if(apply_dur)
- {
- if(apply)
- {
- // set duration
- uint32 duration = item->GetEnchantmentDuration(slot);
- if(duration > 0)
- AddEnchantmentDuration(item, slot, duration);
- }
- else
- {
- // duration == 0 will remove EnchantDuration
- AddEnchantmentDuration(item, slot, 0);
- }
- }
-}
-
-void Player::SendEnchantmentDurations()
-{
- for (EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
- {
- GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
- }
-}
-
-void Player::SendItemDurations()
-{
- for (ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
- {
- (*itr)->SendTimeUpdate(this);
- }
-}
-
-void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
-{
- if(!item) // prevent crash
- return;
-
- // last check 2.0.10
- WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
- data << uint64(GetGUID()); // player GUID
- data << uint32(received); // 0=looted, 1=from npc
- data << uint32(created); // 0=received, 1=created
- data << uint32(1); // always 0x01 (probably meant to be count of listed items)
- data << uint8(item->GetBagSlot()); // bagslot
- // item slot, but when added to stack: 0xFFFFFFFF
- data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
- data << uint32(item->GetEntry()); // item id
- data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
- data << int32(item->GetItemRandomPropertyId()); // random item property id
- data << uint32(count); // count of items
- data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
-
- if (broadcast && GetGroup())
- GetGroup()->BroadcastPacket(&data, true);
- else
- GetSession()->SendPacket(&data);
-}
-
-/*********************************************************/
-/*** GOSSIP SYSTEM ***/
-/*********************************************************/
-
-void Player::PrepareGossipMenu(WorldObject *pSource, uint32 menuId)
-{
- PlayerMenu* pMenu = PlayerTalkClass;
- pMenu->ClearMenus();
-
- pMenu->GetGossipMenu().SetMenuId(menuId);
-
- GossipMenuItemsMapBounds pMenuItemBounds = objmgr.GetGossipMenuItemsMapBounds(menuId);
-
- // if default menuId and no menu options exist for this, use options from default options
- if (pMenuItemBounds.first == pMenuItemBounds.second && menuId == GetDefaultGossipMenuForSource(pSource))
- pMenuItemBounds = objmgr.GetGossipMenuItemsMapBounds(0);
-
- for(GossipMenuItemsMap::const_iterator itr = pMenuItemBounds.first; itr != pMenuItemBounds.second; ++itr)
- {
- bool bCanTalk = true;
-
- if (itr->second.cond_1 && !objmgr.IsPlayerMeetToCondition(this, itr->second.cond_1))
- continue;
-
- if (itr->second.cond_2 && !objmgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
- continue;
-
- if (itr->second.cond_3 && !objmgr.IsPlayerMeetToCondition(this, itr->second.cond_3))
- continue;
-
- if (pSource->GetTypeId() == TYPEID_UNIT)
- {
- Creature *pCreature = (Creature*)pSource;
-
- uint32 npcflags = pCreature->GetUInt32Value(UNIT_NPC_FLAGS);
-
- if (!(itr->second.npc_option_npcflag & npcflags))
- continue;
-
- switch(itr->second.option_id)
- {
- case GOSSIP_OPTION_QUESTGIVER:
- PrepareQuestMenu(pSource->GetGUID());
- bCanTalk = false;
- break;
- case GOSSIP_OPTION_ARMORER:
- bCanTalk = false; // added in special mode
- break;
- case GOSSIP_OPTION_SPIRITHEALER:
- if (!isDead())
- bCanTalk = false;
- break;
- case GOSSIP_OPTION_VENDOR:
- {
- VendorItemData const* vItems = pCreature->GetVendorItems();
- if (!vItems || vItems->Empty())
- {
- sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", pCreature->GetGUIDLow(), pCreature->GetEntry());
- bCanTalk = false;
- }
- break;
- }
- case GOSSIP_OPTION_TRAINER:
- if (!pCreature->isCanTrainingOf(this, false))
- bCanTalk = false;
- break;
- case GOSSIP_OPTION_LEARNDUALSPEC:
- if(!(GetSpecsCount() == 1 && pCreature->isCanTrainingAndResetTalentsOf(this) && !(getLevel() < sWorld.getConfig(CONFIG_MIN_DUALSPEC_LEVEL))))
- bCanTalk = false;
- break;
- case GOSSIP_OPTION_UNLEARNTALENTS:
- if (!pCreature->isCanTrainingAndResetTalentsOf(this))
- bCanTalk = false;
- break;
- case GOSSIP_OPTION_UNLEARNPETSKILLS:
- if (!GetPet() || GetPet()->getPetType() != HUNTER_PET || GetPet()->m_spells.size() <= 1 || pCreature->GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || pCreature->GetCreatureInfo()->trainer_class != CLASS_HUNTER)
- bCanTalk = false;
- break;
- case GOSSIP_OPTION_TAXIVENDOR:
- if (GetSession()->SendLearnNewTaxiNode(pCreature))
- return;
- break;
- case GOSSIP_OPTION_BATTLEFIELD:
- if (!pCreature->isCanInteractWithBattleMaster(this, false))
- bCanTalk = false;
- break;
- case GOSSIP_OPTION_STABLEPET:
- if (getClass() != CLASS_HUNTER)
- bCanTalk = false;
- break;
- case GOSSIP_OPTION_GOSSIP:
- case GOSSIP_OPTION_SPIRITGUIDE:
- case GOSSIP_OPTION_INNKEEPER:
- case GOSSIP_OPTION_BANKER:
- case GOSSIP_OPTION_PETITIONER:
- case GOSSIP_OPTION_TABARDDESIGNER:
- case GOSSIP_OPTION_AUCTIONEER:
- break; // no checks
- case GOSSIP_OPTION_OUTDOORPVP:
- if (!sOutdoorPvPMgr.CanTalkTo(this, pCreature, itr->second))
- bCanTalk = false;
- break;
- default:
- sLog.outErrorDb("Creature entry %u have unknown gossip option %u for menu %u", pCreature->GetEntry(), itr->second.option_id, itr->second.menu_id);
- bCanTalk = false;
- break;
- }
- }
- else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
- {
- GameObject *pGo = (GameObject*)pSource;
-
- switch(itr->second.option_id)
- {
- case GOSSIP_OPTION_QUESTGIVER:
- if (pGo->GetGoType() == GAMEOBJECT_TYPE_QUESTGIVER)
- PrepareQuestMenu(pSource->GetGUID());
- bCanTalk = false;
- break;
- case GOSSIP_OPTION_GOSSIP:
- if (pGo->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER && pGo->GetGoType() != GAMEOBJECT_TYPE_GOOBER)
- bCanTalk = false;
- break;
- default:
- bCanTalk = false;
- break;
- }
- }
-
- if (bCanTalk)
- {
- std::string strOptionText = itr->second.option_text;
- std::string strBoxText = itr->second.box_text;
-
- int loc_idx = GetSession()->GetSessionDbLocaleIndex();
-
- if (loc_idx >= 0)
- {
- uint32 idxEntry = MAKE_PAIR32(menuId, itr->second.id);
-
- if (GossipMenuItemsLocale const *no = objmgr.GetGossipMenuItemsLocale(idxEntry))
- {
- if (no->OptionText.size() > (size_t)loc_idx && !no->OptionText[loc_idx].empty())
- strOptionText = no->OptionText[loc_idx];
-
- if (no->BoxText.size() > (size_t)loc_idx && !no->BoxText[loc_idx].empty())
- strBoxText = no->BoxText[loc_idx];
- }
- }
-
- pMenu->GetGossipMenu().AddMenuItem(itr->second.option_icon, strOptionText, 0, itr->second.option_id, strBoxText, itr->second.box_money, itr->second.box_coded);
- pMenu->GetGossipMenu().AddGossipMenuItemData(itr->second.action_menu_id, itr->second.action_poi_id, itr->second.action_script_id);
- }
- }
-
- // some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
- /*if (pMenu->Empty())
- {
- if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
- {
- // output error message if need
- pCreature->isCanTrainingOf(this, true);
- }
-
- if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
- {
- // output error message if need
- pCreature->isCanInteractWithBattleMaster(this, true);
- }
- }*/
-}
-
-void Player::SendPreparedGossip(WorldObject *pSource)
-{
- if (!pSource)
- return;
-
- if (pSource->GetTypeId() == TYPEID_UNIT)
- {
- // in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
- if (!((Creature*)pSource)->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_GOSSIP) && !PlayerTalkClass->GetQuestMenu().Empty())
- {
- SendPreparedQuest(pSource->GetGUID());
- return;
- }
- }
- else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
- {
- // probably need to find a better way here
- if (!PlayerTalkClass->GetGossipMenu().GetMenuId() && !PlayerTalkClass->GetQuestMenu().Empty())
- {
- SendPreparedQuest(pSource->GetGUID());
- return;
- }
- }
-
- // in case non empty gossip menu (that not included quests list size) show it
- // (quest entries from quest menu will be included in list)
-
- uint32 textId = GetGossipTextId(pSource);
-
- if (uint32 menuId = PlayerTalkClass->GetGossipMenu().GetMenuId())
- textId = GetGossipTextId(menuId);
-
- PlayerTalkClass->SendGossipMenu(textId, pSource->GetGUID());
-}
-
-void Player::OnGossipSelect(WorldObject* pSource, uint32 gossipListId, uint32 menuId)
-{
- GossipMenu& gossipmenu = PlayerTalkClass->GetGossipMenu();
-
- if (gossipListId >= gossipmenu.MenuItemCount())
- return;
-
- // if not same, then something funky is going on
- if (menuId != gossipmenu.GetMenuId())
- return;
-
- uint32 gossipOptionId = gossipmenu.GetItem(gossipListId).m_gOptionId;
- uint64 guid = pSource->GetGUID();
-
- if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
- {
- if (gossipOptionId > GOSSIP_OPTION_QUESTGIVER)
- {
- sLog.outError("Player guid %u request invalid gossip option for GameObject entry %u", GetGUIDLow(), pSource->GetEntry());
- return;
- }
- }
-
- GossipMenuItemData pMenuData = gossipmenu.GetItemData(gossipListId);
-
- switch(gossipOptionId)
- {
- case GOSSIP_OPTION_GOSSIP:
- {
- if (pMenuData.m_gAction_menu)
- {
- PrepareGossipMenu(pSource, pMenuData.m_gAction_menu);
- SendPreparedGossip(pSource);
- }
-
- if (pMenuData.m_gAction_poi)
- PlayerTalkClass->SendPointOfInterest(pMenuData.m_gAction_poi);
-
- if (pMenuData.m_gAction_script)
- {
- if (pSource->GetTypeId() == TYPEID_UNIT)
- GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, this, pSource);
- else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
- GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, pSource, this);
- }
- break;
- }
- case GOSSIP_OPTION_OUTDOORPVP:
- sOutdoorPvPMgr.HandleGossipOption(this, pSource->GetGUID(), gossipListId);
- break;
- case GOSSIP_OPTION_SPIRITHEALER:
- if (isDead())
- ((Creature*)pSource)->CastSpell(((Creature*)pSource),17251,true,NULL,NULL,GetGUID());
- break;
- case GOSSIP_OPTION_QUESTGIVER:
- PrepareQuestMenu(guid);
- SendPreparedQuest(guid);
- break;
- case GOSSIP_OPTION_VENDOR:
- case GOSSIP_OPTION_ARMORER:
- GetSession()->SendListInventory(guid);
- break;
- case GOSSIP_OPTION_STABLEPET:
- GetSession()->SendStablePet(guid);
- break;
- case GOSSIP_OPTION_TRAINER:
- GetSession()->SendTrainerList(guid);
- break;
- case GOSSIP_OPTION_LEARNDUALSPEC:
- if(GetSpecsCount() == 1 && !(getLevel() < sWorld.getConfig(CONFIG_MIN_DUALSPEC_LEVEL)))
- {
- if (GetMoney() < 10000000)
- {
- SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
- PlayerTalkClass->CloseGossip();
- break;
- }
- else
- {
- ModifyMoney(-10000000);
-
- // Cast spells that teach dual spec
- // Both are also ImplicitTarget self and must be cast by player
- this->CastSpell(this, 63680, true, NULL, NULL, this->GetGUID());
- this->CastSpell(this, 63624, true, NULL, NULL, this->GetGUID());
-
- // Should show another Gossip text with "Congratulations..."
- PlayerTalkClass->CloseGossip();
- }
- }
- break;
- case GOSSIP_OPTION_UNLEARNTALENTS:
- PlayerTalkClass->CloseGossip();
- SendTalentWipeConfirm(guid);
- break;
- case GOSSIP_OPTION_UNLEARNPETSKILLS:
- PlayerTalkClass->CloseGossip();
- SendPetSkillWipeConfirm();
- break;
- case GOSSIP_OPTION_TAXIVENDOR:
- GetSession()->SendTaxiMenu(((Creature*)pSource));
- break;
- case GOSSIP_OPTION_INNKEEPER:
- PlayerTalkClass->CloseGossip();
- SetBindPoint(guid);
- break;
- case GOSSIP_OPTION_BANKER:
- GetSession()->SendShowBank(guid);
- break;
- case GOSSIP_OPTION_PETITIONER:
- PlayerTalkClass->CloseGossip();
- GetSession()->SendPetitionShowList(guid);
- break;
- case GOSSIP_OPTION_TABARDDESIGNER:
- PlayerTalkClass->CloseGossip();
- GetSession()->SendTabardVendorActivate(guid);
- break;
- case GOSSIP_OPTION_AUCTIONEER:
- GetSession()->SendAuctionHello(guid, ((Creature*)pSource));
- break;
- case GOSSIP_OPTION_SPIRITGUIDE:
- PrepareGossipMenu(pSource);
- SendPreparedGossip(pSource);
- break;
- case GOSSIP_OPTION_BATTLEFIELD:
- {
- BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(pSource->GetEntry());
-
- if (bgTypeId == BATTLEGROUND_TYPE_NONE)
- {
- sLog.outError("a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUIDLow());
- return;
- }
-
- GetSession()->SendBattlegGroundList(guid, bgTypeId);
- break;
- }
- }
-}
-
-uint32 Player::GetGossipTextId(WorldObject *pSource)
-{
- if (!pSource || pSource->GetTypeId() != TYPEID_UNIT || !((Creature*)pSource)->GetDBTableGUIDLow())
- return DEFAULT_GOSSIP_MESSAGE;
-
- if (uint32 pos = objmgr.GetNpcGossip(((Creature*)pSource)->GetDBTableGUIDLow()))
- return pos;
-
- return DEFAULT_GOSSIP_MESSAGE;
-}
-
-uint32 Player::GetGossipTextId(uint32 menuId)
-{
- uint32 textId = DEFAULT_GOSSIP_MESSAGE;
-
- if (!menuId)
- return textId;
-
- GossipMenusMapBounds pMenuBounds = objmgr.GetGossipMenusMapBounds(menuId);
-
- for(GossipMenusMap::const_iterator itr = pMenuBounds.first; itr != pMenuBounds.second; ++itr)
- {
- if (objmgr.IsPlayerMeetToCondition(this, itr->second.cond_1) && objmgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
- textId = itr->second.text_id;
- }
-
- return textId;
-}
-
-uint32 Player::GetDefaultGossipMenuForSource(WorldObject *pSource)
-{
- if (pSource->GetTypeId() == TYPEID_UNIT)
- return ((Creature*)pSource)->GetCreatureInfo()->GossipMenuId;
- else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
- return((GameObject*)pSource)->GetGOInfo()->GetGossipMenuId();
-
- return 0;
-}
-
-/*********************************************************/
-/*** QUEST SYSTEM ***/
-/*********************************************************/
-
-void Player::PrepareQuestMenu( uint64 guid )
-{
- Object *pObject;
- QuestRelations* pObjectQR;
- QuestRelations* pObjectQIR;
-
- // pets also can have quests
- Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
- if( pCreature )
- {
- pObject = (Object*)pCreature;
- pObjectQR = &objmgr.mCreatureQuestRelations;
- pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
- }
- else
- {
- //we should obtain map pointer from GetMap() in 99% of cases. Special case
- //only for quests which cast teleport spells on player
- Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
- ASSERT(_map);
- GameObject *pGameObject = _map->GetGameObject(guid);
- if( pGameObject )
- {
- pObject = (Object*)pGameObject;
- pObjectQR = &objmgr.mGOQuestRelations;
- pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
- }
- else
- return;
- }
-
- QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
- qm.ClearMenu();
-
- for (QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
- {
- uint32 quest_id = i->second;
- QuestStatus status = GetQuestStatus( quest_id );
- if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
- qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
- else if ( status == QUEST_STATUS_INCOMPLETE )
- qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
- //else if (status == QUEST_STATUS_AVAILABLE )
- // qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
- }
-
- for (QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
- {
- uint32 quest_id = i->second;
- Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
- if(!pQuest) continue;
-
- QuestStatus status = GetQuestStatus( quest_id );
-
- if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
- qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
- else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
- qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
- }
-}
-
-void Player::SendPreparedQuest(uint64 guid)
-{
- QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
- if (questMenu.Empty())
- return;
-
- QuestMenuItem const& qmi0 = questMenu.GetItem(0);
-
- uint32 status = qmi0.m_qIcon;
-
- // single element case
- if (questMenu.MenuItemCount() == 1)
- {
- // Auto open -- maybe also should verify there is no greeting
- uint32 quest_id = qmi0.m_qId;
- Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
-
- if (pQuest)
- {
- if (status == DIALOG_STATUS_UNK2 && !GetQuestRewardStatus(quest_id))
- PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
- else if (status == DIALOG_STATUS_UNK2)
- PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
- // Send completable on repeatable and autoCompletable quest if player don't have quest
- // TODO: verify if check for !pQuest->IsDaily() is really correct (possibly not)
- else if (pQuest->IsAutoComplete() && pQuest->IsRepeatable() && !pQuest->IsDaily())
- PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanCompleteRepeatableQuest(pQuest), true);
- else
- PlayerTalkClass->SendQuestGiverQuestDetails(pQuest, guid, true);
- }
- }
- // multiply entries
- else
- {
- QEmote qe;
- qe._Delay = 0;
- qe._Emote = 0;
- std::string title = "";
-
- // need pet case for some quests
- Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
- if (pCreature)
- {
- uint32 textid = GetGossipTextId(pCreature);
- GossipText const* gossiptext = objmgr.GetGossipText(textid);
- if (!gossiptext)
- {
- qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
- qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
- title = "";
- }
- else
- {
- qe = gossiptext->Options[0].Emotes[0];
-
- if(!gossiptext->Options[0].Text_0.empty())
- {
- title = gossiptext->Options[0].Text_0;
-
- int loc_idx = GetSession()->GetSessionDbLocaleIndex();
- if (loc_idx >= 0)
- {
- NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
- if (nl)
- {
- if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
- title = nl->Text_0[0][loc_idx];
- }
- }
- }
- else
- {
- title = gossiptext->Options[0].Text_1;
-
- int loc_idx = GetSession()->GetSessionDbLocaleIndex();
- if (loc_idx >= 0)
- {
- NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
- if (nl)
- {
- if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
- title = nl->Text_1[0][loc_idx];
- }
- }
- }
- }
- }
- PlayerTalkClass->SendQuestGiverQuestList(qe, title, guid);
- }
-}
-
-bool Player::IsActiveQuest( uint32 quest_id ) const
-{
- QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
-
- return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
-}
-
-Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
-{
- Object *pObject;
- QuestRelations* pObjectQR;
- QuestRelations* pObjectQIR;
-
- Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
- if( pCreature )
- {
- pObject = (Object*)pCreature;
- pObjectQR = &objmgr.mCreatureQuestRelations;
- pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
- }
- else
- {
- //we should obtain map pointer from GetMap() in 99% of cases. Special case
- //only for quests which cast teleport spells on player
- Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
- ASSERT(_map);
- GameObject *pGameObject = _map->GetGameObject(guid);
- if( pGameObject )
- {
- pObject = (Object*)pGameObject;
- pObjectQR = &objmgr.mGOQuestRelations;
- pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
- }
- else
- return NULL;
- }
-
- uint32 nextQuestID = pQuest->GetNextQuestInChain();
- for (QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
- {
- if (itr->second == nextQuestID)
- return objmgr.GetQuestTemplate(nextQuestID);
- }
-
- return NULL;
-}
-
-bool Player::CanSeeStartQuest( Quest const *pQuest )
-{
- if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
- SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
- SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
- SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
- {
- return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
- }
-
- return false;
-}
-
-bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
-{
- return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
- && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
- && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
- && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
- && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
- && SatisfyQuestDay( pQuest, msg );
-}
-
-bool Player::CanAddQuest( Quest const *pQuest, bool msg )
-{
- if( !SatisfyQuestLog( msg ) )
- return false;
-
- uint32 srcitem = pQuest->GetSrcItemId();
- if( srcitem > 0 )
- {
- uint32 count = pQuest->GetSrcItemCount();
- ItemPosCountVec dest;
- uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
-
- // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
- if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
- return true;
- else if( msg2 != EQUIP_ERR_OK )
- {
- SendEquipError( msg2, NULL, NULL );
- return false;
- }
- }
- return true;
-}
-
-bool Player::CanCompleteQuest( uint32 quest_id )
-{
- if( quest_id )
- {
- QuestStatusData& q_status = mQuestStatus[quest_id];
- if( q_status.m_status == QUEST_STATUS_COMPLETE )
- return false; // not allow re-complete quest
-
- Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
-
- if(!qInfo)
- return false;
-
- // auto complete quest
- if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
- return true;
-
- if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
- {
-
- if ( qInfo->HasFlag( QUEST_TRINITY_FLAGS_DELIVER ) )
- {
- for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; i++)
- {
- if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
- return false;
- }
- }
-
- if ( qInfo->HasFlag(QUEST_TRINITY_FLAGS_KILL_OR_CAST | QUEST_TRINITY_FLAGS_SPEAKTO) )
- {
- for (uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
- {
- if( qInfo->ReqCreatureOrGOId[i] == 0 )
- continue;
-
- if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
- return false;
- }
- }
-
- if ( qInfo->HasFlag( QUEST_TRINITY_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
- return false;
-
- if ( qInfo->HasFlag( QUEST_TRINITY_FLAGS_TIMED ) && q_status.m_timer == 0 )
- return false;
-
- if ( qInfo->GetRewOrReqMoney() < 0 )
- {
- if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
- return false;
- }
-
- uint32 repFacId = qInfo->GetRepObjectiveFaction();
- if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
- return false;
-
- uint32 repFacId2 = qInfo->GetRepObjectiveFaction2();
- if ( repFacId2 && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue2() )
- return false;
-
- return true;
- }
- }
- return false;
-}
-
-bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
-{
- // Solve problem that player don't have the quest and try complete it.
- // if repeatable she must be able to complete event if player don't have it.
- // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
- if( !CanTakeQuest(pQuest, false) )
- return false;
-
- if (pQuest->HasFlag( QUEST_TRINITY_FLAGS_DELIVER) )
- for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; i++)
- if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
- return false;
-
- if( !CanRewardQuest(pQuest, false) )
- return false;
-
- return true;
-}
-
-bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
-{
- // not auto complete quest and not completed quest (only cheating case, then ignore without message)
- if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
- return false;
-
- // daily quest can't be rewarded (25 daily quest already completed)
- if(!SatisfyQuestDay(pQuest,true))
- return false;
-
- // rewarded and not repeatable quest (only cheating case, then ignore without message)
- if(GetQuestRewardStatus(pQuest->GetQuestId()))
- return false;
-
- // prevent receive reward with quest items in bank
- if ( pQuest->HasFlag( QUEST_TRINITY_FLAGS_DELIVER ) )
- {
- for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; i++)
- {
- if( pQuest->ReqItemCount[i]!= 0 &&
- GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
- {
- if(msg)
- SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
- return false;
- }
- }
- }
-
- // prevent receive reward with low money and GetRewOrReqMoney() < 0
- if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
- return false;
-
- return true;
-}
-
-bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
-{
- // prevent receive reward with quest items in bank or for not completed quest
- if(!CanRewardQuest(pQuest,msg))
- return false;
-
- if ( pQuest->GetRewChoiceItemsCount() > 0 )
- {
- if( pQuest->RewChoiceItemId[reward] )
- {
- ItemPosCountVec dest;
- uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
- if( res != EQUIP_ERR_OK )
- {
- SendEquipError( res, NULL, NULL );
- return false;
- }
- }
- }
-
- if ( pQuest->GetRewItemsCount() > 0 )
- {
- for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
- {
- if( pQuest->RewItemId[i] )
- {
- ItemPosCountVec dest;
- uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
- if( res != EQUIP_ERR_OK )
- {
- SendEquipError( res, NULL, NULL );
- return false;
- }
- }
- }
- }
-
- return true;
-}
-
-void Player::AddQuest( Quest const *pQuest, Object *questGiver )
-{
- uint16 log_slot = FindQuestSlot( 0 );
- assert(log_slot < MAX_QUEST_LOG_SIZE);
-
- uint32 quest_id = pQuest->GetQuestId();
-
- // if not exist then created with set uState==NEW and rewarded=false
- QuestStatusData& questStatusData = mQuestStatus[quest_id];
-
- // check for repeatable quests status reset
- questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
- questStatusData.m_explored = false;
-
- if ( pQuest->HasFlag( QUEST_TRINITY_FLAGS_DELIVER ) )
- {
- for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
- questStatusData.m_itemcount[i] = 0;
- }
-
- if ( pQuest->HasFlag(QUEST_TRINITY_FLAGS_KILL_OR_CAST | QUEST_TRINITY_FLAGS_SPEAKTO) )
- {
- for (uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
- questStatusData.m_creatureOrGOcount[i] = 0;
- }
-
- GiveQuestSourceItem( pQuest );
- AdjustQuestReqItemCount( pQuest, questStatusData );
-
- if( pQuest->GetRepObjectiveFaction() )
- if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
- GetReputationMgr().SetVisible(factionEntry);
-
- if( pQuest->GetRepObjectiveFaction2() )
- if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction2()))
- GetReputationMgr().SetVisible(factionEntry);
-
- uint32 qtime = 0;
- if( pQuest->HasFlag( QUEST_TRINITY_FLAGS_TIMED ) )
- {
- uint32 limittime = pQuest->GetLimitTime();
-
- // shared timed quest
- if(questGiver && questGiver->GetTypeId() == TYPEID_PLAYER)
- limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
-
- AddTimedQuest( quest_id );
- questStatusData.m_timer = limittime * IN_MILISECONDS;
- qtime = static_cast<uint32>(time(NULL)) + limittime;
- }
- else
- questStatusData.m_timer = 0;
-
- SetQuestSlot(log_slot, quest_id, qtime);
-
- if (questStatusData.uState != QUEST_NEW)
- questStatusData.uState = QUEST_CHANGED;
-
- //starting initial quest script
- if(questGiver && pQuest->GetQuestStartScript()!=0)
- GetMap()->ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
-
- // Some spells applied at quest activation
- SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,true);
- if(saBounds.first != saBounds.second)
- {
- uint32 zone, area;
- GetZoneAndAreaId(zone,area);
-
- for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
- if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
- if( !HasAura(itr->second->spellId) )
- CastSpell(this,itr->second->spellId,true);
- }
-
- UpdateForQuestWorldObjects();
-}
-
-void Player::CompleteQuest( uint32 quest_id )
-{
- if( quest_id )
- {
- SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
-
- uint16 log_slot = FindQuestSlot( quest_id );
- if( log_slot < MAX_QUEST_LOG_SIZE)
- SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
-
- if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
- {
- if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
- RewardQuest(qInfo,0,this,false);
- else
- SendQuestComplete( quest_id );
- }
- }
-}
-
-void Player::IncompleteQuest( uint32 quest_id )
-{
- if( quest_id )
- {
- SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
-
- uint16 log_slot = FindQuestSlot( quest_id );
- if( log_slot < MAX_QUEST_LOG_SIZE)
- RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
- }
-}
-
-void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
-{
- //this THING should be here to protect code from quest, which cast on player far teleport as a reward
- //should work fine, cause far teleport will be executed in Player::Update()
- SetCanDelayTeleport(true);
-
- uint32 quest_id = pQuest->GetQuestId();
-
- for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
- if (pQuest->ReqItemId[i])
- DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
-
- for (uint8 i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i)
- {
- if (pQuest->ReqSourceId[i])
- {
- uint32 count = pQuest->ReqSourceCount[i];
- DestroyItemCount(pQuest->ReqSourceId[i], count ? count : 9999, true);
- }
- }
-
- RemoveTimedQuest(quest_id);
-
- if (pQuest->GetRewChoiceItemsCount() > 0)
- {
- if (uint32 itemId = pQuest->RewChoiceItemId[reward])
- {
- ItemPosCountVec dest;
- if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK)
- {
- Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
- SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
- }
- }
- }
-
- if (pQuest->GetRewItemsCount() > 0)
- {
- for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
- {
- if (uint32 itemId = pQuest->RewItemId[i])
- {
- ItemPosCountVec dest;
- if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewItemCount[i] ) == EQUIP_ERR_OK)
- {
- Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
- SendNewItem(item, pQuest->RewItemCount[i], true, false);
- }
- }
- }
- }
-
- RewardReputation(pQuest);
-
- uint16 log_slot = FindQuestSlot(quest_id);
- if (log_slot < MAX_QUEST_LOG_SIZE)
- SetQuestSlot(log_slot, 0);
-
- QuestStatusData& q_status = mQuestStatus[quest_id];
-
- // Not give XP in case already completed once repeatable quest
- uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
-
- // handle SPELL_AURA_MOD_XP_QUEST_PCT auras
- Unit::AuraEffectList const& ModXPPctAuras = GetAuraEffectsByType(SPELL_AURA_MOD_XP_QUEST_PCT);
- for (Unit::AuraEffectList::const_iterator i = ModXPPctAuras.begin(); i != ModXPPctAuras.end(); ++i)
- XP = uint32(XP*(1.0f + (*i)->GetAmount() / 100.0f));
-
- if (getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
- GiveXP(XP, NULL);
- else
- {
- uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
- ModifyMoney(money);
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
- }
-
- // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
- if (pQuest->GetRewOrReqMoney())
- {
- ModifyMoney(pQuest->GetRewOrReqMoney());
-
- if (pQuest->GetRewOrReqMoney() > 0)
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
- }
-
- // honor reward
- if (pQuest->GetRewHonorableKills())
- RewardHonor(NULL, 0, Trinity::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
-
- // title reward
- if (pQuest->GetCharTitleId())
- {
- if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
- SetTitle(titleEntry);
- }
-
- if (pQuest->GetBonusTalents())
- {
- m_questRewardTalentCount+=pQuest->GetBonusTalents();
- InitTalentForLevel();
- }
-
- // Send reward mail
- if (uint32 mail_template_id = pQuest->GetRewMailTemplateId())
- MailDraft(mail_template_id).SendMailTo(this, questGiver, MAIL_CHECK_MASK_NONE, pQuest->GetRewMailDelaySecs());
-
- if (pQuest->IsDaily())
- {
- SetDailyQuestStatus(quest_id);
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
- }
-
- if (!pQuest->IsRepeatable())
- SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
- else
- SetQuestStatus(quest_id, QUEST_STATUS_NONE);
-
- q_status.m_rewarded = true;
- if (q_status.uState != QUEST_NEW)
- q_status.uState = QUEST_CHANGED;
-
- if (announce)
- SendQuestReward( pQuest, XP, questGiver );
-
- // cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data)
- if (pQuest->GetRewSpellCast() > 0)
- CastSpell( this, pQuest->GetRewSpellCast(), true);
- else if ( pQuest->GetRewSpell() > 0)
- CastSpell( this, pQuest->GetRewSpell(), true);
-
- if (pQuest->GetZoneOrSort() > 0)
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
-
- uint32 zone = 0;
- uint32 area = 0;
-
- // remove auras from spells with quest reward state limitations
- SpellAreaForQuestMapBounds saEndBounds = spellmgr.GetSpellAreaForQuestEndMapBounds(quest_id);
- if(saEndBounds.first != saEndBounds.second)
- {
- GetZoneAndAreaId(zone,area);
-
- for (SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
- if(!itr->second->IsFitToRequirements(this,zone,area))
- RemoveAurasDueToSpell(itr->second->spellId);
- }
-
- // Some spells applied at quest reward
- SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,false);
- if(saBounds.first != saBounds.second)
- {
- if(!zone || !area)
- GetZoneAndAreaId(zone,area);
-
- for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
- if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
- if( !HasAura(itr->second->spellId) )
- CastSpell(this,itr->second->spellId,true);
- }
-
- //lets remove flag for delayed teleports
- SetCanDelayTeleport(false);
-}
-
-void Player::FailQuest(uint32 questId)
-{
- if (Quest const* pQuest = objmgr.GetQuestTemplate(questId))
- {
- SetQuestStatus(questId, QUEST_STATUS_FAILED);
-
- uint16 log_slot = FindQuestSlot(questId);
-
- if (log_slot < MAX_QUEST_LOG_SIZE)
- {
- SetQuestSlotTimer(log_slot, 1);
- SetQuestSlotState(log_slot, QUEST_STATE_FAIL);
- }
-
- if (pQuest->HasFlag(QUEST_TRINITY_FLAGS_TIMED))
- {
- QuestStatusData& q_status = mQuestStatus[questId];
-
- RemoveTimedQuest(questId);
- q_status.m_timer = 0;
-
- SendQuestTimerFailed(questId);
- }
- else
- SendQuestFailed(questId);
-
- // Destroy quest items on quest failure.
- for (uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
- if (pQuest->ReqItemId[i] > 0 && pQuest->ReqItemCount[i] > 0)
- // Destroy items recieved on starting the quest.
- DestroyItemCount(pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true, true);
- for (uint8 i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i)
- if (pQuest->ReqSourceId[i] > 0 && pQuest->ReqSourceCount[i] > 0)
- // Destroy items recieved during the quest.
- DestroyItemCount(pQuest->ReqSourceId[i], pQuest->ReqSourceCount[i], true, true);
- }
-}
-
-bool Player::SatisfyQuestSkillOrClass(Quest const* qInfo, bool msg)
-{
- int32 zoneOrSort = qInfo->GetZoneOrSort();
- int32 skillOrClass = qInfo->GetSkillOrClass();
-
- // skip zone zoneOrSort and 0 case skillOrClass
- if (zoneOrSort >= 0 && skillOrClass == 0)
- return true;
-
- int32 questSort = -zoneOrSort;
- uint8 reqSortClass = ClassByQuestSort(questSort);
-
- // check class sort cases in zoneOrSort
- if( reqSortClass != 0 && getClass() != reqSortClass)
- {
- if (msg)
- SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
- return false;
- }
-
- // check class
- if (skillOrClass < 0)
- {
- uint8 reqClass = -int32(skillOrClass);
- if (getClass() != reqClass)
- {
- if (msg)
- SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
- return false;
- }
- }
- // check skill
- else if(skillOrClass > 0)
- {
- uint32 reqSkill = skillOrClass;
- if(GetSkillValue(reqSkill) < qInfo->GetRequiredSkillValue())
- {
- if (msg)
- SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
- return false;
- }
- }
-
- return true;
-}
-
-bool Player::SatisfyQuestLevel(Quest const* qInfo, bool msg)
-{
- if (getLevel() < qInfo->GetMinLevel())
- {
- if(msg)
- SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
- return false;
- }
- return true;
-}
-
-bool Player::SatisfyQuestLog(bool msg)
-{
- // exist free slot
- if (FindQuestSlot(0) < MAX_QUEST_LOG_SIZE)
- return true;
-
- if (msg)
- {
- WorldPacket data(SMSG_QUESTLOG_FULL, 0);
- GetSession()->SendPacket(&data);
- sLog.outDebug("WORLD: Sent QUEST_LOG_FULL_MESSAGE");
- }
- return false;
-}
-
-bool Player::SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg)
-{
- // No previous quest (might be first quest in a series)
- if (qInfo->prevQuests.empty())
- return true;
-
- for (Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter)
- {
- uint32 prevId = abs(*iter);
-
- QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
- Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
-
- if (qPrevInfo && i_prevstatus != mQuestStatus.end())
- {
- // If any of the positive previous quests completed, return true
- if (*iter > 0 && i_prevstatus->second.m_rewarded)
- {
- // skip one-from-all exclusive group
- if (qPrevInfo->GetExclusiveGroup() >= 0)
- return true;
-
- // each-from-all exclusive group ( < 0)
- // can be start if only all quests in prev quest exclusive group completed and rewarded
- ObjectMgr::ExclusiveQuestGroups::iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
- ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
-
- assert(iter2 != end); // always must be found if qPrevInfo->ExclusiveGroup != 0
-
- for (; iter2 != end; ++iter2)
- {
- uint32 exclude_Id = iter2->second;
-
- // skip checked quest id, only state of other quests in group is interesting
- if (exclude_Id == prevId)
- continue;
-
- QuestStatusMap::iterator i_exstatus = mQuestStatus.find(exclude_Id);
-
- // alternative quest from group also must be completed and rewarded(reported)
- if (i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded)
- {
- if (msg)
- SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
- return false;
- }
- }
- return true;
- }
- // If any of the negative previous quests active, return true
- if (*iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
- || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
- {
- // skip one-from-all exclusive group
- if (qPrevInfo->GetExclusiveGroup() >= 0)
- return true;
-
- // each-from-all exclusive group ( < 0)
- // can be start if only all quests in prev quest exclusive group active
- ObjectMgr::ExclusiveQuestGroups::iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
- ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
-
- assert(iter2 != end); // always must be found if qPrevInfo->ExclusiveGroup != 0
-
- for (; iter2 != end; ++iter2)
- {
- uint32 exclude_Id = iter2->second;
-
- // skip checked quest id, only state of other quests in group is interesting
- if (exclude_Id == prevId)
- continue;
-
- QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
-
- // alternative quest from group also must be active
- if (i_exstatus == mQuestStatus.end() ||
- i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
- (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)))
- {
- if (msg)
- SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
- return false;
- }
- }
- return true;
- }
- }
- }
-
- // Has only positive prev. quests in non-rewarded state
- // and negative prev. quests in non-active state
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
-
- return false;
-}
-
-bool Player::SatisfyQuestRace(Quest const* qInfo, bool msg)
-{
- uint32 reqraces = qInfo->GetRequiredRaces();
- if (reqraces == 0)
- return true;
- if ((reqraces & getRaceMask()) == 0)
- {
- if (msg)
- SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
- return false;
- }
- return true;
-}
-
-bool Player::SatisfyQuestReputation(Quest const* qInfo, bool msg)
-{
- uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
- if (fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
- return false;
- }
-
- uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
- if (fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
- return false;
- }
-
- return true;
-}
-
-bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
-{
- QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
- if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
- {
- if( msg )
- SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
- return false;
- }
- return true;
-}
-
-bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg)
-{
- if (!m_timedquests.empty() && qInfo->HasFlag(QUEST_TRINITY_FLAGS_TIMED))
- {
- if (msg)
- SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED);
- return false;
- }
- return true;
-}
-
-bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
-{
- // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
- if(qInfo->GetExclusiveGroup() <= 0)
- return true;
-
- ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
- ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
-
- assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
-
- for (; iter != end; ++iter)
- {
- uint32 exclude_Id = iter->second;
-
- // skip checked quest id, only state of other quests in group is interesting
- if(exclude_Id == qInfo->GetQuestId())
- continue;
-
- // not allow have daily quest if daily quest from exclusive group already recently completed
- Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
- if( !SatisfyQuestDay(Nquest, false) )
- {
- if( msg )
- SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
- return false;
- }
-
- QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
-
- // alternative quest already started or completed
- if( i_exstatus != mQuestStatus.end()
- && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
- {
- if( msg )
- SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
- return false;
- }
- }
- return true;
-}
-
-bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
-{
- if(!qInfo->GetNextQuestInChain())
- return true;
-
- // next quest in chain already started or completed
- QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
- if( itr != mQuestStatus.end()
- && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
- {
- if( msg )
- SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
- return false;
- }
-
- // check for all quests further up the chain
- // only necessary if there are quest chains with more than one quest that can be skipped
- //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
- return true;
-}
-
-bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
-{
- // No previous quest in chain
- if( qInfo->prevChainQuests.empty())
- return true;
-
- for (Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
- {
- uint32 prevId = *iter;
-
- QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
-
- if( i_prevstatus != mQuestStatus.end() )
- {
- // If any of the previous quests in chain active, return false
- if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
- || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
- {
- if( msg )
- SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
- return false;
- }
- }
-
- // check for all quests further down the chain
- // only necessary if there are quest chains with more than one quest that can be skipped
- //if( !SatisfyQuestPrevChain( prevId, msg ) )
- // return false;
- }
-
- // No previous quest in chain active
- return true;
-}
-
-bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
-{
- if(!qInfo->IsDaily())
- return true;
-
- bool have_slot = false;
- for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
- {
- uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
- if(qInfo->GetQuestId()==id)
- return false;
-
- if(!id)
- have_slot = true;
- }
-
- if(!have_slot)
- {
- if( msg )
- SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
- return false;
- }
-
- return true;
-}
-
-bool Player::GiveQuestSourceItem( Quest const *pQuest )
-{
- uint32 srcitem = pQuest->GetSrcItemId();
- if( srcitem > 0 )
- {
- uint32 count = pQuest->GetSrcItemCount();
- if( count <= 0 )
- count = 1;
-
- ItemPosCountVec dest;
- uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
- if( msg == EQUIP_ERR_OK )
- {
- Item * item = StoreNewItem(dest, srcitem, true);
- SendNewItem(item, count, true, false);
- return true;
- }
- // player already have max amount required item, just report success
- else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
- return true;
- else
- SendEquipError( msg, NULL, NULL );
- return false;
- }
-
- return true;
-}
-
-bool Player::TakeQuestSourceItem(uint32 quest_id, bool msg)
-{
- Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
- if (qInfo)
- {
- uint32 srcitem = qInfo->GetSrcItemId();
- if (srcitem > 0)
- {
- uint32 count = qInfo->GetSrcItemCount();
- if (count <= 0)
- count = 1;
-
- // exist one case when destroy source quest item not possible:
- // non un-equippable item (equipped non-empty bag, for example)
- uint8 res = CanUnequipItems(srcitem,count);
- if (res != EQUIP_ERR_OK)
- {
- if (msg)
- SendEquipError(res, NULL, NULL);
- return false;
- }
-
- DestroyItemCount(srcitem, count, true, true);
- }
- }
- return true;
-}
-
-bool Player::GetQuestRewardStatus(uint32 quest_id) const
-{
- Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
- if (qInfo)
- {
- // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
- QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
- if(itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
- && !qInfo->IsRepeatable())
- return itr->second.m_rewarded;
-
- return false;
- }
- return false;
-}
-
-QuestStatus Player::GetQuestStatus(uint32 quest_id) const
-{
- if (quest_id)
- {
- QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
- if (itr != mQuestStatus.end())
- return itr->second.m_status;
- }
- return QUEST_STATUS_NONE;
-}
-
-bool Player::CanShareQuest(uint32 quest_id) const
-{
- Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
- if (qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE))
- {
- QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
- if (itr != mQuestStatus.end())
- return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
- }
- return false;
-}
-
-void Player::SetQuestStatus(uint32 quest_id, QuestStatus status)
-{
- if (Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
- {
- QuestStatusData& q_status = mQuestStatus[quest_id];
-
- q_status.m_status = status;
-
- if (q_status.uState != QUEST_NEW)
- q_status.uState = QUEST_CHANGED;
- }
-
- UpdateForQuestWorldObjects();
-}
-
-// not used in Trinity, but used in scripting code
-uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
-{
- Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
- if (!qInfo)
- return 0;
-
- for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
- if ( qInfo->ReqCreatureOrGOId[j] == entry )
- return mQuestStatus[quest_id].m_creatureOrGOcount[j];
-
- return 0;
-}
-
-void Player::AdjustQuestReqItemCount(Quest const* pQuest, QuestStatusData& questStatusData)
-{
- if (pQuest->HasFlag( QUEST_TRINITY_FLAGS_DELIVER))
- {
- for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
- {
- uint32 reqitemcount = pQuest->ReqItemCount[i];
- if (reqitemcount != 0)
- {
- uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
-
- questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
- if (questStatusData.uState != QUEST_NEW)
- questStatusData.uState = QUEST_CHANGED;
- }
- }
- }
-}
-
-uint16 Player::FindQuestSlot( uint32 quest_id ) const
-{
- for (uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- if (GetQuestSlotQuestId(i) == quest_id)
- return i;
-
- return MAX_QUEST_LOG_SIZE;
-}
-
-void Player::AreaExploredOrEventHappens(uint32 questId)
-{
- if (questId)
- {
- uint16 log_slot = FindQuestSlot(questId);
- if (log_slot < MAX_QUEST_LOG_SIZE)
- {
- QuestStatusData& q_status = mQuestStatus[questId];
-
- if (!q_status.m_explored)
- {
- q_status.m_explored = true;
- if (q_status.uState != QUEST_NEW)
- q_status.uState = QUEST_CHANGED;
- }
- }
- if (CanCompleteQuest(questId))
- CompleteQuest(questId);
- }
-}
-
-//not used in Trinityd, function for external script library
-void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
-{
- if (Group *pGroup = GetGroup())
- {
- for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
- {
- Player *pGroupGuy = itr->getSource();
-
- // for any leave or dead (with not released body) group member at appropriate distance
- if (pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse())
- pGroupGuy->AreaExploredOrEventHappens(questId);
- }
- }
- else
- AreaExploredOrEventHappens(questId);
-}
-
-void Player::ItemAddedQuestCheck( uint32 entry, uint32 count)
-{
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- uint32 questid = GetQuestSlotQuestId(i);
- if (questid == 0)
- continue;
-
- QuestStatusData& q_status = mQuestStatus[questid];
-
- if (q_status.m_status != QUEST_STATUS_INCOMPLETE)
- continue;
-
- Quest const* qInfo = objmgr.GetQuestTemplate(questid);
- if( !qInfo || !qInfo->HasFlag(QUEST_TRINITY_FLAGS_DELIVER))
- continue;
-
- for (uint8 j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
- {
- uint32 reqitem = qInfo->ReqItemId[j];
- if (reqitem == entry)
- {
- uint32 reqitemcount = qInfo->ReqItemCount[j];
- uint32 curitemcount = q_status.m_itemcount[j];
- if (curitemcount < reqitemcount)
- {
- uint32 additemcount = curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount;
- q_status.m_itemcount[j] += additemcount;
- if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
-
- SendQuestUpdateAddItem(qInfo, j, additemcount);
- }
- if ( CanCompleteQuest( questid))
- CompleteQuest( questid );
- return;
- }
- }
- }
- UpdateForQuestWorldObjects();
-}
-
-void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count)
-{
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- uint32 questid = GetQuestSlotQuestId(i);
- if(!questid)
- continue;
- Quest const* qInfo = objmgr.GetQuestTemplate(questid);
- if (!qInfo)
- continue;
- if( !qInfo->HasFlag(QUEST_TRINITY_FLAGS_DELIVER))
- continue;
-
- for (uint8 j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
- {
- uint32 reqitem = qInfo->ReqItemId[j];
- if (reqitem == entry)
- {
- QuestStatusData& q_status = mQuestStatus[questid];
-
- uint32 reqitemcount = qInfo->ReqItemCount[j];
- uint32 curitemcount;
- if (q_status.m_status != QUEST_STATUS_COMPLETE)
- curitemcount = q_status.m_itemcount[j];
- else
- curitemcount = GetItemCount(entry,true);
- if (curitemcount < reqitemcount + count)
- {
- uint32 remitemcount = curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount;
- q_status.m_itemcount[j] = curitemcount - remitemcount;
- if (q_status.uState != QUEST_NEW)
- q_status.uState = QUEST_CHANGED;
-
- IncompleteQuest(questid);
- }
- return;
- }
- }
- }
- UpdateForQuestWorldObjects();
-}
-
-void Player::KilledMonster(CreatureInfo const* cInfo, uint64 guid)
-{
- if (cInfo->Entry)
- KilledMonsterCredit(cInfo->Entry,guid);
-
- for (uint8 i = 0; i < MAX_KILL_CREDIT; ++i)
- if (cInfo->KillCredit[i])
- KilledMonsterCredit(cInfo->KillCredit[i],guid);
-}
-
-void Player::KilledMonsterCredit(uint32 entry, uint64 guid)
-{
- uint32 addkillcount = 1;
- uint32 real_entry = entry;
- if (guid)
- {
- Creature *killed = GetMap()->GetCreature(guid);
- if (killed && killed->GetEntry())
- real_entry = killed->GetEntry();
- }
-
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, real_entry, addkillcount);
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- uint32 questid = GetQuestSlotQuestId(i);
- if (!questid)
- continue;
-
- Quest const* qInfo = objmgr.GetQuestTemplate(questid);
- if (!qInfo)
- continue;
- // just if !ingroup || !noraidgroup || raidgroup
- QuestStatusData& q_status = mQuestStatus[questid];
- if(q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
- {
- if (qInfo->HasFlag( QUEST_TRINITY_FLAGS_KILL_OR_CAST))
- {
- for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
- {
- // skip GO activate objective or none
- if (qInfo->ReqCreatureOrGOId[j] <= 0)
- continue;
-
- // skip Cast at creature objective
- if (qInfo->ReqSpell[j] != 0)
- continue;
-
- uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
-
- if (reqkill == entry)
- {
- uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
- uint32 curkillcount = q_status.m_creatureOrGOcount[j];
- if (curkillcount < reqkillcount)
- {
- q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
- if (q_status.uState != QUEST_NEW)
- q_status.uState = QUEST_CHANGED;
-
- SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
- }
- if (CanCompleteQuest(questid))
- CompleteQuest(questid);
-
- // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
- continue;
- }
- }
- }
- }
- }
-}
-
-void Player::CastedCreatureOrGO(uint32 entry, uint64 guid, uint32 spell_id)
-{
- bool isCreature = IS_CRE_OR_VEH_GUID(guid);
-
- uint32 addCastCount = 1;
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- uint32 questid = GetQuestSlotQuestId(i);
- if(!questid)
- continue;
-
- Quest const* qInfo = objmgr.GetQuestTemplate(questid);
- if (!qInfo)
- continue;
-
- QuestStatusData& q_status = mQuestStatus[questid];
-
- if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
- {
- if (qInfo->HasFlag( QUEST_TRINITY_FLAGS_KILL_OR_CAST))
- {
- for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
- {
- // skip kill creature objective (0) or wrong spell casts
- if (qInfo->ReqSpell[j] != spell_id)
- continue;
-
- uint32 reqTarget = 0;
-
- if (isCreature)
- {
- // creature activate objectives
- if (qInfo->ReqCreatureOrGOId[j] > 0)
- {
- // checked at quest_template loading
- reqTarget = qInfo->ReqCreatureOrGOId[j];
- if (reqTarget != entry) // if entry doesn't match, check for killcredits referenced in template
- {
- CreatureInfo const *cinfo = objmgr.GetCreatureTemplate(entry);
- for (uint8 i = 0; i < MAX_KILL_CREDIT; ++i)
- if (cinfo->KillCredit[i] == reqTarget)
- entry = cinfo->KillCredit[i];
- }
- }
- }
- else
- {
- // GO activate objective
- if (qInfo->ReqCreatureOrGOId[j] < 0)
- // checked at quest_template loading
- reqTarget = - qInfo->ReqCreatureOrGOId[j];
- }
-
- // other not this creature/GO related objectives
- if (reqTarget != entry)
- continue;
-
- uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
- uint32 curCastCount = q_status.m_creatureOrGOcount[j];
- if (curCastCount < reqCastCount)
- {
- q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
- if (q_status.uState != QUEST_NEW)
- q_status.uState = QUEST_CHANGED;
-
- SendQuestUpdateAddCreatureOrGo(qInfo, guid, j, curCastCount, addCastCount);
- }
-
- if (CanCompleteQuest(questid))
- CompleteQuest(questid);
-
- // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
- break;
- }
- }
- }
- }
-}
-
-void Player::TalkedToCreature(uint32 entry, uint64 guid)
-{
- uint32 addTalkCount = 1;
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- uint32 questid = GetQuestSlotQuestId(i);
- if (!questid)
- continue;
-
- Quest const* qInfo = objmgr.GetQuestTemplate(questid);
- if (!qInfo)
- continue;
-
- QuestStatusData& q_status = mQuestStatus[questid];
-
- if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
- {
- if (qInfo->HasFlag(QUEST_TRINITY_FLAGS_KILL_OR_CAST | QUEST_TRINITY_FLAGS_SPEAKTO))
- {
- for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
- {
- // skip spell casts and Gameobject objectives
- if (qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
- continue;
-
- uint32 reqTarget = 0;
-
- if (qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
- // checked at quest_template loading
- reqTarget = qInfo->ReqCreatureOrGOId[j];
- else
- continue;
-
- if (reqTarget == entry)
- {
- uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
- uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
- if (curTalkCount < reqTalkCount)
- {
- q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
- if (q_status.uState != QUEST_NEW)
- q_status.uState = QUEST_CHANGED;
-
- SendQuestUpdateAddCreatureOrGo(qInfo, guid, j, curTalkCount, addTalkCount);
- }
- if (CanCompleteQuest(questid))
- CompleteQuest(questid);
-
- // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
- continue;
- }
- }
- }
- }
- }
-}
-
-void Player::MoneyChanged( uint32 count )
-{
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- uint32 questid = GetQuestSlotQuestId(i);
- if (!questid)
- continue;
-
- Quest const* qInfo = objmgr.GetQuestTemplate(questid);
- if (qInfo && qInfo->GetRewOrReqMoney() < 0)
- {
- QuestStatusData& q_status = mQuestStatus[questid];
-
- if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
- {
- if (int32(count) >= -qInfo->GetRewOrReqMoney())
- {
- if (CanCompleteQuest(questid))
- CompleteQuest(questid);
- }
- }
- else if (q_status.m_status == QUEST_STATUS_COMPLETE)
- {
- if (int32(count) < -qInfo->GetRewOrReqMoney())
- IncompleteQuest(questid);
- }
- }
- }
-}
-
-void Player::ReputationChanged(FactionEntry const* factionEntry)
-{
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- if(uint32 questid = GetQuestSlotQuestId(i))
- {
- if (Quest const* qInfo = objmgr.GetQuestTemplate(questid))
- {
- if (qInfo->GetRepObjectiveFaction() == factionEntry->ID)
- {
- QuestStatusData& q_status = mQuestStatus[questid];
- if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
- {
- if (GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
- if (CanCompleteQuest(questid))
- CompleteQuest(questid);
- }
- else if(q_status.m_status == QUEST_STATUS_COMPLETE)
- {
- if (GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
- IncompleteQuest(questid);
- }
- }
- }
- }
- }
-}
-
-void Player::ReputationChanged2(FactionEntry const* factionEntry)
-{
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- if(uint32 questid = GetQuestSlotQuestId(i))
- {
- if (Quest const* qInfo = objmgr.GetQuestTemplate(questid))
- {
- if (qInfo->GetRepObjectiveFaction2() == factionEntry->ID)
- {
- QuestStatusData& q_status = mQuestStatus[questid];
- if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
- {
- if (GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue2())
- if (CanCompleteQuest(questid))
- CompleteQuest(questid);
- }
- else if(q_status.m_status == QUEST_STATUS_COMPLETE)
- {
- if (GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue2())
- IncompleteQuest(questid);
- }
- }
- }
- }
- }
-}
-
-bool Player::HasQuestForItem(uint32 itemid) const
-{
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- uint32 questid = GetQuestSlotQuestId(i);
- if (questid == 0)
- continue;
-
- QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
- if(qs_itr == mQuestStatus.end())
- continue;
-
- QuestStatusData const& q_status = qs_itr->second;
-
- if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
- {
- Quest const* qinfo = objmgr.GetQuestTemplate(questid);
- if (!qinfo)
- continue;
-
- // hide quest if player is in raid-group and quest is no raid quest
- if (GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
- if (!InBattleGround()) //there are two ways.. we can make every bg-quest a raidquest, or add this code here.. i don't know if this can be exploited by other quests, but i think all other quests depend on a specific area.. but keep this in mind, if something strange happens later
- continue;
-
- // There should be no mixed ReqItem/ReqSource drop
- // This part for ReqItem drop
- for (uint8 j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
- {
- if (itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j])
- return true;
- }
- // This part - for ReqSource
- for (uint8 j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
- {
- // examined item is a source item
- if (qinfo->ReqSourceId[j] == itemid)
- {
- ItemPrototype const *pProto = objmgr.GetItemPrototype(itemid);
-
- // 'unique' item
- if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
- return true;
-
- // allows custom amount drop when not 0
- if (qinfo->ReqSourceCount[j])
- {
- if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
- return true;
- } else if (GetItemCount(itemid,true) < pProto->Stackable)
- return true;
- }
- }
- }
- }
- return false;
-}
-
-void Player::SendQuestComplete(uint32 quest_id)
-{
- if(quest_id)
- {
- WorldPacket data(SMSG_QUESTUPDATE_COMPLETE, 4);
- data << uint32(quest_id);
- GetSession()->SendPacket(&data);
- sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id);
- }
-}
-
-void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
-{
- uint32 questid = pQuest->GetQuestId();
- sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
- gameeventmgr.HandleQuestComplete(questid);
- WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
- data << uint32(questid);
-
- if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
- {
- data << uint32(XP);
- data << uint32(pQuest->GetRewOrReqMoney());
- }
- else
- {
- data << uint32(0);
- data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
- }
-
- data << uint32(10*Trinity::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
- data << uint32(pQuest->GetBonusTalents()); // bonus talents
- data << uint32(0);
- GetSession()->SendPacket( &data );
-
- if (pQuest->GetQuestCompleteScript() != 0)
- GetMap()->ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
-}
-
-void Player::SendQuestFailed( uint32 quest_id )
-{
- if( quest_id )
- {
- WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
- data << uint32(quest_id);
- data << uint32(0); // failed reason (4 for inventory is full)
- GetSession()->SendPacket( &data );
- sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
- }
-}
-
-void Player::SendQuestTimerFailed( uint32 quest_id )
-{
- if( quest_id )
- {
- WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
- data << uint32(quest_id);
- GetSession()->SendPacket( &data );
- sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
- }
-}
-
-void Player::SendCanTakeQuestResponse( uint32 msg )
-{
- WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
- data << uint32(msg);
- GetSession()->SendPacket( &data );
- sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
-}
-
-void Player::SendQuestConfirmAccept(const Quest* pQuest, Player* pReceiver)
-{
- if (pReceiver)
- {
- std::string strTitle = pQuest->GetTitle();
-
- int loc_idx = pReceiver->GetSession()->GetSessionDbLocaleIndex();
-
- if (loc_idx >= 0)
- {
- if (const QuestLocale* pLocale = objmgr.GetQuestLocale(pQuest->GetQuestId()))
- {
- if (pLocale->Title.size() > loc_idx && !pLocale->Title[loc_idx].empty())
- strTitle = pLocale->Title[loc_idx];
- }
- }
-
- WorldPacket data(SMSG_QUEST_CONFIRM_ACCEPT, (4 + strTitle.size() + 8));
- data << uint32(pQuest->GetQuestId());
- data << strTitle;
- data << uint64(GetGUID());
- pReceiver->GetSession()->SendPacket(&data);
-
- sLog.outDebug("WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT");
- }
-}
-
-void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
-{
- if( pPlayer )
- {
- WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
- data << uint64(pPlayer->GetGUID());
- data << uint8(msg); // valid values: 0-8
- GetSession()->SendPacket( &data );
- sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
- }
-}
-
-void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
-{
- WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
- sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
- //data << pQuest->ReqItemId[item_idx];
- //data << count;
- GetSession()->SendPacket( &data );
-}
-
-void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
-{
- assert(old_count + add_count < 65536 && "mob/GO count store in 16 bits 2^16 = 65536 (0..65536)");
-
- int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
- if (entry < 0)
- // client expected gameobject template id in form (id|0x80000000)
- entry = (-entry) | 0x80000000;
-
- WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
- sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
- data << uint32(pQuest->GetQuestId());
- data << uint32(entry);
- data << uint32(old_count + add_count);
- data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
- data << uint64(guid);
- GetSession()->SendPacket(&data);
-
- uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
- if( log_slot < MAX_QUEST_LOG_SIZE)
- SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
-}
-
-/*********************************************************/
-/*** LOAD SYSTEM ***/
-/*********************************************************/
-
-bool Player::MinimalLoadFromDB( QueryResult_AutoPtr result, uint32 guid )
-{
- if (!result)
- {
- // 0 1 2 3 4 5 6 7 8 9 10 11
- result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login, zone, level FROM characters WHERE guid = '%u'",guid);
- if (!result)
- return false;
- }
-
- Field *fields = result->Fetch();
-
- if (!LoadValues( fields[1].GetString()))
- {
- sLog.outError("Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
- return false;
- }
-
- // overwrite possible wrong/corrupted guid
- SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
-
- m_name = fields[2].GetCppString();
-
- Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
- Map *map = MapManager::Instance().CreateMap(fields[6].GetUInt32(), this, 0);
- SetMap(map);
-
- // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
- // this must help in case next save after mass player load after server startup
- m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
-
- // the instance id is not needed at character enum
-
- m_Played_time[PLAYED_TIME_TOTAL] = fields[7].GetUInt32();
- m_Played_time[PLAYED_TIME_LEVEL] = fields[8].GetUInt32();
-
- m_atLoginFlags = fields[9].GetUInt32();
-
- // I don't see these used anywhere ..
- /*_LoadGroup();
-
- _LoadBoundInstances();*/
-
- for (uint8 i = 0; i < PLAYER_SLOTS_COUNT; i++)
- m_items[i] = NULL;
-
- if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
- m_deathState = DEAD;
-
- return true;
-}
-
-void Player::_LoadDeclinedNames(QueryResult_AutoPtr result)
-{
- if(!result)
- return;
-
- if(m_declinedname)
- delete m_declinedname;
-
- m_declinedname = new DeclinedName;
- Field *fields = result->Fetch();
- for (uint8 i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
- m_declinedname->name[i] = fields[i].GetCppString();
-}
-
-void Player::_LoadArenaTeamInfo(QueryResult_AutoPtr result)
-{
- // arenateamid, played_week, played_season, personal_rating
- memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32) * MAX_ARENA_SLOT * ARENA_TEAM_END);
- if (!result)
- return;
-
- do
- {
- Field *fields = result->Fetch();
-
- uint32 arenateamid = fields[0].GetUInt32();
- uint32 played_week = fields[1].GetUInt32();
- uint32 played_season = fields[2].GetUInt32();
- uint32 wons_season = fields[3].GetUInt32();
- uint32 personal_rating = fields[4].GetUInt32();
-
- ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
- if(!aTeam)
- {
- sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u", arenateamid);
- continue;
- }
- uint8 arenaSlot = aTeam->GetSlot();
-
- m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_ID] = arenateamid; // TeamID
- m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_TYPE] = aTeam->GetType(); // team type
- 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
- m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_GAMES_WEEK] = played_week; // Played Week
- m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_GAMES_SEASON] = played_season; // Played Season
- m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_WINS_SEASON] = wons_season; // wins season
- m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_PERSONAL_RATING] = personal_rating; // Personal Rating
-
- }while (result->NextRow());
-}
-
-void Player::_LoadEquipmentSets(QueryResult_AutoPtr result)
-{
- // 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));
- if (!result)
- return;
-
- uint32 count = 0;
- do
- {
- Field *fields = result->Fetch();
-
- EquipmentSet eqSet;
-
- eqSet.Guid = fields[0].GetUInt64();
- uint32 index = fields[1].GetUInt32();
- eqSet.Name = fields[2].GetCppString();
- eqSet.IconName = fields[3].GetCppString();
- eqSet.state = EQUIPMENT_SET_UNCHANGED;
-
- for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
- eqSet.Items[i] = fields[4+i].GetUInt32();
-
- m_EquipmentSets[index] = eqSet;
-
- ++count;
-
- if(count >= MAX_EQUIPMENT_SET_INDEX) // client limit
- break;
- } while (result->NextRow());
-}
-
-void Player::_LoadBGData(QueryResult_AutoPtr result)
-{
- if (!result)
- return;
-
- // Expecting only one row
- Field *fields = result->Fetch();
- /* bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
- m_bgData.bgInstanceID = fields[0].GetUInt32();
- m_bgData.bgTeam = fields[1].GetUInt32();
- m_bgData.joinPos = WorldLocation(fields[6].GetUInt32(), // Map
- fields[2].GetFloat(), // X
- fields[3].GetFloat(), // Y
- fields[4].GetFloat(), // Z
- fields[5].GetFloat()); // Orientation
- m_bgData.taxiPath[0] = fields[7].GetUInt32();
- m_bgData.taxiPath[1] = fields[8].GetUInt32();
- m_bgData.mountSpell = fields[9].GetUInt32();
-}
-
-bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
-{
- QueryResult_AutoPtr result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
- if(!result)
- return false;
-
- Field *fields = result->Fetch();
-
- x = fields[0].GetFloat();
- y = fields[1].GetFloat();
- z = fields[2].GetFloat();
- o = fields[3].GetFloat();
- mapid = fields[4].GetUInt32();
- in_flight = !fields[5].GetCppString().empty();
-
- return true;
-}
-
-bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
-{
- QueryResult_AutoPtr result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
- if( !result )
- return false;
-
- Field *fields = result->Fetch();
-
- data = StrSplit(fields[0].GetCppString(), " ");
-
- return true;
-}
-
-uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
-{
- if(index >= data.size())
- return 0;
-
- return (uint32)atoi(data[index].c_str());
-}
-
-float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
-{
- float result;
- uint32 temp = Player::GetUInt32ValueFromArray(data,index);
- memcpy(&result, &temp, sizeof(result));
-
- return result;
-}
-
-uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
-{
- Tokens data;
- if(!LoadValuesArrayFromDB(data,guid))
- return 0;
-
- return GetUInt32ValueFromArray(data,index);
-}
-
-float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
-{
- float result;
- uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
- memcpy(&result, &temp, sizeof(result));
-
- return result;
-}
-
-bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
-{
- //// 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 41 42 43
- //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, instance_id, speccount, activespec FROM characters WHERE guid = '%u'", guid);
- QueryResult_AutoPtr result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
-
- if(!result)
- {
- sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
- return false;
- }
-
- Field *fields = result->Fetch();
-
- uint32 dbAccountId = fields[1].GetUInt32();
-
- // check if the character's account in the db and the logged in account match.
- // player should be able to load/delete character only with correct account!
- if( dbAccountId != GetSession()->GetAccountId() )
- {
- sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
- return false;
- }
-
- Object::_Create( guid, 0, HIGHGUID_PLAYER );
-
- m_name = fields[3].GetCppString();
-
- // check name limitations
- if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS ||
- (GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name)))
- {
- CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
- return false;
- }
-
- if(!LoadValues( fields[2].GetString()))
- {
- sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid));
- return false;
- }
-
- // overwrite possible wrong/corrupted guid
- SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
-
- // overwrite some data fields
- uint32 bytes0 = GetUInt32Value(UNIT_FIELD_BYTES_0) & 0xFF000000;
- bytes0 |= fields[4].GetUInt8(); // race
- bytes0 |= fields[5].GetUInt8() << 8; // class
- bytes0 |= fields[6].GetUInt8() << 16; // gender
- SetUInt32Value(UNIT_FIELD_BYTES_0, bytes0);
-
- SetUInt32Value(UNIT_FIELD_LEVEL, fields[7].GetUInt8());
- SetUInt32Value(PLAYER_XP, fields[8].GetUInt32());
- SetUInt32Value(PLAYER_FIELD_COINAGE, fields[9].GetUInt32());
- SetUInt32Value(PLAYER_BYTES, fields[10].GetUInt32());
- SetUInt32Value(PLAYER_BYTES_2, fields[11].GetUInt32());
- SetUInt32Value(PLAYER_BYTES_3, (GetUInt32Value(PLAYER_BYTES_3) & ~1) | fields[6].GetUInt8());
- SetUInt32Value(PLAYER_FLAGS, fields[12].GetUInt32());
-
- InitDisplayIds();
-
- // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
- for (uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
- {
- SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0 );
- SetVisibleItemSlot(slot, NULL);
-
- if (m_items[slot])
- {
- delete m_items[slot];
- m_items[slot] = NULL;
- }
- }
-
- // update money limits
- if(GetMoney() > MAX_MONEY_AMOUNT)
- SetMoney(MAX_MONEY_AMOUNT);
-
- sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
- outDebugValues();
-
- //Need to call it to initialize m_team (m_team can be calculated from race)
- //Other way is to saves m_team into characters table.
- setFactionForRace(getRace());
-
- // load home bind and check in same time class/race pair, it used later for restore broken positions
- if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
- return false;
-
- InitPrimaryProfessions(); // to max set before any spell loaded
-
- // init saved position, and fix it later if problematic
- uint32 transGUID = fields[31].GetUInt32();
- Relocate(fields[13].GetFloat(),fields[14].GetFloat(),fields[15].GetFloat(),fields[17].GetFloat());
- uint32 mapId = fields[16].GetUInt32();
- uint32 instanceId = fields[41].GetFloat();
-
- uint32 difficulty = fields[39].GetUInt32();
- if(difficulty >= MAX_DUNGEON_DIFFICULTY)
- difficulty = DUNGEON_DIFFICULTY_NORMAL;
- SetDungeonDifficulty(Difficulty(difficulty)); // may be changed in _LoadGroup
- std::string taxi_nodes = fields[38].GetCppString();
-
-#define RelocateToHomebind(){ mapId = m_homebindMapId; instanceId = 0; Relocate(m_homebindX, m_homebindY, m_homebindZ); }
-
- _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
-
- _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
-
- uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[40].GetUInt32();
- if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
- arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
-
- SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
-
- // check arena teams integrity
- for (uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
- {
- uint32 arena_team_id = GetArenaTeamId(arena_slot);
- if(!arena_team_id)
- continue;
-
- if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
- if(at->HaveMember(GetGUID()))
- continue;
-
- // arena team not exist or not member, cleanup fields
- for (int j = 0; j < 6; ++j)
- SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arena_slot * ARENA_TEAM_END) + j, 0);
- }
-
- _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
- _LoadBGData(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBGDATA));
-
- MapEntry const * mapEntry = sMapStore.LookupEntry(mapId);
- if(!mapEntry || !IsPositionValid())
- {
- sLog.outError("Player (guidlow %d) have invalid coordinates (MapId: %u X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",guid,mapId,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
- RelocateToHomebind();
- }
- // Player was saved in Arena or Bg
- else if (mapEntry && mapEntry->IsBattleGroundOrArena())
- {
- BattleGround *currentBg = NULL;
- if(m_bgData.bgInstanceID) //saved in BattleGround
- currentBg = sBattleGroundMgr.GetBattleGround(m_bgData.bgInstanceID, BATTLEGROUND_TYPE_NONE);
-
- bool player_at_bg = currentBg && currentBg->IsPlayerInBattleGround(GetGUID());
-
- if(player_at_bg && currentBg->GetStatus() != STATUS_WAIT_LEAVE)
- {
- BattleGroundQueueTypeId bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
- AddBattleGroundQueueId(bgQueueTypeId);
-
- m_bgData.bgTypeID = currentBg->GetTypeID();
-
- //join player to battleground group
- currentBg->EventPlayerLoggedIn(this, GetGUID());
- currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), m_bgData.bgTeam);
-
- SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
- }
- // Bg was not found - go to Entry Point
- else
- {
- // leave bg
- if (player_at_bg)
- currentBg->RemovePlayerAtLeave(GetGUID(), false, true);
-
- // Do not look for instance if bg not found
- const WorldLocation& _loc = GetBattleGroundEntryPoint();
- mapId = _loc.GetMapId(); instanceId = 0;
-
- if(mapId == MAPID_INVALID) // Battleground Entry Point not found (???)
- {
- sLog.outError("Player (guidlow %d) was in BG in database, but BG was not found, and entry point was invalid! Teleport to default race/class locations.",guid);
- RelocateToHomebind();
- }
- else
- Relocate(&_loc);
-
- // We are not in BG anymore
- m_bgData.bgInstanceID = 0;
- }
- }
- // currently we do not support transport in bg
- else if (transGUID)
- {
- // There are no transports on instances
- instanceId = 0;
-
- m_movementInfo.t_x = fields[27].GetFloat();
- m_movementInfo.t_y = fields[28].GetFloat();
- m_movementInfo.t_z = fields[29].GetFloat();
- m_movementInfo.t_o = fields[30].GetFloat();
-
- if( !Trinity::IsValidMapCoord(
- GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
- GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
- // transport size limited
- m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
- {
- sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
- guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
- GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
-
- RelocateToHomebind();
- }
- else
- {
- for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
- {
- if( (*iter)->GetGUIDLow() == transGUID)
- {
- m_transport = *iter;
- m_transport->AddPassenger(this);
- mapId = (m_transport->GetMapId());
- break;
- }
- }
- if(!m_transport)
- {
- sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
- guid,transGUID);
-
- RelocateToHomebind();
- }
- }
- }
- // currently we do not support taxi in instance
- else if (!taxi_nodes.empty())
- {
- instanceId = 0;
-
- // Not finish taxi flight path
- if(m_bgData.HasTaxiPath())
- {
- for (int i = 0; i < 2; ++i)
- m_taxi.AddTaxiDestination(m_bgData.taxiPath[i]);
- }
- else if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
- {
- // problems with taxi path loading
- TaxiNodesEntry const* nodeEntry = NULL;
- if(uint32 node_id = m_taxi.GetTaxiSource())
- nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
-
- if(!nodeEntry) // don't know taxi start node, to homebind
- {
- sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
- RelocateToHomebind();
- }
- else // have start node, to it
- {
- sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
- mapId = nodeEntry->map_id;
- Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
- }
- m_taxi.ClearTaxiDestinations();
- }
-
- if (uint32 node_id = m_taxi.GetTaxiSource())
- {
- // save source node as recall coord to prevent recall and fall from sky
- TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
- if (nodeEntry && nodeEntry->map_id == GetMapId())
- {
- assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
- mapId = nodeEntry->map_id;
- Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
- }
-
- // flight will started later
- }
- }
-
- // Map could be changed before
- mapEntry = sMapStore.LookupEntry(mapId);
- // client without expansion support
- if(mapEntry && GetSession()->Expansion() < mapEntry->Expansion())
- {
- sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), mapId);
- RelocateToHomebind();
- }
-
- // fix crash (because of if(Map *map = _FindMap(instanceId)) in MapInstanced::CreateInstance)
- if(instanceId)
- if(InstanceSave * save = GetInstanceSave(mapId, mapEntry->IsRaid()))
- if(save->GetInstanceId() != instanceId)
- instanceId = 0;
-
- // NOW player must have valid map
- // load the player's map here if it's not already loaded
- Map *map = MapManager::Instance().CreateMap(mapId, this, instanceId);
-
- if (!map)
- {
- instanceId = 0;
- AreaTrigger const* at = objmgr.GetGoBackTrigger(mapId);
- if(at)
- {
- sLog.outError("Player (guidlow %d) is teleported to gobacktrigger (Map: %u X: %f Y: %f Z: %f O: %f).",guid,mapId,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
- Relocate(at->target_X, at->target_Y, at->target_Z, GetOrientation());
- mapId = at->target_mapId;
- }
- else
- {
- sLog.outError("Player (guidlow %d) is teleported to home (Map: %u X: %f Y: %f Z: %f O: %f).",guid,mapId,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
- RelocateToHomebind();
- }
-
- map = MapManager::Instance().CreateMap(mapId, this, 0);
- if(!map)
- {
- PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
- mapId = info->mapId;
- Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
- sLog.outError("ERROR: Player (guidlow %d) have invalid coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",guid,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
- map = MapManager::Instance().CreateMap(mapId, this, 0);
- if (!map)
- {
- sLog.outError("ERROR: Player (guidlow %d) has invalid default map coordinates (X: %f Y: %f Z: %f O: %f). or instance couldn't be created",guid,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
- return false;
- }
- }
- }
-
- // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
- if(instanceId && !sInstanceSaveManager.GetInstanceSave(instanceId))
- {
- AreaTrigger const* at = objmgr.GetMapEntranceTrigger(mapId);
- if(at)
- Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
- else
- {
- 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(), mapId);
- RelocateToHomebind();
- }
- }
-
- SetMap(map);
-
- // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
- // this must help in case next save after mass player load after server startup
- m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
-
- SaveRecallPosition();
-
- time_t now = time(NULL);
- time_t logoutTime = time_t(fields[23].GetUInt64());
-
- // since last logout (in seconds)
- uint32 time_diff = uint32(now - logoutTime); //uint64 is excessive for a time_diff in seconds.. uint32 allows for 136~ year difference.
-
- // set value, including drunk invisibility detection
- // calculate sobering. after 15 minutes logged out, the player will be sober again
- float soberFactor;
- if (time_diff > 15*MINUTE)
- soberFactor = 0;
- else
- soberFactor = 1-time_diff/(15.0f*MINUTE);
- uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
- SetDrunkValue(newDrunkenValue);
-
- m_rest_bonus = fields[22].GetFloat();
- //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
- float bubble0 = 0.031;
- //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
- float bubble1 = 0.125;
-
- if (time_diff > 0)
- {
- float bubble = fields[24].GetUInt32() > 0
- ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
- : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
-
- SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
- }
-
- m_cinematic = fields[19].GetUInt32();
- m_Played_time[PLAYED_TIME_TOTAL]= fields[20].GetUInt32();
- m_Played_time[PLAYED_TIME_LEVEL]= fields[21].GetUInt32();
-
- m_resetTalentsCost = fields[25].GetUInt32();
- m_resetTalentsTime = time_t(fields[26].GetUInt64());
-
- // reserve some flags
- uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
-
- if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM))
- SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
-
- m_taxi.LoadTaxiMask(fields[18].GetString()); // must be before InitTaxiNodesForLevel
-
- uint32 extraflags = fields[32].GetUInt32();
-
- m_stableSlots = fields[33].GetUInt32();
- if (m_stableSlots > MAX_PET_STABLES)
- {
- sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
- m_stableSlots = MAX_PET_STABLES;
- }
-
- m_atLoginFlags = fields[34].GetUInt32();
-
- // Honor system
- // Update Honor kills data
- m_lastHonorUpdateTime = logoutTime;
- UpdateHonorFields();
-
- m_deathExpireTime = (time_t)fields[37].GetUInt64();
- if (m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
- m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
-
- // clear channel spell data (if saved at channel spell casting)
- SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
- SetUInt32Value(UNIT_CHANNEL_SPELL,0);
-
- // clear charm/summon related fields
- SetUInt64Value(UNIT_FIELD_SUMMONEDBY, 0);
- SetUInt64Value(UNIT_FIELD_CHARMEDBY, 0);
- SetUInt64Value(UNIT_FIELD_CHARM, 0);
- SetUInt64Value(UNIT_FIELD_SUMMON, 0);
- SetUInt64Value(PLAYER_FARSIGHT, 0);
- SetCreatorGUID(0);
-
- RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVE);
-
- // reset some aura modifiers before aura apply
- SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
- SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
-
- // make sure the unit is considered out of combat for proper loading
- ClearInCombat();
-
- // make sure the unit is considered not in duel for proper loading
- SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
- SetUInt32Value(PLAYER_DUEL_TEAM, 0);
-
- // remember loaded power/health values to restore after stats initialization and modifier applying
- uint32 savedHealth = GetHealth();
- uint32 savedPower[MAX_POWERS];
- for (uint8 i = 0; i < MAX_POWERS; ++i)
- savedPower[i] = GetPower(Powers(i));
-
- // reset stats before loading any modifiers
- InitStatsForLevel();
- InitGlyphsForLevel();
- InitTaxiNodesForLevel();
- InitRunes();
-
- // load skills after InitStatsForLevel because it triggering aura apply also
- _LoadSkills(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSKILLS));
-
- // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
-
- //mails are loaded only when needed ;-) - when player in game click on mailbox.
- //_LoadMail();
-
- m_specsCount = fields[42].GetUInt8();
- m_activeSpec = fields[43].GetUInt8();
-
- // sanity check
- if (m_specsCount > MAX_TALENT_SPECS || m_activeSpec > MAX_TALENT_SPEC ||
- m_specsCount < MIN_TALENT_SPECS || m_activeSpec < MIN_TALENT_SPEC)
- {
- m_activeSpec = 0;
- sLog.outError("Player %s(GUID: %u) has SpecCount = %u and ActiveSpec = %u.", GetName(), GetGUIDLow(), m_specsCount, m_activeSpec);
- }
-
- _LoadTalents(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTALENTS));
- _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
-
- _LoadGlyphs(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGLYPHS));
- _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
- _LoadGlyphAuras();
- // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
- if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
- m_deathState = DEAD;
-
- // after spell load, learn rewarded spell if need also
- _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
- _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
-
- // after spell and quest load
- InitTalentForLevel();
- learnDefaultSpells();
-
- // must be before inventory (some items required reputation check)
- m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
-
- _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
-
- // update items with duration and realtime
- UpdateItemDuration(time_diff, true);
-
- _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS), true);
-
- // unread mails and next delivery time, actual mails not loaded
- _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
-
- m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
-
- // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
- // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
- if (uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
- if(!HasTitle(curTitle))
- SetUInt32Value(PLAYER_CHOSEN_TITLE, 0);
-
- // has to be called after last Relocate() in Player::LoadFromDB
- SetFallInformation(0, GetPositionZ());
-
- _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
-
- // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
- // Do now before stats re-calculation cleanup for ghost state unexpected auras
- if (!isAlive())
- RemoveAllAurasOnDeath();
-
- //apply all stat bonuses from items and auras
- SetCanModifyStats(true);
- UpdateAllStats();
-
- // restore remembered power/health values (but not more max values)
- SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
- for (uint8 i = 0; i < MAX_POWERS; ++i)
- SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
-
- sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
- outDebugValues();
-
- // GM state
- if (GetSession()->GetSecurity() > SEC_PLAYER)
- {
- switch (sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
- {
- default:
- case 0: break; // disable
- case 1: SetGameMaster(true); break; // enable
- case 2: // save state
- if(extraflags & PLAYER_EXTRA_GM_ON)
- SetGameMaster(true);
- break;
- }
-
- switch (sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
- {
- default:
- case 0: SetGMVisible(false); break; // invisible
- case 1: break; // visible
- case 2: // save state
- if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
- SetGMVisible(false);
- break;
- }
-
- /*switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
- {
- default:
- case 0: break; // disable
- case 1: SetAcceptTicket(true); break; // enable
- case 2: // save state
- if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
- SetAcceptTicket(true);
- break;
- }*/
-
- switch (sWorld.getConfig(CONFIG_GM_CHAT))
- {
- default:
- case 0: break; // disable
- case 1: SetGMChat(true); break; // enable
- case 2: // save state
- if(extraflags & PLAYER_EXTRA_GM_CHAT)
- SetGMChat(true);
- break;
- }
-
- switch (sWorld.getConfig(CONFIG_GM_WISPERING_TO))
- {
- default:
- case 0: break; // disable
- case 1: SetAcceptWhispers(true); break; // enable
- case 2: // save state
- if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
- SetAcceptWhispers(true);
- break;
- }
- }
-
- _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
-
- m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
- m_achievementMgr.CheckAllAchievementCriteria();
-
- _LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
-
- return true;
-}
-
-bool Player::isAllowedToLoot(Creature* creature)
-{
- if (creature->isDead() && !creature->IsDamageEnoughForLootingAndReward())
- return false;
-
- if (Player* recipient = creature->GetLootRecipient())
- {
- if (recipient == this)
- return true;
- if (Group* otherGroup = recipient->GetGroup())
- {
- Group* thisGroup = GetGroup();
- if (!thisGroup)
- return false;
- return thisGroup == otherGroup;
- }
- return false;
- }
- else
- // prevent other players from looting if the recipient got disconnected
- return !creature->hasLootRecipient();
-}
-
-void Player::_LoadActions(QueryResult_AutoPtr result, bool startup)
-{
- if (result)
- {
- do
- {
- Field *fields = result->Fetch();
-
- uint8 button = fields[0].GetUInt8();
- uint32 action = fields[1].GetUInt32();
- uint8 type = fields[2].GetUInt8();
-
- if(ActionButton* ab = addActionButton(button, action, type))
- {
- ab->uState = ACTIONBUTTON_UNCHANGED;
- if(!startup) // Switching specs
- ab->canRemoveByClient = false;
- }
- else
- {
- sLog.outError( " ...at loading, and will deleted in DB also");
-
- // Will deleted in DB at next save (it can create data until save but marked as deleted)
- m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
- }
- }
- while (result->NextRow());
- }
-}
-
-void Player::_LoadAuras(QueryResult_AutoPtr result, uint32 timediff)
-{
- sLog.outDebug("Loading auras for player %u",GetGUIDLow());
-
- //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_mask,recalculate_mask,stackcount,amount0,amount1,amount2,base_amount0,base_amount1,base_amount2,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
-
- if (result)
- {
- do
- {
- int32 damage[3];
- int32 baseDamage[3];
- Field *fields = result->Fetch();
- uint64 caster_guid = fields[0].GetUInt64();
- uint32 spellid = fields[1].GetUInt32();
- uint8 effmask = fields[2].GetUInt8();
- uint8 recalculatemask = fields[3].GetUInt8();
- uint8 stackcount = fields[4].GetUInt8();
- damage[0] = fields[5].GetInt32();
- damage[1] = fields[6].GetInt32();
- damage[2] = fields[7].GetInt32();
- baseDamage[0] = fields[8].GetInt32();
- baseDamage[1] = fields[9].GetInt32();
- baseDamage[2] = fields[10].GetInt32();
- int32 maxduration = fields[11].GetInt32();
- int32 remaintime = fields[12].GetInt32();
- uint8 remaincharges = fields[13].GetUInt8();
-
- SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
- if (!spellproto)
- {
- sLog.outError("Unknown aura (spellid %u), ignore.",spellid);
- continue;
- }
-
- // negative effects should continue counting down after logout
- if (remaintime != -1 && !IsPositiveSpell(spellid))
- {
- if (remaintime/IN_MILISECONDS <= int32(timediff))
- continue;
-
- remaintime -= timediff*IN_MILISECONDS;
- }
-
- // prevent wrong values of remaincharges
- if (spellproto->procCharges)
- {
- if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
- remaincharges = spellproto->procCharges;
- }
- else
- remaincharges = 0;
-
- if (Aura * aura = Aura::TryCreate(spellproto, effmask, this, NULL, &baseDamage[0], NULL, caster_guid))
- {
- if (!aura->CanBeSaved())
- {
- aura->Remove();
- continue;
- }
- aura->SetLoadedState(maxduration,remaintime,remaincharges,stackcount,recalculatemask,&damage[0]);
- aura->ApplyForTargets();
- sLog.outDetail("Added aura spellid %u, effectmask %u", spellproto->Id, effmask);
- }
- }
- while (result->NextRow());
- }
-
- if (getClass() == CLASS_WARRIOR && !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT))
- CastSpell(this, 2457, true);
-}
-
-void Player::_LoadGlyphAuras()
-{
- for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
- {
- if (uint32 glyph = GetGlyph(i))
- {
- if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
- {
- if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
- {
- if (gp->TypeFlags == gs->TypeFlags)
- {
- CastSpell(this, gp->SpellId, true);
- continue;
- }
- else
- sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
- }
- else
- sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
- }
- else
- sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
-
- // On any error remove glyph
- SetGlyph(i, 0);
- }
- }
-}
-
-void Player::LoadCorpse()
-{
- if (isAlive())
- ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
- else
- {
- if (Corpse *corpse = GetCorpse())
- ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
- else
- //Prevent Dead Player login without corpse
- ResurrectPlayer(0.5f);
- }
-}
-
-void Player::_LoadInventory(QueryResult_AutoPtr result, uint32 timediff)
-{
- //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());
- std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
- //NOTE: the "order by `bag`" is important because it makes sure
- //the bagMap is filled before items in the bags are loaded
- //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
- //expected to be equipped before offhand items (TODO: fixme)
-
- uint32 zone = GetZoneId();
-
- if (result)
- {
- std::list<Item*> problematicItems;
-
- // prevent items from being added to the queue when stored
- m_itemUpdateQueueBlocked = true;
- do
- {
- Field *fields = result->Fetch();
- uint32 bag_guid = fields[1].GetUInt32();
- uint8 slot = fields[2].GetUInt8();
- uint32 item_guid = fields[3].GetUInt32();
- uint32 item_id = fields[4].GetUInt32();
-
- ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
-
- if (!proto)
- {
- CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
- CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
- sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
- continue;
- }
-
- Item *item = NewItemOrBag(proto);
-
- if (!item->LoadFromDB(item_guid, GetGUID(), result))
- {
- sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
- CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
- item->FSetState(ITEM_REMOVED);
- item->SaveToDB(); // it also deletes item object !
- continue;
- }
-
- // not allow have in alive state item limited to another map/zone
- if (isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone))
- {
- CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
- item->FSetState(ITEM_REMOVED);
- item->SaveToDB(); // it also deletes item object !
- continue;
- }
-
- // "Conjured items disappear if you are logged out for more than 15 minutes"
- if (timediff > 15*MINUTE && item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED))
- {
- CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
- item->FSetState(ITEM_REMOVED);
- item->SaveToDB(); // it also deletes item object !
- continue;
- }
-
- bool success = true;
-
- if (!bag_guid)
- {
- // the item is not in a bag
- item->SetContainer(NULL);
- item->SetSlot(slot);
-
- if (IsInventoryPos(INVENTORY_SLOT_BAG_0, slot))
- {
- ItemPosCountVec dest;
- if (CanStoreItem(INVENTORY_SLOT_BAG_0, slot, dest, item, false) == EQUIP_ERR_OK)
- item = StoreItem(dest, item, true);
- else
- success = false;
- }
- else if (IsEquipmentPos(INVENTORY_SLOT_BAG_0, slot))
- {
- uint16 dest;
- if (CanEquipItem(slot, dest, item, false, false) == EQUIP_ERR_OK)
- QuickEquipItem(dest, item);
- else
- success = false;
- }
- else if (IsBankPos(INVENTORY_SLOT_BAG_0, slot))
- {
- ItemPosCountVec dest;
- if (CanBankItem(INVENTORY_SLOT_BAG_0, slot, dest, item, false, false) == EQUIP_ERR_OK)
- item = BankItem(dest, item, true);
- else
- success = false;
- }
-
- if (success)
- {
- // store bags that may contain items in them
- if (item->IsBag() && IsBagPos(item->GetPos()))
- bagMap[item_guid] = (Bag*)item;
- }
- }
- else
- {
- item->SetSlot(NULL_SLOT);
- // the item is in a bag, find the bag
- std::map<uint64, Bag*>::iterator itr = bagMap.find(bag_guid);
- if (itr != bagMap.end())
- {
- ItemPosCountVec dest;
- uint8 result = CanStoreItem(itr->second->GetSlot(), slot, dest, item);
- if (result == EQUIP_ERR_OK)
- itr->second->StoreItem(slot, item, true);
- else
- {
- sLog.outError("Player::_LoadInventory: Player %s has item (GUID: %u Entry: %u) can't be loaded to inventory (Bag GUID: %u Slot: %u) by reason %u.", GetName(),item_guid, item_id, bag_guid, slot, result);
- success = false;
- }
- }
- else
- success = false;
- }
-
- // item's state may have changed after stored
- if (success)
- item->SetState(ITEM_UNCHANGED, this);
- else
- {
- 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);
- CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
- problematicItems.push_back(item);
- }
- } while (result->NextRow());
-
- m_itemUpdateQueueBlocked = false;
-
- // send by mail problematic items
- while (!problematicItems.empty())
- {
- std::string subject = GetSession()->GetTrinityString(LANG_NOT_EQUIPPED_ITEM);
-
- // fill mail
- MailDraft draft(subject);
-
- for (uint8 i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
- {
- Item* item = problematicItems.front();
- problematicItems.pop_front();
-
- draft.AddItem(item);
- }
-
- draft.SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM));
- }
- }
- //if(isAlive())
- _ApplyAllItemMods();
-}
-
-// load mailed item which should receive current player
-void Player::_LoadMailedItems(Mail *mail)
-{
- // data needs to be at first place for Item::LoadFromDB
- QueryResult_AutoPtr 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);
- if (!result)
- return;
-
- do
- {
- Field *fields = result->Fetch();
- uint32 item_guid_low = fields[1].GetUInt32();
- uint32 item_template = fields[2].GetUInt32();
-
- mail->AddItem(item_guid_low, item_template);
-
- ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
-
- if (!proto)
- {
- 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);
- CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
- CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
- continue;
- }
-
- Item *item = NewItemOrBag(proto);
-
- if (!item->LoadFromDB(item_guid_low, 0, result))
- {
- sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
- CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
- item->FSetState(ITEM_REMOVED);
- item->SaveToDB(); // it also deletes item object !
- continue;
- }
-
- AddMItem(item);
- } while (result->NextRow());
-}
-
-void Player::_LoadMailInit(QueryResult_AutoPtr resultUnread, QueryResult_AutoPtr resultDelivery)
-{
- //set a count of unread mails
- //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);
- if (resultUnread)
- {
- Field *fieldMail = resultUnread->Fetch();
- unReadMails = fieldMail[0].GetUInt8();
- }
-
- // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
- //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
- if (resultDelivery)
- {
- Field *fieldMail = resultDelivery->Fetch();
- m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
- }
-}
-
-void Player::_LoadMail()
-{
- m_mail.clear();
- //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
- QueryResult_AutoPtr 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());
- if (result)
- {
- do
- {
- Field *fields = result->Fetch();
- Mail *m = new Mail;
- m->messageID = fields[0].GetUInt32();
- m->messageType = fields[1].GetUInt8();
- m->sender = fields[2].GetUInt32();
- m->receiver = fields[3].GetUInt32();
- m->subject = fields[4].GetCppString();
- m->itemTextId = fields[5].GetUInt32();
- bool has_items = fields[6].GetBool();
- m->expire_time = (time_t)fields[7].GetUInt64();
- m->deliver_time = (time_t)fields[8].GetUInt64();
- m->money = fields[9].GetUInt32();
- m->COD = fields[10].GetUInt32();
- m->checked = fields[11].GetUInt32();
- m->stationery = fields[12].GetUInt8();
- m->mailTemplateId = fields[13].GetInt16();
-
- if (m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
- {
- sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
- m->mailTemplateId = 0;
- }
-
- m->state = MAIL_STATE_UNCHANGED;
-
- if (has_items)
- _LoadMailedItems(m);
-
- m_mail.push_back(m);
- } while (result->NextRow());
- }
- m_mailsLoaded = true;
-}
-
-void Player::LoadPet()
-{
- //fixme: the pet should still be loaded if the player is not in world
- // just not added to the map
- if (IsInWorld())
- {
- Pet *pet = new Pet(this);
- if (!pet->LoadPetFromDB(this,0,0,true))
- delete pet;
- }
-}
-
-void Player::_LoadQuestStatus(QueryResult_AutoPtr result)
-{
- mQuestStatus.clear();
-
- uint16 slot = 0;
-
- //// 0 1 2 3 4 5 6 7 8 9 10 11 12
- //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());
-
- if (result)
- {
- do
- {
- Field *fields = result->Fetch();
-
- uint32 quest_id = fields[0].GetUInt32();
- // used to be new, no delete?
- Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
- if (pQuest)
- {
- // find or create
- QuestStatusData& questStatusData = mQuestStatus[quest_id];
-
- uint32 qstatus = fields[1].GetUInt32();
- if (qstatus < MAX_QUEST_STATUS)
- questStatusData.m_status = QuestStatus(qstatus);
- else
- {
- questStatusData.m_status = QUEST_STATUS_NONE;
- sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
- }
-
- questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
- questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
-
- time_t quest_time = time_t(fields[4].GetUInt64());
-
- if (pQuest->HasFlag(QUEST_TRINITY_FLAGS_TIMED) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE)
- {
- AddTimedQuest(quest_id);
-
- if (quest_time <= sWorld.GetGameTime())
- questStatusData.m_timer = 1;
- else
- questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
- }
- else
- quest_time = 0;
-
- questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
- questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
- questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
- questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
- questStatusData.m_itemcount[0] = fields[9].GetUInt32();
- questStatusData.m_itemcount[1] = fields[10].GetUInt32();
- questStatusData.m_itemcount[2] = fields[11].GetUInt32();
- questStatusData.m_itemcount[3] = fields[12].GetUInt32();
-
- questStatusData.uState = QUEST_UNCHANGED;
-
- // add to quest log
- if (slot < MAX_QUEST_LOG_SIZE &&
- ((questStatusData.m_status == QUEST_STATUS_INCOMPLETE ||
- questStatusData.m_status == QUEST_STATUS_COMPLETE ||
- questStatusData.m_status == QUEST_STATUS_FAILED) &&
- (!questStatusData.m_rewarded || pQuest->IsRepeatable())))
- {
- SetQuestSlot(slot, quest_id, quest_time);
-
- if (questStatusData.m_status == QUEST_STATUS_COMPLETE)
- SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
-
- if (questStatusData.m_status == QUEST_STATUS_FAILED)
- SetQuestSlotState(slot, QUEST_STATE_FAIL);
-
- for (uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
- if (questStatusData.m_creatureOrGOcount[idx])
- SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]);
-
- ++slot;
- }
-
- if (questStatusData.m_rewarded)
- {
- // learn rewarded spell if unknown
- learnQuestRewardedSpells(pQuest);
-
- // set rewarded title if any
- if (pQuest->GetCharTitleId())
- {
- if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
- SetTitle(titleEntry);
- }
-
- if(pQuest->GetBonusTalents())
- m_questRewardTalentCount += pQuest->GetBonusTalents();
- }
-
- sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
- }
- }
- while (result->NextRow());
- }
-
- // clear quest log tail
- for (uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i)
- SetQuestSlot(i, 0);
-}
-
-void Player::_LoadDailyQuestStatus(QueryResult_AutoPtr result)
-{
- for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
- SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
-
- //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
-
- if (result)
- {
- uint32 quest_daily_idx = 0;
-
- do
- {
- if (quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
- {
- sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
- break;
- }
-
- Field *fields = result->Fetch();
-
- uint32 quest_id = fields[0].GetUInt32();
-
- // save _any_ from daily quest times (it must be after last reset anyway)
- m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
-
- Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
- if (!pQuest)
- continue;
-
- SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
- ++quest_daily_idx;
-
- sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
- }
- while (result->NextRow());
- }
-
- m_DailyQuestChanged = false;
-}
-
-void Player::_LoadSpells(QueryResult_AutoPtr result)
-{
- //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
-
- if (result)
- {
- do
- {
- Field *fields = result->Fetch();
-
- addSpell(fields[0].GetUInt32(), fields[1].GetBool(), false, false, fields[2].GetBool());
- }
- while (result->NextRow());
- }
-}
-
-void Player::_LoadGroup(QueryResult_AutoPtr result)
-{
- //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
- if (result)
- {
- uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
- if (Group* group = objmgr.GetGroupByLeader(leaderGuid))
- {
- uint8 subgroup = group->GetMemberGroup(GetGUID());
- SetGroup(group, subgroup);
- if (getLevel() >= LEVELREQUIREMENT_HEROIC)
- {
- // the group leader may change the instance difficulty while the player is offline
- SetDungeonDifficulty(group->GetDungeonDifficulty());
- SetRaidDifficulty(group->GetRaidDifficulty());
- }
- }
- }
-}
-
-void Player::_LoadBoundInstances(QueryResult_AutoPtr result)
-{
- for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
- m_boundInstances[i].clear();
-
- Group *group = GetGroup();
-
- //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));
- if (result)
- {
- do
- {
- Field *fields = result->Fetch();
- bool perm = fields[1].GetBool();
- uint32 mapId = fields[2].GetUInt32();
- uint32 instanceId = fields[0].GetUInt32();
- uint8 difficulty = fields[3].GetUInt8();
-
- time_t resetTime = (time_t)fields[4].GetUInt64();
- // the resettime for normal instances is only saved when the InstanceSave is unloaded
- // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
- // and in that case it is not used
-
- MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
- if (!mapEntry || !mapEntry->IsDungeon())
- {
- sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
- CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
- continue;
- }
-
- if(difficulty >= MAX_DIFFICULTY)
- {
- sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
- CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
- continue;
- }
-
- MapDifficulty const* mapDiff = GetMapDifficultyData(mapId,Difficulty(difficulty));
- if(!mapDiff)
- {
- sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
- CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
- continue;
- }
-
-
- if (!perm && group)
- {
- 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);
- CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
- continue;
- }
-
- // since non permanent binds are always solo bind, they can always be reset
- if (InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, Difficulty(difficulty), resetTime, !perm, true))
- BindToInstance(save, perm, true);
- } while (result->NextRow());
- }
-}
-
-InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty)
-{
- // some instances only have one difficulty
- MapDifficulty const* mapDiff = GetMapDifficultyData(mapid,difficulty);
- if(!mapDiff)
- return NULL;
-
- BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
- if (itr != m_boundInstances[difficulty].end())
- return &itr->second;
- else
- return NULL;
-}
-
-InstanceSave * Player::GetInstanceSave(uint32 mapid, bool raid)
-{
- InstancePlayerBind *pBind = GetBoundInstance(mapid, GetDifficulty(raid));
- InstanceSave *pSave = pBind ? pBind->save : NULL;
- if (!pBind || !pBind->perm)
- if(Group *group = GetGroup())
- if(InstanceGroupBind *groupBind = group->GetBoundInstance(this))
- pSave = groupBind->save;
-
- return pSave;
-}
-
-void Player::UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload)
-{
- BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
- UnbindInstance(itr, difficulty, unload);
-}
-
-void Player::UnbindInstance(BoundInstancesMap::iterator &itr, Difficulty difficulty, bool unload)
-{
- if (itr != m_boundInstances[difficulty].end())
- {
- if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
- itr->second.save->RemovePlayer(this); // save can become invalid
- m_boundInstances[difficulty].erase(itr++);
- }
-}
-
-InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
-{
- if(save)
- {
- InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
- if (bind.save)
- {
- // update the save when the group kills a boss
- if (permanent != bind.perm || save != bind.save)
- 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());
- }
- else
- if (!load)
- CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
-
- if (bind.save != save)
- {
- if(bind.save)
- bind.save->RemovePlayer(this);
- save->AddPlayer(this);
- }
-
- if (permanent)
- save->SetCanReset(false);
-
- bind.save = save;
- bind.perm = permanent;
- 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());
- return &bind;
- }
- else
- return NULL;
-}
-
-void Player::SendRaidInfo()
-{
- uint32 counter = 0;
-
- WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
-
- size_t p_counter = data.wpos();
- data << uint32(counter); // placeholder
-
- time_t now = time(NULL);
-
- for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
- {
- for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
- {
- if(itr->second.perm)
- {
- InstanceSave *save = itr->second.save;
- data << uint32(save->GetMapId()); // map id
- data << uint32(save->GetDifficulty()); // difficulty
- data << uint64(save->GetInstanceId()); // instance id
- data << uint8(1); // expired = 0
- data << uint8(0); // extended = 1
- data << uint32(save->GetResetTime() - now); // reset time
- ++counter;
- }
- }
- }
- data.put<uint32>(p_counter, counter);
- GetSession()->SendPacket(&data);
-}
-
-/*
-- called on every successful teleportation to a map
-*/
-void Player::SendSavedInstances()
-{
- bool hasBeenSaved = false;
- WorldPacket data;
-
- for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
- {
- for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
- {
- if (itr->second.perm) // only permanent binds are sent
- {
- hasBeenSaved = true;
- break;
- }
- }
- }
-
- //Send opcode 811. true or false means, whether you have current raid/heroic instances
- data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
- data << uint32(hasBeenSaved);
- GetSession()->SendPacket(&data);
-
- if (!hasBeenSaved)
- return;
-
- for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
- {
- for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
- {
- if (itr->second.perm)
- {
- data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
- data << uint32(itr->second.save->GetMapId());
- GetSession()->SendPacket(&data);
- }
- }
- }
-}
-
-/// convert the player's binds to the group
-void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
-{
- bool has_binds = false;
- bool has_solo = false;
-
- if(player)
- {
- player_guid = player->GetGUID();
- if (!group)
- group = player->GetGroup();
- }
- assert(player_guid);
-
- // copy all binds to the group, when changing leader it's assumed the character
- // will not have any solo binds
-
- if (player)
- {
- for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
- {
- for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
- {
- has_binds = true;
- if (group)
- group->BindToInstance(itr->second.save, itr->second.perm, true);
- // permanent binds are not removed
- if (!itr->second.perm)
- {
- // increments itr in call
- player->UnbindInstance(itr, Difficulty(i), true);
- has_solo = true;
- }
- else
- ++itr;
- }
- }
- }
-
- // if the player's not online we don't know what binds it has
- 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));
- // the following should not get executed when changing leaders
- if(!player || has_solo)
- CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
-}
-
-bool Player::Satisfy(AccessRequirement const *ar, uint32 target_map, bool report)
-{
- if (!isGameMaster() && ar)
- {
- uint8 LevelMin = 0;
- uint8 LevelMax = 0;
-
- if (!sWorld.getConfig(CONFIG_INSTANCE_IGNORE_LEVEL))
- {
- if (ar->levelMin && getLevel() < ar->levelMin)
- LevelMin = ar->levelMin;
- if(ar->heroicLevelMin && GetDungeonDifficulty() == DUNGEON_DIFFICULTY_HEROIC && getLevel() < ar->heroicLevelMin)
- LevelMin = ar->heroicLevelMin;
- if (ar->levelMax && getLevel() > ar->levelMax)
- LevelMax = ar->levelMax;
- }
-
- uint32 missingItem = 0;
- if (ar->item)
- {
- if (!HasItemCount(ar->item, 1) &&
- (!ar->item2 || !HasItemCount(ar->item2, 1)))
- missingItem = ar->item;
- }
- else if(ar->item2 && !HasItemCount(ar->item2, 1))
- missingItem = ar->item2;
-
- MapEntry const* mapEntry = sMapStore.LookupEntry(target_map);
- if(!mapEntry)
- return false;
-
- bool isNormalTargetMap = mapEntry->IsRaid()
- ? (GetRaidDifficulty() == RAID_DIFFICULTY_10MAN_NORMAL)
- : (GetDungeonDifficulty() == DUNGEON_DIFFICULTY_NORMAL);
-
- uint32 missingKey = 0;
- uint32 missingHeroicQuest = 0;
- if(!isNormalTargetMap)
- {
- if (ar->heroicKey)
- {
- if (!HasItemCount(ar->heroicKey, 1) &&
- (!ar->heroicKey2 || !HasItemCount(ar->heroicKey2, 1)))
- missingKey = ar->heroicKey;
- }
- else if (ar->heroicKey2 && !HasItemCount(ar->heroicKey2, 1))
- missingKey = ar->heroicKey2;
-
- if (ar->heroicQuest && !GetQuestRewardStatus(ar->heroicQuest))
- missingHeroicQuest = ar->heroicQuest;
- }
-
- uint32 missingQuest = 0;
- if(ar->quest && !GetQuestRewardStatus(ar->quest))
- missingQuest = ar->quest;
-
- if (LevelMin || LevelMax || missingItem || missingKey || missingQuest || missingHeroicQuest)
- {
- if (report)
- {
- if (missingItem)
- GetSession()->SendAreaTriggerMessage(GetSession()->GetTrinityString(LANG_LEVEL_MINREQUIRED_AND_ITEM), LevelMin, objmgr.GetItemPrototype(missingItem)->Name1);
- else if (missingKey)
- SendTransferAborted(target_map, TRANSFER_ABORT_DIFFICULTY, isNormalTargetMap ? DUNGEON_DIFFICULTY_NORMAL : DUNGEON_DIFFICULTY_HEROIC);
- else if (missingHeroicQuest)
- GetSession()->SendAreaTriggerMessage(ar->heroicQuestFailedText.c_str());
- else if (missingQuest)
- GetSession()->SendAreaTriggerMessage(ar->questFailedText.c_str());
- else if (LevelMin)
- GetSession()->SendAreaTriggerMessage(GetSession()->GetTrinityString(LANG_LEVEL_MINREQUIRED), LevelMin);
- }
- return false;
- }
- }
- return true;
-}
-
-bool Player::_LoadHomeBind(QueryResult_AutoPtr result)
-{
- PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
- if (!info)
- {
- sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
- return false;
- }
-
- bool ok = false;
- //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
- if (result)
- {
- Field *fields = result->Fetch();
- m_homebindMapId = fields[0].GetUInt32();
- m_homebindZoneId = fields[1].GetUInt16();
- m_homebindX = fields[2].GetFloat();
- m_homebindY = fields[3].GetFloat();
- m_homebindZ = fields[4].GetFloat();
-
- MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
-
- // accept saved data only for valid position (and non instanceable), and accessable
- if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
- !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
- ok = true;
- else
- CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
- }
-
- if (!ok)
- {
- m_homebindMapId = info->mapId;
- m_homebindZoneId = info->zoneId;
- m_homebindX = info->positionX;
- m_homebindY = info->positionY;
- m_homebindZ = info->positionZ;
-
- 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);
- }
-
- DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
- m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
-
- return true;
-}
-
-/*********************************************************/
-/*** SAVE SYSTEM ***/
-/*********************************************************/
-
-void Player::SaveToDB()
-{
- // delay auto save at any saves (manual, in code, or autosave)
- m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
-
- //lets allow only players in world to be saved
- if (IsBeingTeleportedFar())
- {
- ScheduleDelayedOperation(DELAYED_SAVE_PLAYER);
- return;
- }
-
- // first save/honor gain after midnight will also update the player's honor fields
- UpdateHonorFields();
-
- sLog.outDebug("The value of player %s at save: ", m_name.c_str());
- outDebugValues();
-
- std::string sql_name = m_name;
- CharacterDatabase.escape_string(sql_name);
-
- std::ostringstream ss;
- ss << "REPLACE INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags,"
- "map, instance_id, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
- "taximask, online, 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, "
- "death_expire_time, taxi_path, arena_pending_points, latency, speccount, activespec) VALUES ("
- << GetGUIDLow() << ", "
- << GetSession()->GetAccountId() << ", '"
- << sql_name << "', "
- << uint32(getRace()) << ", "
- << uint32(getClass()) << ", "
- << uint32(getGender()) << ", "
- << uint32(getLevel()) << ", "
- << GetUInt32Value(PLAYER_XP) << ", "
- << GetMoney() << ", "
- << GetUInt32Value(PLAYER_BYTES) << ", "
- << GetUInt32Value(PLAYER_BYTES_2) << ", "
- << GetUInt32Value(PLAYER_FLAGS) << ", ";
-
- if (!IsBeingTeleported())
- {
- ss << GetMapId() << ", "
- << (uint32)GetInstanceId() << ", "
- << (uint32)GetDungeonDifficulty() << ", "
- << finiteAlways(GetPositionX()) << ", "
- << finiteAlways(GetPositionY()) << ", "
- << finiteAlways(GetPositionZ()) << ", "
- << finiteAlways(GetOrientation()) << ", '";
- }
- else
- {
- ss << GetTeleportDest().GetMapId() << ", "
- << (uint32)0 << ", "
- << (uint32)GetDungeonDifficulty() << ", "
- << finiteAlways(GetTeleportDest().GetPositionX()) << ", "
- << finiteAlways(GetTeleportDest().GetPositionY()) << ", "
- << finiteAlways(GetTeleportDest().GetPositionZ()) << ", "
- << finiteAlways(GetTeleportDest().GetOrientation()) << ", '";
- }
-
- uint16 i;
- for (i = 0; i < m_valuesCount; ++i)
- ss << GetUInt32Value(i) << " ";
-
- ss << "', ";
-
- ss << m_taxi << ", "; // string with TaxiMaskSize numbers
-
- ss << (IsInWorld() ? 1 : 0) << ", ";
-
- ss << m_cinematic << ", ";
-
- ss << m_Played_time[PLAYED_TIME_TOTAL] << ", ";
- ss << m_Played_time[PLAYED_TIME_LEVEL] << ", ";
-
- ss << finiteAlways(m_rest_bonus) << ", ";
- ss << (uint64)time(NULL) << ", ";
- ss << (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0) << ", ";
- //save, far from tavern/city
- //save, but in tavern/city
- ss << m_resetTalentsCost << ", ";
- ss << (uint64)m_resetTalentsTime << ", ";
-
- ss << finiteAlways(m_movementInfo.t_x) << ", ";
- ss << finiteAlways(m_movementInfo.t_y) << ", ";
- ss << finiteAlways(m_movementInfo.t_z) << ", ";
- ss << finiteAlways(m_movementInfo.t_o) << ", ";
- if (m_transport)
- ss << m_transport->GetGUIDLow();
- else
- ss << "0";
- ss << ", ";
-
- ss << m_ExtraFlags << ", ";
-
- ss << uint32(m_stableSlots) << ", "; // to prevent save uint8 as char
-
- ss << uint32(m_atLoginFlags) << ", ";
-
- ss << GetZoneId() << ", ";
-
- ss << (uint64)m_deathExpireTime << ", '";
-
- ss << m_taxi.SaveTaxiDestinationsToString() << "', ";
- ss << "'0', "; // arena_pending_points
- ss << GetSession()->GetLatency();
- ss << ", ";
- ss << uint32(m_specsCount);
- ss << ", ";
- ss << uint32(m_activeSpec);
- ss << ")";
-
- CharacterDatabase.BeginTransaction();
-
- CharacterDatabase.Execute( ss.str().c_str() );
-
- if (m_mailsUpdated) //save mails only when needed
- _SaveMail();
-
- _SaveBGData();
- _SaveInventory();
- _SaveQuestStatus();
- _SaveDailyQuestStatus();
- _SaveTalents();
- _SaveSpells();
- _SaveSpellCooldowns();
- _SaveActions();
- _SaveAuras();
- _SaveSkills();
- m_achievementMgr.SaveToDB();
- m_reputationMgr.SaveToDB();
- _SaveEquipmentSets();
- GetSession()->SaveTutorialsData(); // changed only while character in game
- _SaveGlyphs();
-
- CharacterDatabase.CommitTransaction();
-
- // save pet (hunter pet level and experience and all type pets health/mana).
- if (Pet* pet = GetPet())
- pet->SavePetToDB(PET_SAVE_AS_CURRENT);
-}
-
-// fast save function for item/money cheating preventing - save only inventory and money state
-void Player::SaveInventoryAndGoldToDB()
-{
- _SaveInventory();
- SaveGoldToDB();
-}
-
-void Player::SaveGoldToDB()
-{
- CharacterDatabase.PExecute("UPDATE characters SET money = '%u' WHERE guid = '%u'", GetMoney(), GetGUIDLow());
-}
-
-void Player::_SaveActions()
-{
- for (ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end();)
- {
- switch (itr->second.uState)
- {
- case ACTIONBUTTON_NEW:
- CharacterDatabase.PExecute("INSERT INTO character_action (guid,spec,button,action,type) VALUES ('%u', '%u', '%u', '%u', '%u')",
- GetGUIDLow(), (uint32)m_activeSpec, (uint32)itr->first, (uint32)itr->second.GetAction(), (uint32)itr->second.GetType() );
- itr->second.uState = ACTIONBUTTON_UNCHANGED;
- ++itr;
- break;
- case ACTIONBUTTON_CHANGED:
- CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u' WHERE guid = '%u' AND button = '%u' AND spec = '%u'",
- (uint32)itr->second.GetAction(), (uint32)itr->second.GetType(), GetGUIDLow(), (uint32)itr->first, (uint32)m_activeSpec);
- itr->second.uState = ACTIONBUTTON_UNCHANGED;
- ++itr;
- break;
- case ACTIONBUTTON_DELETED:
- CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u' and spec = '%u'", GetGUIDLow(), (uint32)itr->first, (uint32)m_activeSpec );
- m_actionButtons.erase(itr++);
- break;
- default:
- ++itr;
- break;
- }
- }
-}
-
-void Player::_SaveAuras()
-{
- CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
-
- for (AuraMap::const_iterator itr = m_ownedAuras.begin(); itr != m_ownedAuras.end() ; ++itr)
- {
- if (!itr->second->CanBeSaved())
- continue;
-
- Aura * aura = itr->second;
-
- int32 damage[MAX_SPELL_EFFECTS];
- int32 baseDamage[MAX_SPELL_EFFECTS];
- uint8 effMask = 0;
- uint8 recalculateMask = 0;
- for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
- {
- if (aura->GetEffect(i))
- {
- baseDamage[i] = aura->GetEffect(i)->GetBaseAmount();
- damage[i] = aura->GetEffect(i)->GetAmount();
- effMask |= (1<<i);
- if (aura->GetEffect(i)->CanBeRecalculated())
- recalculateMask |= (1<<i);
- }
- else
- {
- baseDamage[i] = NULL;
- damage[i] = NULL;
- }
- }
-
- CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_mask,recalculate_mask,stackcount,amount0,amount1,amount2,base_amount0,base_amount1,base_amount2,maxduration,remaintime,remaincharges) "
- "VALUES ('%u', '" UI64FMTD "', '%u', '%u', '%u', '%u', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%u')",
- GetGUIDLow(), itr->second->GetCasterGUID(), itr->second->GetId(), effMask, recalculateMask,
- itr->second->GetStackAmount(), damage[0], damage[1], damage[2], baseDamage[0], baseDamage[1], baseDamage[2],
- itr->second->GetMaxDuration(), itr->second->GetDuration(),itr->second->GetCharges());
- }
-}
-
-void Player::_SaveInventory()
-{
- // force items in buyback slots to new state
- // and remove those that aren't already
- for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
- {
- Item *item = m_items[i];
- if (!item || item->GetState() == ITEM_NEW)
- continue;
- CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
- CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
- m_items[i]->FSetState(ITEM_NEW);
- }
-
- // update enchantment durations
- for (EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
- itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
-
- // if no changes
- if (m_itemUpdateQueue.empty())
- return;
-
- // do not save if the update queue is corrupt
- bool error = false;
- for (size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
- {
- Item *item = m_itemUpdateQueue[i];
- if(!item || item->GetState() == ITEM_REMOVED) continue;
- Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
-
- if (test == NULL)
- {
- sLog.outCrash("Player(GUID: %u Name: %s)::_SaveInventory - the bag(%d) and slot(%d) values for the item with guid %d (state %d) are incorrect, the player doesn't have an item at that position!", GetGUIDLow(), GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow(), (int32)item->GetState());
- //error = true;
- //now some items in bags cannot be saved but after cleansup they appear again
- }
- else if (test != item)
- {
- 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());
- error = true;
- }
- }
-
- if (error)
- {
- sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
- ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
- return;
- }
-
- for (size_t i = 0; i < m_itemUpdateQueue.size(); i++)
- {
- Item *item = m_itemUpdateQueue[i];
- if(!item) continue;
-
- Bag *container = item->GetContainer();
- uint32 bag_guid = container ? container->GetGUIDLow() : 0;
-
- switch(item->GetState())
- {
- case ITEM_NEW:
- 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());
- break;
- case ITEM_CHANGED:
- 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());
- break;
- case ITEM_REMOVED:
- CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
- break;
- case ITEM_UNCHANGED:
- break;
- }
-
- item->SaveToDB(); // item have unchanged inventory record and can be save standalone
- }
- m_itemUpdateQueue.clear();
-}
-
-void Player::_SaveMail()
-{
- if (!m_mailsLoaded)
- return;
-
- for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
- {
- Mail *m = (*itr);
- if (m->state == MAIL_STATE_CHANGED)
- {
- 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'",
- m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
- if(m->removedItems.size())
- {
- for (std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
- CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
- m->removedItems.clear();
- }
- m->state = MAIL_STATE_UNCHANGED;
- }
- else if (m->state == MAIL_STATE_DELETED)
- {
- if (m->HasItems())
- for (std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
- CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
- if (m->itemTextId)
- CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
- CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
- CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
- }
- }
-
- //deallocate deleted mails...
- for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();)
- {
- if ((*itr)->state == MAIL_STATE_DELETED)
- {
- Mail* m = *itr;
- m_mail.erase(itr);
- delete m;
- itr = m_mail.begin();
- }
- else
- ++itr;
- }
-
- m_mailsUpdated = false;
-}
-
-void Player::_SaveQuestStatus()
-{
- // we don't need transactions here.
- for (QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
- {
- switch (i->second.uState)
- {
- case QUEST_NEW :
- CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
- "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
- 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]);
- break;
- case QUEST_CHANGED :
- 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' ",
- 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 );
- break;
- case QUEST_UNCHANGED:
- break;
- };
- i->second.uState = QUEST_UNCHANGED;
- }
-}
-
-void Player::_SaveDailyQuestStatus()
-{
- if(!m_DailyQuestChanged)
- return;
-
- m_DailyQuestChanged = false;
-
- // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
-
- // we don't need transactions here.
- CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
- for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
- if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
- CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" UI64FMTD "')",
- GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
-}
-
-void Player::_SaveSkills()
-{
- // we don't need transactions here.
- for( SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); )
- {
- if(itr->second.uState == SKILL_UNCHANGED)
- {
- ++itr;
- continue;
- }
-
- if(itr->second.uState == SKILL_DELETED)
- {
- CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), itr->first );
- mSkillStatus.erase(itr++);
- continue;
- }
-
- uint32 valueData = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos));
- uint16 value = SKILL_VALUE(valueData);
- uint16 max = SKILL_MAX(valueData);
-
- switch (itr->second.uState)
- {
- case SKILL_NEW:
- CharacterDatabase.PExecute("INSERT INTO character_skills (guid, skill, value, max) VALUES ('%u', '%u', '%u', '%u')",
- GetGUIDLow(), itr->first, value, max);
- break;
- case SKILL_CHANGED:
- CharacterDatabase.PExecute("UPDATE character_skills SET value = '%u',max = '%u'WHERE guid = '%u' AND skill = '%u' ",
- value, max, GetGUIDLow(), itr->first );
- break;
- };
- itr->second.uState = SKILL_UNCHANGED;
-
- ++itr;
- }
-}
-
-void Player::_SaveSpells()
-{
- for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
- {
- if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
- CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
-
- // add only changed/new not dependent spells
- if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
- 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);
-
- if (itr->second->state == PLAYERSPELL_REMOVED)
- {
- delete itr->second;
- m_spells.erase(itr++);
- }
- else
- {
- itr->second->state = PLAYERSPELL_UNCHANGED;
- ++itr;
- }
-
- }
-}
-
-void Player::outDebugValues() const
-{
- if(!sLog.IsOutDebug()) // optimize disabled debug output
- return;
-
- sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
- sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
- sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
- sLog.outDebug("STAMINA is: \t\t%f",GetStat(STAT_STAMINA));
- sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
- sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
- sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
- sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
- sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
- sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
- sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
- sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
-}
-
-/*********************************************************/
-/*** FLOOD FILTER SYSTEM ***/
-/*********************************************************/
-
-void Player::UpdateSpeakTime()
-{
- // ignore chat spam protection for GMs in any mode
- if(GetSession()->GetSecurity() > SEC_PLAYER)
- return;
-
- time_t current = time (NULL);
- if(m_speakTime > current)
- {
- uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
- if(!max_count)
- return;
-
- ++m_speakCount;
- if(m_speakCount >= max_count)
- {
- // prevent overwrite mute time, if message send just before mutes set, for example.
- time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
- if(GetSession()->m_muteTime < new_mute)
- GetSession()->m_muteTime = new_mute;
-
- m_speakCount = 0;
- }
- }
- else
- m_speakCount = 0;
-
- m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
-}
-
-bool Player::CanSpeak() const
-{
- return GetSession()->m_muteTime <= time (NULL);
-}
-
-/*********************************************************/
-/*** LOW LEVEL FUNCTIONS:Notifiers ***/
-/*********************************************************/
-
-void Player::SendAttackSwingNotInRange()
-{
- WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
- GetSession()->SendPacket( &data );
-}
-
-void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
-{
- std::ostringstream ss;
- ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
- << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
- << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
- << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
- sLog.outDebug(ss.str().c_str());
- CharacterDatabase.Execute(ss.str().c_str());
-}
-
-void Player::SaveDataFieldToDB()
-{
- std::ostringstream ss;
- ss<<"UPDATE characters SET data='";
-
- for (uint16 i = 0; i < m_valuesCount; i++ )
- {
- ss << GetUInt32Value(i) << " ";
- }
- ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
-
- CharacterDatabase.Execute(ss.str().c_str());
-}
-
-bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
-{
- std::ostringstream ss2;
- ss2<<"UPDATE characters SET data='";
- uint32 i=0;
- for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
- {
- ss2<<tokens[i]<<" ";
- }
- ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
-
- return CharacterDatabase.Execute(ss2.str().c_str());
-}
-
-void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
-{
- char buf[11];
- snprintf(buf,11,"%u",value);
-
- if(index >= tokens.size())
- return;
-
- tokens[index] = buf;
-}
-
-void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
-{
- Tokens tokens;
- if(!LoadValuesArrayFromDB(tokens,guid))
- return;
-
- if(index >= tokens.size())
- return;
-
- char buf[11];
- snprintf(buf,11,"%u",value);
- tokens[index] = buf;
-
- SaveValuesArrayInDB(tokens,guid);
-}
-
-void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
-{
- uint32 temp;
- memcpy(&temp, &value, sizeof(value));
- Player::SetUInt32ValueInDB(index, temp, guid);
-}
-
-void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
-{
- // 0
- QueryResult_AutoPtr result = CharacterDatabase.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
- if(!result)
- return;
-
- Field* fields = result->Fetch();
-
- uint32 player_bytes2 = fields[0].GetUInt32();
- player_bytes2 &= ~0xFF;
- player_bytes2 |= facialHair;
-
- 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));
-}
-
-void Player::SendAttackSwingDeadTarget()
-{
- WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
- GetSession()->SendPacket( &data );
-}
-
-void Player::SendAttackSwingCantAttack()
-{
- WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
- GetSession()->SendPacket( &data );
-}
-
-void Player::SendAttackSwingCancelAttack()
-{
- WorldPacket data(SMSG_CANCEL_COMBAT, 0);
- GetSession()->SendPacket( &data );
-}
-
-void Player::SendAttackSwingBadFacingAttack()
-{
- WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
- GetSession()->SendPacket( &data );
-}
-
-void Player::SendAutoRepeatCancel(Unit *target)
-{
- WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, target->GetPackGUID().size());
- data.append(target->GetPackGUID()); // may be it's target guid
- GetSession()->SendPacket( &data );
-}
-
-void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
-{
- WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
- data << Area;
- data << Experience;
- GetSession()->SendPacket(&data);
-}
-
-void Player::SendDungeonDifficulty(bool IsInGroup)
-{
- uint8 val = 0x00000001;
- WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
- data << (uint32)GetDungeonDifficulty();
- data << uint32(val);
- data << uint32(IsInGroup);
- GetSession()->SendPacket(&data);
-}
-
-void Player::SendRaidDifficulty(bool IsInGroup)
-{
- uint8 val = 0x00000001;
- WorldPacket data(MSG_SET_RAID_DIFFICULTY, 12);
- data << uint32(GetRaidDifficulty());
- data << uint32(val);
- data << uint32(IsInGroup);
- GetSession()->SendPacket(&data);
-}
-
-void Player::SendResetFailedNotify(uint32 mapid)
-{
- WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
- data << uint32(mapid);
- GetSession()->SendPacket(&data);
-}
-
-/// Reset all solo instances and optionally send a message on success for each
-void Player::ResetInstances(uint8 method, bool isRaid)
-{
- // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
-
- // we assume that when the difficulty changes, all instances that can be reset will be
- Difficulty diff = GetDifficulty(isRaid);
-
- for (BoundInstancesMap::iterator itr = m_boundInstances[diff].begin(); itr != m_boundInstances[diff].end(); )
- {
- InstanceSave *p = itr->second.save;
- const MapEntry *entry = sMapStore.LookupEntry(itr->first);
- if(!entry || entry->IsRaid() != isRaid || !p->CanReset())
- {
- ++itr;
- continue;
- }
-
- if(method == INSTANCE_RESET_ALL)
- {
- // the "reset all instances" method can only reset normal maps
- if(entry->map_type == MAP_RAID || diff == DUNGEON_DIFFICULTY_HEROIC)
- {
- ++itr;
- continue;
- }
- }
-
- // if the map is loaded, reset it
- Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
- if(map && map->IsDungeon())
- if(!((InstanceMap*)map)->Reset(method))
- {
- ++itr;
- continue;
- }
-
- // since this is a solo instance there should not be any players inside
- if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
- SendResetInstanceSuccess(p->GetMapId());
-
- p->DeleteFromDB();
- m_boundInstances[diff].erase(itr++);
-
- // the following should remove the instance save from the manager and delete it as well
- p->RemovePlayer(this);
- }
-}
-
-void Player::SendResetInstanceSuccess(uint32 MapId)
-{
- WorldPacket data(SMSG_INSTANCE_RESET, 4);
- data << MapId;
- GetSession()->SendPacket(&data);
-}
-
-void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
-{
- // TODO: find what other fail reasons there are besides players in the instance
- WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
- data << reason;
- data << MapId;
- GetSession()->SendPacket(&data);
-}
-
-/*********************************************************/
-/*** Update timers ***/
-/*********************************************************/
-
-///checks the 15 afk reports per 5 minutes limit
-void Player::UpdateAfkReport(time_t currTime)
-{
- if(m_bgData.bgAfkReportedTimer <= currTime)
- {
- m_bgData.bgAfkReportedCount = 0;
- m_bgData.bgAfkReportedTimer = currTime+5*MINUTE;
- }
-}
-
-void Player::UpdateContestedPvP(uint32 diff)
-{
- if(!m_contestedPvPTimer||isInCombat())
- return;
- if(m_contestedPvPTimer <= diff)
- {
- ResetContestedPvP();
- }
- else
- m_contestedPvPTimer -= diff;
-}
-
-void Player::UpdatePvPFlag(time_t currTime)
-{
- if(!IsPvP())
- return;
- if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
- return;
-
- UpdatePvP(false);
-}
-
-void Player::UpdateDuelFlag(time_t currTime)
-{
- if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
- return;
-
- SetUInt32Value(PLAYER_DUEL_TEAM, 1);
- duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
-
- duel->startTimer = 0;
- duel->startTime = currTime;
- duel->opponent->duel->startTimer = 0;
- duel->opponent->duel->startTime = currTime;
-}
-
-Pet* Player::GetPet() const
-{
- if(uint64 pet_guid = GetPetGUID())
- {
- if(!IS_PET_GUID(pet_guid))
- return NULL;
-
- Pet* pet = ObjectAccessor::GetPet(pet_guid);
-
- if (!pet)
- return NULL;
-
- if(IsInWorld() && pet)
- return pet;
-
- //there may be a guardian in slot
- //sLog.outError("Player::GetPet: Pet %u not exist.",GUID_LOPART(pet_guid));
- //const_cast<Player*>(this)->SetPetGUID(0);
- }
-
- return NULL;
-}
-
-void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
-{
- if(!pet)
- pet = GetPet();
-
- if(pet)
- {
- sLog.outDebug("RemovePet %u, %u, %u", pet->GetEntry(), mode, returnreagent);
-
- if(pet->m_removed)
- return;
- }
-
- if(returnreagent && (pet || m_temporaryUnsummonedPetNumber) && !InBattleGround())
- {
- //returning of reagents only for players, so best done here
- uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
-
- if(spellInfo)
- {
- for (uint32 i = 0; i < 7; ++i)
- {
- if(spellInfo->Reagent[i] > 0)
- {
- ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
- uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
- if( msg == EQUIP_ERR_OK )
- {
- Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
- if(IsInWorld())
- SendNewItem(item,spellInfo->ReagentCount[i],true,false);
- }
- }
- }
- }
- m_temporaryUnsummonedPetNumber = 0;
- }
-
- if(!pet || pet->GetOwnerGUID()!=GetGUID())
- return;
-
- pet->CombatStop();
-
- if(returnreagent)
- {
- switch(pet->GetEntry())
- {
- //warlock pets except imp are removed(?) when logging out
- case 1860:
- case 1863:
- case 417:
- case 17252:
- mode = PET_SAVE_NOT_IN_SLOT;
- break;
- }
- }
-
- // only if current pet in slot
- pet->SavePetToDB(mode);
-
- SetMinion(pet, false);
-
- pet->AddObjectToRemoveList();
- pet->m_removed = true;
-
- if(pet->isControlled())
- {
- WorldPacket data(SMSG_PET_SPELLS, 8);
- data << uint64(0);
- GetSession()->SendPacket(&data);
-
- if(GetGroup())
- SetGroupUpdateFlag(GROUP_UPDATE_PET);
- }
-}
-
-void Player::StopCastingCharm()
-{
- Unit* charm = GetCharm();
- if(!charm)
- return;
-
- if(charm->GetTypeId() == TYPEID_UNIT)
- {
- if(((Creature*)charm)->HasUnitTypeMask(UNIT_MASK_PUPPET))
- ((Puppet*)charm)->UnSummon();
- else if(charm->IsVehicle())
- ExitVehicle();
- }
- if(GetCharmGUID())
- charm->RemoveCharmAuras();
-
- if(GetCharmGUID())
- {
- sLog.outCrash("Player %s (GUID: " UI64FMTD " is not able to uncharm unit (GUID: " UI64FMTD " Entry: %u, Type: %u)", GetName(), GetGUID(), GetCharmGUID(), charm->GetEntry(), charm->GetTypeId());
- if(charm->GetCharmerGUID())
- {
- sLog.outCrash("Charmed unit has charmer guid " UI64FMTD, charm->GetCharmerGUID());
- assert(false);
- }
- else
- SetCharm(charm, false);
- }
-}
-
-void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
-{
- *data << (uint8)msgtype;
- *data << (uint32)language;
- *data << (uint64)GetGUID();
- *data << (uint32)language; //language 2.1.0 ?
- *data << (uint64)GetGUID();
- *data << (uint32)(text.length()+1);
- *data << text;
- *data << (uint8)chatTag();
-}
-
-void Player::Say(const std::string& text, const uint32 language)
-{
- WorldPacket data(SMSG_MESSAGECHAT, 200);
- BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
- SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
-
- if(sWorld.getConfig(CONFIG_CHATLOG_PUBLIC))
- sLog.outChat("[SAY] Player %s says (language %u): %s",
- GetName(), language, text.c_str());
-}
-
-void Player::Yell(const std::string& text, const uint32 language)
-{
- WorldPacket data(SMSG_MESSAGECHAT, 200);
- BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
- SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
-
- if(sWorld.getConfig(CONFIG_CHATLOG_PUBLIC))
- sLog.outChat("[YELL] Player %s yells (language %u): %s",
- GetName(), language, text.c_str());
-}
-
-void Player::TextEmote(const std::string& text)
-{
- WorldPacket data(SMSG_MESSAGECHAT, 200);
- BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
- SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT));
-
- if(sWorld.getConfig(CONFIG_CHATLOG_PUBLIC))
- sLog.outChat("[TEXTEMOTE] Player %s emotes: %s",
- GetName(), text.c_str());
-}
-
-void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
-{
- if (language != LANG_ADDON) // if not addon data
- language = LANG_UNIVERSAL; // whispers should always be readable
-
- Player *rPlayer = objmgr.GetPlayer(receiver);
-
- if(sWorld.getConfig(CONFIG_CHATLOG_WHISPER))
- sLog.outChat("[WHISPER] Player %s tells %s: %s",
- GetName(), rPlayer->GetName(), text.c_str());
-
- // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
- if(!rPlayer->isDND() || isGameMaster())
- {
- WorldPacket data(SMSG_MESSAGECHAT, 200);
- BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
- rPlayer->GetSession()->SendPacket(&data);
-
- // not send confirmation for addon messages
- if (language != LANG_ADDON)
- {
- data.Initialize(SMSG_MESSAGECHAT, 200);
- rPlayer->BuildPlayerChat(&data, CHAT_MSG_WHISPER_INFORM, text, language);
- GetSession()->SendPacket(&data);
- }
- }
- else
- {
- // announce to player that player he is whispering to is dnd and cannot receive his message
- ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
- }
-
- if(!isAcceptWhispers() && !isGameMaster() && !rPlayer->isGameMaster())
- {
- SetAcceptWhispers(true);
- ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
- }
-
- // announce to player that player he is whispering to is afk
- if(rPlayer->isAFK())
- ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
-
- // if player whisper someone, auto turn of dnd to be able to receive an answer
- if(isDND() && !rPlayer->isGameMaster())
- ToggleDND();
-}
-
-void Player::PetSpellInitialize()
-{
- Pet* pet = GetPet();
-
- if(!pet)
- return;
-
- sLog.outDebug("Pet Spells Groups");
-
- CharmInfo *charmInfo = pet->GetCharmInfo();
-
- WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
- data << uint64(pet->GetGUID());
- data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
- data << uint32(0);
- data << uint8(pet->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
-
- // action bar loop
- charmInfo->BuildActionBar(&data);
-
- size_t spellsCountPos = data.wpos();
-
- // spells count
- uint8 addlist = 0;
- data << uint8(addlist); // placeholder
-
- if (pet->IsPermanentPetFor(this))
- {
- // spells loop
- for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
- {
- if(itr->second.state == PETSPELL_REMOVED)
- continue;
-
- data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first,itr->second.active));
- ++addlist;
- }
- }
-
- data.put<uint8>(spellsCountPos, addlist);
-
- uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
- data << uint8(cooldownsCount);
-
- time_t curTime = time(NULL);
-
- for (CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
- {
- time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
-
- data << uint32(itr->first); // spellid
- data << uint16(0); // spell category?
- data << uint32(cooldown); // cooldown
- data << uint32(0); // category cooldown
- }
-
- for (CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
- {
- time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
-
- data << uint32(itr->first); // spellid
- data << uint16(0); // spell category?
- data << uint32(0); // cooldown
- data << uint32(cooldown); // category cooldown
- }
-
- data.hexlike();
-
- GetSession()->SendPacket(&data);
-}
-
-void Player::PossessSpellInitialize()
-{
- Unit* charm = GetCharm();
- if(!charm)
- return;
-
- CharmInfo *charmInfo = charm->GetCharmInfo();
-
- if(!charmInfo)
- {
- sLog.outError("Player::PossessSpellInitialize(): charm ("UI64FMTD") has no charminfo!", charm->GetGUID());
- return;
- }
-
- WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
- data << uint64(charm->GetGUID());
- data << uint16(0);
- data << uint32(0);
- data << uint32(0);
-
- charmInfo->BuildActionBar(&data);
-
- data << uint8(0); // spells count
- data << uint8(0); // cooldowns count
-
- GetSession()->SendPacket(&data);
-}
-
-void Player::VehicleSpellInitialize()
-{
- Creature* veh = GetVehicleCreatureBase();
- if(!veh)
- return;
-
- // GetPosition_ is not a member of 'Vehicle', SetPosition is a member of 'Player': SetPosition(GetVehicle()->GetPositionX(), GetVehicle()->GetPositionY(), GetVehicle()->GetPositionZ(), GetVehicle()->GetOrientation());
-
- // GetPosition_ is not a member of 'Vehicle', SetPosition is a member of 'Player': SetPosition(GetVehicle()->GetPositionX(), GetVehicle()->GetPositionY(), GetVehicle()->GetPositionZ(), GetVehicle()->GetOrientation());
-
- WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*10+1+1);
- data << uint64(veh->GetGUID());
- data << uint16(0);
- data << uint32(0);
- data << uint32(0x00000101);
-
- for (uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
- {
- uint32 spellId = ((Creature*)veh)->m_spells[i];
- if(!spellId)
- continue;
-
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
- if(!spellInfo)
- continue;
-
- if(IsPassiveSpell(spellId))
- {
- veh->CastSpell(veh, spellId, true);
- data << uint16(0) << uint8(0) << uint8(i+8);
- }
- else
- data << uint32(MAKE_UNIT_ACTION_BUTTON(spellId,i+8));
- }
-
- for (uint32 i = CREATURE_MAX_SPELLS; i < MAX_SPELL_CONTROL_BAR; ++i)
- data << uint16(0) << uint8(0) << uint8(i+8);
-
- data << uint8(0);
- data << uint8(0);
- GetSession()->SendPacket(&data);
-}
-
-void Player::CharmSpellInitialize()
-{
- Unit* charm = GetFirstControlled();
- if(!charm)
- return;
-
- CharmInfo *charmInfo = charm->GetCharmInfo();
- if(!charmInfo)
- {
- sLog.outError("Player::CharmSpellInitialize(): the player's charm ("UI64FMTD") has no charminfo!", charm->GetGUID());
- return;
- }
-
- uint8 addlist = 0;
- if(charm->GetTypeId() != TYPEID_PLAYER)
- {
- CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
- //if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
- {
- for (uint32 i = 0; i < MAX_SPELL_CHARM; ++i)
- {
- if(charmInfo->GetCharmSpell(i)->GetAction())
- ++addlist;
- }
- }
- }
-
- WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1);
- data << uint64(charm->GetGUID());
- data << uint16(0);
- data << uint32(0);
-
- if(charm->GetTypeId() != TYPEID_PLAYER)
- data << uint8(((Creature*)charm)->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
- else
- data << uint8(0) << uint8(0) << uint16(0);
-
- charmInfo->BuildActionBar(&data);
-
- data << uint8(addlist);
-
- if(addlist)
- {
- for (uint32 i = 0; i < MAX_SPELL_CHARM; ++i)
- {
- CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
- if(cspell->GetAction())
- data << uint32(cspell->packedData);
- }
- }
-
- data << uint8(0); // cooldowns count
-
- GetSession()->SendPacket(&data);
-}
-
-void Player::SendRemoveControlBar()
-{
- WorldPacket data(SMSG_PET_SPELLS, 8);
- data << uint64(0);
- GetSession()->SendPacket(&data);
-}
-
-bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell * spell)
-{
- if (!mod || !spellInfo)
- return false;
-
- // Mod out of charges
- if (spell && mod->charges == -1 && spell->m_appliedMods.find(mod->ownerAura) == spell->m_appliedMods.end())
- return false;
-
- return spellmgr.IsAffectedByMod(spellInfo, mod);
-}
-
-void Player::AddSpellMod(SpellModifier* mod, bool apply)
-{
- sLog.outDebug("Player::AddSpellMod %d", mod->spellId);
- uint16 Opcode = (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
-
- int i = 0;
- flag96 _mask = 0;
- for (int eff = 0; eff < 96; ++eff)
- {
- if (eff != 0 && eff%32 == 0)
- _mask[i++] = 0;
-
- _mask[i] = uint32(1) << (eff-(32*i));
- if (mod->mask & _mask)
- {
- int32 val = 0;
- for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
- {
- if ((*itr)->type == mod->type && (*itr)->mask & _mask)
- val += (*itr)->value;
- }
- val += apply ? mod->value : -(mod->value);
- WorldPacket data(Opcode, (1+1+4));
- data << uint8(eff);
- data << uint8(mod->op);
- data << int32(val);
- SendDirectMessage(&data);
- }
- }
-
- if (apply)
- m_spellMods[mod->op].push_back(mod);
- else
- {
- m_spellMods[mod->op].remove(mod);
- // mods bound to aura will be removed in AuraEffect::~AuraEffect
- if (!mod->ownerAura)
- delete mod;
- }
-}
-
-// Restore spellmods in case of failed cast
-void Player::RestoreSpellMods(Spell * spell)
-{
- if (!spell || spell->m_appliedMods.empty())
- return;
-
- for (uint8 i=0; i<MAX_SPELLMOD; ++i)
- {
- for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end(); ++itr)
- {
- SpellModifier *mod = *itr;
-
- // spellmods without aura set cannot be charged
- if (!mod->ownerAura || !mod->ownerAura->GetCharges())
- continue;
-
- // check if mod affected this spell
- Spell::UsedSpellMods::iterator iterMod = spell->m_appliedMods.find(mod->ownerAura);
- if (iterMod == spell->m_appliedMods.end())
- continue;
-
- // remove from list
- spell->m_appliedMods.erase(iterMod);
-
- // add mod charges back to mod
- if (mod->charges == -1)
- mod->charges = 1;
- else
- mod->charges++;
-
- // Do not set more spellmods than avalible
- if (mod->ownerAura->GetCharges() < mod->charges)
- mod->charges = mod->ownerAura->GetCharges();
-
- // Skip this check for now - aura charges may change due to various reason
- // TODO: trac these changes correctly
- //assert (mod->ownerAura->GetCharges() <= mod->charges);
- }
- }
-}
-
-void Player::RemoveSpellMods(Spell * spell)
-{
- if (!spell)
- return;
- std::set <Aura *> checkedSpells;
-
- AuraEffectList const & auraList = GetAuraEffectsByType(SPELL_AURA_ABILITY_IGNORE_AURASTATE);
- for (AuraEffectList::const_iterator itr = auraList.begin(); itr != auraList.end();)
- {
- AuraEffect * aurEff = *itr;
- Aura * aura = aurEff->GetBase();
- ++itr;
- if (!aura->GetCharges())
- continue;
-
- SpellEntry const * spellInfo = aura->GetSpellProto();
-
- if (spellInfo->SpellFamilyName != spell->m_spellInfo->SpellFamilyName ||
- checkedSpells.find(aura) != checkedSpells.end())
- continue;
-
- if (spell->m_spellInfo->SpellFamilyFlags & spellInfo->EffectSpellClassMask[aurEff->GetEffIndex()]
- // this is for fingers of frost, look at spell::finish part, a charge will be taken by the triggering spell
- && aura->GetDuration() != aura->GetMaxDuration())
- {
- checkedSpells.insert(aura);
- spell->m_appliedMods.erase(aura);
- if (aura->DropCharge())
- itr = auraList.begin();
- }
- }
-
- if (spell->m_appliedMods.empty())
- return;
-
- for (uint8 i=0; i<MAX_SPELLMOD; ++i)
- {
- for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
- {
- SpellModifier *mod = *itr;
- ++itr;
-
- // spellmods without aura set cannot be charged
- if (!mod->ownerAura || !mod->ownerAura->GetCharges())
- continue;
-
- // check if mod affected this spell
- Spell::UsedSpellMods::iterator iterMod = spell->m_appliedMods.find(mod->ownerAura);
- if (iterMod == spell->m_appliedMods.end())
- continue;
-
- // remove from list
- spell->m_appliedMods.erase(iterMod);
-
- if (mod->ownerAura->DropCharge())
- itr = m_spellMods[i].begin();
- }
- }
-}
-
-void Player::DropModCharge(SpellModifier * mod, Spell * spell)
-{
- if (spell && mod->ownerAura && mod->charges > 0 )
- {
- --mod->charges;
- if (mod->charges == 0)
- {
- mod->charges = -1;
- }
- spell->m_appliedMods.insert(mod->ownerAura);
- }
-}
-
-void Player::SetSpellModTakingSpell(Spell * spell, bool apply)
-{
- if (!spell || (m_spellModTakingSpell && m_spellModTakingSpell != spell))
- return;
-
- if (apply && spell->getState() == SPELL_STATE_FINISHED)
- return;
-
- m_spellModTakingSpell = apply ? spell : NULL;
-}
-
-// send Proficiency
-void Player::SendProficiency(uint8 pr1, uint32 pr2)
-{
- WorldPacket data(SMSG_SET_PROFICIENCY, 8);
- data << pr1 << pr2;
- GetSession()->SendPacket (&data);
-}
-
-void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
-{
- QueryResult_AutoPtr result = QueryResult_AutoPtr(NULL);
- if(type==10)
- result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
- else
- result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
- if(result)
- {
- 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.
- { // and SendPetitionQueryOpcode reads data from the DB
- Field *fields = result->Fetch();
- uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
- uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
-
- // send update if charter owner in game
- Player* owner = objmgr.GetPlayer(ownerguid);
- if(owner)
- owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
-
- } while ( result->NextRow() );
-
- if(type==10)
- CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
- else
- CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
- }
-
- CharacterDatabase.BeginTransaction();
- if(type == 10)
- {
- CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
- CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
- }
- else
- {
- CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
- CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
- }
- CharacterDatabase.CommitTransaction();
-}
-
-void Player::LeaveAllArenaTeams(uint64 guid)
-{
- QueryResult_AutoPtr 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));
- if(!result)
- return;
-
- do
- {
- Field *fields = result->Fetch();
- uint32 at_id = fields[0].GetUInt32();
- if(at_id != 0)
- {
- ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
- if(at)
- at->DelMember(guid);
- }
- } while (result->NextRow());
-}
-
-void Player::SetRestBonus (float rest_bonus_new)
-{
- // Prevent resting on max level
- if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
- rest_bonus_new = 0;
-
- if(rest_bonus_new < 0)
- rest_bonus_new = 0;
-
- float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
-
- if(rest_bonus_new > rest_bonus_max)
- m_rest_bonus = rest_bonus_max;
- else
- m_rest_bonus = rest_bonus_new;
-
- // update data for client
- if(m_rest_bonus>10)
- SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
- else if(m_rest_bonus<=1)
- SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
-
- //RestTickUpdate
- SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
-}
-
-void Player::HandleStealthedUnitsDetection()
-{
- std::list<Unit*> stealthedUnits;
- Trinity::AnyStealthedCheck u_check;
- Trinity::UnitListSearcher<Trinity::AnyStealthedCheck > searcher(this, stealthedUnits, u_check);
- VisitNearbyObject(GetMap()->GetVisibilityDistance(), searcher);
-
- for (std::list<Unit*>::const_iterator i = stealthedUnits.begin(); i != stealthedUnits.end(); ++i)
- {
- if((*i)==this)
- continue;
-
- bool hasAtClient = HaveAtClient((*i));
- bool hasDetected = canSeeOrDetect(*i, true);
-
- if (hasDetected)
- {
- if(!hasAtClient)
- {
- (*i)->SendUpdateToPlayer(this);
- m_clientGUIDs.insert((*i)->GetGUID());
-
- #ifdef TRINITY_DEBUG
- if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
- sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
- #endif
-
- // target aura duration for caster show only if target exist at caster client
- // send data at target visibility change (adding to client)
- SendInitialVisiblePackets(*i);
- }
- }
- else
- {
- if(hasAtClient)
- {
- (*i)->DestroyForPlayer(this);
- m_clientGUIDs.erase((*i)->GetGUID());
- }
- }
- }
-}
-
-bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
-{
- if(nodes.size() < 2)
- return false;
-
- // not let cheating with start flight in time of logout process || while in combat || has type state: stunned || has type state: root
- if(GetSession()->isLogingOut() || isInCombat() || hasUnitState(UNIT_STAT_STUNNED) || hasUnitState(UNIT_STAT_ROOT))
- {
- WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
- data << uint32(ERR_TAXIPLAYERBUSY);
- GetSession()->SendPacket(&data);
- return false;
- }
-
- if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
- return false;
-
- // taximaster case
- if(npc)
- {
- // not let cheating with start flight mounted
- if(IsMounted())
- {
- WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
- data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
- GetSession()->SendPacket(&data);
- return false;
- }
-
- if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
- {
- WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
- data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
- GetSession()->SendPacket(&data);
- return false;
- }
-
- // 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
- if(IsNonMeleeSpellCasted(false))
- {
- WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
- data << uint32(ERR_TAXIPLAYERBUSY);
- GetSession()->SendPacket(&data);
- return false;
- }
- }
- // cast case or scripted call case
- else
- {
- RemoveAurasByType(SPELL_AURA_MOUNTED);
-
- if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
- RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
-
- if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
- if (spell->m_spellInfo->Id != spellid)
- InterruptSpell(CURRENT_GENERIC_SPELL,false);
-
- InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false);
-
- if (Spell* spell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
- if (spell->m_spellInfo->Id != spellid)
- InterruptSpell(CURRENT_CHANNELED_SPELL,true);
- }
-
- uint32 sourcenode = nodes[0];
-
- // starting node too far away (cheat?)
- TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
- if (!node)
- {
- WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
- data << uint32(ERR_TAXINOSUCHPATH);
- GetSession()->SendPacket(&data);
- return false;
- }
-
- // check node starting pos data set case if provided
- if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
- {
- if (node->map_id != GetMapId() ||
- (node->x - GetPositionX())*(node->x - GetPositionX())+
- (node->y - GetPositionY())*(node->y - GetPositionY())+
- (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
- (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
- {
- WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
- data << uint32(ERR_TAXITOOFARAWAY);
- GetSession()->SendPacket(&data);
- return false;
- }
- }
- // node must have pos if taxi master case (npc != NULL)
- else if (npc)
- {
- WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
- data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
- GetSession()->SendPacket(&data);
- return false;
- }
-
- // Prepare to flight start now
-
- // stop combat at start taxi flight if any
- CombatStop();
-
- StopCastingCharm();
- StopCastingBindSight();
- ExitVehicle();
-
- // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
- TradeCancel(true);
-
- // clean not finished taxi path if any
- m_taxi.ClearTaxiDestinations();
-
- // 0 element current node
- m_taxi.AddTaxiDestination(sourcenode);
-
- // fill destinations path tail
- uint32 sourcepath = 0;
- uint32 totalcost = 0;
-
- uint32 prevnode = sourcenode;
- uint32 lastnode = 0;
-
- for (uint32 i = 1; i < nodes.size(); ++i)
- {
- uint32 path, cost;
-
- lastnode = nodes[i];
- objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
-
- if(!path)
- {
- m_taxi.ClearTaxiDestinations();
- return false;
- }
-
- totalcost += cost;
-
- if(prevnode == sourcenode)
- sourcepath = path;
-
- m_taxi.AddTaxiDestination(lastnode);
-
- prevnode = lastnode;
- }
-
- // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
- //
- // Hack-Fix for Alliance not being able to use Acherus taxi. There is
- // only one mount ID for both sides. Probably not good to use 315 in case DBC nodes
- // change but I couldn't find a suitable alternative. OK to use class because only DK
- // can use this taxi.
- uint32 mount_display_id = objmgr.GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL || (sourcenode == 315 && getClass() == CLASS_DEATH_KNIGHT));
-
- // in spell case allow 0 model
- if ((mount_display_id == 0 && spellid == 0) || sourcepath == 0)
- {
- WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
- data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
- GetSession()->SendPacket(&data);
- m_taxi.ClearTaxiDestinations();
- return false;
- }
-
- uint32 money = GetMoney();
-
- if (npc)
- totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
-
- if(money < totalcost)
- {
- WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
- data << uint32(ERR_TAXINOTENOUGHMONEY);
- GetSession()->SendPacket(&data);
- m_taxi.ClearTaxiDestinations();
- return false;
- }
-
- //Checks and preparations done, DO FLIGHT
- ModifyMoney(-(int32)totalcost);
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
-
- // prevent stealth flight
- //RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TALK);
-
- if (sWorld.getConfig(CONFIG_INSTANT_TAXI))
- {
- TaxiNodesEntry const* lastnode = sTaxiNodesStore.LookupEntry(nodes[nodes.size()-1]);
- m_taxi.ClearTaxiDestinations();
- TeleportTo(lastnode->map_id, lastnode->x, lastnode->y, lastnode->z, GetOrientation());
- return false;
- }
- else
- {
- WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
- data << uint32(ERR_TAXIOK);
- GetSession()->SendPacket(&data);
- sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
- GetSession()->SendDoFlight(mount_display_id, sourcepath);
- }
- return true;
-}
-
-bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ )
-{
- TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
- if(!entry)
- return false;
-
- std::vector<uint32> nodes;
-
- nodes.resize(2);
- nodes[0] = entry->from;
- nodes[1] = entry->to;
-
- return ActivateTaxiPathTo(nodes,NULL,spellid);
-}
-
-void Player::CleanupAfterTaxiFlight()
-{
- m_taxi.ClearTaxiDestinations(); // not destinations, clear source node
- Unmount();
- RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_TAXI_FLIGHT);
- getHostilRefManager().setOnlineOfflineState(true);
-}
-
-void Player::ContinueTaxiFlight()
-{
- uint32 sourceNode = m_taxi.GetTaxiSource();
- if (!sourceNode)
- return;
-
- sLog.outDebug( "WORLD: Restart character %u taxi flight", GetGUIDLow() );
-
- uint32 mountDisplayId = objmgr.GetTaxiMountDisplayId(sourceNode, GetTeam(),true);
- uint32 path = m_taxi.GetCurrentTaxiPath();
-
- // search appropriate start path node
- uint32 startNode = 0;
-
- TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];
-
- float distPrev = MAP_SIZE*MAP_SIZE;
- float distNext =
- (nodeList[0].x-GetPositionX())*(nodeList[0].x-GetPositionX())+
- (nodeList[0].y-GetPositionY())*(nodeList[0].y-GetPositionY())+
- (nodeList[0].z-GetPositionZ())*(nodeList[0].z-GetPositionZ());
-
- for (uint32 i = 1; i < nodeList.size(); ++i)
- {
- TaxiPathNode const& node = nodeList[i];
- TaxiPathNode const& prevNode = nodeList[i-1];
-
- // skip nodes at another map
- if(node.mapid != GetMapId())
- continue;
-
- distPrev = distNext;
-
- distNext =
- (node.x-GetPositionX())*(node.x-GetPositionX())+
- (node.y-GetPositionY())*(node.y-GetPositionY())+
- (node.z-GetPositionZ())*(node.z-GetPositionZ());
-
- float distNodes =
- (node.x-prevNode.x)*(node.x-prevNode.x)+
- (node.y-prevNode.y)*(node.y-prevNode.y)+
- (node.z-prevNode.z)*(node.z-prevNode.z);
-
- if(distNext + distPrev < distNodes)
- {
- startNode = i;
- break;
- }
- }
-
- GetSession()->SendDoFlight(mountDisplayId, path, startNode);
-}
-
-void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
-{
- // last check 2.0.10
- WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
- data << GetGUID();
- data << uint8(0x0); // flags (0x1, 0x2)
- time_t curTime = time(NULL);
- for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
- {
- if (itr->second->state == PLAYERSPELL_REMOVED)
- continue;
- uint32 unSpellId = itr->first;
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
- if (!spellInfo)
- {
- ASSERT(spellInfo);
- continue;
- }
-
- // Not send cooldown for this spells
- if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
- continue;
-
- if(spellInfo->PreventionType != SPELL_PREVENTION_TYPE_SILENCE)
- continue;
-
- if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
- {
- data << uint32(unSpellId);
- data << uint32(unTimeMs); // in m.secs
- AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
- }
- }
- GetSession()->SendPacket(&data);
-}
-
-void Player::InitDataForForm(bool reapplyMods)
-{
- SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
- if(ssEntry && ssEntry->attackSpeed)
- {
- SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
- SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
- SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
- }
- else
- SetRegularAttackTime();
-
- switch(m_form)
- {
- case FORM_GHOUL:
- case FORM_CAT:
- {
- if(getPowerType()!=POWER_ENERGY)
- setPowerType(POWER_ENERGY);
- break;
- }
- case FORM_BEAR:
- case FORM_DIREBEAR:
- {
- if(getPowerType()!=POWER_RAGE)
- setPowerType(POWER_RAGE);
- break;
- }
- default: // 0, for example
- {
- ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
- if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
- setPowerType(Powers(cEntry->powerType));
- break;
- }
- }
-
- // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
- if (!reapplyMods)
- UpdateEquipSpellsAtFormChange();
-
- UpdateAttackPowerAndDamage();
- UpdateAttackPowerAndDamage(true);
-}
-
-void Player::InitDisplayIds()
-{
- PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
- if(!info)
- {
- sLog.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
- return;
- }
-
- uint8 gender = getGender();
- switch(gender)
- {
- case GENDER_FEMALE:
- SetDisplayId(info->displayId_f );
- SetNativeDisplayId(info->displayId_f );
- break;
- case GENDER_MALE:
- SetDisplayId(info->displayId_m );
- SetNativeDisplayId(info->displayId_m );
- break;
- default:
- sLog.outError("Invalid gender %u for player",gender);
- return;
- }
-}
-
-// Return true is the bought item has a max count to force refresh of window by caller
-bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint8 bag, uint8 slot)
-{
- // cheating attempt
- if (count < 1) count = 1;
-
- // cheating attempt
- if(slot > MAX_BAG_SIZE && slot !=NULL_SLOT)
- return false;
-
- if (!isAlive())
- return false;
-
- ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
- if (!pProto)
- {
- SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
- return false;
- }
-
- Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
- if (!pCreature)
- {
- sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
- SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
- return false;
- }
-
- VendorItemData const* vItems = pCreature->GetVendorItems();
- if(!vItems || vItems->Empty())
- {
- SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
- return false;
- }
-
- size_t vendor_slot = vItems->FindItemSlot(item);
- if (vendor_slot >= vItems->GetItemCount())
- {
- SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
- return false;
- }
-
- VendorItem const* crItem = vItems->m_items[vendor_slot];
-
- // check current item amount if it limited
- if (crItem->maxcount != 0)
- {
- if (pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
- {
- SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
- return false;
- }
- }
-
- if (pProto->RequiredReputationFaction && (uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank))
- {
- SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
- return false;
- }
- else if (!pProto->RequiredReputationFaction && pProto->RequiredReputationRank > 0)
- {
- if (uint32(GetReputationRank(pCreature->getFactionTemplateEntry()->faction)) < pProto->RequiredReputationRank)
- {
- SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
- return false;
- }
- }
-
- if (crItem->ExtendedCost)
- {
- ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
- if (!iece)
- {
- sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
- return false;
- }
-
- // honor points price
- if (GetHonorPoints() < (iece->reqhonorpoints * count))
- {
- SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
- return false;
- }
-
- // arena points price
- if (GetArenaPoints() < (iece->reqarenapoints * count))
- {
- SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
- return false;
- }
-
- // item base price
- for (uint8 i = 0; i < 5; ++i)
- {
- if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
- {
- SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
- return false;
- }
- }
-
- // check for personal arena rating requirement
- if( GetMaxPersonalArenaRatingRequirement(iece->reqarenaslot) < iece->reqpersonalarenarating )
- {
- // probably not the proper equip err
- SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
- return false;
- }
- }
-
- int32 price = pProto->BuyPrice * count;
-
- // reputation discount
- price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
-
- if (GetMoney() < price)
- {
- SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
- return false;
- }
-
- if ((bag == NULL_BAG && slot == NULL_SLOT) || IsInventoryPos(bag, slot))
- {
- ItemPosCountVec dest;
- uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
- if (msg != EQUIP_ERR_OK)
- {
- SendEquipError( msg, NULL, NULL );
- return false;
- }
-
- ModifyMoney( -(int32)price );
- uint32 arenaPoints = 0;
- uint32 honorPoints = 0;
- uint32 extendedCost[5] = {0,0,0,0,0};
- uint32 extendedCostCount[5] = {0,0,0,0,0};
-
- if (crItem->ExtendedCost) // case for new honor system
- {
- ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
- if (iece->reqhonorpoints)
- {
- honorPoints = iece->reqhonorpoints * count;
- ModifyHonorPoints( - int32(honorPoints) );
- }
- if (iece->reqarenapoints)
- {
- arenaPoints = iece->reqarenapoints * count;
- ModifyArenaPoints( - int32(arenaPoints) );
- }
- for (uint8 i = 0; i < 5; ++i)
- {
- if (iece->reqitem[i])
- {
- DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
- extendedCost[i] = iece->reqitem[i];
- extendedCostCount[i] = iece->reqitemcount[i];
- }
- }
- }
-
- if (Item *it = StoreNewItem( dest, item, true ))
- {
- uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
-
- WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
- data << uint64(pCreature->GetGUID());
- data << uint32(vendor_slot+1); // numbered from 1 at client
- data << int32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
- data << uint32(count);
- GetSession()->SendPacket(&data);
- SendNewItem(it, pProto->BuyCount*count, true, false, false);
-
- // Item Refund system, only works for non stackable items with extendedcost
- if(count == 1 && crItem->ExtendedCost )
- {
- it->SetPaidArenaPoints(arenaPoints);
- it->SetPaidHonorPoints(honorPoints);
- it->SetRefundExpiryTime( time(NULL)+(HOUR*2) );
- for (uint8 i = 0; i < 5; ++i)
- it->SetPaidExtendedCost(i, extendedCost[i], extendedCostCount[i]);
- }
- }
- }
- else if (IsEquipmentPos(bag, slot))
- {
- if (pProto->BuyCount * count != 1)
- {
- SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
- return false;
- }
-
- uint16 dest;
- uint8 msg = CanEquipNewItem( slot, dest, item, false );
- if (msg != EQUIP_ERR_OK)
- {
- SendEquipError( msg, NULL, NULL );
- return false;
- }
-
- ModifyMoney( -(int32)price );
- if (crItem->ExtendedCost) // case for new honor system
- {
- ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
- if (iece->reqhonorpoints)
- ModifyHonorPoints( - int32(iece->reqhonorpoints));
- if (iece->reqarenapoints)
- ModifyArenaPoints( - int32(iece->reqarenapoints));
- for (uint8 i = 0; i < 5; ++i)
- {
- if(iece->reqitem[i])
- DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
- }
- }
-
- if (Item *it = EquipNewItem( dest, item, true ))
- {
- uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
-
- WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
- data << uint64(pCreature->GetGUID());
- data << uint32(vendor_slot + 1); // numbered from 1 at client
- data << int32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
- data << uint32(count);
- GetSession()->SendPacket(&data);
-
- SendNewItem(it, pProto->BuyCount*count, true, false, false);
-
- AutoUnequipOffhandIfNeed();
- }
- }
- else
- {
- SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
- return false;
- }
-
- return crItem->maxcount != 0;
-}
-
-uint32 Player::GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot)
-{
- // returns the maximal personal arena rating that can be used to purchase items requiring this condition
- // the personal rating of the arena team must match the required limit as well
- // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
- uint32 max_personal_rating = 0;
- for (uint8 i = minarenaslot; i < MAX_ARENA_SLOT; ++i)
- {
- if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
- {
- uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * ARENA_TEAM_END) + ARENA_TEAM_PERSONAL_RATING);
- uint32 t_rating = at->GetRating();
- p_rating = p_rating < t_rating ? p_rating : t_rating;
- if(max_personal_rating < p_rating)
- max_personal_rating = p_rating;
- }
- }
- return max_personal_rating;
-}
-
-void Player::UpdateHomebindTime(uint32 time)
-{
- // GMs never get homebind timer online
- if (m_InstanceValid || isGameMaster())
- {
- if(m_HomebindTimer) // instance valid, but timer not reset
- {
- // hide reminder
- WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
- data << uint32(0);
- data << uint32(0);
- GetSession()->SendPacket(&data);
- }
- // instance is valid, reset homebind timer
- m_HomebindTimer = 0;
- }
- else if (m_HomebindTimer > 0)
- {
- if (time >= m_HomebindTimer)
- {
- // teleport to nearest graveyard
- SetPhaseMask(1,true);
- RepopAtGraveyard();
- }
- else
- m_HomebindTimer -= time;
- }
- else
- {
- // instance is invalid, start homebind timer
- m_HomebindTimer = 60000;
- // send message to player
- WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
- data << uint32(m_HomebindTimer);
- data << uint32(1);
- GetSession()->SendPacket(&data);
- sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
- SetPhaseMask(2,true);
- }
-}
-
-void Player::UpdatePvPState(bool onlyFFA)
-{
- // TODO: should we always synchronize UNIT_FIELD_BYTES_2, 1 of controller and controlled?
- if(!pvpInfo.inNoPvPArea && !isGameMaster()
- && (pvpInfo.inFFAPvPArea || sWorld.IsFFAPvPRealm()))
- {
- if(!HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
- {
- SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
- for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
- (*itr)->SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
- }
- }
- else if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
- {
- RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
- for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
- (*itr)->RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
- }
-
- if(onlyFFA)
- return;
-
- if(pvpInfo.inHostileArea) // in hostile area
- {
- if(!IsPvP() || pvpInfo.endTimer != 0)
- UpdatePvP(true, true);
- }
- else // in friendly area
- {
- if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
- pvpInfo.endTimer = time(0); // start toggle-off
- }
-}
-
-void Player::UpdatePvP(bool state, bool override)
-{
- if(!state || override)
- {
- SetPvP(state);
- pvpInfo.endTimer = 0;
- }
- else
- {
- if(pvpInfo.endTimer != 0)
- pvpInfo.endTimer = time(NULL);
- else
- SetPvP(state);
- }
-}
-
-void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
-{
- // init cooldown values
- uint32 cat = 0;
- int32 rec = -1;
- int32 catrec = -1;
-
- // some special item spells without correct cooldown in SpellInfo
- // cooldown information stored in item prototype
- // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
-
- if(itemId)
- {
- if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
- {
- for (uint8 idx = 0; idx < 5; ++idx)
- {
- if(proto->Spells[idx].SpellId == spellInfo->Id)
- {
- cat = proto->Spells[idx].SpellCategory;
- rec = proto->Spells[idx].SpellCooldown;
- catrec = proto->Spells[idx].SpellCategoryCooldown;
- break;
- }
- }
- }
- }
-
- // if no cooldown found above then base at DBC data
- if(rec < 0 && catrec < 0)
- {
- cat = spellInfo->Category;
- rec = spellInfo->RecoveryTime;
- catrec = spellInfo->CategoryRecoveryTime;
- }
-
- time_t curTime = time(NULL);
-
- time_t catrecTime;
- time_t recTime;
-
- // overwrite time for selected category
- if(infinityCooldown)
- {
- // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
- // but not allow ignore until reset or re-login
- catrecTime = catrec > 0 ? curTime+infinityCooldownDelay : 0;
- recTime = rec > 0 ? curTime+infinityCooldownDelay : catrecTime;
- }
- else
- {
- // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
- // prevent 0 cooldowns set by another way
- if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != 75))
- rec = GetAttackTime(RANGED_ATTACK);
-
- // Now we have cooldown data (if found any), time to apply mods
- if(rec > 0)
- ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
-
- if(catrec > 0)
- ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
-
- // replace negative cooldowns by 0
- if (rec < 0) rec = 0;
- if (catrec < 0) catrec = 0;
-
- // no cooldown after applying spell mods
- if( rec == 0 && catrec == 0)
- return;
-
- catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
- recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
- }
-
- // self spell cooldown
- if(recTime > 0)
- AddSpellCooldown(spellInfo->Id, itemId, recTime);
-
- // category spells
- if (cat && catrec > 0)
- {
- SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
- if(i_scstore != sSpellCategoryStore.end())
- {
- for (SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
- {
- if(*i_scset == spellInfo->Id) // skip main spell, already handled above
- continue;
-
- AddSpellCooldown(*i_scset, itemId, catrecTime);
- }
- }
- }
-}
-
-void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
-{
- SpellCooldown sc;
- sc.end = end_time;
- sc.itemid = itemid;
- m_spellCooldowns[spellid] = sc;
-}
-
-void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
-{
- // start cooldowns at server side, if any
- AddSpellAndCategoryCooldowns(spellInfo,itemId,spell);
-
- // Send activate cooldown timer (possible 0) at client side
- WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
- data << uint32(spellInfo->Id);
- data << uint64(GetGUID());
- SendDirectMessage(&data);
-}
-
-void Player::UpdatePotionCooldown(Spell* spell)
-{
- // no potion used i combat or still in combat
- if(!m_lastPotionId || isInCombat())
- return;
-
- // Call not from spell cast, send cooldown event for item spells if no in combat
- if(!spell)
- {
- // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
- if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
- for (uint8 idx = 0; idx < 5; ++idx)
- if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
- if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
- SendCooldownEvent(spellInfo,m_lastPotionId);
- }
- // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
- else
- SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
-
- m_lastPotionId = 0;
-}
-
- //slot to be excluded while counting
-bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
-{
- if(!enchantmentcondition)
- return true;
-
- SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
-
- if(!Condition)
- return true;
-
- uint8 curcount[4] = {0, 0, 0, 0};
-
- //counting current equipped gem colors
- for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
- {
- if (i == slot)
- continue;
- Item *pItem2 = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
- if (pItem2 && !pItem2->IsBroken() && pItem2->GetProto()->Socket[0].Color)
- {
- for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
- {
- uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
- if(!enchant_id)
- continue;
-
- SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
- if(!enchantEntry)
- continue;
-
- uint32 gemid = enchantEntry->GemID;
- if(!gemid)
- continue;
-
- ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
- if(!gemProto)
- continue;
-
- GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
- if(!gemProperty)
- continue;
-
- uint8 GemColor = gemProperty->color;
-
- for (uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
- {
- if(tmpcolormask & GemColor)
- ++curcount[b];
- }
- }
- }
- }
-
- bool activate = true;
-
- for (uint8 i = 0; i < 5; i++)
- {
- if(!Condition->Color[i])
- continue;
-
- uint32 _cur_gem = curcount[Condition->Color[i] - 1];
-
- // if have <CompareColor> use them as count, else use <value> from Condition
- uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
-
- switch(Condition->Comparator[i])
- {
- case 2: // requires less <color> than (<value> || <comparecolor>) gems
- activate &= (_cur_gem < _cmp_gem) ? true : false;
- break;
- case 3: // requires more <color> than (<value> || <comparecolor>) gems
- activate &= (_cur_gem > _cmp_gem) ? true : false;
- break;
- case 5: // requires at least <color> than (<value> || <comparecolor>) gems
- activate &= (_cur_gem >= _cmp_gem) ? true : false;
- break;
- }
- }
-
- 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");
-
- return activate;
-}
-
-void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
-{
- //cycle all equipped items
- for (uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
- {
- //enchants for the slot being socketed are handled by Player::ApplyItemMods
- if(slot == exceptslot)
- continue;
-
- Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
-
- if(!pItem || !pItem->GetProto()->Socket[0].Color)
- continue;
-
- for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
- {
- uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
- if(!enchant_id)
- continue;
-
- SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
- if(!enchantEntry)
- continue;
-
- uint32 condition = enchantEntry->EnchantmentCondition;
- if(condition)
- {
- //was enchant active with/without item?
- bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
- //should it now be?
- if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
- {
- // ignore item gem conditions
- //if state changed, (dis)apply enchant
- ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
- }
- }
- }
- }
-}
-
- //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
-void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
-{
- //cycle all equipped items
- for (int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
- {
- //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
- if(slot == exceptslot)
- continue;
-
- Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
-
- if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
- continue;
-
- //cycle all (gem)enchants
- for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
- {
- uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
- if(!enchant_id) //if no enchant go to next enchant(slot)
- continue;
-
- SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
- if(!enchantEntry)
- continue;
-
- //only metagems to be (de)activated, so only enchants with condition
- uint32 condition = enchantEntry->EnchantmentCondition;
- if(condition)
- ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
- }
- }
-}
-
-void Player::SetBattleGroundEntryPoint()
-{
- // Taxi path store
- if (!m_taxi.empty())
- {
- m_bgData.mountSpell = 0;
- m_bgData.taxiPath[0] = m_taxi.GetTaxiSource();
- m_bgData.taxiPath[1] = m_taxi.GetTaxiDestination();
-
- // On taxi we don't need check for dungeon
- m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
- return;
- }
- else
- {
- m_bgData.ClearTaxiPath();
-
- // Mount spell id storing
- if (IsMounted())
- {
- AuraEffectList const& auras = GetAuraEffectsByType(SPELL_AURA_MOUNTED);
- if (!auras.empty())
- m_bgData.mountSpell = (*auras.begin())->GetId();
- }
- else
- m_bgData.mountSpell = 0;
-
- // If map is dungeon find linked graveyard
- if(GetMap()->IsDungeon())
- {
- if (const WorldSafeLocsEntry* entry = objmgr.GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
- {
- m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f);
- return;
- }
- else
- sLog.outError("SetBattleGroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId());
- }
- // If new entry point is not BG or arena set it
- else if (!GetMap()->IsBattleGroundOrArena())
- {
- m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
- return;
- }
- }
-
- // In error cases use homebind position
- m_bgData.joinPos = WorldLocation(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, 0.0f);
-}
-
-void Player::LeaveBattleground(bool teleportToEntryPoint)
-{
- if(BattleGround *bg = GetBattleGround())
- {
- bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
-
- // call after remove to be sure that player resurrected for correct cast
- if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) )
- {
- if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
- {
- //lets check if player was teleported from BG and schedule delayed Deserter spell cast
- if(IsBeingTeleportedFar())
- {
- ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER);
- return;
- }
-
- CastSpell(this, 26013, true); // Deserter
- }
- }
- }
-}
-
-bool Player::CanJoinToBattleground() const
-{
- // check Deserter debuff
- if (HasAura(26013))
- return false;
-
- return true;
-}
-
-bool Player::CanReportAfkDueToLimit()
-{
- // a player can complain about 15 people per 5 minutes
- if(m_bgData.bgAfkReportedCount++ >= 15)
- return false;
-
- return true;
-}
-
-///This player has been blamed to be inactive in a battleground
-void Player::ReportedAfkBy(Player* reporter)
-{
- BattleGround *bg = GetBattleGround();
- if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
- return;
-
- // check if player has 'Idle' or 'Inactive' debuff
- if(m_bgData.bgAfkReporter.find(reporter->GetGUIDLow())==m_bgData.bgAfkReporter.end() && !HasAura(43680) && !HasAura(43681) && reporter->CanReportAfkDueToLimit())
- {
- m_bgData.bgAfkReporter.insert(reporter->GetGUIDLow());
- // 3 players have to complain to apply debuff
- if(m_bgData.bgAfkReporter.size() >= 3)
- {
- // cast 'Idle' spell
- CastSpell(this, 43680, true);
- m_bgData.bgAfkReporter.clear();
- }
- }
-}
-
-WorldLocation Player::GetStartPosition() const
-{
- PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
- uint32 mapId = info->mapId;
- if (getClass() == CLASS_DEATH_KNIGHT && HasSpell(50977))
- mapId = 0;
- return WorldLocation(mapId, info->positionX, info->positionY, info->positionZ, 0);
-}
-
-bool Player::canSeeOrDetect(Unit const* u, bool detect, bool inVisibleList, bool is3dDistance) const
-{
- // Always can see self
- if (m_mover == u || this == u)
- return true;
-
- // phased visibility (both must phased in same way)
- if(!InSamePhase(u))
- return false;
-
- // player visible for other player if not logout and at same transport
- // including case when player is out of world
- bool at_same_transport =
- GetTransport() && u->GetTypeId() == TYPEID_PLAYER
- && !GetSession()->PlayerLogout() && !((Player*)u)->GetSession()->PlayerLogout()
- && !GetSession()->PlayerLoading() && !((Player*)u)->GetSession()->PlayerLoading()
- && GetTransport() == ((Player*)u)->GetTransport();
-
- // not in world
- if(!at_same_transport && (!IsInWorld() || !u->IsInWorld()))
- return false;
-
- // forbidden to seen (at GM respawn command)
- //if(u->GetVisibility() == VISIBILITY_RESPAWN)
- // return false;
-
- Map& _map = *u->GetMap();
- // Grid dead/alive checks
- // non visible at grid for any stealth state
- if(!u->IsVisibleInGridForPlayer(this))
- return false;
-
- // always seen by owner
- if(uint64 guid = u->GetCharmerOrOwnerGUID())
- if(GetGUID() == guid)
- return true;
-
- if(uint64 guid = GetUInt64Value(PLAYER_FARSIGHT))
- if(u->GetGUID() == guid)
- return true;
-
- // different visible distance checks
- if(isInFlight()) // what see player in flight
- {
- if (!m_seer->IsWithinDistInMap(u, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
- return false;
- }
- else if(!u->isAlive()) // distance for show body
- {
- if (!m_seer->IsWithinDistInMap(u, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
- return false;
- }
- else if(u->GetTypeId() == TYPEID_PLAYER) // distance for show player
- {
- // Players far than max visible distance for player or not in our map are not visible too
- if (!at_same_transport && !m_seer->IsWithinDistInMap(u, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
- return false;
- }
- else if(u->GetCharmerOrOwnerGUID()) // distance for show pet/charmed
- {
- // Pet/charmed far than max visible distance for player or not in our map are not visible too
- if (!m_seer->IsWithinDistInMap(u, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
- return false;
- }
- else // distance for show creature
- {
- // Units farther than max visible distance for creature or not in our map are not visible too
- if (!m_seer->IsWithinDistInMap(u
- , u->isActiveObject() ? (MAX_VISIBILITY_DISTANCE - (inVisibleList ? 0.0f : World::GetVisibleUnitGreyDistance()))
- : (_map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f))
- , is3dDistance))
- return false;
- }
-
- if(u->GetVisibility() == VISIBILITY_OFF)
- {
- // GMs see any players, not higher GMs and all units
- if(isGameMaster())
- {
- if(u->GetTypeId() == TYPEID_PLAYER)
- return ((Player *)u)->GetSession()->GetSecurity() <= GetSession()->GetSecurity();
- else
- return true;
- }
- return false;
- }
-
- // GM's can see everyone with invisibilitymask with less or equal security level
- if(m_mover->m_invisibilityMask || u->m_invisibilityMask)
- {
- if(isGameMaster())
- {
- if(u->GetTypeId() == TYPEID_PLAYER)
- return ((Player*)u)->GetSession()->GetSecurity() <= GetSession()->GetSecurity();
- else
- return true;
- }
-
- // player see other player with stealth/invisibility only if he in same group or raid or same team (raid/team case dependent from conf setting)
- if(!m_mover->canDetectInvisibilityOf(u))
- if(!(u->GetTypeId() == TYPEID_PLAYER && !IsHostileTo(u) && IsGroupVisibleFor(((Player*)u))))
- return false;
- }
-
- // GM invisibility checks early, invisibility if any detectable, so if not stealth then visible
- if(u->GetVisibility() == VISIBILITY_GROUP_STEALTH && !isGameMaster())
- {
- // if player is dead then he can't detect anyone in any cases
- //do not know what is the use of this detect
- // stealth and detected and visible for some seconds
- if(!isAlive())
- detect = false;
- if(m_DetectInvTimer < 300 || !HaveAtClient(u))
- if(!(u->GetTypeId() == TYPEID_PLAYER && !IsHostileTo(u) && IsGroupVisibleFor(((Player*)u))))
- if(!detect || !m_mover->canDetectStealthOf(u, GetDistance(u)))
- return false;
- }
-
- // If use this server will be too laggy
- // Now check is target visible with LoS
- //return u->IsWithinLOS(GetPositionX(),GetPositionY(),GetPositionZ());
- return true;
-}
-
-bool Player::IsVisibleInGridForPlayer( Player const * pl ) const
-{
- // gamemaster in GM mode see all, including ghosts
- if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
- return true;
-
- // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
- if (InBattleGround())
- {
- if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
- return false;
- return true;
- }
-
- // Live player see live player or dead player with not realized corpse
- if(pl->isAlive() || pl->m_deathTimer > 0)
- {
- return isAlive() || m_deathTimer > 0;
- }
-
- // Ghost see other friendly ghosts, that's for sure
- if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
- return true;
-
- // Dead player see live players near own corpse
- if(isAlive())
- {
- Corpse *corpse = pl->GetCorpse();
- if(corpse)
- {
- // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
- if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
- return true;
- }
- }
-
- // and not see any other
- return false;
-}
-
-bool Player::IsVisibleGloballyFor( Player* u ) const
-{
- if(!u)
- return false;
-
- // Always can see self
- if (u==this)
- return true;
-
- // Visible units, always are visible for all players
- if (GetVisibility() == VISIBILITY_ON)
- return true;
-
- // GMs are visible for higher gms (or players are visible for gms)
- if (u->GetSession()->GetSecurity() > SEC_PLAYER)
- return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
-
- // non faction visibility non-breakable for non-GMs
- if (GetVisibility() == VISIBILITY_OFF)
- return false;
-
- // non-gm stealth/invisibility not hide from global player lists
- return true;
-}
-
-template<class T>
-inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target, std::set<Unit*>& v)
-{
- s64.insert(target->GetGUID());
-}
-
-template<>
-inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target, std::set<Unit*>& v)
-{
- if(!target->IsTransport())
- s64.insert(target->GetGUID());
-}
-
-template<>
-inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, Creature* target, std::set<Unit*>& v)
-{
- s64.insert(target->GetGUID());
- v.insert(target);
-}
-
-template<>
-inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, Player* target, std::set<Unit*>& v)
-{
- s64.insert(target->GetGUID());
- v.insert(target);
-}
-
-template<class T>
-inline void BeforeVisibilityDestroy(T* /*t*/, Player* /*p*/)
-{
-}
-
-template<>
-inline void BeforeVisibilityDestroy<Creature>(Creature* t, Player* p)
-{
- if (p->GetPetGUID()==t->GetGUID() && ((Creature*)t)->isPet())
- ((Pet*)t)->Remove(PET_SAVE_NOT_IN_SLOT, true);
-}
-
-void Player::UpdateVisibilityOf(WorldObject* target)
-{
- if(HaveAtClient(target))
- {
- if(!target->isVisibleForInState(this, true))
- {
- if (target->GetTypeId()==TYPEID_UNIT)
- BeforeVisibilityDestroy<Creature>((Creature*)target,this);
-
- target->DestroyForPlayer(this);
- m_clientGUIDs.erase(target->GetGUID());
-
- #ifdef TRINITY_DEBUG
- if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
- sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
- #endif
- }
- }
- else
- {
- if(target->isVisibleForInState(this,false))
- {
- //if(target->isType(TYPEMASK_UNIT) && ((Unit*)target)->m_Vehicle)
- // UpdateVisibilityOf(((Unit*)target)->m_Vehicle);
-
- target->SendUpdateToPlayer(this);
- m_clientGUIDs.insert(target->GetGUID());
-
- #ifdef TRINITY_DEBUG
- if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
- sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
- #endif
-
- // target aura duration for caster show only if target exist at caster client
- // send data at target visibility change (adding to client)
- if(target->isType(TYPEMASK_UNIT))
- SendInitialVisiblePackets((Unit*)target);
- }
- }
-}
-
-void Player::SendInitialVisiblePackets(Unit* target)
-{
- SendAurasForTarget(target);
- if(target->isAlive())
- {
- if(target->GetMotionMaster()->GetCurrentMovementGeneratorType() != IDLE_MOTION_TYPE)
- target->SendMonsterMoveWithSpeedToCurrentDestination(this);
- if(target->hasUnitState(UNIT_STAT_MELEE_ATTACKING) && target->getVictim())
- target->SendMeleeAttackStart(target->getVictim());
- }
-}
-
-template<class T>
-void Player::UpdateVisibilityOf(T* target, UpdateData& data, std::set<Unit*>& visibleNow)
-{
- if(HaveAtClient(target))
- {
- if(!target->isVisibleForInState(this,true))
- {
- BeforeVisibilityDestroy<T>(target,this);
-
- target->BuildOutOfRangeUpdateBlock(&data);
- m_clientGUIDs.erase(target->GetGUID());
-
- #ifdef TRINITY_DEBUG
- if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
- 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));
- #endif
- }
- }
- else //if(visibleNow.size() < 30 || target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->IsVehicle())
- {
- if(target->isVisibleForInState(this,false))
- {
- //if(target->isType(TYPEMASK_UNIT) && ((Unit*)target)->m_Vehicle)
- // UpdateVisibilityOf(((Unit*)target)->m_Vehicle, data, visibleNow);
-
- target->BuildCreateUpdateBlockForPlayer(&data, this);
- UpdateVisibilityOf_helper(m_clientGUIDs,target,visibleNow);
-
- #ifdef TRINITY_DEBUG
- if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
- 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));
- #endif
- }
- }
-}
-
-template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, std::set<Unit*>& visibleNow);
-template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, std::set<Unit*>& visibleNow);
-template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, std::set<Unit*>& visibleNow);
-template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, std::set<Unit*>& visibleNow);
-template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, std::set<Unit*>& visibleNow);
-
-void Player::InitPrimaryProfessions()
-{
- SetFreePrimaryProfessions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
-}
-
-Unit * Player::GetSelectedUnit() const
-{
- if(m_curSelection)
- return ObjectAccessor::GetUnit(*this, m_curSelection);
- return NULL;
-}
-
-Player * Player::GetSelectedPlayer() const
-{
- if(m_curSelection)
- return ObjectAccessor::GetPlayer(*this, m_curSelection);
- return NULL;
-}
-
-void Player::SendComboPoints()
-{
- Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
- if (combotarget)
- {
- WorldPacket data;
- if(m_mover != this)
- {
- data.Initialize(SMSG_PET_UPDATE_COMBO_POINTS, m_mover->GetPackGUID().size()+combotarget->GetPackGUID().size()+1);
- data.append(m_mover->GetPackGUID());
- }
- else
- data.Initialize(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
- data.append(combotarget->GetPackGUID());
- data << uint8(m_comboPoints);
- GetSession()->SendPacket(&data);
- }
-}
-
-void Player::AddComboPoints(Unit* target, int8 count, Spell * spell)
-{
- if(!count)
- return;
-
- int8 * comboPoints = spell ? &spell->m_comboPointGain : &m_comboPoints;
-
- // without combo points lost (duration checked in aura)
- RemoveAurasByType(SPELL_AURA_RETAIN_COMBO_POINTS);
-
- if (target->GetGUID() == m_comboTarget)
- *comboPoints += count;
- else
- {
- if (m_comboTarget)
- if (Unit* target2 = ObjectAccessor::GetUnit(*this, m_comboTarget))
- target2->RemoveComboPointHolder(GetGUIDLow());
-
- // Spells will always add value to m_comboPoints eventualy, so it must be cleared first
- if (spell)
- m_comboPoints = 0;
-
- m_comboTarget = target->GetGUID();
- *comboPoints = count;
-
- target->AddComboPointHolder(GetGUIDLow());
- }
-
- if (*comboPoints > 5)
- *comboPoints = 5;
- else if (*comboPoints < 0)
- *comboPoints = 0;
-
- if (!spell)
- SendComboPoints();
-}
-
-void Player::GainSpellComboPoints(int8 count)
-{
- if(!count)
- return;
-
- m_comboPoints += count;
- if (m_comboPoints > 5) m_comboPoints = 5;
- else if (m_comboPoints < 0) m_comboPoints = 0;
-
- SendComboPoints();
-}
-
-void Player::ClearComboPoints()
-{
- if(!m_comboTarget)
- return;
-
- // without combopoints lost (duration checked in aura)
- RemoveAurasByType(SPELL_AURA_RETAIN_COMBO_POINTS);
-
- m_comboPoints = 0;
-
- SendComboPoints();
-
- if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
- target->RemoveComboPointHolder(GetGUIDLow());
-
- m_comboTarget = 0;
-}
-
-void Player::SetGroup(Group *group, int8 subgroup)
-{
- if(group == NULL)
- m_group.unlink();
- else
- {
- // never use SetGroup without a subgroup unless you specify NULL for group
- assert(subgroup >= 0);
- m_group.link(group, this);
- m_group.setSubGroup((uint8)subgroup);
- }
-}
-
-void Player::SendInitialPacketsBeforeAddToMap()
-{
- GetSocial()->SendSocialList();
-
- // guild bank list wtf?
-
- // Homebind
- WorldPacket data(SMSG_BINDPOINTUPDATE, 5*4);
- data << m_homebindX << m_homebindY << m_homebindZ;
- data << (uint32) m_homebindMapId;
- data << (uint32) m_homebindZoneId;
- GetSession()->SendPacket(&data);
-
- // SMSG_SET_PROFICIENCY
- // SMSG_SET_PCT_SPELL_MODIFIER
- // SMSG_SET_FLAT_SPELL_MODIFIER
- // SMSG_UPDATE_AURA_DURATION
-
- SendTalentsInfoData(false);
-
- // SMSG_INSTANCE_DIFFICULTY
-
- SendInitialSpells();
-
- data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
- data << uint32(0); // count, for(count) uint32;
- GetSession()->SendPacket(&data);
-
- SendInitialActionButtons();
- m_reputationMgr.SendInitialReputations();
- m_achievementMgr.SendAllAchievementData();
-
- SendEquipmentSetList();
-
- data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4);
- data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
- data << (float)0.01666667f; // game speed
- data << uint32(0); // added in 3.1.2
- GetSession()->SendPacket( &data );
-
- GetReputationMgr().SendForceReactions(); // SMSG_SET_FORCED_REACTIONS
-
- // SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...)
- // SMSG_PET_GUIDS
- // SMSG_UPDATE_WORLD_STATE
- // SMSG_POWER_UPDATE
-
-}
-
-void Player::SendInitialPacketsAfterAddToMap()
-{
- // update zone
- uint32 newzone, newarea;
- GetZoneAndAreaId(newzone,newarea);
- UpdateZone(newzone,newarea); // also call SendInitWorldStates();
-
- ResetTimeSync();
- SendTimeSync();
-
- CastSpell(this, 836, true); // LOGINEFFECT
-
- // set some aura effects that send packet to player client after add player to map
- // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
- // same auras state lost at far teleport, send it one more time in this case also
- static const AuraType auratypes[] =
- {
- SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
- SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
- SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED, SPELL_AURA_NONE
- };
- for (AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
- {
- Unit::AuraEffectList const& auraList = GetAuraEffectsByType(*itr);
- if(!auraList.empty())
- auraList.front()->HandleEffect(this, AURA_EFFECT_HANDLE_SEND_FOR_CLIENT, true);
- }
-
- if(HasAuraType(SPELL_AURA_MOD_STUN))
- SetMovement(MOVE_ROOT);
-
- // manual send package (have code in HandleEffect(this, AURA_EFFECT_HANDLE_SEND_FOR_CLIENT, true); that don't must be re-applied.
- if(HasAuraType(SPELL_AURA_MOD_ROOT))
- {
- WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
- data2.append(GetPackGUID());
- data2 << (uint32)2;
- SendMessageToSet(&data2,true);
- }
-
- SendAurasForTarget(this);
- SendEnchantmentDurations(); // must be after add to map
- SendItemDurations(); // must be after add to map
-}
-
-void Player::SendUpdateToOutOfRangeGroupMembers()
-{
- if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
- return;
- if(Group* group = GetGroup())
- group->UpdatePlayerOutOfRange(this);
-
- m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
- m_auraRaidUpdateMask = 0;
- if(Pet *pet = GetPet())
- pet->ResetAuraUpdateMaskForRaid();
-}
-
-void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
-{
- WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
- data << uint32(mapid);
- data << uint8(reason); // transfer abort reason
- switch(reason)
- {
- case TRANSFER_ABORT_INSUF_EXPAN_LVL:
- case TRANSFER_ABORT_DIFFICULTY:
- case TRANSFER_ABORT_UNIQUE_MESSAGE:
- case TRANSFER_ABORT_ZONE_IN_COMBAT:
- case TRANSFER_ABORT_MAX_PLAYERS:
- data << uint8(arg);
- break;
- }
- GetSession()->SendPacket(&data);
-}
-
-void Player::SendInstanceResetWarning( uint32 mapid, Difficulty difficulty, uint32 time )
-{
- // type of warning, based on the time remaining until reset
- uint32 type;
- if(time > 3600)
- type = RAID_INSTANCE_WELCOME;
- else if(time > 900 && time <= 3600)
- type = RAID_INSTANCE_WARNING_HOURS;
- else if(time > 300 && time <= 900)
- type = RAID_INSTANCE_WARNING_MIN;
- else
- type = RAID_INSTANCE_WARNING_MIN_SOON;
-
- WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4);
- data << uint32(type);
- data << uint32(mapid);
- data << uint32(difficulty); // difficulty
- data << uint32(time);
- if(type == RAID_INSTANCE_WELCOME)
- {
- data << uint8(0); // is your (1)
- data << uint8(0); // is extended (1), ignored if prev field is 0
- }
- GetSession()->SendPacket(&data);
-}
-
-void Player::ApplyEquipCooldown( Item * pItem )
-{
- for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
- {
- _Spell const& spellData = pItem->GetProto()->Spells[i];
-
- // no spell
- if( !spellData.SpellId )
- continue;
-
- // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
- if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
- continue;
-
- AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
-
- WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
- data << pItem->GetGUID();
- data << uint32(spellData.SpellId);
- GetSession()->SendPacket(&data);
- }
-}
-
-void Player::resetSpells(bool myClassOnly)
-{
- // not need after this call
- if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
- RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS,true);
-
- // make full copy of map (spells removed and marked as deleted at another spell remove
- // and we can't use original map for safe iterative with visit each spell at loop end
- PlayerSpellMap smap = GetSpellMap();
-
- uint32 family;
-
- if(myClassOnly)
- {
- ChrClassesEntry const* clsEntry = sChrClassesStore.LookupEntry(getClass());
- if(!clsEntry)
- return;
- family = clsEntry->spellfamily;
- }
-
- for (PlayerSpellMap::const_iterator iter = smap.begin(); iter != smap.end(); ++iter)
- {
- if(myClassOnly)
- {
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(iter->first);
- if(!spellInfo)
- continue;
-
- // skip server-side/triggered spells
- if(spellInfo->spellLevel == 0)
- continue;
-
- // skip wrong class/race skills
- if(!IsSpellFitByClassAndRace(spellInfo->Id))
- continue;
-
- // skip other spell families
- if(spellInfo->SpellFamilyName != family)
- continue;
-
- // skip spells with first rank learned as talent (and all talents then also)
- uint32 first_rank = spellmgr.GetFirstSpellInChain(spellInfo->Id);
- if(GetTalentSpellCost(first_rank) > 0)
- continue;
-
- // skip broken spells
- if(!SpellMgr::IsSpellValid(spellInfo,this,false))
- continue;
- }
- removeSpell(iter->first,false,false); // only iter->first can be accessed, object by iter->second can be deleted already
- }
-
- learnDefaultSpells();
- learnQuestRewardedSpells();
-}
-
-void Player::learnDefaultSpells()
-{
- // learn default race/class spells
- PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
- for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
- {
- uint32 tspell = *itr;
- sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
- if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
- addSpell(tspell,true,true,true,false);
- else // but send in normal spell in game learn case
- learnSpell(tspell,true);
- }
-}
-
-void Player::learnQuestRewardedSpells(Quest const* quest)
-{
- int32 spell_id = quest->GetRewSpellCast();
- uint32 src_spell_id = quest->GetSrcSpell();
-
- // skip quests without rewarded spell
- if( !spell_id )
- return;
-
- // if RewSpellCast = -1 we remove aura do to SrcSpell from player.
- if (spell_id == -1 && src_spell_id)
- {
- this->RemoveAurasDueToSpell(src_spell_id);
- return;
- }
-
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
- if(!spellInfo)
- return;
-
- // check learned spells state
- bool found = false;
- for (uint8 i = 0; i < 3; ++i)
- {
- if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
- {
- found = true;
- break;
- }
- }
-
- // skip quests with not teaching spell or already known spell
- if(!found)
- return;
-
- // prevent learn non first rank unknown profession and second specialization for same profession)
- uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
- if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
- {
- // not have first rank learned (unlearned prof?)
- uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
- if( !HasSpell(first_spell) )
- return;
-
- SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
- if(!learnedInfo)
- return;
-
- SpellsRequiringSpellMapBounds spellsRequired = spellmgr.GetSpellsRequiredForSpellBounds(learned_0);
- for (SpellsRequiringSpellMap::const_iterator itr2 = spellsRequired.first; itr2 != spellsRequired.second; ++itr2)
- {
- uint32 profSpell = itr2->second;
-
- // specialization
- if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0 && profSpell)
- {
- // search other specialization for same prof
- for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
- {
- if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
- continue;
-
- SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
- if(!itrInfo)
- return;
-
- // compare only specializations
- if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
- continue;
-
- // compare same chain spells
- if (spellmgr.IsSpellRequiringSpell(itr->first, profSpell))
- return;
- }
- }
- }
- }
-
- CastSpell( this, spell_id, true);
-}
-
-void Player::learnQuestRewardedSpells()
-{
- // learn spells received from quest completing
- for (QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
- {
- // skip no rewarded quests
- if(!itr->second.m_rewarded)
- continue;
-
- Quest const* quest = objmgr.GetQuestTemplate(itr->first);
- if( !quest )
- continue;
-
- learnQuestRewardedSpells(quest);
- }
-}
-
-void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
-{
- uint32 raceMask = getRaceMask();
- uint32 classMask = getClassMask();
- for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
- {
- SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
- if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
- continue;
- // Check race if set
- if (pAbility->racemask && !(pAbility->racemask & raceMask))
- continue;
- // Check class if set
- if (pAbility->classmask && !(pAbility->classmask & classMask))
- continue;
-
- if (sSpellStore.LookupEntry(pAbility->spellId))
- {
- // need unlearn spell
- if (skill_value < pAbility->req_skill_value)
- removeSpell(pAbility->spellId);
- // need learn
- else if (!IsInWorld())
- addSpell(pAbility->spellId,true,true,true,false);
- else
- learnSpell(pAbility->spellId,true);
- }
- }
-}
-
-void Player::SendAurasForTarget(Unit *target)
-{
- if(!target || target->GetVisibleAuras()->empty()) // speedup things
- return;
-
- WorldPacket data(SMSG_AURA_UPDATE_ALL);
- data.append(target->GetPackGUID());
-
- Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
- for (Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
- {
- AuraApplication * auraApp = itr->second;
- Aura * aura = auraApp->GetBase();
- data << uint8(auraApp->GetSlot());
- data << uint32(aura->GetId());
-
- // flags
- uint32 flags = auraApp->GetFlags();
- if (aura->GetMaxDuration() > 0)
- flags |= AFLAG_DURATION;
- data << uint8(flags);
- // level
- data << uint8(aura->GetCasterLevel());
- // charges
- data << uint8(aura->GetStackAmount() > 1 ? aura->GetStackAmount() : (aura->GetCharges()) ? aura->GetCharges() : 1);
-
- if(!(flags & AFLAG_CASTER))
- data.appendPackGUID(aura->GetCasterGUID());
-
- if(flags & AFLAG_DURATION) // include aura duration
- {
- data << uint32(aura->GetMaxDuration());
- data << uint32(aura->GetDuration());
- }
- }
-
- GetSession()->SendPacket(&data);
-}
-
-void Player::SetDailyQuestStatus( uint32 quest_id )
-{
- for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
- {
- if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
- {
- SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
- m_lastDailyQuestTime = time(NULL); // last daily quest time
- m_DailyQuestChanged = true;
- break;
- }
- }
-}
-
-void Player::ResetDailyQuestStatus()
-{
- for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
- SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
-
- // DB data deleted in caller
- m_DailyQuestChanged = false;
- m_lastDailyQuestTime = 0;
-}
-
-BattleGround* Player::GetBattleGround() const
-{
- if(GetBattleGroundId()==0)
- return NULL;
-
- return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgData.bgTypeID);
-}
-
-bool Player::InArena() const
-{
- BattleGround *bg = GetBattleGround();
- if(!bg || !bg->isArena())
- return false;
-
- return true;
-}
-
-bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
-{
- // get a template bg instead of running one
- BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
- if(!bg)
- return false;
-
- // limit check leel to dbc compatible level range
- uint32 level = getLevel();
- if (level > DEFAULT_MAX_LEVEL)
- level = DEFAULT_MAX_LEVEL;
-
- if(level < bg->GetMinLevel() || level > bg->GetMaxLevel())
- return false;
-
- return true;
-}
-
-float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
-{
- FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
- if (!vendor_faction || !vendor_faction->faction)
- return 1.0f;
-
- ReputationRank rank = GetReputationRank(vendor_faction->faction);
- if (rank <= REP_NEUTRAL)
- return 1.0f;
-
- return 1.0f - 0.05f* (rank - REP_NEUTRAL);
-}
-
-bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
-{
- uint32 racemask = getRaceMask();
- uint32 classmask = getClassMask();
-
- SkillLineAbilityMapBounds bounds = spellmgr.GetSkillLineAbilityMapBounds(spell_id);
- if (bounds.first==bounds.second)
- return true;
-
- for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
- {
- // skip wrong race skills
- if (_spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
- continue;
-
- // skip wrong class skills
- if (_spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
- continue;
-
- return true;
- }
-
- return false;
-}
-
-bool Player::HasQuestForGO(int32 GOId) const
-{
- for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
- {
- uint32 questid = GetQuestSlotQuestId(i);
- if (questid == 0)
- continue;
-
- QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
- if (qs_itr == mQuestStatus.end())
- continue;
-
- QuestStatusData const& qs = qs_itr->second;
-
- if (qs.m_status == QUEST_STATUS_INCOMPLETE)
- {
- Quest const* qinfo = objmgr.GetQuestTemplate(questid);
- if (!qinfo)
- continue;
-
- if (GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
- continue;
-
- for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
- {
- if (qinfo->ReqCreatureOrGOId[j] >= 0) //skip non GO case
- continue;
-
- if ((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
- return true;
- }
- }
- }
- return false;
-}
-
-void Player::UpdateForQuestWorldObjects()
-{
- if (m_clientGUIDs.empty())
- return;
-
- UpdateData udata;
- WorldPacket packet;
- for (ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
- {
- if (IS_GAMEOBJECT_GUID(*itr))
- {
- if (GameObject *obj = HashMapHolder<GameObject>::Find(*itr))
- obj->BuildValuesUpdateBlockForPlayer(&udata,this);
- }
- else if (IS_CRE_OR_VEH_GUID(*itr))
- {
- Creature *obj = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr);
- if (!obj)
- continue;
-
- // check if this unit requires quest specific flags
- if(!obj->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
- continue;
-
- SpellClickInfoMapBounds clickPair = objmgr.GetSpellClickInfoMapBounds(obj->GetEntry());
- for (SpellClickInfoMap::const_iterator _itr = clickPair.first; _itr != clickPair.second; ++_itr)
- if(_itr->second.questStart || _itr->second.questEnd)
- {
- obj->BuildCreateUpdateBlockForPlayer(&udata,this);
- break;
- }
- }
- }
- udata.BuildPacket(&packet);
- GetSession()->SendPacket(&packet);
-}
-
-void Player::SummonIfPossible(bool agree)
-{
- if (!agree)
- {
- m_summon_expire = 0;
- return;
- }
-
- // expire and auto declined
- if (m_summon_expire < time(NULL))
- return;
-
- // stop taxi flight at summon
- if (isInFlight())
- {
- GetMotionMaster()->MovementExpired();
- CleanupAfterTaxiFlight();
- }
-
- // drop flag at summon
- // 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
- if (BattleGround *bg = GetBattleGround())
- bg->EventPlayerDroppedFlag(this);
-
- m_summon_expire = 0;
-
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
-
- TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
-}
-
-void Player::RemoveItemDurations(Item *item)
-{
- for (ItemDurationList::iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
- {
- if(*itr == item)
- {
- m_itemDuration.erase(itr);
- break;
- }
- }
-}
-
-void Player::AddItemDurations(Item *item)
-{
- if (item->GetUInt32Value(ITEM_FIELD_DURATION))
- {
- m_itemDuration.push_back(item);
- item->SendTimeUpdate(this);
- }
-}
-
-void Player::AutoUnequipOffhandIfNeed(bool force /*= false*/)
-{
- Item *offItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
- if (!offItem)
- return;
-
- // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
- if (!force && (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed())))
- return;
-
- ItemPosCountVec off_dest;
- uint8 off_msg = CanStoreItem(NULL_BAG, NULL_SLOT, off_dest, offItem, false);
- if (off_msg == EQUIP_ERR_OK)
- {
- RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
- StoreItem(off_dest, offItem, true);
- }
- else
- {
- MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
- CharacterDatabase.BeginTransaction();
- offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
- offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
- CharacterDatabase.CommitTransaction();
-
- std::string subject = GetSession()->GetTrinityString(LANG_NOT_EQUIPPED_ITEM);
- MailDraft(subject).AddItem(offItem).SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM));
- }
-}
-
-OutdoorPvP * Player::GetOutdoorPvP() const
-{
- return sOutdoorPvPMgr.GetOutdoorPvPToZoneId(GetZoneId());
-}
-
-bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
-{
- if (spellInfo->EquippedItemClass < 0)
- return true;
-
- // scan other equipped items for same requirements (mostly 2 daggers/etc)
- // for optimize check 2 used cases only
- switch (spellInfo->EquippedItemClass)
- {
- case ITEM_CLASS_WEAPON:
- {
- for (uint8 i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
- if(Item *item = GetUseableItemByPos( INVENTORY_SLOT_BAG_0, i ))
- if(item != ignoreItem && item->IsFitToSpellRequirements(spellInfo))
- return true;
- break;
- }
- case ITEM_CLASS_ARMOR:
- {
- // tabard not have dependent spells
- for (uint8 i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
- if(Item *item = GetUseableItemByPos( INVENTORY_SLOT_BAG_0, i ))
- if(item != ignoreItem && item->IsFitToSpellRequirements(spellInfo))
- return true;
-
- // shields can be equipped to offhand slot
- if(Item *item = GetUseableItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
- if(item != ignoreItem && item->IsFitToSpellRequirements(spellInfo))
- return true;
-
- // ranged slot can have some armor subclasses
- if(Item *item = GetUseableItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
- if(item != ignoreItem && item->IsFitToSpellRequirements(spellInfo))
- return true;
-
- break;
- }
- default:
- sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
- break;
- }
-
- return false;
-}
-
-bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
-{
- // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
- if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
- HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
- return true;
-
- // Check no reagent use mask
- flag96 noReagentMask;
- noReagentMask[0] = GetUInt32Value(PLAYER_NO_REAGENT_COST_1);
- noReagentMask[1] = GetUInt32Value(PLAYER_NO_REAGENT_COST_1+1);
- noReagentMask[2] = GetUInt32Value(PLAYER_NO_REAGENT_COST_1+2);
- if (spellInfo->SpellFamilyFlags & noReagentMask)
- return true;
-
- return false;
-}
-
-void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
-{
- for (AuraMap::iterator itr = m_ownedAuras.begin(); itr != m_ownedAuras.end();)
- {
- Aura * aura = itr->second;
-
- // skip passive (passive item dependent spells work in another way) and not self applied auras
- SpellEntry const* spellInfo = aura->GetSpellProto();
- if(aura->IsPassive() || aura->GetCasterGUID() != GetGUID())
- {
- ++itr;
- continue;
- }
-
- // skip if not item dependent or have alternative item
- if(HasItemFitToSpellReqirements(spellInfo,pItem))
- {
- ++itr;
- continue;
- }
-
- // no alt item, remove aura, restart check
- RemoveOwnedAura(itr);
- }
-
- // currently casted spells can be dependent from item
- for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
- if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i)))
- if (spell->getState()!=SPELL_STATE_DELAYED && !HasItemFitToSpellReqirements(spell->m_spellInfo,pItem) )
- InterruptSpell(CurrentSpellTypes(i));
-}
-
-uint32 Player::GetResurrectionSpellId()
-{
- // search priceless resurrection possibilities
- uint32 prio = 0;
- uint32 spell_id = 0;
- AuraEffectList const& dummyAuras = GetAuraEffectsByType(SPELL_AURA_DUMMY);
- for (AuraEffectList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
- {
- // Soulstone Resurrection // prio: 3 (max, non death persistent)
- if (prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
- {
- switch ((*itr)->GetId())
- {
- case 20707: spell_id = 3026; break; // rank 1
- case 20762: spell_id = 20758; break; // rank 2
- case 20763: spell_id = 20759; break; // rank 3
- case 20764: spell_id = 20760; break; // rank 4
- case 20765: spell_id = 20761; break; // rank 5
- case 27239: spell_id = 27240; break; // rank 6
- case 47883: spell_id = 47882; break; // rank 7
- default:
- sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
- continue;
- }
-
- prio = 3;
- }
- // Twisting Nether // prio: 2 (max)
- else if ((*itr)->GetId()==23701 && roll_chance_i(10))
- {
- prio = 2;
- spell_id = 23700;
- }
- }
-
- // Reincarnation (passive spell) // prio: 1 // Glyph of Renewed Life
- if (prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && (HasAura(58059) || HasItemCount(17030,1)))
- spell_id = 21169;
-
- return spell_id;
-}
-
-// Used in triggers for check "Only to targets that grant experience or honor" req
-bool Player::isHonorOrXPTarget(Unit* pVictim)
-{
- uint8 v_level = pVictim->getLevel();
- uint8 k_grey = Trinity::XP::GetGrayLevel(getLevel());
-
- // Victim level less gray level
- if(v_level <= k_grey)
- return false;
-
- if(pVictim->GetTypeId() == TYPEID_UNIT)
- {
- if (((Creature*)pVictim)->isTotem() ||
- ((Creature*)pVictim)->isPet() ||
- ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
- return false;
- }
- return true;
-}
-
-bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
-{
- bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
-
- // prepare data for near group iteration (PvP and !PvP cases)
- uint32 xp = 0;
- bool honored_kill = false;
-
- if(Group *pGroup = GetGroup())
- {
- uint32 count = 0;
- uint32 sum_level = 0;
- Player* member_with_max_level = NULL;
- Player* not_gray_member_with_max_level = NULL;
-
- pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
-
- if(member_with_max_level)
- {
- // PvP kills doesn't yield experience
- // also no XP gained if there is no member below gray level
- xp = (PvP || !not_gray_member_with_max_level || GetVehicle()) ? 0 : Trinity::XP::Gain(not_gray_member_with_max_level, pVictim);
-
- /// skip in check PvP case (for speed, not used)
- bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
- bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
- float group_rate = Trinity::XP::xp_in_group_rate(count,is_raid);
-
- for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
- {
- Player* pGroupGuy = itr->getSource();
- if(!pGroupGuy)
- continue;
-
- if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
- continue; // member (alive or dead) or his corpse at req. distance
-
- // honor can be in PvP and !PvP (racial leader) cases (for alive)
- if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count, -1, true) && pGroupGuy==this)
- honored_kill = true;
-
- // xp and reputation only in !PvP case
- if(!PvP)
- {
- float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
-
- // if is in dungeon then all receive full reputation at kill
- // rewarded any alive/dead/near_corpse group member
- pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
-
- // XP updated only for alive group member
- if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
- pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
- {
- uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
-
- // handle SPELL_AURA_MOD_XP_PCT auras
- Unit::AuraEffectList const& ModXPPctAuras = GetAuraEffectsByType(SPELL_AURA_MOD_XP_PCT);
- for (Unit::AuraEffectList::const_iterator i = ModXPPctAuras.begin(); i != ModXPPctAuras.end(); ++i)
- itr_xp = uint32(itr_xp*(1.0f + (*i)->GetAmount() / 100.0f));
-
- pGroupGuy->GiveXP(itr_xp, pVictim);
- if(Pet* pet = pGroupGuy->GetPet())
- pet->GivePetXP(itr_xp/2);
- }
-
- // quest objectives updated only for alive group member or dead but with not released body
- if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
- {
- // normal creature (not pet/etc) can be only in !PvP case
- if(pVictim->GetTypeId() == TYPEID_UNIT)
- pGroupGuy->KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
- }
- }
- }
- }
- }
- else // if (!pGroup)
- {
- xp = (PvP || GetVehicle()) ? 0 : Trinity::XP::Gain(this, pVictim);
-
- // honor can be in PvP and !PvP (racial leader) cases
- if(RewardHonor(pVictim,1, -1, true))
- honored_kill = true;
-
- // xp and reputation only in !PvP case
- if(!PvP)
- {
- RewardReputation(pVictim,1);
-
- // handle SPELL_AURA_MOD_XP_PCT auras
- Unit::AuraEffectList const& ModXPPctAuras = GetAuraEffectsByType(SPELL_AURA_MOD_XP_PCT);
- for (Unit::AuraEffectList::const_iterator i = ModXPPctAuras.begin(); i != ModXPPctAuras.end(); ++i)
- xp = uint32(xp*(1.0f + (*i)->GetAmount() / 100.0f));
-
- GiveXP(xp, pVictim);
-
- if(Pet* pet = GetPet())
- pet->GivePetXP(xp);
-
- // normal creature (not pet/etc) can be only in !PvP case
- if(pVictim->GetTypeId() == TYPEID_UNIT)
- KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
- }
- }
- return xp || honored_kill;
-}
-
-void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
-{
- if (!pRewardSource)
- return;
- uint64 creature_guid = (pRewardSource->GetTypeId() == TYPEID_UNIT) ? pRewardSource->GetGUID() : uint64(0);
-
- // prepare data for near group iteration
- if(Group *pGroup = GetGroup())
- {
- for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
- {
- Player* pGroupGuy = itr->getSource();
- if(!pGroupGuy)
- continue;
-
- if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
- continue; // member (alive or dead) or his corpse at req. distance
-
- // quest objectives updated only for alive group member or dead but with not released body
- if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
- pGroupGuy->KilledMonsterCredit(creature_id, creature_guid);
- }
- }
- else // if (!pGroup)
- KilledMonsterCredit(creature_id, creature_guid);
-}
-
-bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
-{
- if (!pRewardSource)
- return false;
- const WorldObject* player = GetCorpse();
- if(!player || isAlive())
- player = this;
-
- if(player->GetMapId() != pRewardSource->GetMapId() || player->GetInstanceId() != pRewardSource->GetInstanceId())
- return false;
-
- return pRewardSource->GetDistance(player) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE);
-}
-
-uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
-{
- Item* item = GetWeaponForAttack(attType,true);
-
- // unarmed only with base attack
- if(attType != BASE_ATTACK && !item)
- return 0;
-
- // weapon skill or (unarmed for base attack and for fist weapons)
- uint32 skill = (item && item->GetSkill() != SKILL_FIST_WEAPONS) ? item->GetSkill() : uint32(SKILL_UNARMED);
- return GetBaseSkillValue(skill);
-}
-
-void Player::ResurectUsingRequestData()
-{
- /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
- if(IS_PLAYER_GUID(m_resurrectGUID))
- TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
-
- //we cannot resurrect player when we triggered far teleport
- //player will be resurrected upon teleportation
- if(IsBeingTeleportedFar())
- {
- ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER);
- return;
- }
-
- ResurrectPlayer(0.0f,false);
-
- if(GetMaxHealth() > m_resurrectHealth)
- SetHealth( m_resurrectHealth );
- else
- SetHealth( GetMaxHealth() );
-
- if(GetMaxPower(POWER_MANA) > m_resurrectMana)
- SetPower(POWER_MANA, m_resurrectMana );
- else
- SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
-
- SetPower(POWER_RAGE, 0 );
-
- SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
-
- SpawnCorpseBones();
-}
-
-void Player::SetClientControl(Unit* target, uint8 allowMove)
-{
- WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
- data.append(target->GetPackGUID());
- data << uint8(allowMove);
- GetSession()->SendPacket(&data);
- if(target == this)
- SetMover(this);
-}
-
-void Player::UpdateZoneDependentAuras( uint32 newZone )
-{
- // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
- SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newZone);
- for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
- if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
- if( !HasAura(itr->second->spellId) )
- CastSpell(this,itr->second->spellId,true);
-}
-
-void Player::UpdateAreaDependentAuras( uint32 newArea )
-{
- // remove auras from spells with area limitations
- for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();)
- {
- // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
- if(spellmgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
- RemoveOwnedAura(iter);
- else
- ++iter;
- }
-
- // some auras applied at subzone enter
- SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newArea);
- for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
- if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
- if( !HasAura(itr->second->spellId) )
- CastSpell(this,itr->second->spellId,true);
-
- if(newArea == 4273 && GetVehicle() && GetPositionX() > 400) // Ulduar
- {
- switch(GetVehicleBase()->GetEntry())
- {
- case 33062:
- case 33109:
- case 33060:
- GetVehicle()->Dismiss();
- break;
- }
- }
-}
-
-uint32 Player::GetCorpseReclaimDelay(bool pvp) const
-{
- if(pvp)
- {
- if(!sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP))
- return copseReclaimDelay[0];
- }
- else if(!sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
- return 0;
-
- time_t now = time(NULL);
- // 0..2 full period
- // should be ceil(x)-1 but not floor(x)
- uint32 count = (now < m_deathExpireTime - 1) ? (m_deathExpireTime - 1 - now)/DEATH_EXPIRE_STEP : 0;
- return copseReclaimDelay[count];
-}
-
-void Player::UpdateCorpseReclaimDelay()
-{
- bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
-
- if ((pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
- (!pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
- return;
-
- time_t now = time(NULL);
- if(now < m_deathExpireTime)
- {
- // full and partly periods 1..3
- uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
- if(count < MAX_DEATH_COUNT)
- m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
- else
- m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
- }
- else
- m_deathExpireTime = now+DEATH_EXPIRE_STEP;
-}
-
-void Player::SendCorpseReclaimDelay(bool load)
-{
- Corpse* corpse = GetCorpse();
- if(load && !corpse)
- return;
-
- bool pvp;
- if(corpse)
- pvp = (corpse->GetType() == CORPSE_RESURRECTABLE_PVP);
- else
- pvp = (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH);
-
- uint32 delay;
- if(load)
- {
- if(corpse->GetGhostTime() > m_deathExpireTime)
- return;
-
- uint32 count;
- if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
- !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
- {
- count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
- if(count>=MAX_DEATH_COUNT)
- count = MAX_DEATH_COUNT-1;
- }
- else
- count=0;
-
- time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
-
- time_t now = time(NULL);
- if(now >= expected_time)
- return;
-
- delay = expected_time-now;
- }
- else
- delay = GetCorpseReclaimDelay(pvp);
-
- if(!delay) return;
-
- //! corpse reclaim delay 30 * 1000ms or longer at often deaths
- WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
- data << uint32(delay*IN_MILISECONDS);
- GetSession()->SendPacket( &data );
-}
-
-Player* Player::GetNextRandomRaidMember(float radius)
-{
- Group *pGroup = GetGroup();
- if(!pGroup)
- return NULL;
-
- std::vector<Player*> nearMembers;
- nearMembers.reserve(pGroup->GetMembersCount());
-
- for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
- {
- Player* Target = itr->getSource();
-
- // IsHostileTo check duel and controlled by enemy
- if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
- !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
- nearMembers.push_back(Target);
- }
-
- if (nearMembers.empty())
- return NULL;
-
- uint32 randTarget = urand(0,nearMembers.size()-1);
- return nearMembers[randTarget];
-}
-
-PartyResult Player::CanUninviteFromGroup() const
-{
- const Group* grp = GetGroup();
- if(!grp)
- return PARTY_RESULT_YOU_NOT_IN_GROUP;
-
- if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
- return PARTY_RESULT_YOU_NOT_LEADER;
-
- if(InBattleGround())
- return PARTY_RESULT_INVITE_RESTRICTED;
-
- return PARTY_RESULT_OK;
-}
-
-void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
-{
- //we must move references from m_group to m_originalGroup
- SetOriginalGroup(GetGroup(), GetSubGroup());
-
- m_group.unlink();
- m_group.link(group, this);
- m_group.setSubGroup((uint8)subgroup);
-}
-
-void Player::RemoveFromBattleGroundRaid()
-{
- //remove existing reference
- m_group.unlink();
- if( Group* group = GetOriginalGroup() )
- {
- m_group.link(group, this);
- m_group.setSubGroup(GetOriginalSubGroup());
- }
- SetOriginalGroup(NULL);
-}
-
-void Player::SetOriginalGroup(Group *group, int8 subgroup)
-{
- if( group == NULL )
- m_originalGroup.unlink();
- else
- {
- // never use SetOriginalGroup without a subgroup unless you specify NULL for group
- assert(subgroup >= 0);
- m_originalGroup.link(group, this);
- m_originalGroup.setSubGroup((uint8)subgroup);
- }
-}
-
-void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
-{
- LiquidData liquid_status;
- ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
- if (!res)
- {
- m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
- // Small hack for enable breath in WMO
- if (IsInWater())
- m_MirrorTimerFlags|=UNDERWATER_INWATER;
- return;
- }
-
- // All liquids type - check under water position
- if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
- {
- if ( res & LIQUID_MAP_UNDER_WATER)
- m_MirrorTimerFlags |= UNDERWATER_INWATER;
- else
- m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
- }
-
- // Allow travel in dark water on taxi or transport
- if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
- m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
- else
- m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
-
- // in lava check, anywhere in lava level
- if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
- {
- if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
- m_MirrorTimerFlags |= UNDERWATER_INLAVA;
- else
- m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
- }
- // in slime check, anywhere in slime level
- if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
- {
- if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
- m_MirrorTimerFlags |= UNDERWATER_INSLIME;
- else
- m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
- }
-}
-
-void Player::SetCanParry( bool value )
-{
- if(m_canParry==value)
- return;
-
- m_canParry = value;
- UpdateParryPercentage();
-}
-
-void Player::SetCanBlock( bool value )
-{
- if(m_canBlock==value)
- return;
-
- m_canBlock = value;
- UpdateBlockPercentage();
-}
-
-bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
-{
- for (ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end(); ++itr)
- if(itr->pos == pos)
- return true;
- return false;
-}
-
-//***********************************
-//-------------TRINITY---------------
-//***********************************
-
-void Player::StopCastingBindSight()
-{
- if(WorldObject* target = GetViewpoint())
- {
- if(target->isType(TYPEMASK_UNIT))
- {
- ((Unit*)target)->RemoveAura(SPELL_AURA_BIND_SIGHT, GetGUID());
- ((Unit*)target)->RemoveAura(SPELL_AURA_MOD_POSSESS, GetGUID());
- ((Unit*)target)->RemoveAura(SPELL_AURA_MOD_POSSESS_PET, GetGUID());
- }
- }
-}
-
-void Player::SetViewpoint(WorldObject* target, bool apply)
-{
- if(apply)
- {
- sLog.outDebug("Player::CreateViewpoint: Player %s create seer %u (TypeId: %u).", GetName(), target->GetEntry(), target->GetTypeId());
-
- if(!AddUInt64Value(PLAYER_FARSIGHT, target->GetGUID()))
- {
- sLog.outCrash("Player::CreateViewpoint: Player %s cannot add new viewpoint!", GetName());
- return;
- }
-
- // farsight dynobj or puppet may be very far away
- UpdateVisibilityOf(target);
-
- if(target->isType(TYPEMASK_UNIT) && !GetVehicle())
- ((Unit*)target)->AddPlayerToVision(this);
- }
- else
- {
- sLog.outDebug("Player::CreateViewpoint: Player %s remove seer", GetName());
-
- if(!RemoveUInt64Value(PLAYER_FARSIGHT, target->GetGUID()))
- {
- sLog.outCrash("Player::CreateViewpoint: Player %s cannot remove current viewpoint!", GetName());
- return;
- }
-
- if(target->isType(TYPEMASK_UNIT) && !GetVehicle())
- ((Unit*)target)->RemovePlayerFromVision(this);
-
- //must immediately set seer back otherwise may crash
- m_seer = this;
-
- //WorldPacket data(SMSG_CLEAR_FAR_SIGHT_IMMEDIATE, 0);
- //GetSession()->SendPacket(&data);
- }
-}
-
-WorldObject* Player::GetViewpoint() const
-{
- if(uint64 guid = GetUInt64Value(PLAYER_FARSIGHT))
- return (WorldObject*)ObjectAccessor::GetObjectByTypeMask(*this, guid, TYPEMASK_SEER);
- return NULL;
-}
-
-bool Player::CanUseBattleGroundObject()
-{
- // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
- // maybe gameobject code should handle that ForceReaction usage
- // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
- return ( //InBattleGround() && // in battleground - not need, check in other cases
- //!IsMounted() && - not correct, player is dismounted when he clicks on flag
- //player cannot use object when he is invulnerable (immune)
- !isTotalImmune() && // not totally immune
- //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
- !HasStealthAura() && // not stealthed
- !HasInvisibilityAura() && // not invisible
- !HasAura(SPELL_RECENTLY_DROPPED_FLAG) && // can't pickup
- isAlive() // live player
- );
-}
-
-bool Player::CanCaptureTowerPoint()
-{
- return ( !HasStealthAura() && // not stealthed
- !HasInvisibilityAura() && // not invisible
- isAlive() // live player
- );
-}
-
-uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair, BarberShopStyleEntry const* newSkin )
-
-{
- uint8 level = getLevel();
-
- if(level > GT_MAX_LEVEL)
- level = GT_MAX_LEVEL; // max level in this dbc
-
- uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
- uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
- uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
- uint8 skincolor = GetByteValue(PLAYER_BYTES, 0);
-
- if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair) && (!newSkin || (newSkin->hair_id == skincolor)))
- return 0;
-
- GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
-
- if(!bsc) // shouldn't happen
- return 0xFFFFFFFF;
-
- float cost = 0;
-
- if(hairstyle != newhairstyle)
- cost += bsc->cost; // full price
-
- if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
- cost += bsc->cost * 0.5f; // +1/2 of price
-
- if(facialhair != newfacialhair)
- cost += bsc->cost * 0.75f; // +3/4 of price
-
- if(newSkin && skincolor != newSkin->hair_id)
- cost += bsc->cost * 0.75f; // +5/6 of price
-
- return uint32(cost);
-}
-
-void Player::InitGlyphsForLevel()
-{
- for (uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
- if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
- if(gs->Order)
- SetGlyphSlot(gs->Order - 1, gs->Id);
-
- uint8 level = getLevel();
- uint32 value = 0;
-
- // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
- if(level >= 15)
- value |= (0x01 | 0x02);
- if(level >= 30)
- value |= 0x08;
- if(level >= 50)
- value |= 0x04;
- if(level >= 70)
- value |= 0x10;
- if(level >= 80)
- value |= 0x20;
-
- SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
-}
-
-bool Player::isTotalImmune()
-{
- AuraEffectList const& immune = GetAuraEffectsByType(SPELL_AURA_SCHOOL_IMMUNITY);
-
- uint32 immuneMask = 0;
- for (AuraEffectList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
- {
- immuneMask |= (*itr)->GetMiscValue();
- if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
- return true;
- }
- return false;
-}
-
-bool Player::HasTitle(uint32 bitIndex)
-{
- if (bitIndex > MAX_TITLE_INDEX)
- return false;
-
- uint32 fieldIndexOffset = bitIndex / 32;
- uint32 flag = 1 << (bitIndex % 32);
- return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
-}
-
-void Player::SetTitle(CharTitlesEntry const* title, bool lost)
-{
- uint32 fieldIndexOffset = title->bit_index / 32;
- uint32 flag = 1 << (title->bit_index % 32);
-
- if(lost)
- {
- if(!HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
- return;
-
- RemoveFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
- }
- else
- {
- if(HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
- return;
-
- SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
- }
-
- WorldPacket data(SMSG_TITLE_EARNED, 4 + 4);
- data << uint32(title->bit_index);
- data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost
- GetSession()->SendPacket(&data);
-}
-
-/*-----------------------TRINITY--------------------------*/
-bool Player::isTotalImmunity()
-{
- AuraEffectList const& immune = GetAuraEffectsByType(SPELL_AURA_SCHOOL_IMMUNITY);
-
- for (AuraEffectList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
- {
- if (((*itr)->GetMiscValue() & SPELL_SCHOOL_MASK_ALL) !=0) // total immunity
- {
- return true;
- }
- if (((*itr)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL) !=0) // physical damage immunity
- {
- for (AuraEffectList::const_iterator i = immune.begin(); i != immune.end(); ++i)
- {
- if (((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_MAGIC) !=0) // magic immunity
- {
- return true;
- }
- }
- }
- }
- return false;
-}
-
-void Player::UpdateCharmedAI()
-{
- //This should only called in Player::Update
- Creature *charmer = (Creature*)GetCharmer();
-
- //kill self if charm aura has infinite duration
- if(charmer->IsInEvadeMode())
- {
- AuraEffectList const& auras = GetAuraEffectsByType(SPELL_AURA_MOD_CHARM);
- for (AuraEffectList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
- if((*iter)->GetCasterGUID() == charmer->GetGUID() && (*iter)->GetBase()->IsPermanent())
- {
- charmer->DealDamage(this, GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
- return;
- }
- }
-
- if(!charmer->isInCombat())
- GetMotionMaster()->MoveFollow(charmer, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE);
-
- Unit *target = getVictim();
- if(!target || !charmer->canAttack(target))
- {
- target = charmer->SelectNearestTarget();
- if(!target)
- return;
-
- GetMotionMaster()->MoveChase(target);
- Attack(target, true);
- }
-}
-
-uint32 Player::GetRuneBaseCooldown(uint8 index)
-{
- uint8 rune = GetBaseRune(index);
- uint32 cooldown = RUNE_COOLDOWN;
-
- AuraEffectList const& regenAura = GetAuraEffectsByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
- for(AuraEffectList::const_iterator i = regenAura.begin();i != regenAura.end(); ++i)
- {
- if((*i)->GetMiscValue() == POWER_RUNE && (*i)->GetMiscValueB() == rune)
- cooldown = cooldown*(100-(*i)->GetAmount())/100;
- }
-
- return cooldown;
-}
-
-void Player::RemoveRunesByAuraEffect(AuraEffect const * aura)
-{
- for(uint8 i = 0; i < MAX_RUNES; ++i)
- {
- if (m_runes->runes[i].ConvertAura == aura)
- {
- ConvertRune(i, GetBaseRune(i));
- SetRuneConvertAura(i, NULL);
- }
- }
-}
-
-void Player::RestoreBaseRune(uint8 index)
-{
- AuraEffect const * aura = m_runes->runes[index].ConvertAura;
- ConvertRune(index, GetBaseRune(index));
- SetRuneConvertAura(index, NULL);
- // Don't drop passive talents providing rune convertion
- if (!aura || aura->GetAuraType() != SPELL_AURA_CONVERT_RUNE)
- return;
- for(uint8 i = 0; i < MAX_RUNES; ++i)
- {
- if (aura == m_runes->runes[i].ConvertAura)
- return;
- }
- aura->GetBase()->Remove();
-}
-
-void Player::ConvertRune(uint8 index, RuneType newType)
-{
- SetCurrentRune(index, newType);
-
- WorldPacket data(SMSG_CONVERT_RUNE, 2);
- data << uint8(index);
- data << uint8(newType);
- GetSession()->SendPacket(&data);
-}
-
-void Player::ResyncRunes(uint8 count)
-{
- WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
- for (uint32 i = 0; i < count; ++i)
- {
- data << uint8(GetCurrentRune(i)); // rune type
- data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
- }
- GetSession()->SendPacket(&data);
-}
-
-void Player::AddRunePower(uint8 index)
-{
- WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
- data << uint32(1 << index); // mask (0x00-0x3F probably)
- GetSession()->SendPacket(&data);
-}
-
-static RuneType runeSlotTypes[MAX_RUNES] = {
- /*0*/ RUNE_BLOOD,
- /*1*/ RUNE_BLOOD,
- /*2*/ RUNE_UNHOLY,
- /*3*/ RUNE_UNHOLY,
- /*4*/ RUNE_FROST,
- /*5*/ RUNE_FROST
-};
-
-void Player::InitRunes()
-{
- if(getClass() != CLASS_DEATH_KNIGHT)
- return;
-
- m_runes = new Runes;
-
- m_runes->runeState = 0;
- m_runes->lastUsedRune = RUNE_BLOOD;
-
- for (uint32 i = 0; i < MAX_RUNES; ++i)
- {
- SetBaseRune(i, runeSlotTypes[i]); // init base types
- SetCurrentRune(i, runeSlotTypes[i]); // init current types
- SetRuneCooldown(i, 0); // reset cooldowns
- SetRuneConvertAura(i, NULL);
- m_runes->SetRuneState(i);
- }
-
- for (uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
- SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
-}
-
-bool Player::IsBaseRuneSlotsOnCooldown(RuneType runeType) const
-{
- for (uint32 i = 0; i < MAX_RUNES; ++i)
- if (GetBaseRune(i) == runeType && GetRuneCooldown(i) == 0)
- return false;
-
- return true;
-}
-
-void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
-{
- Loot loot;
- loot.FillLoot (loot_id,store,this,true);
-
- uint32 max_slot = loot.GetMaxSlotInLootFor(this);
- for (uint32 i = 0; i < max_slot; ++i)
- {
- LootItem* lootItem = loot.LootItemInSlot(i,this);
-
- ItemPosCountVec dest;
- uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
- if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
- msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
- if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
- msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
- if(msg != EQUIP_ERR_OK)
- {
- SendEquipError( msg, NULL, NULL );
- continue;
- }
-
- Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
- SendNewItem(pItem, lootItem->count, false, false, broadcast);
- }
-}
-
-uint32 Player::CalculateTalentsPoints() const
-{
- uint32 base_talent = getLevel() < 10 ? 0 : getLevel()-9;
-
- if(getClass() != CLASS_DEATH_KNIGHT || GetMapId() != 609)
- return uint32(base_talent * sWorld.getRate(RATE_TALENT));
-
- uint32 talentPointsForLevel = getLevel() < 56 ? 0 : getLevel() - 55;
- talentPointsForLevel += m_questRewardTalentCount;
-
- if(talentPointsForLevel > base_talent)
- talentPointsForLevel = base_talent;
-
- return uint32(talentPointsForLevel * sWorld.getRate(RATE_TALENT));
-}
-
-bool Player::IsKnowHowFlyIn(uint32 mapid, uint32 zone) const
-{
- // continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update
- uint32 v_map = GetVirtualMapForMapAndZone(mapid, zone);
- return v_map != 571 || HasSpell(54197); // Cold Weather Flying
-}
-
-void Player::learnSpellHighRank(uint32 spellid)
-{
- learnSpell(spellid,false);
-
- if(uint32 next = spellmgr.GetNextSpellInChain(spellid))
- learnSpellHighRank(next);
-}
-
-void Player::_LoadSkills(QueryResult_AutoPtr result)
-{
- // 0 1 2
- // SetPQuery(PLAYER_LOGIN_QUERY_LOADSKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = '%u'", GUID_LOPART(m_guid));
-
- uint32 count = 0;
- if (result)
- {
- do
- {
- Field *fields = result->Fetch();
-
- uint16 skill = fields[0].GetUInt16();
- uint16 value = fields[1].GetUInt16();
- uint16 max = fields[2].GetUInt16();
-
- SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(skill);
- if(!pSkill)
- {
- sLog.outError("Character %u has skill %u that does not exist.", GetGUIDLow(), skill);
- continue;
- }
-
- // set fixed skill ranges
- switch(GetSkillRangeType(pSkill,false))
- {
- case SKILL_RANGE_LANGUAGE: // 300..300
- value = max = 300;
- break;
- case SKILL_RANGE_MONO: // 1..1, grey monolite bar
- value = max = 1;
- break;
- default:
- break;
- }
- if(value == 0)
- {
- sLog.outError("Character %u has skill %u with value 0. Will be deleted.", GetGUIDLow(), skill);
- CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), skill );
- continue;
- }
-
- // enable unlearn button for primary professions only
- if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
- SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,1));
- else
- SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,0));
-
- SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),MAKE_SKILL_VALUE(value, max));
- SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
-
- mSkillStatus.insert(SkillStatusMap::value_type(skill, SkillStatusData(count, SKILL_UNCHANGED)));
-
- learnSkillRewardedSpells(skill, value);
-
- ++count;
-
- if(count >= PLAYER_MAX_SKILLS) // client limit
- {
- sLog.outError("Character %u has more than %u skills.", PLAYER_MAX_SKILLS);
- break;
- }
- } while (result->NextRow());
- }
-
- for (; count < PLAYER_MAX_SKILLS; ++count)
- {
- SetUInt32Value(PLAYER_SKILL_INDEX(count), 0);
- SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),0);
- SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
- }
-
- // special settings
- if (getClass() == CLASS_DEATH_KNIGHT)
- {
- uint8 base_level = std::min(getLevel(),uint8(sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL)));
- if (base_level < 1)
- base_level = 1;
- uint16 base_skill = (base_level-1)*5; // 270 at starting level 55
- if (base_skill < 1)
- base_skill = 1; // skill mast be known and then > 0 in any case
-
- if (GetPureSkillValue(SKILL_FIRST_AID) < base_skill)
- SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
- if (GetPureSkillValue(SKILL_AXES) < base_skill)
- SetSkill(SKILL_AXES, base_skill,base_skill);
- if (GetPureSkillValue(SKILL_DEFENSE) < base_skill)
- SetSkill(SKILL_DEFENSE, base_skill,base_skill);
- if (GetPureSkillValue(SKILL_POLEARMS) < base_skill)
- SetSkill(SKILL_POLEARMS, base_skill,base_skill);
- if (GetPureSkillValue(SKILL_SWORDS) < base_skill)
- SetSkill(SKILL_SWORDS, base_skill,base_skill);
- if (GetPureSkillValue(SKILL_2H_AXES) < base_skill)
- SetSkill(SKILL_2H_AXES, base_skill,base_skill);
- if (GetPureSkillValue(SKILL_2H_SWORDS) < base_skill)
- SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
- if (GetPureSkillValue(SKILL_UNARMED) < base_skill)
- SetSkill(SKILL_UNARMED, base_skill,base_skill);
- }
-}
-
-uint32 Player::GetPhaseMaskForSpawn() const
-{
- uint32 phase = PHASEMASK_NORMAL;
- if (!isGameMaster())
- phase = GetPhaseMask();
- else
- {
- AuraEffectList const& phases = GetAuraEffectsByType(SPELL_AURA_PHASE);
- if (!phases.empty())
- phase = phases.front()->GetMiscValue();
- }
-
- // some aura phases include 1 normal map in addition to phase itself
- if (uint32 n_phase = phase & ~PHASEMASK_NORMAL)
- return n_phase;
-
- return PHASEMASK_NORMAL;
-}
-
-uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
-{
- ItemPrototype const* pProto = pItem->GetProto();
-
- // proto based limitations
- if (uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
- return res;
-
- // check unique-equipped on gems
- for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
- {
- uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
- if (!enchant_id)
- continue;
- SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
- if (!enchantEntry)
- continue;
-
- ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
- if (!pGem)
- continue;
-
- // include for check equip another gems with same limit category for not equipped item (and then not counted)
- uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
- ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
-
- if (uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
- return res;
- }
-
- return EQUIP_ERR_OK;
-}
-
-uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
-{
- // check unique-equipped on item
- if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
- {
- // there is an equip limit on this item
- if (HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
- return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
- }
-
- // check unique-equipped limit
- if (itemProto->ItemLimitCategory)
- {
- ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
- if (!limitEntry)
- return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
-
- if (limit_count > limitEntry->maxCount)
- return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
-
- // there is an equip limit on this item
- if (HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
- return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
- }
-
- return EQUIP_ERR_OK;
-}
-
-void Player::HandleFall(MovementInfo const& movementInfo)
-{
- // calculate total z distance of the fall
- float z_diff = m_lastFallZ - movementInfo.z;
- //sLog.outDebug("zDiff = %f", z_diff);
-
- //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
- // 14.57 can be calculated by resolving damageperc formula below to 0
- if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
- !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
- !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
- {
- //Safe fall, fall height reduction
- int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
-
- float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
-
- if (damageperc > 0)
- {
- uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
-
- float height = movementInfo.z;
- UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
-
- if (damage > 0)
- {
- //Prevent fall damage from being more than the player maximum health
- if (damage > GetMaxHealth())
- damage = GetMaxHealth();
-
- // Gust of Wind
- if (HasAura(43621))
- damage = GetMaxHealth()/2;
-
- uint32 original_health = GetHealth();
- uint32 final_damage = EnvironmentalDamage(DAMAGE_FALL, damage);
-
- // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
- if (isAlive() && final_damage < original_health)
- GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
- }
-
- //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
- 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);
- }
- }
- RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_LANDING); // No fly zone - Parachute
-}
-
-void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
-{
- GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1, miscvalue2, unit, time);
-}
-
-void Player::CompletedAchievement(AchievementEntry const* entry)
-{
- GetAchievementMgr().CompletedAchievement(entry);
-}
-
-void Player::LearnTalent(uint32 talentId, uint32 talentRank)
-{
- uint32 CurTalentPoints = GetFreeTalentPoints();
-
- if(CurTalentPoints == 0)
- return;
-
- if (talentRank >= MAX_TALENT_RANK)
- return;
-
- TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
-
- if(!talentInfo)
- return;
-
- TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
-
- if(!talentTabInfo)
- return;
-
- // prevent learn talent for different class (cheating)
- if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
- return;
-
- // find current max talent rank (0~5)
- uint8 curtalent_maxrank = 0; // 0 = not learned any rank
- for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
- {
- if(talentInfo->RankID[rank] && HasSpell(talentInfo->RankID[rank]))
- {
- curtalent_maxrank = (rank + 1);
- break;
- }
- }
-
- // we already have same or higher talent rank learned
- if(curtalent_maxrank >= (talentRank + 1))
- return;
-
- // check if we have enough talent points
- if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
- return;
-
- // Check if it requires another talent
- if (talentInfo->DependsOn > 0)
- {
- if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
- {
- bool hasEnoughRank = false;
- for (uint8 rank = talentInfo->DependsOnRank; rank < MAX_TALENT_RANK; rank++)
- {
- if (depTalentInfo->RankID[rank] != 0)
- if (HasSpell(depTalentInfo->RankID[rank]))
- hasEnoughRank = true;
- }
- if (!hasEnoughRank)
- return;
- }
- }
-
- // Find out how many points we have in this field
- uint32 spentPoints = 0;
-
- uint32 tTab = talentInfo->TalentTab;
- if (talentInfo->Row > 0)
- {
- uint32 numRows = sTalentStore.GetNumRows();
- for (uint32 i = 0; i < numRows; i++) // Loop through all talents.
- {
- // Someday, someone needs to revamp
- const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
- if (tmpTalent) // the way talents are tracked
- {
- if (tmpTalent->TalentTab == tTab)
- {
- for (uint8 rank = 0; rank < MAX_TALENT_RANK; rank++)
- {
- if (tmpTalent->RankID[rank] != 0)
- {
- if (HasSpell(tmpTalent->RankID[rank]))
- {
- spentPoints += (rank + 1);
- }
- }
- }
- }
- }
- }
- }
-
- // not have required min points spent in talent tree
- if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
- return;
-
- // spell not set in talent.dbc
- uint32 spellid = talentInfo->RankID[talentRank];
- if( spellid == 0 )
- {
- sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
- return;
- }
-
- // already known
- if(HasSpell(spellid))
- return;
-
- // learn! (other talent ranks will unlearned at learning)
- learnSpell(spellid, false);
- AddTalent(spellid, m_activeSpec, true);
-
- sLog.outDetail("TalentID: %u Rank: %u Spell: %u Spec: %u\n", talentId, talentRank, spellid, m_activeSpec);
-
- // update free talent points
- SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
-}
-
-void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
-{
- Pet *pet = GetPet();
-
- if(!pet)
- return;
-
- if(petGuid != pet->GetGUID())
- return;
-
- uint32 CurTalentPoints = pet->GetFreeTalentPoints();
-
- if(CurTalentPoints == 0)
- return;
-
- if (talentRank >= MAX_PET_TALENT_RANK)
- return;
-
- TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
-
- if(!talentInfo)
- return;
-
- TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
-
- if(!talentTabInfo)
- return;
-
- CreatureInfo const *ci = pet->GetCreatureInfo();
-
- if(!ci)
- return;
-
- CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
-
- if(!pet_family)
- return;
-
- if(pet_family->petTalentType < 0) // not hunter pet
- return;
-
- // prevent learn talent for different family (cheating)
- if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
- return;
-
- // find current max talent rank (0~5)
- uint8 curtalent_maxrank = 0; // 0 = not learned any rank
- for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
- {
- if(talentInfo->RankID[rank] && pet->HasSpell(talentInfo->RankID[rank]))
- {
- curtalent_maxrank = (rank + 1);
- break;
- }
- }
-
- // we already have same or higher talent rank learned
- if(curtalent_maxrank >= (talentRank + 1))
- return;
-
- // check if we have enough talent points
- if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
- return;
-
- // Check if it requires another talent
- if (talentInfo->DependsOn > 0)
- {
- if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
- {
- bool hasEnoughRank = false;
- for (uint8 rank = talentInfo->DependsOnRank; rank < MAX_TALENT_RANK; rank++)
- {
- if (depTalentInfo->RankID[rank] != 0)
- if (pet->HasSpell(depTalentInfo->RankID[rank]))
- hasEnoughRank = true;
- }
- if (!hasEnoughRank)
- return;
- }
- }
-
- // Find out how many points we have in this field
- uint32 spentPoints = 0;
-
- uint32 tTab = talentInfo->TalentTab;
- if (talentInfo->Row > 0)
- {
- uint32 numRows = sTalentStore.GetNumRows();
- for (uint32 i = 0; i < numRows; ++i) // Loop through all talents.
- {
- // Someday, someone needs to revamp
- const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
- if (tmpTalent) // the way talents are tracked
- {
- if (tmpTalent->TalentTab == tTab)
- {
- for (uint8 rank = 0; rank < MAX_TALENT_RANK; rank++)
- {
- if (tmpTalent->RankID[rank] != 0)
- {
- if (pet->HasSpell(tmpTalent->RankID[rank]))
- {
- spentPoints += (rank + 1);
- }
- }
- }
- }
- }
- }
- }
-
- // not have required min points spent in talent tree
- if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
- return;
-
- // spell not set in talent.dbc
- uint32 spellid = talentInfo->RankID[talentRank];
- if( spellid == 0 )
- {
- sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
- return;
- }
-
- // already known
- if(pet->HasSpell(spellid))
- return;
-
- // learn! (other talent ranks will unlearned at learning)
- pet->learnSpell(spellid);
- sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
-
- // update free talent points
- pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
-}
-
-void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
-{
- if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
- {
- if(apply)
- SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(1LL << (ctEntry->BitIndex-1)));
- else
- RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(1LL << (ctEntry->BitIndex-1)));
- }
-}
-
-void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
-{
- if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <=minfo.z || opcode == MSG_MOVE_FALL_LAND)
- SetFallInformation(minfo.fallTime, minfo.z);
-}
-
-void Player::UnsummonPetTemporaryIfAny()
-{
- Pet* pet = GetPet();
- if(!pet)
- return;
-
- if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
- {
- m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
- m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
- }
-
- RemovePet(pet, PET_SAVE_AS_CURRENT);
-}
-
-void Player::ResummonPetTemporaryUnSummonedIfAny()
-{
- if(!m_temporaryUnsummonedPetNumber)
- return;
-
- // not resummon in not appropriate state
- if(IsPetNeedBeTemporaryUnsummoned())
- return;
-
- if(GetPetGUID())
- return;
-
- Pet* NewPet = new Pet(this);
- if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
- delete NewPet;
-
- m_temporaryUnsummonedPetNumber = 0;
-}
-
-bool Player::canSeeSpellClickOn(Creature const *c) const
-{
- if(!c->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
- return false;
-
- SpellClickInfoMapBounds clickPair = objmgr.GetSpellClickInfoMapBounds(c->GetEntry());
- if(clickPair.first == clickPair.second)
- return true;
-
- for (SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
- if(itr->second.IsFitToRequirements(this, c))
- return true;
-
- return false;
-}
-
-void Player::BuildPlayerTalentsInfoData(WorldPacket *data)
-{
- *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
- *data << uint8(m_specsCount); // talent group count (0, 1 or 2)
- *data << uint8(m_activeSpec); // talent group index (0 or 1)
-
- if(m_specsCount)
- {
- // loop through all specs (only 1 for now)
- for (uint32 specIdx = 0; specIdx < m_specsCount; ++specIdx)
- {
- uint8 talentIdCount = 0;
- size_t pos = data->wpos();
- *data << uint8(talentIdCount); // [PH], talentIdCount
-
- // find class talent tabs (all players have 3 talent tabs)
- uint32 const* talentTabIds = GetTalentTabPages(getClass());
-
- for (uint8 i = 0; i < 3; ++i)
- {
- uint32 talentTabId = talentTabIds[i];
-
- for (uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
- {
- TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
- if(!talentInfo)
- continue;
-
- // skip another tab talents
- if(talentInfo->TalentTab != talentTabId)
- continue;
-
- // find max talent rank (0~4)
- int8 curtalent_maxrank = -1;
- for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
- {
- if(talentInfo->RankID[rank] && HasTalent(talentInfo->RankID[rank], specIdx))
- {
- curtalent_maxrank = rank;
- break;
- }
- }
-
- // not learned talent
- if(curtalent_maxrank < 0)
- continue;
-
- *data << uint32(talentInfo->TalentID); // Talent.dbc
- *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
-
- ++talentIdCount;
- }
- }
-
- data->put<uint8>(pos, talentIdCount); // put real count
-
- *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
-
- for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
- *data << uint16(m_Glyphs[specIdx][i]); // GlyphProperties.dbc
- }
- }
-}
-
-void Player::BuildPetTalentsInfoData(WorldPacket *data)
-{
- uint32 unspentTalentPoints = 0;
- size_t pointsPos = data->wpos();
- *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
-
- uint8 talentIdCount = 0;
- size_t countPos = data->wpos();
- *data << uint8(talentIdCount); // [PH], talentIdCount
-
- Pet *pet = GetPet();
- if(!pet)
- return;
-
- unspentTalentPoints = pet->GetFreeTalentPoints();
-
- data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
-
- CreatureInfo const *ci = pet->GetCreatureInfo();
- if(!ci)
- return;
-
- CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
- if(!pet_family || pet_family->petTalentType < 0)
- return;
-
- for (uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
- {
- TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
- if(!talentTabInfo)
- continue;
-
- if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
- continue;
-
- for (uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
- {
- TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
- if(!talentInfo)
- continue;
-
- // skip another tab talents
- if(talentInfo->TalentTab != talentTabId)
- continue;
-
- // find max talent rank (0~4)
- int8 curtalent_maxrank = -1;
- for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
- {
- if(talentInfo->RankID[rank] && pet->HasSpell(talentInfo->RankID[rank]))
- {
- curtalent_maxrank = rank;
- break;
- }
- }
-
- // not learned talent
- if(curtalent_maxrank < 0)
- continue;
-
- *data << uint32(talentInfo->TalentID); // Talent.dbc
- *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
-
- ++talentIdCount;
- }
-
- data->put<uint8>(countPos, talentIdCount); // put real count
-
- break;
- }
-}
-
-void Player::SendTalentsInfoData(bool pet)
-{
- WorldPacket data(SMSG_TALENTS_INFO, 50);
- data << uint8(pet ? 1 : 0);
- if(pet)
- BuildPetTalentsInfoData(&data);
- else
- BuildPlayerTalentsInfoData(&data);
- GetSession()->SendPacket(&data);
-}
-
-void Player::BuildEnchantmentsInfoData(WorldPacket *data)
-{
- uint32 slotUsedMask = 0;
- size_t slotUsedMaskPos = data->wpos();
- *data << uint32(slotUsedMask); // slotUsedMask < 0x80000
-
- for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
- {
- Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
-
- if(!item)
- continue;
-
- slotUsedMask |= (1 << i);
-
- *data << uint32(item->GetEntry()); // item entry
-
- uint16 enchantmentMask = 0;
- size_t enchantmentMaskPos = data->wpos();
- *data << uint16(enchantmentMask); // enchantmentMask < 0x1000
-
- for (uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
- {
- uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
-
- if(!enchId)
- continue;
-
- enchantmentMask |= (1 << j);
-
- *data << uint16(enchId); // enchantmentId?
- }
-
- data->put<uint16>(enchantmentMaskPos, enchantmentMask);
-
- *data << uint16(0); // unknown
- data->appendPackGUID(item->GetUInt64Value(ITEM_FIELD_CREATOR)); // item creator
- *data << uint32(0); // seed?
- }
-
- data->put<uint32>(slotUsedMaskPos, slotUsedMask);
-}
-
-void Player::SendEquipmentSetList()
-{
- uint32 count = 0;
- WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4);
- size_t count_pos = data.wpos();
- data << uint32(count); // count placeholder
- for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
- {
- if(itr->second.state==EQUIPMENT_SET_DELETED)
- continue;
- data.appendPackGUID(itr->second.Guid);
- data << uint32(itr->first);
- data << itr->second.Name;
- data << itr->second.IconName;
- for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
- data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM));
-
- ++count; // client have limit but it checked at loading and set
- }
- data.put<uint32>(count_pos, count);
- GetSession()->SendPacket(&data);
-}
-
-void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
-{
- if(eqset.Guid != 0)
- {
- bool found = false;
-
- for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
- {
- if((itr->second.Guid == eqset.Guid) && (itr->first == index))
- {
- found = true;
- break;
- }
- }
-
- if(!found) // something wrong...
- {
- sLog.outError("Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
- return;
- }
- }
-
- EquipmentSet& eqslot = m_EquipmentSets[index];
-
- EquipmentSetUpdateState old_state = eqslot.state;
-
- eqslot = eqset;
-
- if(eqset.Guid == 0)
- {
- eqslot.Guid = objmgr.GenerateEquipmentSetGuid();
-
- WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1);
- data << uint32(index);
- data.appendPackGUID(eqslot.Guid);
- GetSession()->SendPacket(&data);
- }
-
- eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
-}
-
-void Player::_SaveEquipmentSets()
-{
- for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
- {
- uint32 index = itr->first;
- EquipmentSet& eqset = itr->second;
- switch(eqset.state)
- {
- case EQUIPMENT_SET_UNCHANGED:
- ++itr;
- break; // nothing do
- case EQUIPMENT_SET_CHANGED:
- 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'",
- 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],
- 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);
- eqset.state = EQUIPMENT_SET_UNCHANGED;
- ++itr;
- break;
- case EQUIPMENT_SET_NEW:
- 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')",
- 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],
- 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]);
- eqset.state = EQUIPMENT_SET_UNCHANGED;
- ++itr;
- break;
- case EQUIPMENT_SET_DELETED:
- CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE setguid="UI64FMTD, eqset.Guid);
- m_EquipmentSets.erase(itr++);
- break;
- }
- }
-}
-
-void Player::_SaveBGData()
-{
- CharacterDatabase.PExecute("DELETE FROM character_battleground_data WHERE guid='%u'", GetGUIDLow());
- if (m_bgData.bgInstanceID)
- {
- /* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
- CharacterDatabase.PExecute("INSERT INTO character_battleground_data VALUES ('%u', '%u', '%u', '%f', '%f', '%f', '%f', '%u', '%u', '%u', '%u')",
- GetGUIDLow(), m_bgData.bgInstanceID, m_bgData.bgTeam, m_bgData.joinPos.GetPositionX(), m_bgData.joinPos.GetPositionY(), m_bgData.joinPos.GetPositionZ(),
- m_bgData.joinPos.GetOrientation(), m_bgData.joinPos.GetMapId(), m_bgData.taxiPath[0], m_bgData.taxiPath[1], m_bgData.mountSpell);
- }
-}
-
-void Player::DeleteEquipmentSet(uint64 setGuid)
-{
- for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
- {
- if(itr->second.Guid == setGuid)
- {
- if(itr->second.state == EQUIPMENT_SET_NEW)
- m_EquipmentSets.erase(itr);
- else
- itr->second.state = EQUIPMENT_SET_DELETED;
- break;
- }
- }
-}
-
-void Player::RemoveAtLoginFlag( AtLoginFlags f, bool in_db_also /*= false*/ )
-{
- m_atLoginFlags &= ~f;
-
- if(in_db_also)
- CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f), GetGUIDLow());
-}
-
-void Player::SendClearCooldown( uint32 spell_id, Unit* target )
-{
- WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
- data << uint32(spell_id);
- data << uint64(target->GetGUID());
- SendDirectMessage(&data);
-}
-
-void Player::ResetMap()
-{
- // this may be called during Map::Update
- // after decrement+unlink, ++m_mapRefIter will continue correctly
- // when the first element of the list is being removed
- // nocheck_prev will return the padding element of the RefManager
- // instead of NULL in the case of prev
- GetMap()->UpdateIteratorBack(this);
- Unit::ResetMap();
- GetMapRef().unlink();
-}
-
-void Player::SetMap(Map * map)
-{
- Unit::SetMap(map);
- m_mapRef.link(map, this);
-}
-
-void Player::_LoadGlyphs(QueryResult_AutoPtr result)
-{
- // SetPQuery(PLAYER_LOGIN_QUERY_LOADGLYPHS, "SELECT spec, glyph1, glyph2, glyph3, glyph4, glyph5, glyph6 from character_glyphs WHERE guid = '%u'", GUID_LOPART(m_guid));
- if (!result)
- return;
-
- do
- {
- Field *fields = result->Fetch();
-
- uint8 spec = fields[0].GetUInt8();
- if (spec >= m_specsCount)
- continue;
-
- m_Glyphs[spec][0] = fields[1].GetUInt32();
- m_Glyphs[spec][1] = fields[2].GetUInt32();
- m_Glyphs[spec][2] = fields[3].GetUInt32();
- m_Glyphs[spec][3] = fields[4].GetUInt32();
- m_Glyphs[spec][4] = fields[5].GetUInt32();
- m_Glyphs[spec][5] = fields[6].GetUInt32();
-
- } while (result->NextRow());
-}
-
-void Player::_SaveGlyphs()
-{
- CharacterDatabase.PExecute("DELETE FROM character_glyphs WHERE guid='%u'",GetGUIDLow());
- for (uint8 spec = 0; spec < m_specsCount; ++spec)
- {
- CharacterDatabase.PExecute("INSERT INTO character_glyphs VALUES('%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
- GetGUIDLow(), spec, m_Glyphs[spec][0], m_Glyphs[spec][1], m_Glyphs[spec][2], m_Glyphs[spec][3], m_Glyphs[spec][4], m_Glyphs[spec][5]);
- }
-}
-
-void Player::_LoadTalents(QueryResult_AutoPtr result)
-{
- // SetPQuery(PLAYER_LOGIN_QUERY_LOADTALENTS, "SELECT spell, spec FROM character_talent WHERE guid = '%u'", GUID_LOPART(m_guid));
- if (result)
- {
- do
- {
- Field *fields = result->Fetch();
-
- AddTalent(fields[0].GetUInt32(), fields[1].GetUInt32(), false);
- }
- while( result->NextRow() );
- }
-}
-
-void Player::_SaveTalents()
-{
- for (uint8 i = 0; i < MAX_TALENT_SPECS; ++i)
- {
- for (PlayerTalentMap::iterator itr = m_talents[i]->begin(); itr != m_talents[i]->end();)
- {
- if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
- CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u' and spell = '%u' and spec = '%u'", GetGUIDLow(), itr->first, itr->second->spec);
-
- if (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED)
- CharacterDatabase.PExecute("INSERT INTO character_talent (guid,spell,spec) VALUES ('%u', '%u', '%u')", GetGUIDLow(), itr->first, itr->second->spec);
-
- if (itr->second->state == PLAYERSPELL_REMOVED)
- {
- delete itr->second;
- m_talents[i]->erase(itr++);
- }
- else
- {
- itr->second->state = PLAYERSPELL_UNCHANGED;
- ++itr;
- }
- }
- }
-}
-
-void Player::UpdateSpecCount(uint8 count)
-{
- if (GetSpecsCount() == count)
- return;
-
- if (count == MIN_TALENT_SPECS)
- {
- _SaveActions(); // make sure the button list is cleaned up
- // active spec becomes only spec?
- CharacterDatabase.PExecute("DELETE FROM character_action WHERE spec<>'%u' AND guid='%u'",m_activeSpec, GetGUIDLow());
- m_activeSpec = 0;
- }
- else if (count == MAX_TALENT_SPECS)
- {
- _SaveActions(); // make sure the button list is cleaned up
- for (ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); ++itr)
- CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,spec) VALUES ('%u', '%u', '%u', '%u', '%u')",
- GetGUIDLow(), uint32(itr->first), uint32(itr->second.GetAction()), uint32(itr->second.GetType()), 1);
- }
- else
- return;
-
- SetSpecsCount(count);
-
- SendTalentsInfoData(false);
-}
-
-void Player::ActivateSpec(uint8 spec)
-{
- if (GetActiveSpec() == spec)
- return;
-
- if (GetSpecsCount() != MAX_TALENT_SPECS)
- return;
-
- if (GetMap()->IsBattleGround() && !HasAura(44521)) // In BattleGround with no Preparation buff
- return;
-
- _SaveActions();
-
- if (IsNonMeleeSpellCasted(false))
- InterruptNonMeleeSpells(false);
-
- // "Hunter pets should have their talents refunded when a hunter switches talent specs, even if they are dismissed at the time."
- if (getClass() == CLASS_HUNTER)
- Pet::resetTalentsForAllPetsOf(this, GetPet());
-
- UnsummonPetTemporaryIfAny();
- ClearComboPointHolders();
- ClearAllReactives();
- UnsummonAllTotems();
- RemoveAllControlled();
- /*RemoveAllAurasOnDeath();
- if (GetPet())
- GetPet()->RemoveAllAurasOnDeath();*/
-
- //RemoveAllAuras(this->GetGUID(), NULL, false, true); // removes too many auras
- //ExitVehicle(); // should be impossible to switch specs from inside a vehicle..
-
- for (uint32 i = 0; i < sTalentStore.GetNumRows(); ++i)
- {
- TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
-
- if (!talentInfo)
- continue;
-
- TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
-
- if (!talentTabInfo)
- continue;
-
- // unlearn only talents for character class
- // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
- // to prevent unexpected lost normal learned spell skip another class talents
- if ((getClassMask() & talentTabInfo->ClassMask) == 0)
- continue;
-
- for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
- {
- // skip non-existant talent ranks
- if (talentInfo->RankID[rank] == 0)
- continue;
- removeSpell(talentInfo->RankID[rank], true); // removes the talent, and all dependant, learned, and chained spells..
- if (const SpellEntry *_spellEntry = sSpellStore.LookupEntry(talentInfo->RankID[rank]))
- for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) // search through the SpellEntry for valid trigger spells
- if (_spellEntry->EffectTriggerSpell[i] > 0 && _spellEntry->Effect[i] == SPELL_EFFECT_LEARN_SPELL)
- removeSpell(_spellEntry->EffectTriggerSpell[i], true); // and remove any spells that the talent teaches
- // if this talent rank can be found in the PlayerTalentMap, mark the talent as removed so it gets deleted
- //PlayerTalentMap::iterator plrTalent = m_talents[m_activeSpec]->find(talentInfo->RankID[rank]);
- //if (plrTalent != m_talents[m_activeSpec]->end())
- // plrTalent->second->state = PLAYERSPELL_REMOVED;
- }
- }
-
- // set glyphs
- for (uint8 slot = 0; slot < MAX_GLYPH_SLOT_INDEX; ++slot)
- // remove secondary glyph
- if (uint32 oldglyph = m_Glyphs[m_activeSpec][slot])
- if (GlyphPropertiesEntry const *old_gp = sGlyphPropertiesStore.LookupEntry(oldglyph))
- RemoveAurasDueToSpell(old_gp->SpellId);
-
- SetActiveSpec(spec);
- uint32 spentTalents = 0;
-
- for (uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
- {
- TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
-
- if (!talentInfo)
- continue;
-
- TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
-
- if (!talentTabInfo)
- continue;
-
- // learn only talents for character class
- if ((getClassMask() & talentTabInfo->ClassMask) == 0)
- continue;
-
- // learn highest talent rank that exists in newly activated spec
- for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
- {
- // skip non-existant talent ranks
- if (talentInfo->RankID[rank] == 0)
- continue;
- // if the talent can be found in the newly activated PlayerTalentMap
- if (HasTalent(talentInfo->RankID[rank], m_activeSpec))
- {
- learnSpell(talentInfo->RankID[rank], false); // add the talent to the PlayerSpellMap
- spentTalents += (rank + 1); // increment the spentTalents count
- }
- }
- }
-
- // set glyphs
- for (uint8 slot = 0; slot < MAX_GLYPH_SLOT_INDEX; ++slot)
- {
- uint32 glyph = m_Glyphs[m_activeSpec][slot];
-
- // apply primary glyph
- if (glyph)
- if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
- CastSpell(this, gp->SpellId, true);
-
- SetGlyph(slot, glyph);
- }
-
- m_usedTalentCount = spentTalents;
- InitTalentForLevel();
-
- // Let client clear his current Actions
- SendActionButtons(2);
- m_actionButtons.clear();
- if (QueryResult_AutoPtr result = CharacterDatabase.PQuery("SELECT button,action,type FROM character_action WHERE guid = '%u' AND spec = '%u' ORDER BY button", GetGUIDLow(), m_activeSpec))
- _LoadActions(result, false);
-
- ResummonPetTemporaryUnSummonedIfAny();
- SendActionButtons(1);
-
- Powers pw = getPowerType();
- if (pw != POWER_MANA)
- SetPower(POWER_MANA, 0); // Mana must be 0 even if it isn't the active power type.
-
- SetPower(pw, 0);
-}
-
-void Player::ResetTimeSync()
-{
- m_timeSyncCount = 0;
- m_timeSyncTimer = 0;
-}
-
-void Player::SendTimeSync()
-{
- WorldPacket data(SMSG_TIME_SYNC_REQ, 4);
- data << uint32(m_timeSyncCount++);
- GetSession()->SendPacket(&data);
-
- // Send another opcode in 10s again
- m_timeSyncTimer = 10000;
-}
-
-void Player::SetReputation(uint32 factionentry, uint32 value)
-{
- GetReputationMgr().SetReputation(sFactionStore.LookupEntry(factionentry),value);
-}
-uint32 Player::GetReputation(uint32 factionentry)
-{
- return GetReputationMgr().GetReputation(sFactionStore.LookupEntry(factionentry));
-}
-std::string Player::GetGuildName()
-{
- return objmgr.GetGuildById(GetGuildId())->GetName();
-}
-
-void Player::SendDuelCountdown(uint32 counter)
-{
- WorldPacket data(SMSG_DUEL_COUNTDOWN, 4);
- data << uint32(counter); // seconds
- GetSession()->SendPacket(&data);
-}
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "Common.h"
+#include "Language.h"
+#include "Database/DatabaseEnv.h"
+#include "Log.h"
+#include "Opcodes.h"
+#include "SpellMgr.h"
+#include "World.h"
+#include "WorldPacket.h"
+#include "WorldSession.h"
+#include "UpdateMask.h"
+#include "Player.h"
+#include "Vehicle.h"
+#include "SkillDiscovery.h"
+#include "QuestDef.h"
+#include "GossipDef.h"
+#include "UpdateData.h"
+#include "Channel.h"
+#include "ChannelMgr.h"
+#include "MapManager.h"
+#include "MapInstanced.h"
+#include "InstanceSaveMgr.h"
+#include "GridNotifiers.h"
+#include "GridNotifiersImpl.h"
+#include "CellImpl.h"
+#include "ObjectMgr.h"
+#include "ObjectAccessor.h"
+#include "CreatureAI.h"
+#include "Formulas.h"
+#include "Group.h"
+#include "Guild.h"
+#include "Pet.h"
+#include "Util.h"
+#include "Transports.h"
+#include "Weather.h"
+#include "BattleGround.h"
+#include "BattleGroundAV.h"
+#include "BattleGroundMgr.h"
+#include "OutdoorPvP.h"
+#include "OutdoorPvPMgr.h"
+#include "ArenaTeam.h"
+#include "Chat.h"
+#include "Database/DatabaseImpl.h"
+#include "Spell.h"
+#include "SocialMgr.h"
+#include "GameEventMgr.h"
+#include "AchievementMgr.h"
+#include "SpellAuras.h"
+#include "SpellAuraEffects.h"
+
+#include <cmath>
+
+#define ZONE_UPDATE_INTERVAL (1*IN_MILISECONDS)
+
+#define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
+#define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
+#define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
+
+#define SKILL_VALUE(x) PAIR32_LOPART(x)
+#define SKILL_MAX(x) PAIR32_HIPART(x)
+#define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
+
+#define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
+#define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
+#define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
+
+enum CharacterFlags
+{
+ CHARACTER_FLAG_NONE = 0x00000000,
+ CHARACTER_FLAG_UNK1 = 0x00000001,
+ CHARACTER_FLAG_UNK2 = 0x00000002,
+ CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
+ CHARACTER_FLAG_UNK4 = 0x00000008,
+ CHARACTER_FLAG_UNK5 = 0x00000010,
+ CHARACTER_FLAG_UNK6 = 0x00000020,
+ CHARACTER_FLAG_UNK7 = 0x00000040,
+ CHARACTER_FLAG_UNK8 = 0x00000080,
+ CHARACTER_FLAG_UNK9 = 0x00000100,
+ CHARACTER_FLAG_UNK10 = 0x00000200,
+ CHARACTER_FLAG_HIDE_HELM = 0x00000400,
+ CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
+ CHARACTER_FLAG_UNK13 = 0x00001000,
+ CHARACTER_FLAG_GHOST = 0x00002000,
+ CHARACTER_FLAG_RENAME = 0x00004000,
+ CHARACTER_FLAG_UNK16 = 0x00008000,
+ CHARACTER_FLAG_UNK17 = 0x00010000,
+ CHARACTER_FLAG_UNK18 = 0x00020000,
+ CHARACTER_FLAG_UNK19 = 0x00040000,
+ CHARACTER_FLAG_UNK20 = 0x00080000,
+ CHARACTER_FLAG_UNK21 = 0x00100000,
+ CHARACTER_FLAG_UNK22 = 0x00200000,
+ CHARACTER_FLAG_UNK23 = 0x00400000,
+ CHARACTER_FLAG_UNK24 = 0x00800000,
+ CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
+ CHARACTER_FLAG_DECLINED = 0x02000000,
+ CHARACTER_FLAG_UNK27 = 0x04000000,
+ CHARACTER_FLAG_UNK28 = 0x08000000,
+ CHARACTER_FLAG_UNK29 = 0x10000000,
+ CHARACTER_FLAG_UNK30 = 0x20000000,
+ CHARACTER_FLAG_UNK31 = 0x40000000,
+ CHARACTER_FLAG_UNK32 = 0x80000000
+};
+
+enum CharacterCustomizeFlags
+{
+ CHAR_CUSTOMIZE_FLAG_NONE = 0x00000000,
+ CHAR_CUSTOMIZE_FLAG_CUSTOMIZE = 0x00000001, // name, gender, etc...
+ CHAR_CUSTOMIZE_FLAG_FACTION = 0x00010000, // name, gender, faction, etc...
+ CHAR_CUSTOMIZE_FLAG_RACE = 0x00100000 // name, gender, race, etc...
+};
+
+// corpse reclaim times
+#define DEATH_EXPIRE_STEP (5*MINUTE)
+#define MAX_DEATH_COUNT 3
+
+static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
+
+//== PlayerTaxi ================================================
+
+PlayerTaxi::PlayerTaxi()
+{
+ // Taxi nodes
+ memset(m_taximask, 0, sizeof(m_taximask));
+}
+
+void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint8 level)
+{
+ // class specific initial known nodes
+ switch(chrClass)
+ {
+ case CLASS_DEATH_KNIGHT:
+ {
+ for (uint8 i = 0; i < TaxiMaskSize; ++i)
+ m_taximask[i] |= sOldContinentsNodesMask[i];
+ break;
+ }
+ }
+
+ // race specific initial known nodes: capital and taxi hub masks
+ switch(race)
+ {
+ case RACE_HUMAN: SetTaximaskNode(2); break; // Human
+ case RACE_ORC: SetTaximaskNode(23); break; // Orc
+ case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
+ case RACE_NIGHTELF: SetTaximaskNode(26);
+ SetTaximaskNode(27); break; // Night Elf
+ case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
+ case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
+ case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
+ case RACE_TROLL: SetTaximaskNode(23); break; // Troll
+ case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
+ case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
+ }
+
+ // new continent starting masks (It will be accessible only at new map)
+ switch(Player::TeamForRace(race))
+ {
+ case ALLIANCE: SetTaximaskNode(100); break;
+ case HORDE: SetTaximaskNode(99); break;
+ }
+ // level dependent taxi hubs
+ if(level>=68)
+ SetTaximaskNode(213); //Shattered Sun Staging Area
+}
+
+void PlayerTaxi::LoadTaxiMask(const char* data)
+{
+ Tokens tokens = StrSplit(data, " ");
+
+ uint8 index;
+ Tokens::iterator iter;
+ for (iter = tokens.begin(), index = 0;
+ (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
+ {
+ // load and set bits only for existed taxi nodes
+ m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
+ }
+}
+
+void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
+{
+ if(all)
+ {
+ for (uint8 i=0; i<TaxiMaskSize; i++)
+ data << uint32(sTaxiNodesMask[i]); // all existed nodes
+ }
+ else
+ {
+ for (uint8 i=0; i<TaxiMaskSize; i++)
+ data << uint32(m_taximask[i]); // known nodes
+ }
+}
+
+bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team )
+{
+ ClearTaxiDestinations();
+
+ Tokens tokens = StrSplit(values," ");
+
+ for (Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
+ {
+ uint32 node = uint32(atol(iter->c_str()));
+ AddTaxiDestination(node);
+ }
+
+ if(m_TaxiDestinations.empty())
+ return true;
+
+ // Check integrity
+ if(m_TaxiDestinations.size() < 2)
+ return false;
+
+ for (size_t i = 1; i < m_TaxiDestinations.size(); ++i)
+ {
+ uint32 cost;
+ uint32 path;
+ objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
+ if(!path)
+ return false;
+ }
+
+ // can't load taxi path without mount set (quest taxi path?)
+ if(!objmgr.GetTaxiMountDisplayId(GetTaxiSource(),team,true))
+ return false;
+
+ return true;
+}
+
+std::string PlayerTaxi::SaveTaxiDestinationsToString()
+{
+ if(m_TaxiDestinations.empty())
+ return "";
+
+ std::ostringstream ss;
+
+ for (size_t i=0; i < m_TaxiDestinations.size(); ++i)
+ ss << m_TaxiDestinations[i] << " ";
+
+ return ss.str();
+}
+
+uint32 PlayerTaxi::GetCurrentTaxiPath() const
+{
+ if(m_TaxiDestinations.size() < 2)
+ return 0;
+
+ uint32 path;
+ uint32 cost;
+
+ objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
+
+ return path;
+}
+
+std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
+{
+ ss << "'";
+ for (uint8 i = 0; i < TaxiMaskSize; ++i)
+ ss << taxi.m_taximask[i] << " ";
+ ss << "'";
+ return ss;
+}
+
+//== Player ====================================================
+
+UpdateMask Player::updateVisualBits;
+
+Player::Player (WorldSession *session): Unit(), m_achievementMgr(this), m_reputationMgr(this)
+{
+ m_speakTime = 0;
+ m_speakCount = 0;
+
+ m_objectType |= TYPEMASK_PLAYER;
+ m_objectTypeId = TYPEID_PLAYER;
+
+ m_valuesCount = PLAYER_END;
+
+ m_session = session;
+
+ m_divider = 0;
+
+ m_ExtraFlags = 0;
+
+ m_spellModTakingSpell = NULL;
+ //m_pad = 0;
+
+ // players always accept
+ if(GetSession()->GetSecurity() == SEC_PLAYER)
+ SetAcceptWhispers(true);
+
+ m_curSelection = 0;
+ m_lootGuid = 0;
+
+ m_comboTarget = 0;
+ m_comboPoints = 0;
+
+ m_usedTalentCount = 0;
+ m_questRewardTalentCount = 0;
+
+ m_regenTimer = 0;
+ m_regenTimerCount = 0;
+ m_weaponChangeTimer = 0;
+
+ m_zoneUpdateId = 0;
+ m_zoneUpdateTimer = 0;
+
+ m_areaUpdateId = 0;
+
+ m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
+
+ clearResurrectRequestData();
+
+ memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
+
+ m_social = NULL;
+
+ // group is initialized in the reference constructor
+ SetGroupInvite(NULL);
+ m_groupUpdateMask = 0;
+ m_auraRaidUpdateMask = 0;
+
+ duel = NULL;
+
+ m_GuildIdInvited = 0;
+ m_ArenaTeamIdInvited = 0;
+
+ m_atLoginFlags = AT_LOGIN_NONE;
+
+ mSemaphoreTeleport_Near = false;
+ mSemaphoreTeleport_Far = false;
+
+ m_DelayedOperations = 0;
+ m_bCanDelayTeleport = false;
+ m_bHasDelayedTeleport = false;
+ m_teleport_options = 0;
+
+ pTrader = 0;
+ ClearTrade();
+
+ m_cinematic = 0;
+
+ PlayerTalkClass = new PlayerMenu( GetSession() );
+ m_currentBuybackSlot = BUYBACK_SLOT_START;
+
+ m_DailyQuestChanged = false;
+ m_lastDailyQuestTime = 0;
+
+ for (uint8 i=0; i<MAX_TIMERS; i++)
+ m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
+
+ m_MirrorTimerFlags = UNDERWATER_NONE;
+ m_MirrorTimerFlagsLast = UNDERWATER_NONE;
+ m_isInWater = false;
+ m_drunkTimer = 0;
+ m_drunk = 0;
+ m_restTime = 0;
+ m_deathTimer = 0;
+ m_deathExpireTime = 0;
+
+ m_swingErrorMsg = 0;
+
+ m_DetectInvTimer = 1*IN_MILISECONDS;
+
+ for (uint8 j = 0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
+ {
+ m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
+ m_bgBattleGroundQueueID[j].invitedToInstance = 0;
+ }
+
+ m_logintime = time(NULL);
+ m_Last_tick = m_logintime;
+ m_WeaponProficiency = 0;
+ m_ArmorProficiency = 0;
+ m_canParry = false;
+ m_canBlock = false;
+ m_canDualWield = false;
+ m_canTitanGrip = false;
+ m_ammoDPS = 0.0f;
+
+ m_temporaryUnsummonedPetNumber = 0;
+ //cache for UNIT_CREATED_BY_SPELL to allow
+ //returning reagents for temporarily removed pets
+ //when dying/logging out
+ m_oldpetspell = 0;
+ m_lastpetnumber = 0;
+
+ ////////////////////Rest System/////////////////////
+ time_inn_enter=0;
+ inn_pos_mapid=0;
+ inn_pos_x=0;
+ inn_pos_y=0;
+ inn_pos_z=0;
+ m_rest_bonus=0;
+ rest_type=REST_TYPE_NO;
+ ////////////////////Rest System/////////////////////
+
+ m_mailsLoaded = false;
+ m_mailsUpdated = false;
+ unReadMails = 0;
+ m_nextMailDelivereTime = 0;
+
+ m_resetTalentsCost = 0;
+ m_resetTalentsTime = 0;
+ m_itemUpdateQueueBlocked = false;
+
+ for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i)
+ m_forced_speed_changes[i] = 0;
+
+ m_stableSlots = 0;
+
+ /////////////////// Instance System /////////////////////
+
+ m_HomebindTimer = 0;
+ m_InstanceValid = true;
+ m_dungeonDifficulty = DUNGEON_DIFFICULTY_NORMAL;
+ m_raidDifficulty = RAID_DIFFICULTY_10MAN_NORMAL;
+
+ m_lastPotionId = 0;
+
+ m_activeSpec = 0;
+ m_specsCount = 1;
+
+ for (uint8 i = 0; i < MAX_TALENT_SPECS; ++i)
+ {
+ for (uint8 g = 0; g < MAX_GLYPH_SLOT_INDEX; ++g)
+ m_Glyphs[i][g] = 0;
+
+ m_talents[i] = new PlayerTalentMap();
+ }
+
+ for (uint8 i = 0; i < BASEMOD_END; ++i)
+ {
+ m_auraBaseMod[i][FLAT_MOD] = 0.0f;
+ m_auraBaseMod[i][PCT_MOD] = 1.0f;
+ }
+
+ for (uint8 i = 0; i < MAX_COMBAT_RATING; i++)
+ m_baseRatingValue[i] = 0;
+
+ m_baseSpellPower = 0;
+ m_baseFeralAP = 0;
+ m_baseManaRegen = 0;
+ m_baseHealthRegen = 0;
+
+ // Honor System
+ m_lastHonorUpdateTime = time(NULL);
+
+ // Player summoning
+ m_summon_expire = 0;
+ m_summon_mapid = 0;
+ m_summon_x = 0.0f;
+ m_summon_y = 0.0f;
+ m_summon_z = 0.0f;
+
+ //Default movement to run mode
+ //m_unit_movement_flags = 0;
+
+ m_mover = this;
+ m_movedPlayer = this;
+ m_seer = this;
+
+ m_contestedPvPTimer = 0;
+
+ m_declinedname = NULL;
+
+ m_isActive = true;
+
+ m_runes = NULL;
+
+ m_lastFallTime = 0;
+ m_lastFallZ = 0;
+
+ m_ControlledByPlayer = true;
+ m_isWorldObject = true;
+
+ sWorld.IncreasePlayerCount();
+
+ m_ChampioningFaction = 0;
+
+ for (int i = 0; i < MAX_POWERS; ++i)
+ m_powerFraction[i] = 0;
+}
+
+Player::~Player ()
+{
+ // it must be unloaded already in PlayerLogout and accessed only for loggined player
+ //m_social = NULL;
+
+ // Note: buy back item already deleted from DB when player was saved
+ for (uint8 i = 0; i < PLAYER_SLOTS_COUNT; ++i)
+ {
+ if(m_items[i])
+ delete m_items[i];
+ }
+
+ for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
+ delete itr->second;
+
+ for (uint8 i = 0; i < MAX_TALENT_SPECS; ++i)
+ {
+ for (PlayerTalentMap::const_iterator itr = m_talents[i]->begin(); itr != m_talents[i]->end(); ++itr)
+ delete itr->second;
+ delete m_talents[i];
+ }
+
+ //all mailed items should be deleted, also all mail should be deallocated
+ for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
+ delete *itr;
+
+ for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
+ delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
+
+ delete PlayerTalkClass;
+
+ for (size_t x = 0; x < ItemSetEff.size(); x++)
+ if(ItemSetEff[x])
+ delete ItemSetEff[x];
+
+ delete m_declinedname;
+ delete m_runes;
+
+ sWorld.DecreasePlayerCount();
+}
+
+void Player::CleanupsBeforeDelete(bool finalCleanup)
+{
+ TradeCancel(false);
+ DuelComplete(DUEL_INTERUPTED);
+
+ Unit::CleanupsBeforeDelete(finalCleanup);
+
+ if (m_transport)
+ m_transport->RemovePassenger(this);
+
+ // clean up player-instance binds, may unload some instance saves
+ for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
+ for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
+ itr->second.save->RemovePlayer(this);
+}
+
+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 )
+{
+ //FIXME: outfitId not used in player creating
+
+ Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
+
+ m_name = name;
+
+ PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
+ if(!info)
+ {
+ sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
+ return false;
+ }
+
+ for (uint8 i = 0; i < PLAYER_SLOTS_COUNT; i++)
+ m_items[i] = NULL;
+
+ Relocate(info->positionX,info->positionY,info->positionZ);
+
+ ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
+ if(!cEntry)
+ {
+ sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
+ return false;
+ }
+
+ SetMap(MapManager::Instance().CreateMap(info->mapId, this, 0));
+
+ uint8 powertype = cEntry->powerType;
+
+ SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
+ SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
+
+ setFactionForRace(race);
+
+ uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
+
+ SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
+ InitDisplayIds();
+ if(sWorld.getConfig(CONFIG_GAME_TYPE) == REALM_TYPE_PVP || sWorld.getConfig(CONFIG_GAME_TYPE) == REALM_TYPE_RPPVP)
+ {
+ SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
+ SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
+ }
+ SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
+ SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
+ SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
+
+ // -1 is default value
+ SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
+
+ SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
+ SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
+ SetByteValue(PLAYER_BYTES_3, 0, gender);
+
+ SetUInt32Value( PLAYER_GUILDID, 0 );
+ SetUInt32Value( PLAYER_GUILDRANK, 0 );
+ SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
+
+ SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
+ SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
+ SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES2, 0 ); // 0=disabled
+ SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
+ SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
+ SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORABLE_KILLS, 0 );
+ SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
+ SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
+
+ // set starting level
+ uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
+ ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
+ : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
+
+ if (GetSession()->GetSecurity() >= SEC_MODERATOR)
+ {
+ uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
+ if(gm_level > start_level)
+ start_level = gm_level;
+ }
+
+ SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
+
+ InitRunes();
+
+ SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
+ SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
+ SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
+
+ // start with every map explored
+ if(sWorld.getConfig(CONFIG_START_ALL_EXPLORED))
+ {
+ for (uint8 i=0; i<64; i++)
+ SetFlag(PLAYER_EXPLORED_ZONES_1+i,0xFFFFFFFF);
+ }
+
+ //Reputations if "StartAllReputation" is enabled, -- TODO: Fix this in a better way
+ if(sWorld.getConfig(CONFIG_START_ALL_REP))
+ {
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(942),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(935),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(936),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(1011),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(970),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(967),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(989),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(932),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(934),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(1038),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(1077),42999);
+
+ // Factions depending on team, like cities and some more stuff
+ switch(GetTeam())
+ {
+ case ALLIANCE:
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(72),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(47),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(69),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(930),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(730),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(978),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(54),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(946),42999);
+ break;
+ case HORDE:
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(76),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(68),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(81),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(911),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(729),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(941),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(530),42999);
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(947),42999);
+ break;
+ default:
+ break;
+ }
+ }
+
+ // Played time
+ m_Last_tick = time(NULL);
+ m_Played_time[PLAYED_TIME_TOTAL] = 0;
+ m_Played_time[PLAYED_TIME_LEVEL] = 0;
+
+ // base stats and related field values
+ InitStatsForLevel();
+ InitTaxiNodesForLevel();
+ InitGlyphsForLevel();
+ InitTalentForLevel();
+ InitPrimaryProfessions(); // to max set before any spell added
+
+ // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
+ UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
+ SetHealth(GetMaxHealth());
+ if (getPowerType()==POWER_MANA)
+ {
+ UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
+ SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
+ }
+
+ if(getPowerType() == POWER_RUNIC_POWER)
+ {
+ SetPower(POWER_RUNE, 8);
+ SetMaxPower(POWER_RUNE, 8);
+ SetPower(POWER_RUNIC_POWER, 0);
+ SetMaxPower(POWER_RUNIC_POWER, 1000);
+ }
+
+ // original spells
+ learnDefaultSpells();
+
+ // original action bar
+ for (PlayerCreateInfoActions::const_iterator action_itr = info->action.begin(); action_itr != info->action.end(); ++action_itr)
+ addActionButton(action_itr->button,action_itr->action,action_itr->type);
+
+ // original items
+ CharStartOutfitEntry const* oEntry = NULL;
+ for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
+ {
+ if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
+ {
+ if(entry->RaceClassGender == RaceClassGender)
+ {
+ oEntry = entry;
+ break;
+ }
+ }
+ }
+
+ if(oEntry)
+ {
+ for (int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
+ {
+ if(oEntry->ItemId[j] <= 0)
+ continue;
+
+ uint32 item_id = oEntry->ItemId[j];
+
+ // just skip, reported in ObjectMgr::LoadItemPrototypes
+ ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
+ if (!iProto)
+ continue;
+
+ // BuyCount by default
+ uint32 count = iProto->BuyCount;
+
+ // special amount for food/drink
+ if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
+ {
+ switch(iProto->Spells[0].SpellCategory)
+ {
+ case SPELL_CATEGORY_FOOD: // food
+ count = getClass()==CLASS_DEATH_KNIGHT ? 10 : 4;
+ break;
+ case SPELL_CATEGORY_DRINK: // drink
+ count = 2;
+ break;
+ }
+ if(iProto->Stackable < count)
+ count = iProto->Stackable;
+ }
+ // special amount for daggers
+ else if(iProto->Class==ITEM_CLASS_WEAPON && iProto->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER)
+ {
+ count = 2; // will placed to 2 slots
+ }
+
+ StoreNewItemInBestSlots(item_id, count);
+ }
+ }
+
+ for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
+ StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
+
+ // bags and main-hand weapon must equipped at this moment
+ // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
+ // or ammo not equipped in special bag
+ for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
+ {
+ if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ {
+ uint16 eDest;
+ // equip offhand weapon/shield if it attempt equipped before main-hand weapon
+ uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
+ if( msg == EQUIP_ERR_OK )
+ {
+ RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
+ EquipItem( eDest, pItem, true);
+ }
+ // move other items to more appropriate slots (ammo not equipped in special bag)
+ else
+ {
+ ItemPosCountVec sDest;
+ msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
+ if( msg == EQUIP_ERR_OK )
+ {
+ RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
+ pItem = StoreItem( sDest, pItem, true);
+ }
+
+ // if this is ammo then use it
+ msg = CanUseAmmo( pItem->GetEntry() );
+ if( msg == EQUIP_ERR_OK )
+ SetAmmo( pItem->GetEntry() );
+ }
+ }
+ }
+ // all item positions resolved
+
+ return true;
+}
+
+bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
+{
+ sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
+
+ // attempt equip by one
+ while(titem_amount > 0)
+ {
+ uint16 eDest;
+ uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
+ if( msg != EQUIP_ERR_OK )
+ break;
+
+ EquipNewItem( eDest, titem_id, true);
+ AutoUnequipOffhandIfNeed();
+ --titem_amount;
+ }
+
+ if(titem_amount == 0)
+ return true; // equipped
+
+ // attempt store
+ ItemPosCountVec sDest;
+ // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
+ uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
+ if( msg == EQUIP_ERR_OK )
+ {
+ StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
+ return true; // stored
+ }
+
+ // item can't be added
+ sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
+ return false;
+}
+
+void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
+{
+ if (int(MaxValue) == DISABLED_MIRROR_TIMER)
+ {
+ if (int(CurrentValue) != DISABLED_MIRROR_TIMER)
+ StopMirrorTimer(Type);
+ return;
+ }
+ WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
+ data << (uint32)Type;
+ data << CurrentValue;
+ data << MaxValue;
+ data << Regen;
+ data << (uint8)0;
+ data << (uint32)0; // spell id
+ GetSession()->SendPacket( &data );
+}
+
+void Player::StopMirrorTimer(MirrorTimerType Type)
+{
+ m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
+ WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
+ data << (uint32)Type;
+ GetSession()->SendPacket( &data );
+}
+
+uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
+{
+ if(!isAlive() || isGameMaster())
+ return 0;
+
+ // Absorb, resist some environmental damage type
+ uint32 absorb = 0;
+ uint32 resist = 0;
+ if (type == DAMAGE_LAVA)
+ CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
+ else if (type == DAMAGE_SLIME)
+ CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
+
+ damage-=absorb+resist;
+
+ DealDamageMods(this,damage,&absorb);
+
+ WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
+ data << uint64(GetGUID());
+ data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
+ data << uint32(damage);
+ data << uint32(absorb);
+ data << uint32(resist);
+ SendMessageToSet(&data, true);
+
+ uint32 final_damage = DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
+
+ if(!isAlive())
+ {
+ if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
+ {
+ DEBUG_LOG("We are fall to death, loosing 10 percents durability");
+ DurabilityLossAll(0.10f,false);
+ // durability lost message
+ WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
+ GetSession()->SendPacket(&data2);
+ }
+
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
+ }
+
+ return final_damage;
+}
+
+int32 Player::getMaxTimer(MirrorTimerType timer)
+{
+ switch (timer)
+ {
+ case FATIGUE_TIMER:
+ return MINUTE*IN_MILISECONDS;
+ case BREATH_TIMER:
+ {
+ if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
+ return DISABLED_MIRROR_TIMER;
+ int32 UnderWaterTime = 3*MINUTE*IN_MILISECONDS;
+ AuraEffectList const& mModWaterBreathing = GetAuraEffectsByType(SPELL_AURA_MOD_WATER_BREATHING);
+ for (AuraEffectList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
+ UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetAmount()) / 100.0f);
+ return UnderWaterTime;
+ }
+ case FIRE_TIMER:
+ {
+ if (!isAlive())
+ return DISABLED_MIRROR_TIMER;
+ return 1*IN_MILISECONDS;
+ }
+ default:
+ return 0;
+ }
+ return 0;
+}
+
+void Player::UpdateMirrorTimers()
+{
+ // Desync flags for update on next HandleDrowning
+ if (m_MirrorTimerFlags)
+ m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
+}
+
+void Player::HandleDrowning(uint32 time_diff)
+{
+ if (!m_MirrorTimerFlags)
+ return;
+
+ // In water
+ if (m_MirrorTimerFlags & UNDERWATER_INWATER)
+ {
+ // Breath timer not activated - activate it
+ if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
+ {
+ m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
+ SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
+ }
+ else // If activated - do tick
+ {
+ m_MirrorTimer[BREATH_TIMER]-=time_diff;
+ // Timer limit - need deal damage
+ if (m_MirrorTimer[BREATH_TIMER] < 0)
+ {
+ m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILISECONDS;
+ // Calculate and deal damage
+ // TODO: Check this formula
+ uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
+ EnvironmentalDamage(DAMAGE_DROWNING, damage);
+ }
+ else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
+ SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
+ }
+ }
+ else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
+ {
+ int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
+ // Need breath regen
+ m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
+ if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
+ StopMirrorTimer(BREATH_TIMER);
+ else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
+ SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
+ }
+
+ // In dark water
+ if (m_MirrorTimerFlags & UNDERWARER_INDARKWATER)
+ {
+ // Fatigue timer not activated - activate it
+ if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
+ {
+ m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
+ SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
+ }
+ else
+ {
+ m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
+ // Timer limit - need deal damage or teleport ghost to graveyard
+ if (m_MirrorTimer[FATIGUE_TIMER] < 0)
+ {
+ m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILISECONDS;
+ if (isAlive()) // Calculate and deal damage
+ {
+ uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
+ EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
+ }
+ else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
+ RepopAtGraveyard();
+ }
+ else if (!(m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER))
+ SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
+ }
+ }
+ else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
+ {
+ int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
+ m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
+ if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
+ StopMirrorTimer(FATIGUE_TIMER);
+ else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER)
+ SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
+ }
+
+ if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
+ {
+ // Breath timer not activated - activate it
+ if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
+ m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
+ else
+ {
+ m_MirrorTimer[FIRE_TIMER]-=time_diff;
+ if (m_MirrorTimer[FIRE_TIMER] < 0)
+ {
+ m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILISECONDS;
+ // Calculate and deal damage
+ // TODO: Check this formula
+ uint32 damage = urand(600, 700);
+ if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
+ EnvironmentalDamage(DAMAGE_LAVA, damage);
+ else
+ EnvironmentalDamage(DAMAGE_SLIME, damage);
+ }
+ }
+ }
+ else
+ m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
+
+ // Recheck timers flag
+ m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
+ for (uint8 i = 0; i< MAX_TIMERS; ++i)
+ if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
+ {
+ m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
+ break;
+ }
+ m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
+}
+
+///The player sobers by 256 every 10 seconds
+void Player::HandleSobering()
+{
+ m_drunkTimer = 0;
+
+ uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
+ SetDrunkValue(drunk);
+}
+
+DrunkenState Player::GetDrunkenstateByValue(uint16 value)
+{
+ if(value >= 23000)
+ return DRUNKEN_SMASHED;
+ if(value >= 12800)
+ return DRUNKEN_DRUNK;
+ if(value & 0xFFFE)
+ return DRUNKEN_TIPSY;
+ return DRUNKEN_SOBER;
+}
+
+void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
+{
+ uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
+
+ m_drunk = newDrunkenValue;
+ SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
+
+ uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
+
+ // special drunk invisibility detection
+ if(newDrunkenState >= DRUNKEN_DRUNK)
+ m_detectInvisibilityMask |= (1<<6);
+ else
+ m_detectInvisibilityMask &= ~(1<<6);
+
+ if(newDrunkenState == oldDrunkenState)
+ return;
+
+ WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
+ data << uint64(GetGUID());
+ data << uint32(newDrunkenState);
+ data << uint32(itemId);
+
+ SendMessageToSet(&data, true);
+}
+
+void Player::Update( uint32 p_time )
+{
+ if (!IsInWorld())
+ return;
+
+ // undelivered mail
+ if (m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
+ {
+ SendNewMail();
+ ++unReadMails;
+
+ // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
+ m_nextMailDelivereTime = 0;
+ }
+
+ // If this is set during update SetSpellModTakingSpell call is missing somewhere in the code
+ // Having this would prevent more aura charges to be dropped, so let's crash
+ //assert (!m_spellModTakingSpell);
+ if (/*m_pad ||*/ m_spellModTakingSpell)
+ {
+ //sLog.outCrash("Player has m_pad %u during update!", m_pad);
+ //if(m_spellModTakingSpell)
+ sLog.outCrash("Player has m_spellModTakingSpell %u during update!", m_spellModTakingSpell->m_spellInfo->Id);
+ return;
+ m_spellModTakingSpell = NULL;
+ }
+
+ //used to implement delayed far teleports
+ SetCanDelayTeleport(true);
+ Unit::Update(p_time);
+ SetCanDelayTeleport(false);
+
+ time_t now = time(NULL);
+
+ UpdatePvPFlag(now);
+
+ UpdateContestedPvP(p_time);
+
+ UpdateDuelFlag(now);
+
+ CheckDuelDistance(now);
+
+ UpdateAfkReport(now);
+
+ if (isCharmed())
+ if (Unit *charmer = GetCharmer())
+ if (charmer->GetTypeId() == TYPEID_UNIT && charmer->isAlive())
+ UpdateCharmedAI();
+
+ // Update items that have just a limited lifetime
+ if (now > m_Last_tick)
+ UpdateItemDuration(uint32(now - m_Last_tick));
+
+ if (!m_timedquests.empty())
+ {
+ std::set<uint32>::iterator iter = m_timedquests.begin();
+ while (iter != m_timedquests.end())
+ {
+ QuestStatusData& q_status = mQuestStatus[*iter];
+ if (q_status.m_timer <= p_time)
+ {
+ uint32 quest_id = *iter;
+ ++iter; // current iter will be removed in FailQuest
+ FailQuest(quest_id);
+ }
+ else
+ {
+ q_status.m_timer -= p_time;
+ if (q_status.uState != QUEST_NEW)
+ q_status.uState = QUEST_CHANGED;
+ ++iter;
+ }
+ }
+ }
+
+ if (hasUnitState(UNIT_STAT_MELEE_ATTACKING) && !hasUnitState(UNIT_STAT_CASTING))
+ {
+ if (Unit *pVictim = getVictim())
+ {
+ // default combat reach 10
+ // TODO add weapon,skill check
+
+ if (isAttackReady(BASE_ATTACK))
+ {
+ if (!IsWithinMeleeRange(pVictim))
+ {
+ setAttackTimer(BASE_ATTACK,100);
+ if (m_swingErrorMsg != 1) // send single time (client auto repeat)
+ {
+ SendAttackSwingNotInRange();
+ m_swingErrorMsg = 1;
+ }
+ }
+ //120 degrees of radiant range
+ else if (!HasInArc(2*M_PI/3, pVictim))
+ {
+ setAttackTimer(BASE_ATTACK,100);
+ if (m_swingErrorMsg != 2) // send single time (client auto repeat)
+ {
+ SendAttackSwingBadFacingAttack();
+ m_swingErrorMsg = 2;
+ }
+ }
+ else
+ {
+ m_swingErrorMsg = 0; // reset swing error state
+
+ // prevent base and off attack in same time, delay attack at 0.2 sec
+ if (haveOffhandWeapon())
+ if (getAttackTimer(OFF_ATTACK) < ATTACK_DISPLAY_DELAY)
+ setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
+
+ // do attack
+ AttackerStateUpdate(pVictim, BASE_ATTACK);
+ resetAttackTimer(BASE_ATTACK);
+ }
+ }
+
+ if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
+ {
+ if (!IsWithinMeleeRange(pVictim))
+ setAttackTimer(OFF_ATTACK,100);
+ else if (!HasInArc(2*M_PI/3, pVictim))
+ setAttackTimer(OFF_ATTACK,100);
+ else
+ {
+ // prevent base and off attack in same time, delay attack at 0.2 sec
+ if (getAttackTimer(BASE_ATTACK) < ATTACK_DISPLAY_DELAY)
+ setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
+
+ // do attack
+ AttackerStateUpdate(pVictim, OFF_ATTACK);
+ resetAttackTimer(OFF_ATTACK);
+ }
+ }
+
+ /*Unit *owner = pVictim->GetOwner();
+ Unit *u = owner ? owner : pVictim;
+ if(u->IsPvP() && (!duel || duel->opponent != u))
+ {
+ UpdatePvP(true);
+ RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
+ }*/
+ }
+ }
+
+ if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
+ {
+ if (roll_chance_i(3) && GetTimeInnEnter() > 0) // freeze update
+ {
+ int time_inn = time(NULL)-GetTimeInnEnter();
+ if (time_inn >= 10) // freeze update
+ {
+ float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
+ // speed collect rest bonus (section/in hour)
+ SetRestBonus(GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
+ UpdateInnerTime(time(NULL));
+ }
+ }
+ }
+
+ if (m_weaponChangeTimer > 0)
+ {
+ if (p_time >= m_weaponChangeTimer)
+ m_weaponChangeTimer = 0;
+ else
+ m_weaponChangeTimer -= p_time;
+ }
+
+ if (m_zoneUpdateTimer > 0)
+ {
+ if (p_time >= m_zoneUpdateTimer)
+ {
+ uint32 newzone, newarea;
+ GetZoneAndAreaId(newzone,newarea);
+
+ if (m_zoneUpdateId != newzone)
+ UpdateZone(newzone,newarea); // also update area
+ else
+ {
+ // use area updates as well
+ // needed for free far all arenas for example
+ if (m_areaUpdateId != newarea)
+ UpdateArea(newarea);
+
+ m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
+ }
+ }
+ else
+ m_zoneUpdateTimer -= p_time;
+ }
+
+ if (m_timeSyncTimer > 0)
+ {
+ if(p_time >= m_timeSyncTimer)
+ SendTimeSync();
+ else
+ m_timeSyncTimer -= p_time;
+ }
+
+ if (isAlive())
+ {
+ m_regenTimer += p_time;
+ RegenerateAll();
+ }
+
+ if (m_deathState == JUST_DIED)
+ KillPlayer();
+
+ if (m_nextSave > 0)
+ {
+ if (p_time >= m_nextSave)
+ {
+ // m_nextSave reseted in SaveToDB call
+ SaveToDB();
+ sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
+ }
+ else
+ m_nextSave -= p_time;
+ }
+
+ //Handle Water/drowning
+ HandleDrowning(p_time);
+
+ //Handle detect stealth players
+ if (m_DetectInvTimer > 0)
+ {
+ if (p_time >= m_DetectInvTimer)
+ {
+ HandleStealthedUnitsDetection();
+ m_DetectInvTimer = 3000;
+ }
+ else
+ m_DetectInvTimer -= p_time;
+ }
+
+ // Played time
+ if (now > m_Last_tick)
+ {
+ uint32 elapsed = uint32(now - m_Last_tick);
+ m_Played_time[PLAYED_TIME_TOTAL] += elapsed; // Total played time
+ m_Played_time[PLAYED_TIME_LEVEL] += elapsed; // Level played time
+ m_Last_tick = now;
+ }
+
+ if (m_drunk)
+ {
+ m_drunkTimer += p_time;
+
+ if (m_drunkTimer > 10*IN_MILISECONDS)
+ HandleSobering();
+ }
+
+ // not auto-free ghost from body in instances
+ if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
+ {
+ if(p_time >= m_deathTimer)
+ {
+ m_deathTimer = 0;
+ BuildPlayerRepop();
+ RepopAtGraveyard();
+ }
+ else
+ m_deathTimer -= p_time;
+ }
+
+ UpdateEnchantTime(p_time);
+ UpdateHomebindTime(p_time);
+
+ // group update
+ SendUpdateToOutOfRangeGroupMembers();
+
+ Pet* pet = GetPet();
+ if (pet && !pet->IsWithinDistInMap(this, GetMap()->GetVisibilityDistance()) && !pet->isPossessed())
+ //if(pet && !pet->IsWithinDistInMap(this, GetMap()->GetVisibilityDistance()) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
+ RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
+
+ //we should execute delayed teleports only for alive(!) players
+ //because we don't want player's ghost teleported from graveyard
+ if (IsHasDelayedTeleport() && isAlive())
+ TeleportTo(m_teleport_dest, m_teleport_options);
+}
+
+void Player::setDeathState(DeathState s)
+{
+ uint32 ressSpellId = 0;
+
+ bool cur = isAlive();
+
+ if (s == JUST_DIED)
+ {
+ if (!cur)
+ {
+ sLog.outError("setDeathState: attempt to kill a dead player %s(%d)", GetName(), GetGUIDLow());
+ return;
+ }
+
+ // drunken state is cleared on death
+ SetDrunkValue(0);
+ // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
+ ClearComboPoints();
+
+ clearResurrectRequestData();
+
+ // remove form before other mods to prevent incorrect stats calculation
+ RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
+
+ //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
+ RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
+
+ // save value before aura remove in Unit::setDeathState
+ ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
+
+ // passive spell
+ if(!ressSpellId)
+ ressSpellId = GetResurrectionSpellId();
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
+ }
+ Unit::setDeathState(s);
+
+ // restore resurrection spell id for player after aura remove
+ if (s == JUST_DIED && cur && ressSpellId)
+ SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
+
+ if (isAlive() && !cur)
+ {
+ //clear aura case after resurrection by another way (spells will be applied before next death)
+ SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
+
+ // restore default warrior stance
+ if (getClass() == CLASS_WARRIOR)
+ CastSpell(this, 2457, true);
+ }
+}
+
+bool Player::BuildEnumData( QueryResult_AutoPtr result, WorldPacket * p_data )
+{
+ // 0 1 2 3 4 5 6 7
+ // "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.playerBytes, characters.playerBytes2, characters.level, "
+ // 8 9 10 11 12 13 14
+ // "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, "
+ // 15 16 17 18 19 20
+ // "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.data, character_declinedname.genitive "
+
+ Field *fields = result->Fetch();
+
+ uint32 guid = fields[0].GetUInt32();
+ uint8 pRace = fields[2].GetUInt8();
+ uint8 pClass = fields[3].GetUInt8();
+
+ PlayerInfo const *info = objmgr.GetPlayerInfo(pRace, pClass);
+ if (!info)
+ {
+ sLog.outError("Player %u has incorrect race/class pair. Don't build enum.", guid);
+ return false;
+ }
+
+ *p_data << uint64(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
+ *p_data << fields[1].GetString(); // name
+ *p_data << uint8(pRace); // race
+ *p_data << uint8(pClass); // class
+ *p_data << uint8(fields[4].GetUInt8()); // gender
+
+ uint32 playerBytes = fields[5].GetUInt32();
+ *p_data << uint8(playerBytes); // skin
+ *p_data << uint8(playerBytes >> 8); // face
+ *p_data << uint8(playerBytes >> 16); // hair style
+ *p_data << uint8(playerBytes >> 24); // hair color
+
+ uint32 playerBytes2 = fields[6].GetUInt32();
+ *p_data << uint8(playerBytes2 & 0xFF); // facial hair
+
+ *p_data << uint8(fields[7].GetUInt8()); // level
+ *p_data << uint32(fields[8].GetUInt32()); // zone
+ *p_data << uint32(fields[9].GetUInt32()); // map
+
+ *p_data << fields[10].GetFloat(); // x
+ *p_data << fields[11].GetFloat(); // y
+ *p_data << fields[12].GetFloat(); // z
+
+ *p_data << uint32(fields[13].GetUInt32()); // guild id
+
+ uint32 char_flags = 0;
+ uint32 playerFlags = fields[14].GetUInt32();
+ uint32 atLoginFlags = fields[15].GetUInt32();
+ if (playerFlags & PLAYER_FLAGS_HIDE_HELM)
+ char_flags |= CHARACTER_FLAG_HIDE_HELM;
+ if (playerFlags & PLAYER_FLAGS_HIDE_CLOAK)
+ char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
+ if (playerFlags & PLAYER_FLAGS_GHOST)
+ char_flags |= CHARACTER_FLAG_GHOST;
+ if (atLoginFlags & AT_LOGIN_RENAME)
+ char_flags |= CHARACTER_FLAG_RENAME;
+ if (sWorld.getConfig(CONFIG_DECLINED_NAMES_USED))
+ {
+ if (!fields[20].GetCppString().empty())
+ char_flags |= CHARACTER_FLAG_DECLINED;
+ }
+ else
+ char_flags |= CHARACTER_FLAG_DECLINED;
+
+ *p_data << uint32(char_flags); // character flags
+ // character customize flags
+ *p_data << uint32(atLoginFlags & AT_LOGIN_CUSTOMIZE ? CHAR_CUSTOMIZE_FLAG_CUSTOMIZE : CHAR_CUSTOMIZE_FLAG_NONE);
+ // First login
+ *p_data << uint8(atLoginFlags & AT_LOGIN_FIRST ? 1 : 0);
+
+ // Pets info
+ {
+ uint32 petDisplayId = 0;
+ uint32 petLevel = 0;
+ uint32 petFamily = 0;
+
+ // show pet at selection character in character list only for non-ghost character
+ if (result && !(playerFlags & PLAYER_FLAGS_GHOST) && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER || pClass == CLASS_DEATH_KNIGHT))
+ {
+ uint32 entry = fields[16].GetUInt32();
+ CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
+ if (cInfo)
+ {
+ petDisplayId = fields[17].GetUInt32();
+ petLevel = fields[18].GetUInt32();
+ petFamily = cInfo->family;
+ }
+ }
+
+ *p_data << uint32(petDisplayId);
+ *p_data << uint32(petLevel);
+ *p_data << uint32(petFamily);
+ }
+
+ // TODO: do not access data field here
+ Tokens data = StrSplit(fields[19].GetCppString(), " ");
+
+ for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; ++slot)
+ {
+ uint32 visualbase = PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2);
+ uint32 item_id = GetUInt32ValueFromArray(data, visualbase);
+ const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
+ if (!proto)
+ {
+ *p_data << uint32(0);
+ *p_data << uint8(0);
+ *p_data << uint32(0);
+ continue;
+ }
+
+ SpellItemEnchantmentEntry const *enchant = NULL;
+
+ uint32 enchants = GetUInt32ValueFromArray(data, visualbase + 1);
+ for (uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot)
+ {
+ // values stored in 2 uint16
+ uint32 enchantId = 0x0000FFFF & (enchants >> enchantSlot*16);
+ if (!enchantId)
+ continue;
+
+ if ((enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId)))
+ break;
+ }
+
+ *p_data << uint32(proto->DisplayInfoID);
+ *p_data << uint8(proto->InventoryType);
+ *p_data << uint32(enchant ? enchant->aura_id : 0);
+ }
+ *p_data << uint32(0); // first bag display id
+ *p_data << uint8(0); // first bag inventory type
+ *p_data << uint32(0); // enchant?
+
+ return true;
+}
+
+bool Player::ToggleAFK()
+{
+ ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
+
+ bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
+
+ // afk player not allowed in battleground
+ if (state && InBattleGround())
+ LeaveBattleground();
+
+ return state;
+}
+
+bool Player::ToggleDND()
+{
+ ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
+
+ return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
+}
+
+uint8 Player::chatTag() const
+{
+ // it's bitmask
+ // 0x8 - ??
+ // 0x4 - gm
+ // 0x2 - dnd
+ // 0x1 - afk
+ if (isGMChat())
+ return 4;
+ else if (isDND())
+ return 3;
+ if (isAFK())
+ return 1;
+ else
+ return 0;
+}
+
+void Player::SendTeleportAckMsg()
+{
+ WorldPacket data(MSG_MOVE_TELEPORT_ACK, 41);
+ data.append(GetPackGUID());
+ data << uint32(0); // this value increments every time
+ BuildMovementPacket(&data);
+ GetSession()->SendPacket(&data);
+}
+
+// this is not used anywhere
+void Player::TeleportOutOfMap(Map *oldMap)
+{
+ while (IsBeingTeleportedFar())
+ GetSession()->HandleMoveWorldportAckOpcode();
+
+ if (GetMap() != oldMap)
+ return;
+
+ TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
+
+ while (IsBeingTeleportedFar())
+ GetSession()->HandleMoveWorldportAckOpcode();
+
+ if (GetMap() == oldMap)
+ {
+ sLog.outCrash("Cannot teleport player out of map!");
+ ResetMap();
+ assert(false);
+ }
+}
+
+bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
+{
+ if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
+ {
+ sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
+ return false;
+ }
+
+ if((GetSession()->GetSecurity() < SEC_GAMEMASTER) && !sWorld.IsAllowedMap(mapid))
+ {
+ sLog.outError("Player %s tried to enter a forbidden map", GetName());
+ return false;
+ }
+
+ // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
+ Pet* pet = GetPet();
+
+ MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
+
+ // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
+ // don't let gm level > 1 either
+ if (!InBattleGround() && mEntry->IsBattleGroundOrArena())
+ return false;
+
+ // client without expansion support
+ if (GetSession()->Expansion() < mEntry->Expansion())
+ {
+ sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
+
+ if (GetTransport())
+ RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
+
+ SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
+
+ return false; // normal client can't teleport to this map...
+ }
+ else
+ sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
+
+ // reset movement flags at teleport, because player will continue move with these flags after teleport
+ SetUnitMovementFlags(0);
+
+ if (m_transport)
+ {
+ if (options & TELE_TO_NOT_LEAVE_TRANSPORT)
+ AddUnitMovementFlag(MOVEMENTFLAG_ONTRANSPORT);
+ else
+ {
+ m_transport->RemovePassenger(this);
+ m_transport = NULL;
+ m_movementInfo.t_x = 0.0f;
+ m_movementInfo.t_y = 0.0f;
+ m_movementInfo.t_z = 0.0f;
+ m_movementInfo.t_o = 0.0f;
+ m_movementInfo.t_time = 0;
+ m_movementInfo.t_seat = -1;
+ }
+ }
+
+ // The player was ported to another map and looses the duel immediately.
+ // We have to perform this check before the teleport, otherwise the
+ // ObjectAccessor won't find the flag.
+ if (duel && GetMapId() != mapid)
+ if (GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER)))
+ DuelComplete(DUEL_FLED);
+
+ if (GetMapId() == mapid && !m_transport)
+ {
+ //lets reset far teleport flag if it wasn't reset during chained teleports
+ SetSemaphoreTeleportFar(false);
+ //setup delayed teleport flag
+ SetDelayedTeleportFlag(IsCanDelayTeleport());
+ //if teleport spell is casted in Unit::Update() func
+ //then we need to delay it until update process will be finished
+ if(IsHasDelayedTeleport())
+ {
+ SetSemaphoreTeleportNear(true);
+ //lets save teleport destination for player
+ m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
+ m_teleport_options = options;
+ return true;
+ }
+
+ if (!(options & TELE_TO_NOT_UNSUMMON_PET))
+ {
+ //same map, only remove pet if out of range for new position
+ if(pet && !pet->IsWithinDist3d(x,y,z, GetMap()->GetVisibilityDistance()))
+ UnsummonPetTemporaryIfAny();
+ }
+
+ if (!(options & TELE_TO_NOT_LEAVE_COMBAT))
+ CombatStop();
+
+ // this will be used instead of the current location in SaveToDB
+ m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
+ SetFallInformation(0, z);
+
+ // code for finish transfer called in WorldSession::HandleMovementOpcodes()
+ // at client packet MSG_MOVE_TELEPORT_ACK
+ SetSemaphoreTeleportNear(true);
+ // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
+ if(!GetSession()->PlayerLogout())
+ {
+ Position oldPos;
+ GetPosition(&oldPos);
+ Relocate(x, y, z, orientation);
+ SendTeleportAckMsg();
+ Relocate(&oldPos);
+ }
+ }
+ else
+ {
+ if (getClass() == CLASS_DEATH_KNIGHT && GetMapId() == 609 && !isGameMaster() && !HasSpell(50977))
+ return false;
+
+ // far teleport to another map
+ Map* oldmap = IsInWorld() ? GetMap() : NULL;
+ // check if we can enter before stopping combat / removing pet / totems / interrupting spells
+
+ // Check enter rights before map getting to avoid creating instance copy for player
+ // this check not dependent from map instance copy and same for all instance copies of selected map
+ if (!MapManager::Instance().CanPlayerEnter(mapid, this))
+ return false;
+
+ // If the map is not created, assume it is possible to enter it.
+ // It will be created in the WorldPortAck.
+ Map *map = MapManager::Instance().FindMap(mapid);
+ if (!map || map->CanEnter(this))
+ {
+ //lets reset near teleport flag if it wasn't reset during chained teleports
+ SetSemaphoreTeleportNear(false);
+ //setup delayed teleport flag
+ SetDelayedTeleportFlag(IsCanDelayTeleport());
+ //if teleport spell is casted in Unit::Update() func
+ //then we need to delay it until update process will be finished
+ if(IsHasDelayedTeleport())
+ {
+ SetSemaphoreTeleportFar(true);
+ //lets save teleport destination for player
+ m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
+ m_teleport_options = options;
+ return true;
+ }
+
+ SetSelection(0);
+
+ CombatStop();
+
+ ResetContestedPvP();
+
+ // remove player from battleground on far teleport (when changing maps)
+ if(BattleGround const* bg = GetBattleGround())
+ {
+ // Note: at battleground join battleground id set before teleport
+ // and we already will found "current" battleground
+ // just need check that this is targeted map or leave
+ if (bg->GetMapId() != mapid)
+ LeaveBattleground(false); // don't teleport to entry point
+ }
+
+ // remove pet on map change
+ if (pet)
+ UnsummonPetTemporaryIfAny();
+
+ // remove all dyn objects
+ RemoveAllDynObjects();
+
+ // stop spellcasting
+ // not attempt interrupt teleportation spell at caster teleport
+ if(!(options & TELE_TO_SPELL))
+ if(IsNonMeleeSpellCasted(true))
+ InterruptNonMeleeSpells(true);
+
+ //remove auras before removing from map...
+ RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
+
+ if (!GetSession()->PlayerLogout())
+ {
+ // send transfer packets
+ WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
+ data << uint32(mapid);
+ if (m_transport)
+ {
+ data << m_transport->GetEntry() << GetMapId();
+ }
+ GetSession()->SendPacket(&data);
+
+ data.Initialize(SMSG_NEW_WORLD, (20));
+ if (m_transport)
+ data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
+ else
+ data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
+
+ GetSession()->SendPacket( &data );
+ SendSavedInstances();
+ }
+
+ // remove from old map now
+ if(oldmap)
+ oldmap->Remove(this, false);
+
+ // new final coordinates
+ float final_x = x;
+ float final_y = y;
+ float final_z = z;
+ float final_o = orientation;
+
+ if (m_transport)
+ {
+ final_x += m_movementInfo.t_x;
+ final_y += m_movementInfo.t_y;
+ final_z += m_movementInfo.t_z;
+ final_o += m_movementInfo.t_o;
+ }
+
+ m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
+ SetFallInformation(0, final_z);
+ // if the player is saved before worldportack (at logout for example)
+ // this will be used instead of the current location in SaveToDB
+
+ // move packet sent by client always after far teleport
+ // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
+ SetSemaphoreTeleportFar(true);
+ }
+ else
+ return false;
+ }
+ return true;
+}
+
+bool Player::TeleportToBGEntryPoint()
+{
+ ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE);
+ ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE);
+ return TeleportTo(m_bgData.joinPos);
+}
+
+void Player::ProcessDelayedOperations()
+{
+ if (m_DelayedOperations == 0)
+ return;
+
+ if (m_DelayedOperations & DELAYED_RESURRECT_PLAYER)
+ {
+ ResurrectPlayer(0.0f, false);
+
+ if (GetMaxHealth() > m_resurrectHealth)
+ SetHealth(m_resurrectHealth);
+ else
+ SetHealth(GetMaxHealth());
+
+ if (GetMaxPower(POWER_MANA) > m_resurrectMana)
+ SetPower(POWER_MANA, m_resurrectMana);
+ else
+ SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
+
+ SetPower(POWER_RAGE, 0);
+ SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
+
+ SpawnCorpseBones();
+ }
+
+ if (m_DelayedOperations & DELAYED_SAVE_PLAYER)
+ SaveToDB();
+
+ if (m_DelayedOperations & DELAYED_SPELL_CAST_DESERTER)
+ CastSpell(this, 26013, true); // Deserter
+
+ if (m_DelayedOperations & DELAYED_BG_MOUNT_RESTORE)
+ {
+ if (m_bgData.mountSpell)
+ {
+ CastSpell(this, m_bgData.mountSpell, true);
+ m_bgData.mountSpell = 0;
+ }
+ }
+
+ if (m_DelayedOperations & DELAYED_BG_TAXI_RESTORE)
+ {
+ if (m_bgData.HasTaxiPath())
+ {
+ m_taxi.AddTaxiDestination(m_bgData.taxiPath[0]);
+ m_taxi.AddTaxiDestination(m_bgData.taxiPath[1]);
+ m_bgData.ClearTaxiPath();
+
+ ContinueTaxiFlight();
+ }
+ }
+
+ //we have executed ALL delayed ops, so clear the flag
+ m_DelayedOperations = 0;
+}
+
+void Player::AddToWorld()
+{
+ ///- Do not add/remove the player from the object storage
+ ///- It will crash when updating the ObjectAccessor
+ ///- The player should only be added when logging in
+ Unit::AddToWorld();
+
+ for (uint8 i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
+ if(m_items[i])
+ m_items[i]->AddToWorld();
+}
+
+void Player::RemoveFromWorld()
+{
+ // cleanup
+ if(IsInWorld())
+ {
+ ///- Release charmed creatures, unsummon totems and remove pets/guardians
+ StopCastingCharm();
+ StopCastingBindSight();
+ UnsummonPetTemporaryIfAny();
+ sOutdoorPvPMgr.HandlePlayerLeaveZone(this, m_zoneUpdateId);
+ }
+
+ ///- Do not add/remove the player from the object storage
+ ///- It will crash when updating the ObjectAccessor
+ ///- The player should only be removed when logging out
+ Unit::RemoveFromWorld();
+
+ for (uint8 i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
+ {
+ if (m_items[i])
+ m_items[i]->RemoveFromWorld();
+ }
+
+ for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
+ iter->second->RemoveFromWorld();
+
+ if (m_uint32Values)
+ {
+ if (WorldObject *viewpoint = GetViewpoint())
+ {
+ sLog.outCrash("Player %s has viewpoint %u %u when removed from world", GetName(), viewpoint->GetEntry(), viewpoint->GetTypeId());
+ SetViewpoint(viewpoint, false);
+ }
+ }
+}
+
+void Player::RegenerateAll()
+{
+ //if (m_regenTimer <= 500)
+ // return;
+
+ m_regenTimerCount += m_regenTimer;
+
+ Regenerate(POWER_ENERGY);
+
+ Regenerate(POWER_MANA);
+
+ // Runes act as cooldowns, and they don't need to send any data
+ if(getClass() == CLASS_DEATH_KNIGHT)
+ for (uint32 i = 0; i < MAX_RUNES; ++i)
+ if(uint32 cd = GetRuneCooldown(i))
+ SetRuneCooldown(i, (cd > m_regenTimer) ? cd - m_regenTimer : 0);
+
+ if (m_regenTimerCount >= 2000)
+ {
+ // Not in combat or they have regeneration
+ if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
+ HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
+ {
+ RegenerateHealth();
+ }
+
+ Regenerate(POWER_RAGE);
+ if (getClass() == CLASS_DEATH_KNIGHT)
+ Regenerate(POWER_RUNIC_POWER);
+
+ m_regenTimerCount -= 2000;
+ }
+
+ m_regenTimer = 0;
+}
+
+void Player::Regenerate(Powers power)
+{
+ uint32 maxValue = GetMaxPower(power);
+ if (!maxValue)
+ return;
+
+ uint32 curValue = GetPower(power);
+
+ // TODO: possible use of miscvalueb instead of amount
+ if (HasAuraTypeWithValue(SPELL_AURA_PREVENT_REGENERATE_POWER, power))
+ return;
+
+ float addvalue = 0.0f;
+
+ switch (power)
+ {
+ case POWER_MANA:
+ {
+ bool recentCast = IsUnderLastManaUseEffect();
+ float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
+
+ if (getLevel() < 15)
+ ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA) * (2.066f - (getLevel() * 0.066f));
+
+ if (recentCast) // Trinity Updates Mana in intervals of 2s, which is correct
+ addvalue += GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 0.001f * m_regenTimer;
+ else
+ addvalue += GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 0.001f * m_regenTimer;
+ } break;
+ case POWER_RAGE: // Regenerate rage
+ {
+ if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
+ {
+ float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
+ addvalue += -20 * RageDecreaseRate; // 2 rage by tick (= 2 seconds => 1 rage/sec)
+ }
+ } break;
+ case POWER_ENERGY: // Regenerate energy (rogue)
+ addvalue += 0.01f * m_regenTimer;
+ break;
+ case POWER_RUNIC_POWER:
+ {
+ if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
+ {
+ float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
+ addvalue += -30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
+ }
+ } break;
+ case POWER_RUNE:
+ case POWER_FOCUS:
+ case POWER_HAPPINESS:
+ case POWER_HEALTH:
+ break;
+ }
+
+ // Mana regen calculated in Player::UpdateManaRegen()
+ if (power != POWER_MANA)
+ {
+ AuraEffectList const& ModPowerRegenPCTAuras = GetAuraEffectsByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
+ for (AuraEffectList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
+ if ((*i)->GetMiscValue() == power)
+ addvalue *= ((*i)->GetAmount() + 100) / 100.0f;
+
+ // Butchery requires combat for this effect
+ if (power != POWER_RUNIC_POWER || isInCombat())
+ addvalue += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_POWER_REGEN, power) * ((power != POWER_ENERGY) ? m_regenTimerCount : m_regenTimer) / (5 * IN_MILISECONDS);
+ }
+
+ if (addvalue < 0.0f)
+ {
+ if (curValue == 0)
+ return;
+ }
+ else if (addvalue > 0.0f)
+ {
+ if (curValue == maxValue)
+ return;
+ }
+ else
+ return;
+
+ addvalue += m_powerFraction[power];
+ uint32 integerValue = uint32(abs(addvalue));
+
+ if (addvalue < 0.0f)
+ {
+ if(curValue > integerValue)
+ {
+ curValue -= integerValue;
+ m_powerFraction[power] = addvalue + integerValue;
+ }
+ else
+ {
+ curValue = 0;
+ m_powerFraction[power] = 0;
+ }
+ }
+ else
+ {
+ curValue += integerValue;
+
+ if (curValue > maxValue)
+ {
+ curValue = maxValue;
+ m_powerFraction[power] = 0;
+ }
+ else
+ m_powerFraction[power] = addvalue - integerValue;
+ }
+ if(m_regenTimerCount >= 2000)
+ SetPower(power, curValue);
+ else
+ UpdateUInt32Value(UNIT_FIELD_POWER1 + power, curValue);
+}
+
+void Player::RegenerateHealth()
+{
+ uint32 curValue = GetHealth();
+ uint32 maxValue = GetMaxHealth();
+
+ if (curValue >= maxValue)
+ return;
+
+ float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
+
+ if (getLevel() < 15)
+ HealthIncreaseRate = sWorld.getRate(RATE_HEALTH) * (2.066f - (getLevel() * 0.066f));
+
+ float addvalue = 0.0f;
+
+ // polymorphed case
+ if (IsPolymorphed())
+ addvalue = GetMaxHealth()/3;
+ // normal regen case (maybe partly in combat case)
+ else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
+ {
+ addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
+ if (!isInCombat())
+ {
+ AuraEffectList const& mModHealthRegenPct = GetAuraEffectsByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
+ for (AuraEffectList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
+ addvalue *= (100.0f + (*i)->GetAmount()) / 100.0f;
+
+ addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_REGEN) * 2 * IN_MILISECONDS / (5 * IN_MILISECONDS);
+ }
+ else if (HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
+ addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
+
+ if (!IsStandState())
+ addvalue *= 1.5;
+ }
+
+ // always regeneration bonus (including combat)
+ addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
+ addvalue += m_baseHealthRegen / 2.5f;
+
+ if (addvalue < 0)
+ addvalue = 0;
+
+ ModifyHealth(int32(addvalue));
+}
+
+bool Player::CanInteractWithNPCs(bool alive) const
+{
+ if (alive && !isAlive())
+ return false;
+ if (isInFlight())
+ return false;
+
+ return true;
+}
+
+Creature*
+Player::GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask)
+{
+ // unit checks
+ if (!guid)
+ return NULL;
+
+ if (!IsInWorld())
+ return NULL;
+
+ // exist (we need look pets also for some interaction (quest/etc)
+ Creature *unit = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
+ if (!unit)
+ return NULL;
+
+ // player check
+ if (!CanInteractWithNPCs(!unit->isSpiritService()))
+ return NULL;
+
+ // appropriate npc type
+ if (npcflagmask && !unit->HasFlag(UNIT_NPC_FLAGS, npcflagmask))
+ return NULL;
+
+ // alive or spirit healer
+ if (!unit->isAlive() && (!unit->isSpiritService() || isAlive()))
+ return NULL;
+
+ // not allow interaction under control, but allow with own pets
+ if (unit->GetCharmerGUID())
+ return NULL;
+
+ // not enemy
+ if (unit->IsHostileTo(this))
+ return NULL;
+
+ // not unfriendly
+ if (FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction()))
+ if (factionTemplate->faction)
+ if (FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
+ if (faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
+ return NULL;
+
+ // not too far
+ if (!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE))
+ return NULL;
+
+ return unit;
+}
+
+GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const
+{
+ if (GameObject *go = GetMap()->GetGameObject(guid))
+ {
+ if (go->GetGoType() == type)
+ {
+ float maxdist;
+ switch (type)
+ {
+ // TODO: find out how the client calculates the maximal usage distance to spellless working
+ // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
+ case GAMEOBJECT_TYPE_GUILD_BANK:
+ case GAMEOBJECT_TYPE_MAILBOX:
+ maxdist = 10.0f;
+ break;
+ case GAMEOBJECT_TYPE_FISHINGHOLE:
+ maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
+ break;
+ default:
+ maxdist = INTERACTION_DISTANCE;
+ break;
+ }
+
+ if (go->IsWithinDistInMap(this, maxdist))
+ return go;
+
+ sLog.outDebug("IsGameObjectOfTypeInRange: GameObject '%s' [GUID: %u] is too far away from player %s [GUID: %u] to be used by him (distance=%f, maximal 10 is allowed)", go->GetGOInfo()->name,
+ go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
+ }
+ }
+ return NULL;
+}
+
+bool Player::IsUnderWater() const
+{
+ return IsInWater() &&
+ GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(),GetPositionY())-2);
+}
+
+void Player::SetInWater(bool apply)
+{
+ if(m_isInWater==apply)
+ return;
+
+ //define player in water by opcodes
+ //move player's guid into HateOfflineList of those mobs
+ //which can't swim and move guid back into ThreatList when
+ //on surface.
+ //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
+ m_isInWater = apply;
+
+ // remove auras that need water/land
+ RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
+
+ getHostilRefManager().updateThreatTables();
+}
+
+void Player::SetGameMaster(bool on)
+{
+ if(on)
+ {
+ m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
+ setFaction(35);
+ SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
+
+ if (Pet* pet = GetPet())
+ {
+ pet->setFaction(35);
+ pet->getHostilRefManager().setOnlineOfflineState(false);
+ }
+
+ RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
+ ResetContestedPvP();
+
+ getHostilRefManager().setOnlineOfflineState(false);
+ CombatStopWithPets();
+
+ SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
+ }
+ else
+ {
+ // restore phase
+ AuraEffectList const& phases = GetAuraEffectsByType(SPELL_AURA_PHASE);
+ SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
+
+ m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
+ setFactionForRace(getRace());
+ RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
+
+ if (Pet* pet = GetPet())
+ {
+ pet->setFaction(getFaction());
+ pet->getHostilRefManager().setOnlineOfflineState(true);
+ }
+
+ // restore FFA PvP Server state
+ if(sWorld.IsFFAPvPRealm())
+ SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
+
+ // restore FFA PvP area state, remove not allowed for GM mounts
+ UpdateArea(m_areaUpdateId);
+
+ getHostilRefManager().setOnlineOfflineState(true);
+ }
+
+ //ObjectAccessor::UpdateVisibilityForPlayer(this);
+ SetToNotify();
+}
+
+void Player::SetGMVisible(bool on)
+{
+ if(on)
+ {
+ m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
+
+ // Reapply stealth/invisibility if active or show if not any
+ if(HasAuraType(SPELL_AURA_MOD_STEALTH))
+ SetVisibility(VISIBILITY_GROUP_STEALTH);
+ //else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
+ // SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
+ else
+ SetVisibility(VISIBILITY_ON);
+ }
+ else
+ {
+ m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
+
+ SetAcceptWhispers(false);
+ SetGameMaster(true);
+
+ SetVisibility(VISIBILITY_OFF);
+ }
+}
+
+bool Player::IsGroupVisibleFor(Player* p) const
+{
+ switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
+ {
+ default: return IsInSameGroupWith(p);
+ case 1: return IsInSameRaidWith(p);
+ case 2: return GetTeam()==p->GetTeam();
+ }
+}
+
+bool Player::IsInSameGroupWith(Player const* p) const
+{
+ return (p==this || (GetGroup() != NULL &&
+ GetGroup() == p->GetGroup() &&
+ GetGroup()->SameSubGroup((Player*)this, (Player*)p)));
+}
+
+///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
+/// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
+void Player::UninviteFromGroup()
+{
+ Group* group = GetGroupInvite();
+ if(!group)
+ return;
+
+ group->RemoveInvite(this);
+
+ if(group->GetMembersCount() <= 1) // group has just 1 member => disband
+ {
+ if(group->IsCreated())
+ {
+ group->Disband(true);
+ objmgr.RemoveGroup(group);
+ }
+ else
+ group->RemoveAllInvites();
+
+ delete group;
+ }
+}
+
+void Player::RemoveFromGroup(Group* group, uint64 guid)
+{
+ if(group)
+ {
+ if (group->RemoveMember(guid, 0) <= 1)
+ {
+ // group->Disband(); already disbanded in RemoveMember
+ objmgr.RemoveGroup(group);
+ delete group;
+ // removemember sets the player's group pointer to NULL
+ }
+ }
+}
+
+void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
+{
+ WorldPacket data(SMSG_LOG_XPGAIN, 21);
+ data << uint64(victim ? victim->GetGUID() : 0); // guid
+ data << uint32(GivenXP+RestXP); // given experience
+ data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
+ if(victim)
+ {
+ data << uint32(GivenXP); // experience without rested bonus
+ data << float(1); // 1 - none 0 - 100% group bonus output
+ }
+ data << uint8(0); // new 2.4.0
+ GetSession()->SendPacket(&data);
+}
+
+void Player::GiveXP(uint32 xp, Unit* victim)
+{
+ if ( xp < 1 )
+ return;
+
+ if(!isAlive())
+ return;
+
+ if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_NO_XP_GAIN))
+ return;
+
+ uint8 level = getLevel();
+
+ // Favored experience increase START
+ uint32 zone = GetZoneId();
+ float favored_exp_mult = 0;
+ if( (HasAura(32096) || HasAura(32098)) && (zone == 3483 || zone == 3562 || zone == 3836 || zone == 3713 || zone == 3714) ) favored_exp_mult = 0.05; // Thrallmar's Favor and Honor Hold's Favor
+ xp *= (1 + favored_exp_mult);
+ // Favored experience increase END
+
+ // XP to money conversion processed in Player::RewardQuest
+ if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
+ return;
+
+ // XP resting bonus for kill
+ uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
+
+ // Heirloom Experience Bonus
+ float heirloomModifier = 1.0f;
+ for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
+ if (m_items[i] && m_items[i]->GetProto()->Spells->SpellId == 57353)
+ heirloomModifier += 0.1f;
+ xp = uint32(xp * heirloomModifier);
+
+ SendLogXPGain(xp,victim,rested_bonus_xp);
+
+ uint32 curXP = GetUInt32Value(PLAYER_XP);
+ uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
+ uint32 newXP = curXP + xp + rested_bonus_xp;
+
+ while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
+ {
+ newXP -= nextLvlXP;
+
+ if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
+ GiveLevel(level + 1);
+
+ level = getLevel();
+ nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
+ }
+ newXP = GetSession()->HandleOnGetXP(newXP);
+ SetUInt32Value(PLAYER_XP, newXP);
+}
+
+// Update player to next level
+// Current player experience not update (must be update by caller)
+void Player::GiveLevel(uint8 level)
+{
+ if (level == getLevel())
+ return;
+
+ PlayerLevelInfo info;
+ objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
+
+ PlayerClassLevelInfo classInfo;
+ objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
+
+ // send levelup info to client
+ WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
+ data << uint32(level);
+ data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
+ // for (int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
+ data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
+ data << uint32(0);
+ data << uint32(0);
+ data << uint32(0);
+ data << uint32(0);
+ data << uint32(0);
+ data << uint32(0);
+ // end for
+ for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
+ data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
+
+ GetSession()->SendPacket(&data);
+
+ SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level));
+
+ //update level, max level of skills
+ m_Played_time[PLAYED_TIME_LEVEL] = 0; // Level Played Time reset
+
+ _ApplyAllLevelScaleItemMods(false);
+
+ SetLevel(level);
+
+ UpdateSkillsForLevel();
+
+ // save base values (bonuses already included in stored stats
+ for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i)
+ SetCreateStat(Stats(i), info.stats[i]);
+
+ SetCreateHealth(classInfo.basehealth);
+ SetCreateMana(classInfo.basemana);
+
+ InitTalentForLevel();
+ InitTaxiNodesForLevel();
+ InitGlyphsForLevel();
+
+ UpdateAllStats();
+
+ if(sWorld.getConfig(CONFIG_ALWAYS_MAXSKILL)) // Max weapon skill when leveling up
+ UpdateSkillsToMaxSkillsForLevel();
+
+ // set current level health and mana/energy to maximum after applying all mods.
+ SetHealth(GetMaxHealth());
+ SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
+ SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
+ if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
+ SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
+ SetPower(POWER_FOCUS, 0);
+ SetPower(POWER_HAPPINESS, 0);
+
+ _ApplyAllLevelScaleItemMods(true);
+
+ // update level to hunter/summon pet
+ if (Pet* pet = GetPet())
+ pet->SynchronizeLevelWithOwner();
+
+ if (MailLevelReward const* mailReward = objmgr.GetMailLevelReward(level,getRaceMask()))
+ MailDraft(mailReward->mailTemplateId).SendMailTo(this,MailSender(MAIL_CREATURE,mailReward->senderEntry));
+
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
+}
+
+void Player::InitTalentForLevel()
+{
+ uint8 level = getLevel();
+ // talents base at level diff ( talents = level - 9 but some can be used already)
+ if (level < 10)
+ {
+ // Remove all talent points
+ if(m_usedTalentCount > 0) // Free any used talents
+ {
+ resetTalents(true);
+ SetFreeTalentPoints(0);
+ }
+ }
+ else
+ {
+ if (level < sWorld.getConfig(CONFIG_MIN_DUALSPEC_LEVEL) || m_specsCount == 0)
+ {
+ m_specsCount = 1;
+ m_activeSpec = 0;
+ }
+
+ uint32 talentPointsForLevel = CalculateTalentsPoints();
+
+ // if used more that have then reset
+ if(m_usedTalentCount > talentPointsForLevel)
+ {
+ if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
+ resetTalents(true);
+ else
+ SetFreeTalentPoints(0);
+ }
+ // else update amount of free points
+ else
+ SetFreeTalentPoints(talentPointsForLevel - m_usedTalentCount);
+ }
+
+ if(!GetSession()->PlayerLoading())
+ SendTalentsInfoData(false); // update at client
+}
+
+void Player::InitStatsForLevel(bool reapplyMods)
+{
+ if (reapplyMods) //reapply stats values only on .reset stats (level) command
+ _RemoveAllStatBonuses();
+
+ PlayerClassLevelInfo classInfo;
+ objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
+
+ PlayerLevelInfo info;
+ objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
+
+ SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
+ SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel()));
+
+ // reset before any aura state sources (health set/aura apply)
+ SetUInt32Value(UNIT_FIELD_AURASTATE, 0);
+
+ UpdateSkillsForLevel ();
+
+ // set default cast time multiplier
+ SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
+
+ // reset size before reapply auras
+ SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
+
+ // save base values (bonuses already included in stored stats
+ for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i)
+ SetCreateStat(Stats(i), info.stats[i]);
+
+ for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i)
+ SetStat(Stats(i), info.stats[i]);
+
+ SetCreateHealth(classInfo.basehealth);
+
+ //set create powers
+ SetCreateMana(classInfo.basemana);
+
+ SetArmor(int32(m_createStats[STAT_AGILITY]*2));
+
+ InitStatBuffMods();
+
+ //reset rating fields values
+ for (uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
+ SetUInt32Value(index, 0);
+
+ SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
+ for (uint8 i = 0; i < 7; ++i)
+ {
+ SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
+ SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
+ SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
+ }
+
+ //reset attack power, damage and attack speed fields
+ SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f);
+ SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f); // offhand attack time
+ SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f);
+
+ SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f);
+ SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f);
+ SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f);
+ SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f);
+ SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f);
+ SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f);
+
+ SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0);
+ SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0);
+ SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
+ SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0);
+ SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0);
+ SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
+
+ // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
+ SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
+ SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
+ SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
+
+ // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
+ for (uint8 i = 0; i < 7; ++i)
+ SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
+
+ SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
+ SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
+ SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
+
+ // Dodge percentage
+ SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
+
+ // set armor (resistance 0) to original value (create_agility*2)
+ SetArmor(int32(m_createStats[STAT_AGILITY]*2));
+ SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
+ SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
+ // set other resistance to original value (0)
+ for (uint8 i = 1; i < MAX_SPELL_SCHOOL; ++i)
+ {
+ SetResistance(SpellSchools(i), 0);
+ SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
+ SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
+ }
+
+ SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
+ SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
+ for (uint8 i = 0; i < MAX_SPELL_SCHOOL; ++i)
+ {
+ SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
+ SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
+ }
+ // Reset no reagent cost field
+ for (uint8 i = 0; i < 3; ++i)
+ SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
+ // Init data for form but skip reapply item mods for form
+ InitDataForForm(reapplyMods);
+
+ // save new stats
+ for (uint8 i = POWER_MANA; i < MAX_POWERS; ++i)
+ SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
+
+ SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
+
+ // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
+ SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
+
+ // cleanup unit flags (will be re-applied if need at aura load).
+ RemoveFlag( UNIT_FIELD_FLAGS,
+ UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
+ UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
+ UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
+ UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
+ UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
+ SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
+
+ SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
+
+ // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
+ RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST | PLAYER_ALLOW_ONLY_ABILITY);
+
+ RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
+ RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
+
+ // restore if need some important flags
+ SetUInt32Value(PLAYER_FIELD_BYTES2, 0); // flags empty by default
+
+ if (reapplyMods) // reapply stats values only on .reset stats (level) command
+ _ApplyAllStatBonuses();
+
+ // set current level health and mana/energy to maximum after applying all mods.
+ SetHealth(GetMaxHealth());
+ SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
+ SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
+ if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
+ SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
+ SetPower(POWER_FOCUS, 0);
+ SetPower(POWER_HAPPINESS, 0);
+ SetPower(POWER_RUNIC_POWER, 0);
+
+ // update level to hunter/summon pet
+ if (Pet* pet = GetPet())
+ pet->SynchronizeLevelWithOwner();
+}
+
+void Player::SendInitialSpells()
+{
+ time_t curTime = time(NULL);
+ time_t infTime = curTime + infinityCooldownDelayCheck;
+
+ uint16 spellCount = 0;
+
+ WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
+ data << uint8(0);
+
+ size_t countPos = data.wpos();
+ data << uint16(spellCount); // spell count placeholder
+
+ for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
+ {
+ if(itr->second->state == PLAYERSPELL_REMOVED)
+ continue;
+
+ if(!itr->second->active || itr->second->disabled)
+ continue;
+
+ data << uint32(itr->first);
+ data << uint16(0); // it's not slot id
+
+ spellCount +=1;
+ }
+
+ data.put<uint16>(countPos,spellCount); // write real count value
+
+ uint16 spellCooldowns = m_spellCooldowns.size();
+ data << uint16(spellCooldowns);
+ for (SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
+ {
+ SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
+ if(!sEntry)
+ continue;
+
+ data << uint32(itr->first);
+
+ data << uint16(itr->second.itemid); // cast item id
+ data << uint16(sEntry->Category); // spell category
+
+ // send infinity cooldown in special format
+ if(itr->second.end >= infTime)
+ {
+ data << uint32(1); // cooldown
+ data << uint32(0x80000000); // category cooldown
+ continue;
+ }
+
+ time_t cooldown = itr->second.end > curTime ? (itr->second.end-curTime)*IN_MILISECONDS : 0;
+
+ if(sEntry->Category) // may be wrong, but anyway better than nothing...
+ {
+ data << uint32(0); // cooldown
+ data << uint32(cooldown); // category cooldown
+ }
+ else
+ {
+ data << uint32(cooldown); // cooldown
+ data << uint32(0); // category cooldown
+ }
+ }
+
+ GetSession()->SendPacket(&data);
+
+ sLog.outDetail( "CHARACTER: Sent Initial Spells" );
+}
+
+void Player::RemoveMail(uint32 id)
+{
+ for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
+ {
+ if ((*itr)->messageID == id)
+ {
+ //do not delete item, because Player::removeMail() is called when returning mail to sender.
+ m_mail.erase(itr);
+ return;
+ }
+ }
+}
+
+void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
+{
+ WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
+ data << (uint32) mailId;
+ data << (uint32) mailAction;
+ data << (uint32) mailError;
+ if ( mailError == MAIL_ERR_EQUIP_ERROR )
+ data << (uint32) equipError;
+ else if( mailAction == MAIL_ITEM_TAKEN )
+ {
+ data << (uint32) item_guid; // item guid low?
+ data << (uint32) item_count; // item count?
+ }
+ GetSession()->SendPacket(&data);
+}
+
+void Player::SendNewMail()
+{
+ // deliver undelivered mail
+ WorldPacket data(SMSG_RECEIVED_MAIL, 4);
+ data << (uint32) 0;
+ GetSession()->SendPacket(&data);
+}
+
+void Player::UpdateNextMailTimeAndUnreads()
+{
+ // calculate next delivery time (min. from non-delivered mails
+ // and recalculate unReadMail
+ time_t cTime = time(NULL);
+ m_nextMailDelivereTime = 0;
+ unReadMails = 0;
+ for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
+ {
+ if((*itr)->deliver_time > cTime)
+ {
+ if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
+ m_nextMailDelivereTime = (*itr)->deliver_time;
+ }
+ else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
+ ++unReadMails;
+ }
+}
+
+void Player::AddNewMailDeliverTime(time_t deliver_time)
+{
+ if(deliver_time <= time(NULL)) // ready now
+ {
+ ++unReadMails;
+ SendNewMail();
+ }
+ else // not ready and no have ready mails
+ {
+ if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
+ m_nextMailDelivereTime = deliver_time;
+ }
+}
+
+bool Player::AddTalent(uint32 spell_id, uint8 spec, bool learning)
+{
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
+ if (!spellInfo)
+ {
+ // do character spell book cleanup (all characters)
+ if(!IsInWorld() && !learning) // spell load case
+ {
+ sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
+ CharacterDatabase.PExecute("DELETE FROM character_talent WHERE spell = '%u'",spell_id);
+ }
+ else
+ sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
+
+ return false;
+ }
+
+ if(!SpellMgr::IsSpellValid(spellInfo,this,false))
+ {
+ // do character spell book cleanup (all characters)
+ if(!IsInWorld() && !learning) // spell load case
+ {
+ sLog.outError("Player::addTalent: Broken spell #%u learning not allowed, deleting for all characters in `character_talent`.",spell_id);
+ CharacterDatabase.PExecute("DELETE FROM character_talent WHERE spell = '%u'",spell_id);
+ }
+ else
+ sLog.outError("Player::addTalent: Broken spell #%u learning not allowed.",spell_id);
+
+ return false;
+ }
+
+ PlayerTalentMap::iterator itr = m_talents[spec]->find(spell_id);
+ if (itr != m_talents[spec]->end())
+ itr->second->state = PLAYERSPELL_UNCHANGED;
+ else if (TalentSpellPos const *talentPos = GetTalentSpellPos(spell_id))
+ {
+ if (TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
+ {
+ for (uint8 rank = 0; rank < MAX_TALENT_RANK; ++rank)
+ {
+ // skip learning spell and no rank spell case
+ uint32 rankSpellId = talentInfo->RankID[rank];
+ if (!rankSpellId || rankSpellId == spell_id)
+ continue;
+
+ PlayerTalentMap::iterator itr = m_talents[spec]->find(rankSpellId);
+ if (itr != m_talents[spec]->end())
+ itr->second->state = PLAYERSPELL_REMOVED;
+ }
+ }
+
+ PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
+ PlayerTalent *newtalent = new PlayerTalent();
+
+ newtalent->state = state;
+ newtalent->spec = spec;
+
+ (*m_talents[spec])[spell_id] = newtalent;
+ return true;
+ }
+ return false;
+}
+
+bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
+{
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
+ if (!spellInfo)
+ {
+ // do character spell book cleanup (all characters)
+ if(!IsInWorld() && !learning) // spell load case
+ {
+ sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
+ CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
+ }
+ else
+ sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
+
+ return false;
+ }
+
+ if(!SpellMgr::IsSpellValid(spellInfo,this,false))
+ {
+ // do character spell book cleanup (all characters)
+ if(!IsInWorld() && !learning) // spell load case
+ {
+ sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
+ CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
+ }
+ else
+ sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
+
+ return false;
+ }
+
+ PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
+
+ bool dependent_set = false;
+ bool disabled_case = false;
+ bool superceded_old = false;
+
+ PlayerSpellMap::iterator itr = m_spells.find(spell_id);
+
+ // Remove temporary spell if found to prevent conflicts
+ if (itr != m_spells.end() && itr->second->state == PLAYERSPELL_TEMPORARY)
+ RemoveTemporarySpell(spell_id);
+ else if (itr != m_spells.end())
+ {
+ uint32 next_active_spell_id = 0;
+ // fix activate state for non-stackable low rank (and find next spell for !active case)
+ if(!SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
+ {
+ if(uint32 next = spellmgr.GetNextSpellInChain(spell_id))
+ {
+ if(HasSpell(next))
+ {
+ // high rank already known so this must !active
+ active = false;
+ next_active_spell_id = next;
+ }
+ }
+ }
+
+ // not do anything if already known in expected state
+ if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
+ itr->second->dependent == dependent && itr->second->disabled == disabled)
+ {
+ if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
+ itr->second->state = PLAYERSPELL_UNCHANGED;
+
+ return false;
+ }
+
+ // dependent spell known as not dependent, overwrite state
+ if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
+ {
+ itr->second->dependent = dependent;
+ if (itr->second->state != PLAYERSPELL_NEW)
+ itr->second->state = PLAYERSPELL_CHANGED;
+ dependent_set = true;
+ }
+
+ // update active state for known spell
+ if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
+ {
+ itr->second->active = active;
+
+ if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
+ itr->second->state = PLAYERSPELL_UNCHANGED;
+ else if(itr->second->state != PLAYERSPELL_NEW)
+ itr->second->state = PLAYERSPELL_CHANGED;
+
+ if(active)
+ {
+ if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
+ CastSpell (this,spell_id,true);
+ }
+ else if(IsInWorld())
+ {
+ if(next_active_spell_id)
+ {
+ // update spell ranks in spellbook and action bar
+ WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
+ data << uint32(spell_id);
+ data << uint32(next_active_spell_id);
+ GetSession()->SendPacket( &data );
+ }
+ else
+ {
+ WorldPacket data(SMSG_REMOVED_SPELL, 4);
+ data << uint32(spell_id);
+ GetSession()->SendPacket(&data);
+ }
+ }
+
+ return active; // learn (show in spell book if active now)
+ }
+
+ if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
+ {
+ if(itr->second->state != PLAYERSPELL_NEW)
+ itr->second->state = PLAYERSPELL_CHANGED;
+ itr->second->disabled = disabled;
+
+ if(disabled)
+ return false;
+
+ disabled_case = true;
+ }
+ else switch(itr->second->state)
+ {
+ case PLAYERSPELL_UNCHANGED: // known saved spell
+ return false;
+ case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
+ {
+ delete itr->second;
+ m_spells.erase(itr);
+ state = PLAYERSPELL_CHANGED;
+ break; // need re-add
+ }
+ default: // known not saved yet spell (new or modified)
+ {
+ // can be in case spell loading but learned at some previous spell loading
+ if(!IsInWorld() && !learning && !dependent_set)
+ itr->second->state = PLAYERSPELL_UNCHANGED;
+
+ return false;
+ }
+ }
+ }
+
+ if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
+ {
+ // talent: unlearn all other talent ranks (high and low)
+ if(TalentSpellPos const *talentPos = GetTalentSpellPos(spell_id))
+ {
+ if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
+ {
+ for (uint8 rank = 0; rank < MAX_TALENT_RANK; ++rank)
+ {
+ // skip learning spell and no rank spell case
+ uint32 rankSpellId = talentInfo->RankID[rank];
+ if(!rankSpellId || rankSpellId == spell_id)
+ continue;
+
+ removeSpell(rankSpellId,false,false);
+ }
+ }
+ }
+ // non talent spell: learn low ranks (recursive call)
+ else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
+ {
+ if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
+ addSpell(prev_spell,active,true,true,disabled);
+ else // at normal learning
+ learnSpell(prev_spell,true);
+ }
+
+ PlayerSpell *newspell = new PlayerSpell;
+ newspell->state = state;
+ newspell->active = active;
+ newspell->dependent = dependent;
+ newspell->disabled = disabled;
+
+ // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
+ if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
+ {
+ for (PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
+ {
+ if(itr2->second->state == PLAYERSPELL_REMOVED) continue;
+ SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
+ if(!i_spellInfo) continue;
+
+ if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
+ {
+ if(itr2->second->active)
+ {
+ if(spellmgr.IsHighRankOfSpell(spell_id,itr2->first))
+ {
+ if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
+ {
+ WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
+ data << uint32(itr2->first);
+ data << uint32(spell_id);
+ GetSession()->SendPacket( &data );
+ }
+
+ // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
+ itr2->second->active = false;
+ if(itr2->second->state != PLAYERSPELL_NEW)
+ itr2->second->state = PLAYERSPELL_CHANGED;
+ superceded_old = true; // new spell replace old in action bars and spell book.
+ }
+ else if(spellmgr.IsHighRankOfSpell(itr2->first,spell_id))
+ {
+ if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
+ {
+ WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
+ data << uint32(spell_id);
+ data << uint32(itr2->first);
+ GetSession()->SendPacket( &data );
+ }
+
+ // mark new spell as disable (not learned yet for client and will not learned)
+ newspell->active = false;
+ if(newspell->state != PLAYERSPELL_NEW)
+ newspell->state = PLAYERSPELL_CHANGED;
+ }
+ }
+ }
+ }
+ }
+
+ m_spells[spell_id] = newspell;
+
+ // return false if spell disabled
+ if (newspell->disabled)
+ return false;
+ }
+
+ uint32 talentCost = GetTalentSpellCost(spell_id);
+
+ // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
+ // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
+ if (talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL))
+ {
+ // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
+ CastSpell(this, spell_id, true);
+ }
+ // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
+ else if (IsPassiveSpell(spell_id))
+ {
+ if (IsNeedCastPassiveSpellAtLearn(spellInfo))
+ CastSpell(this, spell_id, true);
+ }
+ else if (IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP))
+ {
+ CastSpell(this, spell_id, true);
+ return false;
+ }
+
+ // update used talent points count
+ m_usedTalentCount += talentCost;
+
+ // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
+ if (uint32 freeProfs = GetFreePrimaryProfessionPoints())
+ {
+ if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
+ SetFreePrimaryProfessions(freeProfs-1);
+ }
+
+ // add dependent skills
+ uint16 maxskill = GetMaxSkillValueForLevel();
+
+ SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
+
+ SkillLineAbilityMapBounds skill_bounds = spellmgr.GetSkillLineAbilityMapBounds(spell_id);
+
+ if (spellLearnSkill)
+ {
+ uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
+ uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
+
+ if (skill_value < spellLearnSkill->value)
+ skill_value = spellLearnSkill->value;
+
+ uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
+
+ if (skill_max_value < new_skill_max_value)
+ skill_max_value = new_skill_max_value;
+
+ SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
+ }
+ else
+ {
+ // not ranked skills
+ for (SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
+ {
+ SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
+ if (!pSkill)
+ continue;
+
+ if (HasSkill(pSkill->id))
+ continue;
+
+ if (_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
+ // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
+ ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
+ {
+ switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
+ {
+ case SKILL_RANGE_LANGUAGE:
+ SetSkill(pSkill->id, 300, 300 );
+ break;
+ case SKILL_RANGE_LEVEL:
+ SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
+ break;
+ case SKILL_RANGE_MONO:
+ SetSkill(pSkill->id, 1, 1 );
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ }
+
+ // learn dependent spells
+ SpellLearnSpellMapBounds spell_bounds = spellmgr.GetSpellLearnSpellMapBounds(spell_id);
+
+ for (SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
+ {
+ if (!itr2->second.autoLearned)
+ {
+ if (!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
+ addSpell(itr2->second.spell,itr2->second.active,true,true,false);
+ else // at normal learning
+ learnSpell(itr2->second.spell,true);
+ }
+ }
+
+ if (!GetSession()->PlayerLoading())
+ {
+ // not ranked skills
+ for (SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
+ {
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
+ }
+
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
+ }
+
+ // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
+ return active && !disabled && !superceded_old;
+}
+
+void Player::AddTemporarySpell(uint32 spellId)
+{
+ PlayerSpellMap::iterator itr = m_spells.find(spellId);
+ // spell already added - do not do anything
+ if (itr != m_spells.end())
+ return;
+ PlayerSpell *newspell = new PlayerSpell;
+ newspell->state = PLAYERSPELL_TEMPORARY;
+ newspell->active = true;
+ newspell->dependent = false;
+ newspell->disabled = false;
+ m_spells[spellId] = newspell;
+}
+
+void Player::RemoveTemporarySpell(uint32 spellId)
+{
+ PlayerSpellMap::iterator itr = m_spells.find(spellId);
+ // spell already not in list - do not do anything
+ if (itr == m_spells.end())
+ return;
+ // spell has other state than temporary - do not change it
+ if (itr->second->state != PLAYERSPELL_TEMPORARY)
+ return;
+ delete itr->second;
+ m_spells.erase(itr);
+}
+
+bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
+{
+ // note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell
+ // talent dependent passives activated at form apply have proper stance data
+ bool need_cast = (!spellInfo->Stances || (m_form != 0 && (spellInfo->Stances & (1<<(m_form-1)))));
+
+ //Check CasterAuraStates
+ return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
+}
+
+void Player::learnSpell(uint32 spell_id, bool dependent)
+{
+ PlayerSpellMap::iterator itr = m_spells.find(spell_id);
+
+ bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
+ bool active = disabled ? itr->second->active : true;
+
+ bool learning = addSpell(spell_id,active,true,dependent,false);
+
+ // learn all disabled higher ranks (recursive)
+ if (disabled)
+ {
+ SpellChainNode const* node = spellmgr.GetSpellChainNode(spell_id);
+ if (node)
+ {
+ PlayerSpellMap::iterator iter = m_spells.find(node->next);
+ if (iter != m_spells.end() && iter->second->disabled)
+ learnSpell(node->next,false);
+ }
+ }
+
+ // prevent duplicated entires in spell book, also not send if not in world (loading)
+ if (!learning || !IsInWorld())
+ return;
+
+ WorldPacket data(SMSG_LEARNED_SPELL, 4);
+ data << uint32(spell_id);
+ GetSession()->SendPacket(&data);
+}
+
+void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank)
+{
+ PlayerSpellMap::iterator itr = m_spells.find(spell_id);
+ if (itr == m_spells.end())
+ return;
+
+ if (itr->second->state == PLAYERSPELL_REMOVED || (disabled && itr->second->disabled) || itr->second->state == PLAYERSPELL_TEMPORARY)
+ return;
+
+ // unlearn non talent higher ranks (recursive)
+ if (SpellChainNode const* node = spellmgr.GetSpellChainNode(spell_id))
+ {
+ if (HasSpell(node->next) && !GetTalentSpellPos(node->next))
+ removeSpell(node->next,disabled, false);
+ }
+ //unlearn spells dependent from recently removed spells
+ SpellsRequiringSpellMapBounds spellsRequiringSpell = spellmgr.GetSpellsRequiringSpellBounds(spell_id);
+ for (SpellsRequiringSpellMap::const_iterator itr2 = spellsRequiringSpell.first; itr2 != spellsRequiringSpell.second; ++itr2)
+ removeSpell(itr2->second,disabled);
+
+ // re-search, it can be corrupted in prev loop
+ itr = m_spells.find(spell_id);
+ if (itr == m_spells.end())
+ return; // already unleared
+
+ bool cur_active = itr->second->active;
+ bool cur_dependent = itr->second->dependent;
+
+ if (disabled)
+ {
+ itr->second->disabled = disabled;
+ if (itr->second->state != PLAYERSPELL_NEW)
+ itr->second->state = PLAYERSPELL_CHANGED;
+ }
+ else
+ {
+ if (itr->second->state == PLAYERSPELL_NEW)
+ {
+ delete itr->second;
+ m_spells.erase(itr);
+ }
+ else
+ itr->second->state = PLAYERSPELL_REMOVED;
+ }
+
+ RemoveAurasDueToSpell(spell_id);
+
+ // remove pet auras
+ for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
+ if (PetAura const *petSpell = spellmgr.GetPetAura(spell_id, i))
+ RemovePetAura(petSpell);
+
+ // free talent points
+ uint32 talentCosts = GetTalentSpellCost(spell_id);
+ if (talentCosts > 0)
+ {
+ if (talentCosts < m_usedTalentCount)
+ m_usedTalentCount -= talentCosts;
+ else
+ m_usedTalentCount = 0;
+ }
+
+ // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
+ if (spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
+ {
+ uint32 freeProfs = GetFreePrimaryProfessionPoints()+1;
+ if (freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
+ SetFreePrimaryProfessions(freeProfs);
+ }
+
+ // remove dependent skill
+ SpellLearnSkillNode const *spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
+ if (spellLearnSkill)
+ {
+ uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
+ if (!prev_spell) // first rank, remove skill
+ SetSkill(spellLearnSkill->skill,0,0);
+ else
+ {
+ // search prev. skill setting by spell ranks chain
+ SpellLearnSkillNode const *prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
+ while (!prevSkill && prev_spell)
+ {
+ prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
+ prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
+ }
+
+ if (!prevSkill) // not found prev skill setting, remove skill
+ SetSkill(spellLearnSkill->skill,0,0);
+ else // set to prev. skill setting values
+ {
+ uint32 skill_value = GetPureSkillValue(prevSkill->skill);
+ uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
+
+ if (skill_value > prevSkill->value)
+ skill_value = prevSkill->value;
+
+ uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
+
+ if (skill_max_value > new_skill_max_value)
+ skill_max_value = new_skill_max_value;
+
+ SetSkill(prevSkill->skill,skill_value,skill_max_value);
+ }
+ }
+
+ }
+ else
+ {
+ // not ranked skills
+ SkillLineAbilityMapBounds bounds = spellmgr.GetSkillLineAbilityMapBounds(spell_id);
+
+ for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
+ {
+ SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
+ if (!pSkill)
+ continue;
+
+ if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL &&
+ pSkill->categoryId != SKILL_CATEGORY_CLASS ||// not unlearn class skills (spellbook/talent pages)
+ // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
+ ((pSkill->id == SKILL_LOCKPICKING || pSkill->id == SKILL_RUNEFORGING) && _spell_idx->second->max_value == 0))
+ {
+ // not reset skills for professions and racial abilities
+ if ((pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
+ (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0))
+ continue;
+
+ SetSkill(pSkill->id, 0, 0);
+ }
+ }
+ }
+
+ // remove dependent spells
+ SpellLearnSpellMapBounds spell_bounds = spellmgr.GetSpellLearnSpellMapBounds(spell_id);
+
+ for (SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
+ removeSpell(itr2->second.spell, disabled);
+
+ // activate lesser rank in spellbook/action bar, and cast it if need
+ bool prev_activate = false;
+
+ if (uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id))
+ {
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
+
+ // if talent then lesser rank also talent and need learn
+ if (talentCosts)
+ {
+ // I cannot see why mangos has these lines.
+ //if (learn_low_rank)
+ // learnSpell(prev_id,false);
+ }
+ // if ranked non-stackable spell: need activate lesser rank and update dendence state
+ else if (cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
+ {
+ // need manually update dependence state (learn spell ignore like attempts)
+ PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
+ if (prev_itr != m_spells.end())
+ {
+ if (prev_itr->second->dependent != cur_dependent)
+ {
+ prev_itr->second->dependent = cur_dependent;
+ if (prev_itr->second->state != PLAYERSPELL_NEW)
+ prev_itr->second->state = PLAYERSPELL_CHANGED;
+ }
+
+ // now re-learn if need re-activate
+ if (cur_active && !prev_itr->second->active && learn_low_rank)
+ {
+ if (addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
+ {
+ // downgrade spell ranks in spellbook and action bar
+ WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
+ data << uint32(spell_id);
+ data << uint32(prev_id);
+ GetSession()->SendPacket(&data);
+ prev_activate = true;
+ }
+ }
+ }
+ }
+ }
+
+ if (spell_id == 46917 && m_canTitanGrip)
+ SetCanTitanGrip(false);
+
+ if (sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_SPELL_UNLEARN))
+ AutoUnequipOffhandIfNeed();
+
+ // remove from spell book if not replaced by lesser rank
+ if (!prev_activate)
+ {
+ WorldPacket data(SMSG_REMOVED_SPELL, 4);
+ data << uint32(spell_id);
+ GetSession()->SendPacket(&data);
+ }
+}
+
+void Player::RemoveSpellCooldown( uint32 spell_id, bool update /* = false */)
+{
+ m_spellCooldowns.erase(spell_id);
+
+ if (update)
+ SendClearCooldown(spell_id, this);
+}
+
+// I am not sure which one is more efficient
+void Player::RemoveCategoryCooldown(uint32 cat)
+{
+ SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
+ if (i_scstore != sSpellCategoryStore.end())
+ for (SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
+ RemoveSpellCooldown(*i_scset, true);
+}
+
+void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */)
+{
+ SpellCategoryStore::const_iterator ct = sSpellCategoryStore.find(cat);
+ if (ct == sSpellCategoryStore.end())
+ return;
+
+ const SpellCategorySet& ct_set = ct->second;
+ for (SpellCooldowns::const_iterator i = m_spellCooldowns.begin(); i != m_spellCooldowns.end();)
+ {
+ if (ct_set.find(i->first) != ct_set.end())
+ RemoveSpellCooldown((i++)->first, update);
+ else
+ ++i;
+ }
+}
+
+void Player::RemoveArenaSpellCooldowns()
+{
+ // remove cooldowns on spells that has < 15 min CD
+ SpellCooldowns::iterator itr, next;
+ // iterate spell cooldowns
+ for (itr = m_spellCooldowns.begin(); itr != m_spellCooldowns.end(); itr = next)
+ {
+ next = itr;
+ ++next;
+ SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
+ // check if spellentry is present and if the cooldown is less than 10 mins
+ if( entry &&
+ entry->RecoveryTime <= 10 * MINUTE * IN_MILISECONDS &&
+ entry->CategoryRecoveryTime <= 10 * MINUTE * IN_MILISECONDS )
+ {
+ // remove & notify
+ RemoveSpellCooldown(itr->first, true);
+ }
+ }
+}
+
+void Player::RemoveAllSpellCooldown()
+{
+ if (!m_spellCooldowns.empty())
+ {
+ for (SpellCooldowns::const_iterator itr = m_spellCooldowns.begin(); itr != m_spellCooldowns.end(); ++itr)
+ SendClearCooldown(itr->first, this);
+
+ m_spellCooldowns.clear();
+ }
+}
+
+void Player::_LoadSpellCooldowns(QueryResult_AutoPtr result)
+{
+ // some cooldowns can be already set at aura loading...
+
+ //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
+
+ if (result)
+ {
+ time_t curTime = time(NULL);
+
+ do
+ {
+ Field *fields = result->Fetch();
+
+ uint32 spell_id = fields[0].GetUInt32();
+ uint32 item_id = fields[1].GetUInt32();
+ time_t db_time = (time_t)fields[2].GetUInt64();
+
+ if(!sSpellStore.LookupEntry(spell_id))
+ {
+ sLog.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
+ continue;
+ }
+
+ // skip outdated cooldown
+ if(db_time <= curTime)
+ continue;
+
+ AddSpellCooldown(spell_id, item_id, db_time);
+
+ sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
+ }
+ while( result->NextRow() );
+ }
+}
+
+void Player::_SaveSpellCooldowns()
+{
+ CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
+
+ time_t curTime = time(NULL);
+ time_t infTime = curTime + infinityCooldownDelayCheck;
+
+ bool first_round = true;
+ std::ostringstream ss;
+
+ // remove outdated and save active
+ for (SpellCooldowns::iterator itr = m_spellCooldowns.begin(); itr != m_spellCooldowns.end();)
+ {
+ if(itr->second.end <= curTime)
+ m_spellCooldowns.erase(itr++);
+ else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
+ {
+ if (first_round)
+ {
+ ss << "INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ";
+ first_round = false;
+ }
+ // next new/changed record prefix
+ else
+ ss << ", ";
+ ss << "(" << GetGUIDLow() << "," << itr->first << "," << itr->second.itemid << "," << uint64(itr->second.end) << ")";
+ ++itr;
+ }
+ else
+ ++itr;
+
+ }
+ // if something changed execute
+ if (!first_round)
+ CharacterDatabase.Execute( ss.str().c_str() );
+}
+
+uint32 Player::resetTalentsCost() const
+{
+ // The first time reset costs 1 gold
+ if(m_resetTalentsCost < 1*GOLD)
+ return 1*GOLD;
+ // then 5 gold
+ else if(m_resetTalentsCost < 5*GOLD)
+ return 5*GOLD;
+ // After that it increases in increments of 5 gold
+ else if(m_resetTalentsCost < 10*GOLD)
+ return 10*GOLD;
+ else
+ {
+ uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
+ if(months > 0)
+ {
+ // This cost will be reduced by a rate of 5 gold per month
+ int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
+ // to a minimum of 10 gold.
+ return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
+ }
+ else
+ {
+ // After that it increases in increments of 5 gold
+ int32 new_cost = m_resetTalentsCost + 5*GOLD;
+ // until it hits a cap of 50 gold.
+ if(new_cost > 50*GOLD)
+ new_cost = 50*GOLD;
+ return new_cost;
+ }
+ }
+}
+
+bool Player::resetTalents(bool no_cost)
+{
+ // not need after this call
+ if (HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
+ RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS, true);
+
+ uint32 talentPointsForLevel = CalculateTalentsPoints();
+
+ if (m_usedTalentCount == 0)
+ {
+ SetFreeTalentPoints(talentPointsForLevel);
+ return false;
+ }
+
+ uint32 cost = 0;
+
+ if (!no_cost && !sWorld.getConfig(CONFIG_NO_RESET_TALENT_COST))
+ {
+ cost = resetTalentsCost();
+
+ if (GetMoney() < cost)
+ {
+ SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
+ return false;
+ }
+ }
+
+ for (uint32 i = 0; i < sTalentStore.GetNumRows(); ++i)
+ {
+ TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
+
+ if (!talentInfo)
+ continue;
+
+ TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
+
+ if (!talentTabInfo)
+ continue;
+
+ // unlearn only talents for character class
+ // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
+ // to prevent unexpected lost normal learned spell skip another class talents
+ if ((getClassMask() & talentTabInfo->ClassMask) == 0)
+ continue;
+
+ for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
+ {
+ // skip non-existant talent ranks
+ if (talentInfo->RankID[rank] == 0)
+ continue;
+ removeSpell(talentInfo->RankID[rank], true);
+ if (const SpellEntry *_spellEntry = sSpellStore.LookupEntry(talentInfo->RankID[rank]))
+ for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) // search through the SpellEntry for valid trigger spells
+ if (_spellEntry->EffectTriggerSpell[i] > 0 && _spellEntry->Effect[i] == SPELL_EFFECT_LEARN_SPELL)
+ removeSpell(_spellEntry->EffectTriggerSpell[i], true); // and remove any spells that the talent teaches
+ // if this talent rank can be found in the PlayerTalentMap, mark the talent as removed so it gets deleted
+ PlayerTalentMap::iterator plrTalent = m_talents[m_activeSpec]->find(talentInfo->RankID[rank]);
+ if (plrTalent != m_talents[m_activeSpec]->end())
+ plrTalent->second->state = PLAYERSPELL_REMOVED;
+ }
+ }
+
+ _SaveSpells();
+
+ SetFreeTalentPoints(talentPointsForLevel);
+
+ if (!no_cost)
+ {
+ ModifyMoney(-(int32)cost);
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
+
+ m_resetTalentsCost = cost;
+ m_resetTalentsTime = time(NULL);
+ }
+
+ //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
+ RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
+ /* when prev line will dropped use next line
+ if(Pet* pet = GetPet())
+ {
+ if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
+ RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
+ }
+ */
+
+ return true;
+}
+
+Mail* Player::GetMail(uint32 id)
+{
+ for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
+ if ((*itr)->messageID == id)
+ return (*itr);
+
+ return NULL;
+}
+
+void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
+{
+ if(target == this)
+ Object::_SetCreateBits(updateMask, target);
+ else
+ {
+ for (uint16 index = 0; index < m_valuesCount; index++)
+ if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
+ updateMask->SetBit(index);
+ }
+}
+
+void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
+{
+ if(target == this)
+ Object::_SetUpdateBits(updateMask, target);
+ else
+ {
+ Object::_SetUpdateBits(updateMask, target);
+ *updateMask &= updateVisualBits;
+ }
+}
+
+void Player::InitVisibleBits()
+{
+ updateVisualBits.SetCount(PLAYER_END);
+
+ updateVisualBits.SetBit(OBJECT_FIELD_GUID);
+ updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
+ updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
+ updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
+ updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
+ updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
+ updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
+ updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
+ updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
+ updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
+ updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
+ updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
+ updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
+ updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
+ updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
+ updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
+ updateVisualBits.SetBit(UNIT_FIELD_POWER1);
+ updateVisualBits.SetBit(UNIT_FIELD_POWER2);
+ updateVisualBits.SetBit(UNIT_FIELD_POWER3);
+ updateVisualBits.SetBit(UNIT_FIELD_POWER4);
+ updateVisualBits.SetBit(UNIT_FIELD_POWER5);
+ updateVisualBits.SetBit(UNIT_FIELD_POWER6);
+ updateVisualBits.SetBit(UNIT_FIELD_POWER7);
+ updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
+ updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
+ updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
+ updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
+ updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
+ updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
+ updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
+ updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
+ updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
+ updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
+ updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
+ updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
+ updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
+ updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
+ updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
+ updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
+ updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
+ updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
+ updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
+ updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
+ updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
+ updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
+ updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
+ updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
+ updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
+ updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
+ updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
+ updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
+ updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
+ updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
+ updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
+ updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
+
+ updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
+ updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
+ updateVisualBits.SetBit(PLAYER_FLAGS);
+ updateVisualBits.SetBit(PLAYER_GUILDID);
+ updateVisualBits.SetBit(PLAYER_GUILDRANK);
+ updateVisualBits.SetBit(PLAYER_BYTES);
+ updateVisualBits.SetBit(PLAYER_BYTES_2);
+ updateVisualBits.SetBit(PLAYER_BYTES_3);
+ updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
+ updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
+ updateVisualBits.SetBit(UNIT_NPC_FLAGS);
+
+ // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
+ for (uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += MAX_QUEST_OFFSET)
+ updateVisualBits.SetBit(i);
+
+ // Players visible items are not inventory stuff
+ for (uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i)
+ {
+ uint16 offset = i * 2;
+
+ // item entry
+ updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset);
+ // enchant
+ updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset);
+ }
+
+ updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
+}
+
+void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
+{
+ for (uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i)
+ {
+ if(m_items[i] == NULL)
+ continue;
+
+ m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
+ }
+
+ if(target == this)
+ {
+ for (uint8 i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
+ {
+ if(m_items[i] == NULL)
+ continue;
+
+ m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
+ }
+ for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
+ {
+ if(m_items[i] == NULL)
+ continue;
+
+ m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
+ }
+ }
+
+ Unit::BuildCreateUpdateBlockForPlayer( data, target );
+}
+
+void Player::DestroyForPlayer( Player *target, bool anim ) const
+{
+ Unit::DestroyForPlayer( target, anim );
+
+ for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
+ {
+ if(m_items[i] == NULL)
+ continue;
+
+ m_items[i]->DestroyForPlayer( target );
+ }
+
+ if(target == this)
+ {
+ for (uint8 i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
+ {
+ if(m_items[i] == NULL)
+ continue;
+
+ m_items[i]->DestroyForPlayer( target );
+ }
+ for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
+ {
+ if(m_items[i] == NULL)
+ continue;
+
+ m_items[i]->DestroyForPlayer( target );
+ }
+ }
+}
+
+bool Player::HasSpell(uint32 spell) const
+{
+ PlayerSpellMap::const_iterator itr = m_spells.find(spell);
+ return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
+ !itr->second->disabled);
+}
+
+bool Player::HasTalent(uint32 spell, uint8 spec) const
+{
+ PlayerTalentMap::const_iterator itr = m_talents[spec]->find(spell);
+ return (itr != m_talents[spec]->end() && itr->second->state != PLAYERSPELL_REMOVED);
+}
+
+bool Player::HasActiveSpell(uint32 spell) const
+{
+ PlayerSpellMap::const_iterator itr = m_spells.find(spell);
+ return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
+ itr->second->active && !itr->second->disabled);
+}
+
+TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
+{
+ if (!trainer_spell)
+ return TRAINER_SPELL_RED;
+
+ bool hasSpell = true;
+ for (uint8 i = 0; i < MAX_SPELL_EFFECTS ; ++i)
+ {
+ if (!trainer_spell->learnedSpell[i])
+ continue;
+
+ if(!HasSpell(trainer_spell->learnedSpell[i]))
+ {
+ hasSpell = false;
+ break;
+ }
+ }
+ // known spell
+ if (hasSpell)
+ return TRAINER_SPELL_GRAY;
+
+ // check skill requirement
+ if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
+ return TRAINER_SPELL_RED;
+
+ // check level requirement
+ if(getLevel() < trainer_spell->reqLevel)
+ return TRAINER_SPELL_RED;
+
+ for (uint8 i = 0; i < MAX_SPELL_EFFECTS ; ++i)
+ {
+ if (!trainer_spell->learnedSpell[i])
+ continue;
+
+ // check race/class requirement
+ if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell[i]))
+ return TRAINER_SPELL_RED;
+
+ if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learnedSpell[i]))
+ {
+ // check prev.rank requirement
+ if(spell_chain->prev && !HasSpell(spell_chain->prev))
+ return TRAINER_SPELL_RED;
+ }
+
+ SpellsRequiringSpellMapBounds spellsRequired = spellmgr.GetSpellsRequiredForSpellBounds(trainer_spell->learnedSpell[i]);
+ for (SpellsRequiringSpellMap::const_iterator itr = spellsRequired.first; itr != spellsRequired.second; ++itr)
+ {
+ // check additional spell requirement
+ if(!HasSpell(itr->second))
+ return TRAINER_SPELL_RED;
+ }
+ }
+
+ // check primary prof. limit
+ // first rank of primary profession spell when there are no proffesions avalible is disabled
+ for (uint8 i = 0; i < MAX_SPELL_EFFECTS ; ++i)
+ {
+ if (!trainer_spell->learnedSpell[i])
+ continue;
+ if((spellmgr.IsPrimaryProfessionFirstRankSpell(trainer_spell->learnedSpell[i])) && (GetFreePrimaryProfessionPoints() == 0))
+ return TRAINER_SPELL_GREEN_DISABLED;
+ }
+
+ return TRAINER_SPELL_GREEN;
+}
+
+void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
+{
+ uint32 guid = GUID_LOPART(playerguid);
+
+ // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
+ // bones will be deleted by corpse/bones deleting thread shortly
+ ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
+
+ // remove from guild
+ uint32 guildId = GetGuildIdFromDB(playerguid);
+ if(guildId != 0)
+ {
+ Guild* guild = objmgr.GetGuildById(guildId);
+ if(guild)
+ guild->DelMember(guid);
+ }
+
+ // remove from arena teams
+ LeaveAllArenaTeams(playerguid);
+
+ // the player was uninvited already on logout so just remove from group
+ QueryResult_AutoPtr resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
+ if(resultGroup)
+ {
+ uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
+ Group* group = objmgr.GetGroupByLeader(leaderGuid);
+ if(group)
+ {
+ RemoveFromGroup(group, playerguid);
+ }
+ }
+
+ // remove signs from petitions (also remove petitions if owner);
+ RemovePetitionsAndSigns(playerguid, 10);
+
+ // return back all mails with COD and Item 0 1 2 3 4 5 6 7
+ QueryResult_AutoPtr 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);
+ if(resultMail)
+ {
+ do
+ {
+ Field *fields = resultMail->Fetch();
+
+ uint32 mail_id = fields[0].GetUInt32();
+ uint16 mailType = fields[1].GetUInt16();
+ uint16 mailTemplateId= fields[2].GetUInt16();
+ uint32 sender = fields[3].GetUInt32();
+ std::string subject = fields[4].GetCppString();
+ uint32 itemTextId = fields[5].GetUInt32();
+ uint32 money = fields[6].GetUInt32();
+ bool has_items = fields[7].GetBool();
+
+ //we can return mail now
+ //so firstly delete the old one
+ CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
+
+ // mail not from player
+ if (mailType != MAIL_NORMAL)
+ {
+ if(has_items)
+ CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
+ continue;
+ }
+
+ MailDraft draft(subject, itemTextId);
+ if (mailTemplateId)
+ draft = MailDraft(mailTemplateId,false); // itesm already included
+
+ if(has_items)
+ {
+ // data needs to be at first place for Item::LoadFromDB
+ QueryResult_AutoPtr 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);
+ if(resultItems)
+ {
+ do
+ {
+ Field *fields2 = resultItems->Fetch();
+
+ uint32 item_guidlow = fields2[1].GetUInt32();
+ uint32 item_template = fields2[2].GetUInt32();
+
+ ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
+ if(!itemProto)
+ {
+ CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
+ continue;
+ }
+
+ Item *pItem = NewItemOrBag(itemProto);
+ if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
+ {
+ pItem->FSetState(ITEM_REMOVED);
+ pItem->SaveToDB(); // it also deletes item object !
+ continue;
+ }
+
+ draft.AddItem(pItem);
+ }
+ while (resultItems->NextRow());
+ }
+ }
+
+ CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
+
+ uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
+
+ draft.AddMoney(money).SendReturnToSender(pl_account, guid, sender);
+ }
+ while (resultMail->NextRow());
+ }
+
+ // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
+ // Get guids of character's pets, will deleted in transaction
+ QueryResult_AutoPtr resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
+
+ // NOW we can finally clear other DB data related to character
+ CharacterDatabase.BeginTransaction();
+ if (resultPets)
+ {
+ do
+ {
+ Field *fields3 = resultPets->Fetch();
+ uint32 petguidlow = fields3[0].GetUInt32();
+ Pet::DeleteFromDB(petguidlow);
+ } while (resultPets->NextRow());
+ }
+
+ CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_account_data WHERE guid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM groups WHERE leaderGuid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM group_member WHERE leaderGuid = '%u' OR memberGuid = '%u'",guid,guid);
+ CharacterDatabase.PExecute("DELETE FROM groups WHERE leaderGuid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM gm_tickets WHERE playerGuid = '%u'", guid);
+ CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
+ CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u' " // NOTE: These achievements have flags & 256 in DBC.
+ "AND achievement NOT BETWEEN '456' AND '467' " // Realm First Level 80
+ "AND achievement NOT BETWEEN '1400' AND '1427' " // Realm First Raid Achievements
+ "AND achievement NOT IN(1463, 3117, 3259) ", guid); // Realm First Northen Vanguard + Raid Achievements
+ CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid1 = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid2 = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM guild_bank_eventlog WHERE PlayerGuid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_battleground_data WHERE guid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_glyphs WHERE guid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u'",guid);
+ CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u'",guid);
+
+ CharacterDatabase.CommitTransaction();
+
+ //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
+ if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
+}
+
+void Player::SetMovement(PlayerMovementType pType)
+{
+ WorldPacket data;
+ switch(pType)
+ {
+ case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
+ case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
+ case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
+ case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
+ default:
+ sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
+ return;
+ }
+ data.append(GetPackGUID());
+ data << uint32(0);
+ GetSession()->SendPacket( &data );
+}
+
+/* Preconditions:
+ - a resurrectable corpse must not be loaded for the player (only bones)
+ - the player must be in world
+*/
+void Player::BuildPlayerRepop()
+{
+ WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
+ data.append(GetPackGUID());
+ GetSession()->SendPacket(&data);
+
+ if (getRace() == RACE_NIGHTELF)
+ CastSpell(this, 20584, true);
+ CastSpell(this, 8326, true);
+
+ // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
+ // there must be SMSG.STOP_MIRROR_TIMER
+ // there we must send 888 opcode
+
+ // the player cannot have a corpse already, only bones which are not returned by GetCorpse
+ if(GetCorpse())
+ {
+ sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
+ assert(false);
+ }
+
+ // create a corpse and place it at the player's location
+ CreateCorpse();
+ Corpse *corpse = GetCorpse();
+ if(!corpse)
+ {
+ sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
+ return;
+ }
+ GetMap()->Add(corpse);
+
+ // convert player body to ghost
+ SetHealth( 1 );
+
+ SetMovement(MOVE_WATER_WALK);
+ if(!GetSession()->isLogingOut())
+ SetMovement(MOVE_UNROOT);
+
+ // BG - remove insignia related
+ RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
+
+// SendCorpseReclaimDelay();
+
+ // to prevent cheating
+ corpse->ResetGhostTime();
+
+ StopMirrorTimers(); //disable timers(bars)
+
+ SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
+
+ // set and clear other
+ SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
+}
+
+void Player::ResurrectPlayer(float restore_percent, bool applySickness)
+{
+ WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
+ data << uint32(-1);
+ data << float(0);
+ data << float(0);
+ data << float(0);
+ GetSession()->SendPacket(&data);
+
+ // speed change, land walk
+
+ // remove death flag + set aura
+ SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
+ if (getRace() == RACE_NIGHTELF)
+ RemoveAurasDueToSpell(20584); // speed bonuses
+ RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
+
+ setDeathState(ALIVE);
+
+ SetMovement(MOVE_LAND_WALK);
+ SetMovement(MOVE_UNROOT);
+
+ m_deathTimer = 0;
+
+ // set health/powers (0- will be set in caller)
+ if(restore_percent>0.0f)
+ {
+ SetHealth(uint32(GetMaxHealth()*restore_percent));
+ SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
+ SetPower(POWER_RAGE, 0);
+ SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
+ }
+
+ // trigger update zone for alive state zone updates
+ uint32 newzone, newarea;
+ GetZoneAndAreaId(newzone,newarea);
+ UpdateZone(newzone,newarea);
+ sOutdoorPvPMgr.HandlePlayerResurrects(this, newzone);
+
+ // update visibility
+ //ObjectAccessor::UpdateVisibilityForPlayer(this);
+ SetToNotify();
+
+ if(!applySickness)
+ return;
+
+ //Characters from level 1-10 are not affected by resurrection sickness.
+ //Characters from level 11-19 will suffer from one minute of sickness
+ //for each level they are above 10.
+ //Characters level 20 and up suffer from ten minutes of sickness.
+ int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
+
+ if(int32(getLevel()) >= startLevel)
+ {
+ // set resurrection sickness
+ CastSpell(this, 15007, true);
+
+ // not full duration
+ if(int32(getLevel()) < startLevel+9)
+ {
+ int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
+
+ if(Aura * aur = GetAura(15007, GetGUID()))
+ {
+ aur->SetDuration(delta*IN_MILISECONDS);
+ }
+ }
+ }
+}
+
+/**
+ * FallMode = 0 implies that the player is dying, or already dead, and the proper death state will be set.
+ * = 1 simply causes the player to plummet towards the ground, and not suffer any damage.
+ * = 2 causes the player to plummet towards the ground, and causes falling damage, regardless
+ * of any auras that might of prevented fall damage.
+ */
+bool Player::FallGround(uint8 FallMode)
+{
+ // Let's abort after we called this function one time
+ if (getDeathState() == DEAD_FALLING && FallMode == 0)
+ return false;
+
+ float x, y, z;
+ GetPosition(x, y, z);
+ float ground_Z = GetMap()->GetVmapHeight(x, y, z);
+ float z_diff = 0.0f;
+ if ((z_diff = fabs(ground_Z - z)) < 0.1f)
+ return false;
+
+ GetMotionMaster()->MoveFall(ground_Z, EVENT_FALL_GROUND);
+
+ // Below formula for falling damage is from Player::HandleFall
+ if(FallMode == 2 && z_diff >= 14.57f)
+ {
+ uint32 damage = std::min(GetMaxHealth(), (uint32)((0.018f*z_diff-0.2426f)*GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL)));
+ if(damage > 0) EnvironmentalDamage(DAMAGE_FALL, damage);
+ }
+ else if(FallMode == 0)
+ Unit::setDeathState(DEAD_FALLING);
+ return true;
+}
+
+void Player::KillPlayer()
+{
+ if(IsFlying() && !GetTransport()) FallGround();
+
+ SetMovement(MOVE_ROOT);
+
+ StopMirrorTimers(); //disable timers(bars)
+
+ setDeathState(CORPSE);
+ //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
+
+ SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
+ ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
+
+ // 6 minutes until repop at graveyard
+ m_deathTimer = 6*MINUTE*IN_MILISECONDS;
+
+ UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
+ SendCorpseReclaimDelay();
+
+ // don't create corpse at this moment, player might be falling
+
+ // update visibility
+ UpdateObjectVisibility();
+}
+
+void Player::CreateCorpse()
+{
+ // prevent existence 2 corpse for player
+ SpawnCorpseBones();
+
+ uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
+
+ Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
+ SetPvPDeath(false);
+
+ if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
+ {
+ delete corpse;
+ return;
+ }
+
+ _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
+ _pb = GetUInt32Value(PLAYER_BYTES);
+ _pb2 = GetUInt32Value(PLAYER_BYTES_2);
+
+ uint8 race = (uint8)(_uf);
+ uint8 skin = (uint8)(_pb);
+ uint8 face = (uint8)(_pb >> 8);
+ uint8 hairstyle = (uint8)(_pb >> 16);
+ uint8 haircolor = (uint8)(_pb >> 24);
+ uint8 facialhair = (uint8)(_pb2);
+
+ _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
+ _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
+
+ corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
+ corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
+
+ uint32 flags = CORPSE_FLAG_UNK2;
+ if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
+ flags |= CORPSE_FLAG_HIDE_HELM;
+ if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
+ flags |= CORPSE_FLAG_HIDE_CLOAK;
+ if(InBattleGround() && !InArena())
+ flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
+ corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
+
+ corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
+
+ corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
+
+ uint32 iDisplayID;
+ uint32 iIventoryType;
+ uint32 _cfi;
+ for (uint8 i = 0; i < EQUIPMENT_SLOT_END; i++)
+ {
+ if(m_items[i])
+ {
+ iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
+ iIventoryType = m_items[i]->GetProto()->InventoryType;
+
+ _cfi = iDisplayID | (iIventoryType << 24);
+ corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i, _cfi);
+ }
+ }
+
+ // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
+ const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
+ assert(entry);
+ if(entry->map_type != MAP_BATTLEGROUND)
+ corpse->SaveToDB();
+
+ // register for player, but not show
+ ObjectAccessor::Instance().AddCorpse(corpse);
+}
+
+void Player::SpawnCorpseBones()
+{
+ if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
+ if (!GetSession()->PlayerLogoutWithSave()) // at logout we will already store the player
+ SaveToDB(); // prevent loading as ghost without corpse
+}
+
+Corpse* Player::GetCorpse() const
+{
+ return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
+}
+
+void Player::DurabilityLossAll(double percent, bool inventory)
+{
+ for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
+ if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ DurabilityLoss(pItem,percent);
+
+ if(inventory)
+ {
+ // bags not have durability
+ // for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
+
+ for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
+ if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ DurabilityLoss(pItem,percent);
+
+ // keys not have durability
+ //for (int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
+
+ for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
+ if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ for (uint32 j = 0; j < pBag->GetBagSize(); j++)
+ if(Item* pItem = GetItemByPos( i, j ))
+ DurabilityLoss(pItem,percent);
+ }
+}
+
+void Player::DurabilityLoss(Item* item, double percent)
+{
+ if(!item )
+ return;
+
+ uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
+
+ if(!pMaxDurability)
+ return;
+
+ uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
+
+ if(pDurabilityLoss < 1 )
+ pDurabilityLoss = 1;
+
+ DurabilityPointsLoss(item,pDurabilityLoss);
+}
+
+void Player::DurabilityPointsLossAll(int32 points, bool inventory)
+{
+ for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
+ if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ DurabilityPointsLoss(pItem,points);
+
+ if(inventory)
+ {
+ // bags not have durability
+ // for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
+
+ for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
+ if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ DurabilityPointsLoss(pItem,points);
+
+ // keys not have durability
+ //for (int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
+
+ for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
+ if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ for (uint32 j = 0; j < pBag->GetBagSize(); j++)
+ if(Item* pItem = GetItemByPos( i, j ))
+ DurabilityPointsLoss(pItem,points);
+ }
+}
+
+void Player::DurabilityPointsLoss(Item* item, int32 points)
+{
+ int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
+ int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
+ int32 pNewDurability = pOldDurability - points;
+
+ if (pNewDurability < 0)
+ pNewDurability = 0;
+ else if (pNewDurability > pMaxDurability)
+ pNewDurability = pMaxDurability;
+
+ if (pOldDurability != pNewDurability)
+ {
+ // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
+ if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
+ _ApplyItemMods(item,item->GetSlot(), false);
+
+ item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
+
+ // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
+ if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
+ _ApplyItemMods(item,item->GetSlot(), true);
+
+ item->SetState(ITEM_CHANGED, this);
+ }
+}
+
+void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
+{
+ if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
+ DurabilityPointsLoss(pItem,1);
+}
+
+uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
+{
+ uint32 TotalCost = 0;
+ // equipped, backpack, bags itself
+ for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
+ TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
+
+ // bank, buyback and keys not repaired
+
+ // items in inventory bags
+ for (uint8 j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
+ for (uint8 i = 0; i < MAX_BAG_SIZE; i++)
+ TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
+ return TotalCost;
+}
+
+uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
+{
+ Item* item = GetItemByPos(pos);
+
+ uint32 TotalCost = 0;
+ if(!item)
+ return TotalCost;
+
+ uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
+ if(!maxDurability)
+ return TotalCost;
+
+ uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
+
+ if(cost)
+ {
+ uint32 LostDurability = maxDurability - curDurability;
+ if(LostDurability>0)
+ {
+ ItemPrototype const *ditemProto = item->GetProto();
+
+ DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
+ if(!dcost)
+ {
+ sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
+ return TotalCost;
+ }
+
+ uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
+ DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
+ if(!dQualitymodEntry)
+ {
+ sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
+ return TotalCost;
+ }
+
+ uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
+ uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
+
+ costs = uint32(costs * discountMod) * sWorld.getRate(RATE_REPAIRCOST);
+
+ if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
+ costs = 1;
+
+ if (guildBank)
+ {
+ if (GetGuildId()==0)
+ {
+ DEBUG_LOG("You are not member of a guild");
+ return TotalCost;
+ }
+
+ Guild *pGuild = objmgr.GetGuildById(GetGuildId());
+ if (!pGuild)
+ return TotalCost;
+
+ if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
+ {
+ DEBUG_LOG("You do not have rights to withdraw for repairs");
+ return TotalCost;
+ }
+
+ if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
+ {
+ DEBUG_LOG("You do not have enough money withdraw amount remaining");
+ return TotalCost;
+ }
+
+ if (pGuild->GetGuildBankMoney() < costs)
+ {
+ DEBUG_LOG("There is not enough money in bank");
+ return TotalCost;
+ }
+
+ pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
+ TotalCost = costs;
+ }
+ else if (GetMoney() < costs)
+ {
+ DEBUG_LOG("You do not have enough money");
+ return TotalCost;
+ }
+ else
+ ModifyMoney( -int32(costs) );
+ }
+ }
+
+ item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
+ item->SetState(ITEM_CHANGED, this);
+
+ // reapply mods for total broken and repaired item if equipped
+ if(IsEquipmentPos(pos) && !curDurability)
+ _ApplyItemMods(item,pos & 255, true);
+ return TotalCost;
+}
+
+void Player::RepopAtGraveyard()
+{
+ // note: this can be called also when the player is alive
+ // for example from WorldSession::HandleMovementOpcodes
+
+ AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
+
+ // Such zones are considered unreachable as a ghost and the player must be automatically revived
+ if ((!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY) || GetTransport() || GetPositionZ() < -500.0f)
+ {
+ ResurrectPlayer(0.5f);
+ SpawnCorpseBones();
+ }
+
+ WorldSafeLocsEntry const *ClosestGrave = NULL;
+
+ // Special handle for battleground maps
+ if( BattleGround *bg = GetBattleGround() )
+ ClosestGrave = bg->GetClosestGraveYard(this);
+ else
+ ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
+
+ // stop countdown until repop
+ m_deathTimer = 0;
+
+ // if no grave found, stay at the current location
+ // and don't show spirit healer location
+ if(ClosestGrave)
+ {
+ TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
+ if(isDead()) // not send if alive, because it used in TeleportTo()
+ {
+ WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
+ data << ClosestGrave->map_id;
+ data << ClosestGrave->x;
+ data << ClosestGrave->y;
+ data << ClosestGrave->z;
+ GetSession()->SendPacket(&data);
+ }
+ }
+ else if(GetPositionZ() < -500.0f)
+ TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
+}
+
+void Player::JoinedChannel(Channel *c)
+{
+ m_channels.push_back(c);
+}
+
+void Player::LeftChannel(Channel *c)
+{
+ m_channels.remove(c);
+}
+
+void Player::CleanupChannels()
+{
+ while(!m_channels.empty())
+ {
+ Channel* ch = *m_channels.begin();
+ m_channels.erase(m_channels.begin()); // remove from player's channel list
+ ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
+ if (ChannelMgr* cMgr = channelMgr(GetTeam()))
+ cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
+
+ }
+ sLog.outDebug("Player: channels cleaned up!");
+}
+
+void Player::UpdateLocalChannels(uint32 newZone )
+{
+ if(m_channels.empty())
+ return;
+
+ AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
+ if(!current_zone)
+ return;
+
+ ChannelMgr* cMgr = channelMgr(GetTeam());
+ if(!cMgr)
+ return;
+
+ std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
+
+ for (JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
+ {
+ next = i; ++next;
+
+ // skip non built-in channels
+ if(!(*i)->IsConstant())
+ continue;
+
+ ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
+ if(!ch)
+ continue;
+
+ if((ch->flags & 4) == 4) // global channel without zone name in pattern
+ continue;
+
+ // new channel
+ char new_channel_name_buf[100];
+ snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
+ Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
+
+ if((*i)!=new_channel)
+ {
+ new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
+
+ // leave old channel
+ (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
+ std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
+ LeftChannel(*i); // remove from player's channel list
+ cMgr->LeftChannel(name); // delete if empty
+ }
+ }
+ sLog.outDebug("Player: channels cleaned up!");
+}
+
+void Player::LeaveLFGChannel()
+{
+ for (JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
+ {
+ if((*i)->IsLFG())
+ {
+ (*i)->Leave(GetGUID());
+ break;
+ }
+ }
+}
+
+void Player::UpdateDefense()
+{
+ uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
+
+ if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
+ {
+ // update dependent from defense skill part
+ UpdateDefenseBonusesMod();
+ }
+}
+
+void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
+{
+ if(modGroup >= BASEMOD_END || modType >= MOD_END)
+ {
+ sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
+ return;
+ }
+
+ float val = 1.0f;
+
+ switch(modType)
+ {
+ case FLAT_MOD:
+ m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
+ break;
+ case PCT_MOD:
+ if(amount <= -100.0f)
+ amount = -200.0f;
+
+ val = (100.0f + amount) / 100.0f;
+ m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
+ break;
+ }
+
+ if(!CanModifyStats())
+ return;
+
+ switch(modGroup)
+ {
+ case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
+ case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
+ case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
+ case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
+ default: break;
+ }
+}
+
+float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
+{
+ if(modGroup >= BASEMOD_END || modType > MOD_END)
+ {
+ sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
+ return 0.0f;
+ }
+
+ if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
+ return 0.0f;
+
+ return m_auraBaseMod[modGroup][modType];
+}
+
+float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
+{
+ if(modGroup >= BASEMOD_END)
+ {
+ sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
+ return 0.0f;
+ }
+
+ if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
+ return 0.0f;
+
+ return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
+}
+
+uint32 Player::GetShieldBlockValue() const
+{
+ float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
+
+ value = (value < 0) ? 0 : value;
+
+ return uint32(value);
+}
+
+float Player::GetMeleeCritFromAgility()
+{
+ uint8 level = getLevel();
+ uint32 pclass = getClass();
+
+ if (level > GT_MAX_LEVEL)
+ level = GT_MAX_LEVEL;
+
+ GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
+ GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
+ if (critBase == NULL || critRatio == NULL)
+ return 0.0f;
+
+ float crit = critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
+ return crit*100.0f;
+}
+
+float Player::GetDodgeFromAgility()
+{
+ // Table for base dodge values
+ float dodge_base[MAX_CLASSES] = {
+ 0.0075f, // Warrior
+ 0.00652f, // Paladin
+ -0.0545f, // Hunter
+ -0.0059f, // Rogue
+ 0.03183f, // Priest
+ 0.0114f, // DK
+ 0.0167f, // Shaman
+ 0.034575f, // Mage
+ 0.02011f, // Warlock
+ 0.0f, // ??
+ -0.0187f // Druid
+ };
+ // Crit/agility to dodge/agility coefficient multipliers
+ float crit_to_dodge[MAX_CLASSES] = {
+ 1.1f, // Warrior
+ 1.0f, // Paladin
+ 1.6f, // Hunter
+ 2.0f, // Rogue
+ 1.0f, // Priest
+ 1.0f, // DK?
+ 1.0f, // Shaman
+ 1.0f, // Mage
+ 1.0f, // Warlock
+ 0.0f, // ??
+ 1.7f // Druid
+ };
+
+ uint8 level = getLevel();
+ uint32 pclass = getClass();
+
+ if (level > GT_MAX_LEVEL)
+ level = GT_MAX_LEVEL;
+
+ // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
+ GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
+ if (dodgeRatio == NULL || pclass > MAX_CLASSES)
+ return 0.0f;
+
+ float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
+ return dodge*100.0f;
+}
+
+float Player::GetSpellCritFromIntellect()
+{
+ uint8 level = getLevel();
+ uint32 pclass = getClass();
+
+ if (level > GT_MAX_LEVEL)
+ level = GT_MAX_LEVEL;
+
+ GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
+ GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
+ if (critBase == NULL || critRatio == NULL)
+ return 0.0f;
+
+ float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
+ return crit*100.0f;
+}
+
+float Player::GetRatingCoefficient(CombatRating cr) const
+{
+ uint8 level = getLevel();
+
+ if (level > GT_MAX_LEVEL)
+ level = GT_MAX_LEVEL;
+
+ GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
+ if (Rating == NULL)
+ return 1.0f; // By default use minimum coefficient (not must be called)
+
+ return Rating->ratio;
+}
+
+float Player::GetRatingBonusValue(CombatRating cr) const
+{
+ return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
+}
+
+float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
+{
+ switch (attType)
+ {
+ case BASE_ATTACK:
+ return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
+ case OFF_ATTACK:
+ return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
+ default:
+ break;
+ }
+ return 0.0f;
+}
+
+float Player::OCTRegenHPPerSpirit()
+{
+ uint8 level = getLevel();
+ uint32 pclass = getClass();
+
+ if (level > GT_MAX_LEVEL)
+ level = GT_MAX_LEVEL;
+
+ GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
+ GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
+ if (baseRatio == NULL || moreRatio == NULL)
+ return 0.0f;
+
+ // Formula from PaperDollFrame script
+ float spirit = GetStat(STAT_SPIRIT);
+ float baseSpirit = spirit;
+ if (baseSpirit > 50)
+ baseSpirit = 50;
+ float moreSpirit = spirit - baseSpirit;
+ float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
+ return regen;
+}
+
+float Player::OCTRegenMPPerSpirit()
+{
+ uint8 level = getLevel();
+ uint32 pclass = getClass();
+
+ if (level > GT_MAX_LEVEL)
+ level = GT_MAX_LEVEL;
+
+// GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
+ GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
+ if (moreRatio == NULL)
+ return 0.0f;
+
+ // Formula get from PaperDollFrame script
+ float spirit = GetStat(STAT_SPIRIT);
+ float regen = spirit * moreRatio->ratio;
+ return regen;
+}
+
+void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
+{
+ m_baseRatingValue[cr]+=(apply ? value : -value);
+
+ // explicit affected values
+ switch (cr)
+ {
+ case CR_HASTE_MELEE:
+ {
+ float RatingChange = value / GetRatingCoefficient(cr);
+ ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
+ ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
+ break;
+ }
+ case CR_HASTE_RANGED:
+ {
+ float RatingChange = value / GetRatingCoefficient(cr);
+ ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
+ break;
+ }
+ case CR_HASTE_SPELL:
+ {
+ float RatingChange = value / GetRatingCoefficient(cr);
+ ApplyCastTimePercentMod(RatingChange,apply);
+ break;
+ }
+ }
+
+ UpdateRating(cr);
+}
+
+void Player::UpdateRating(CombatRating cr)
+{
+ int32 amount = m_baseRatingValue[cr];
+ // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
+ // stat used stored in miscValueB for this aura
+ AuraEffectList const& modRatingFromStat = GetAuraEffectsByType(SPELL_AURA_MOD_RATING_FROM_STAT);
+ for (AuraEffectList::const_iterator i = modRatingFromStat.begin(); i != modRatingFromStat.end(); ++i)
+ if ((*i)->GetMiscValue() & (1<<cr))
+ amount += int32(GetStat(Stats((*i)->GetMiscValueB())) * (*i)->GetAmount() / 100.0f);
+ if (amount < 0)
+ amount = 0;
+ SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
+
+ bool affectStats = CanModifyStats();
+
+ switch (cr)
+ {
+ case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
+ case CR_DEFENSE_SKILL:
+ UpdateDefenseBonusesMod();
+ break;
+ case CR_DODGE:
+ UpdateDodgePercentage();
+ break;
+ case CR_PARRY:
+ UpdateParryPercentage();
+ break;
+ case CR_BLOCK:
+ UpdateBlockPercentage();
+ break;
+ case CR_HIT_MELEE:
+ UpdateMeleeHitChances();
+ break;
+ case CR_HIT_RANGED:
+ UpdateRangedHitChances();
+ break;
+ case CR_HIT_SPELL:
+ UpdateSpellHitChances();
+ break;
+ case CR_CRIT_MELEE:
+ if(affectStats)
+ {
+ UpdateCritPercentage(BASE_ATTACK);
+ UpdateCritPercentage(OFF_ATTACK);
+ }
+ break;
+ case CR_CRIT_RANGED:
+ if(affectStats)
+ UpdateCritPercentage(RANGED_ATTACK);
+ break;
+ case CR_CRIT_SPELL:
+ if(affectStats)
+ UpdateAllSpellCritChances();
+ break;
+ case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
+ case CR_HIT_TAKEN_RANGED:
+ break;
+ case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
+ break;
+ case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
+ case CR_CRIT_TAKEN_RANGED:
+ break;
+ case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
+ break;
+ case CR_HASTE_MELEE: // Implemented in Player::ApplyRatingMod
+ case CR_HASTE_RANGED:
+ case CR_HASTE_SPELL:
+ break;
+ case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
+ case CR_WEAPON_SKILL_OFFHAND:
+ case CR_WEAPON_SKILL_RANGED:
+ break;
+ case CR_EXPERTISE:
+ if(affectStats)
+ {
+ UpdateExpertise(BASE_ATTACK);
+ UpdateExpertise(OFF_ATTACK);
+ }
+ break;
+ case CR_ARMOR_PENETRATION:
+ if(affectStats)
+ UpdateArmorPenetration(amount);
+ break;
+ }
+}
+
+void Player::UpdateAllRatings()
+{
+ for(int cr = 0; cr < MAX_COMBAT_RATING; ++cr)
+ UpdateRating(CombatRating(cr));
+}
+
+void Player::SetRegularAttackTime()
+{
+ for (uint8 i = 0; i < MAX_ATTACK; ++i)
+ {
+ Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
+ if(tmpitem && !tmpitem->IsBroken())
+ {
+ ItemPrototype const *proto = tmpitem->GetProto();
+ if(proto->Delay)
+ SetAttackTime(WeaponAttackType(i), proto->Delay);
+ else
+ SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
+ }
+ }
+}
+
+//skill+step, checking for max value
+bool Player::UpdateSkill(uint32 skill_id, uint32 step)
+{
+ if(!skill_id)
+ return false;
+
+ if(skill_id == SKILL_FIST_WEAPONS)
+ skill_id = SKILL_UNARMED;
+
+ SkillStatusMap::iterator itr = mSkillStatus.find(skill_id);
+ if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
+ return false;
+
+ uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
+ uint32 data = GetUInt32Value(valueIndex);
+ uint32 value = SKILL_VALUE(data);
+ uint32 max = SKILL_MAX(data);
+
+ if ((!max) || (!value) || (value >= max))
+ return false;
+
+ if (value < max)
+ {
+ uint32 new_value = value+step;
+ if(new_value > max)
+ new_value = max;
+
+ SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,max));
+ if(itr->second.uState != SKILL_NEW)
+ itr->second.uState = SKILL_CHANGED;
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
+ return true;
+ }
+
+ return false;
+}
+
+inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
+{
+ if ( SkillValue >= GrayLevel )
+ return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
+ if ( SkillValue >= GreenLevel )
+ return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
+ if ( SkillValue >= YellowLevel )
+ return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
+ return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
+}
+
+bool Player::UpdateCraftSkill(uint32 spellid)
+{
+ sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
+
+ SkillLineAbilityMapBounds bounds = spellmgr.GetSkillLineAbilityMapBounds(spellid);
+
+ for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
+ {
+ if (_spell_idx->second->skillId)
+ {
+ uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
+
+ // Alchemy Discoveries here
+ SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
+ if (spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
+ {
+ if (uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
+ learnSpell(discoveredSpell,false);
+ }
+
+ uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
+
+ return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
+ _spell_idx->second->max_value,
+ (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
+ _spell_idx->second->min_value),
+ craft_skill_gain);
+ }
+ }
+ return false;
+}
+
+bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
+{
+ sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
+
+ uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
+
+ // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
+ switch (SkillId)
+ {
+ case SKILL_HERBALISM:
+ case SKILL_LOCKPICKING:
+ case SKILL_JEWELCRAFTING:
+ case SKILL_INSCRIPTION:
+ return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
+ case SKILL_SKINNING:
+ if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
+ return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
+ else
+ return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
+ case SKILL_MINING:
+ if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
+ return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
+ else
+ return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
+ }
+ return false;
+}
+
+bool Player::UpdateFishingSkill()
+{
+ sLog.outDebug("UpdateFishingSkill");
+
+ uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
+
+ int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
+
+ uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
+
+ return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
+}
+
+// levels sync. with spell requirement for skill levels to learn
+// bonus abilities in sSkillLineAbilityStore
+// Used only to avoid scan DBC at each skill grow
+static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
+
+bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
+{
+ sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
+ if ( !SkillId )
+ return false;
+
+ if(Chance <= 0) // speedup in 0 chance case
+ {
+ sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
+ return false;
+ }
+
+ SkillStatusMap::iterator itr = mSkillStatus.find(SkillId);
+ if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
+ return false;
+
+ uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
+
+ uint32 data = GetUInt32Value(valueIndex);
+ uint16 SkillValue = SKILL_VALUE(data);
+ uint16 MaxValue = SKILL_MAX(data);
+
+ if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
+ return false;
+
+ int32 Roll = irand(1,1000);
+
+ if ( Roll <= Chance )
+ {
+ uint32 new_value = SkillValue+step;
+ if(new_value > MaxValue)
+ new_value = MaxValue;
+
+ SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,MaxValue));
+ if(itr->second.uState != SKILL_NEW)
+ itr->second.uState = SKILL_CHANGED;
+ for (uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
+ {
+ if((SkillValue < *bsl && new_value >= *bsl))
+ {
+ learnSkillRewardedSpells( SkillId, new_value);
+ break;
+ }
+ }
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
+ sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
+ return true;
+ }
+
+ sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
+ return false;
+}
+
+void Player::UpdateWeaponSkill (WeaponAttackType attType)
+{
+ // no skill gain in pvp
+ Unit *pVictim = getVictim();
+ if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
+ return;
+
+ if(IsInFeralForm())
+ return; // always maximized SKILL_FERAL_COMBAT in fact
+
+ if(m_form == FORM_TREE)
+ return; // use weapon but not skill up
+
+ if(pVictim && pVictim->GetTypeId() == TYPEID_UNIT && (((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_SKILLGAIN))
+ return;
+
+ uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
+
+ switch(attType)
+ {
+ case BASE_ATTACK:
+ {
+ Item *tmpitem = GetWeaponForAttack(attType,true);
+
+ if (!tmpitem)
+ UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
+ else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
+ UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
+ break;
+ }
+ case OFF_ATTACK:
+ case RANGED_ATTACK:
+ {
+ Item *tmpitem = GetWeaponForAttack(attType,true);
+ if (tmpitem)
+ UpdateSkill(tmpitem->GetSkill(), weapon_skill_gain);
+ break;
+ }
+ }
+ UpdateAllCritPercentages();
+}
+
+void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
+{
+ uint8 plevel = getLevel(); // if defense than pVictim == attacker
+ uint8 greylevel = Trinity::XP::GetGrayLevel(plevel);
+ uint8 moblevel = pVictim->getLevelForTarget(this);
+ if(moblevel < greylevel)
+ return;
+
+ if (moblevel > plevel + 5)
+ moblevel = plevel + 5;
+
+ uint8 lvldif = moblevel - greylevel;
+ if (lvldif < 3)
+ lvldif = 3;
+
+ uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
+ if (skilldif <= 0)
+ return;
+
+ float chance = float(3 * lvldif * skilldif) / plevel;
+ if (!defence)
+ if (getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
+ chance += chance * 0.02f * GetStat(STAT_INTELLECT);
+
+ chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
+
+ if (roll_chance_f(chance))
+ {
+ if (defence)
+ UpdateDefense();
+ else
+ UpdateWeaponSkill(attType);
+ }
+ else
+ return;
+}
+
+void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
+{
+ SkillStatusMap::const_iterator itr = mSkillStatus.find(skillid);
+ if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
+ return;
+
+ uint32 bonusIndex = PLAYER_SKILL_BONUS_INDEX(itr->second.pos);
+
+ uint32 bonus_val = GetUInt32Value(bonusIndex);
+ int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
+ int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
+
+ if(talent) // permanent bonus stored in high part
+ SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
+ else // temporary/item bonus stored in low part
+ SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
+}
+
+void Player::UpdateSkillsForLevel()
+{
+ uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
+ uint32 maxSkill = GetMaxSkillValueForLevel();
+
+ bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
+
+ for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
+ {
+ if(itr->second.uState == SKILL_DELETED)
+ continue;
+
+ uint32 pskill = itr->first;
+ SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
+ if (!pSkill)
+ continue;
+
+ if (GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
+ continue;
+
+ uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
+ uint32 data = GetUInt32Value(valueIndex);
+ uint32 max = SKILL_MAX(data);
+ uint32 val = SKILL_VALUE(data);
+
+ /// update only level dependent max skill values
+ if (max != 1)
+ {
+ /// maximize skill always
+ if (alwaysMaxSkill)
+ {
+ SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(maxSkill,maxSkill));
+ if(itr->second.uState != SKILL_NEW)
+ itr->second.uState = SKILL_CHANGED;
+ }
+ else if(max != maxconfskill) /// update max skill value if current max skill not maximized
+ {
+ SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(val,maxSkill));
+ if(itr->second.uState != SKILL_NEW)
+ itr->second.uState = SKILL_CHANGED;
+ }
+ }
+ }
+}
+
+void Player::UpdateSkillsToMaxSkillsForLevel()
+{
+ for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
+ {
+ if(itr->second.uState == SKILL_DELETED)
+ continue;
+
+ uint32 pskill = itr->first;
+ if (IsProfessionOrRidingSkill(pskill))
+ continue;
+ uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
+ uint32 data = GetUInt32Value(valueIndex);
+ uint32 max = SKILL_MAX(data);
+
+ if (max > 1)
+ {
+ SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(max,max));
+ if(itr->second.uState != SKILL_NEW)
+ itr->second.uState = SKILL_CHANGED;
+ }
+ if (pskill == SKILL_DEFENSE)
+ UpdateDefenseBonusesMod();
+ }
+}
+
+// This functions sets a skill line value (and adds if doesn't exist yet)
+// To "remove" a skill line, set it's values to zero
+void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
+{
+ if (!id)
+ return;
+
+ SkillStatusMap::iterator itr = mSkillStatus.find(id);
+
+ //has skill
+ if(itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED)
+ {
+ if (currVal)
+ {
+ SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos),MAKE_SKILL_VALUE(currVal,maxVal));
+ if(itr->second.uState != SKILL_NEW)
+ itr->second.uState = SKILL_CHANGED;
+ learnSkillRewardedSpells(id, currVal);
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
+ }
+ else //remove
+ {
+ // clear skill fields
+ SetUInt32Value(PLAYER_SKILL_INDEX(itr->second.pos),0);
+ SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos),0);
+ SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos),0);
+
+ // mark as deleted or simply remove from map if not saved yet
+ if(itr->second.uState != SKILL_NEW)
+ itr->second.uState = SKILL_DELETED;
+ else
+ mSkillStatus.erase(itr);
+
+ // remove all spells that related to this skill
+ for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j)
+ if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
+ if (pAbility->skillId == id)
+ removeSpell(spellmgr.GetFirstSpellInChain(pAbility->spellId));
+ }
+ }
+ else if (currVal) //add
+ {
+ for (int i=0; i < PLAYER_MAX_SKILLS; ++i)
+ if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
+ {
+ SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
+ if (!pSkill)
+ {
+ sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
+ return;
+ }
+ // enable unlearn button for primary professions only
+ if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
+ SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
+ else
+ SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
+ SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
+
+ // insert new entry or update if not deleted old entry yet
+ if(itr != mSkillStatus.end())
+ {
+ itr->second.pos = i;
+ itr->second.uState = SKILL_CHANGED;
+ }
+ else
+ mSkillStatus.insert(SkillStatusMap::value_type(id, SkillStatusData(i, SKILL_NEW)));
+
+ // apply skill bonuses
+ SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
+
+ // temporary bonuses
+ AuraEffectList const& mModSkill = GetAuraEffectsByType(SPELL_AURA_MOD_SKILL);
+ for (AuraEffectList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
+ if ((*j)->GetMiscValue() == int32(id))
+ (*j)->HandleEffect(this, 0, true);
+
+ // permanent bonuses
+ AuraEffectList const& mModSkillTalent = GetAuraEffectsByType(SPELL_AURA_MOD_SKILL_TALENT);
+ for (AuraEffectList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
+ if ((*j)->GetMiscValue() == int32(id))
+ (*j)->HandleEffect(this, 0, true);
+
+ // Learn all spells for skill
+ learnSkillRewardedSpells(id, currVal);
+ return;
+ }
+ }
+}
+
+bool Player::HasSkill(uint32 skill) const
+{
+ if(!skill)
+ return false;
+
+ SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
+ return (itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED);
+}
+
+uint16 Player::GetSkillValue(uint32 skill) const
+{
+ if (!skill)
+ return 0;
+
+ SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
+ if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
+ return 0;
+
+ uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
+
+ int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
+ result += SKILL_TEMP_BONUS(bonus);
+ result += SKILL_PERM_BONUS(bonus);
+ return result < 0 ? 0 : result;
+}
+
+uint16 Player::GetMaxSkillValue(uint32 skill) const
+{
+ if (!skill)
+ return 0;
+
+ SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
+ if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
+ return 0;
+
+ uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
+
+ int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
+ result += SKILL_TEMP_BONUS(bonus);
+ result += SKILL_PERM_BONUS(bonus);
+ return result < 0 ? 0 : result;
+}
+
+uint16 Player::GetPureMaxSkillValue(uint32 skill) const
+{
+ if(!skill)
+ return 0;
+
+ SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
+ if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
+ return 0;
+
+ return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
+}
+
+uint16 Player::GetBaseSkillValue(uint32 skill) const
+{
+ if(!skill)
+ return 0;
+
+ SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
+ if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
+ return 0;
+
+ int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
+ result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
+ return result < 0 ? 0 : result;
+}
+
+uint16 Player::GetPureSkillValue(uint32 skill) const
+{
+ if(!skill)
+ return 0;
+
+ SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
+ if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
+ return 0;
+
+ return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
+}
+
+int16 Player::GetSkillPermBonusValue(uint32 skill) const
+{
+ if (!skill)
+ return 0;
+
+ SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
+ if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
+ return 0;
+
+ return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
+}
+
+int16 Player::GetSkillTempBonusValue(uint32 skill) const
+{
+ if (!skill)
+ return 0;
+
+ SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
+ if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
+ return 0;
+
+return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
+}
+
+void Player::SendActionButtons(uint32 state) const
+{
+ sLog.outDetail( "Sending Action Buttons for '%u' spec '%u'", GetGUIDLow(), m_activeSpec);
+
+ WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
+ data << uint8(state); // can be 0, 1, 2
+ if (state != 2)
+ {
+ for (uint16 button = 0; button < MAX_ACTION_BUTTONS; ++button)
+ {
+ ActionButtonList::const_iterator itr = m_actionButtons.find(button);
+ if (itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
+ data << uint32(itr->second.packedData);
+ else
+ data << uint32(0);
+ }
+ }
+
+ GetSession()->SendPacket(&data);
+ sLog.outDetail("Action Buttons for '%u' spec '%u' Sent", GetGUIDLow(), m_activeSpec);
+}
+
+ActionButton* Player::addActionButton(uint8 button, uint32 action, uint8 type)
+{
+ if(button >= MAX_ACTION_BUTTONS)
+ {
+ sLog.outError( "Action %u not added into button %u for player %s: button must be < 144", action, button, GetName() );
+ return NULL;
+ }
+
+ if(action >= MAX_ACTION_BUTTON_ACTION_VALUE)
+ {
+ sLog.outError( "Action %u not added into button %u for player %s: action must be < %u", action, button, GetName(), MAX_ACTION_BUTTON_ACTION_VALUE );
+ return NULL;
+ }
+
+ switch (type)
+ {
+ case ACTION_BUTTON_SPELL:
+ if (!sSpellStore.LookupEntry(action))
+ {
+ sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
+ return NULL;
+ }
+
+ if (!HasSpell(action))
+ {
+ sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
+ return NULL;
+ }
+ break;
+ case ACTION_BUTTON_ITEM:
+ if (!objmgr.GetItemPrototype(action))
+ {
+ sLog.outError( "Action %u not added into button %u for player %s: item not exist", action, button, GetName() );
+ return NULL;
+ }
+ break;
+ default:
+ break; // pther cases not checked at this moment
+ }
+
+ // it create new button (NEW state) if need or return existed
+ ActionButton& ab = m_actionButtons[button];
+
+ // set data and update to CHANGED if not NEW
+ ab.SetActionAndType(action,ActionButtonType(type));
+
+ sLog.outDetail("Player '%u' Added Action '%u' (type %u) to Button '%u'", GetGUIDLow(), action, type, button);
+ return &ab;
+}
+
+void Player::removeActionButton(uint8 button)
+{
+ ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
+ if (buttonItr == m_actionButtons.end())
+ return;
+
+ if (!buttonItr->second.canRemoveByClient)
+ {
+ buttonItr->second.canRemoveByClient = true;
+ return;
+ }
+ if(buttonItr->second.uState==ACTIONBUTTON_NEW)
+ m_actionButtons.erase(buttonItr); // new and not saved
+ else
+ buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
+
+ sLog.outDetail("Action Button '%u' Removed from Player '%u'", button, GetGUIDLow());
+}
+
+bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
+{
+ if (!Unit::SetPosition(x, y, z, orientation, teleport))
+ return false;
+
+ //if(movementInfo.flags & MOVEMENTFLAG_MOVING)
+ // mover->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE);
+ //if(movementInfo.flags & MOVEMENTFLAG_TURNING)
+ // mover->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
+ //AURA_INTERRUPT_FLAG_JUMP not sure
+
+ // group update
+ if (GetGroup())
+ SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
+
+ // code block for underwater state update
+ UpdateUnderwaterState(GetMap(), x, y, z);
+
+ if(GetTrader() && !IsWithinDistInMap(GetTrader(), INTERACTION_DISTANCE))
+ GetSession()->SendCancelTrade();
+
+ CheckExploreSystem();
+
+ return true;
+}
+
+void Player::SaveRecallPosition()
+{
+ m_recallMap = GetMapId();
+ m_recallX = GetPositionX();
+ m_recallY = GetPositionY();
+ m_recallZ = GetPositionZ();
+ m_recallO = GetOrientation();
+}
+
+void Player::SendMessageToSet(WorldPacket *data, bool self)
+{
+ if (self)
+ GetSession()->SendPacket(data);
+
+ // we use World::GetMaxVisibleDistance() because i cannot see why not use a distance
+ // update: replaced by GetMap()->GetVisibilityDistance()
+ Trinity::MessageDistDeliverer notifier(this, data, GetMap()->GetVisibilityDistance());
+ VisitNearbyWorldObject(GetMap()->GetVisibilityDistance(), notifier);
+}
+
+void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
+{
+ if (self)
+ GetSession()->SendPacket(data);
+
+ Trinity::MessageDistDeliverer notifier(this, data, dist);
+ VisitNearbyWorldObject(dist, notifier);
+}
+
+void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
+{
+ if (self)
+ GetSession()->SendPacket(data);
+
+ Trinity::MessageDistDeliverer notifier(this, data, dist, own_team_only);
+ VisitNearbyWorldObject(dist, notifier);
+}
+
+void Player::SendDirectMessage(WorldPacket *data)
+{
+ if (m_session)
+ m_session->SendPacket(data);
+}
+
+void Player::SendCinematicStart(uint32 CinematicSequenceId)
+{
+ WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
+ data << uint32(CinematicSequenceId);
+ SendDirectMessage(&data);
+}
+
+void Player::SendMovieStart(uint32 MovieId)
+{
+ WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
+ data << uint32(MovieId);
+ SendDirectMessage(&data);
+}
+
+void Player::CheckExploreSystem()
+{
+ if (!isAlive())
+ return;
+
+ if (isInFlight())
+ return;
+
+ if(!m_AreaID)
+ m_AreaID = GetAreaId();
+ if(m_AreaID != GetAreaId())
+ {
+ m_AreaID = GetAreaId();
+ GetSession()->HandleOnAreaChange(GetAreaEntryByAreaID(m_AreaID));
+ }
+
+ uint16 areaFlag = GetBaseMap()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
+ if(areaFlag==0xffff)
+ return;
+ int offset = areaFlag / 32;
+
+ if(offset >= 128)
+ {
+ 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);
+ return;
+ }
+
+ uint32 val = (uint32)(1 << (areaFlag % 32));
+ uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
+
+ if( !(currFields & val) )
+ {
+ SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
+
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
+
+ AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
+ if(!p)
+ {
+ sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
+ }
+ else if(p->area_level > 0)
+ {
+ uint32 area = p->ID;
+ if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
+ {
+ SendExplorationExperience(area,0);
+ }
+ else
+ {
+ int32 diff = int32(getLevel()) - p->area_level;
+ uint32 XP = 0;
+ if (diff < -5)
+ {
+ XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
+ }
+ else if (diff > 5)
+ {
+ int32 exploration_percent = (100-((diff-5)*5));
+ if (exploration_percent > 100)
+ exploration_percent = 100;
+ else if (exploration_percent < 0)
+ exploration_percent = 0;
+
+ XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
+ }
+ else
+ {
+ XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
+ }
+
+ GiveXP( XP, NULL );
+ SendExplorationExperience(area,XP);
+ }
+ sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
+ }
+ }
+}
+
+uint32 Player::TeamForRace(uint8 race)
+{
+ ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
+ if(!rEntry)
+ {
+ sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
+ return ALLIANCE;
+ }
+
+ switch(rEntry->TeamID)
+ {
+ case 7: return ALLIANCE;
+ case 1: return HORDE;
+ }
+
+ sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
+ return ALLIANCE;
+}
+
+uint32 Player::getFactionForRace(uint8 race)
+{
+ ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
+ if(!rEntry)
+ {
+ sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
+ return 0;
+ }
+
+ return rEntry->FactionID;
+}
+
+void Player::setFactionForRace(uint8 race)
+{
+ m_team = TeamForRace(race);
+ setFaction( getFactionForRace(race) );
+}
+
+ReputationRank Player::GetReputationRank(uint32 faction) const
+{
+ FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
+ return GetReputationMgr().GetRank(factionEntry);
+}
+
+//Calculate total reputation percent player gain with quest/creature level
+int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest)
+{
+ float percent = 100.0f;
+
+ float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL);
+
+ if (rate != 1.0f && creatureOrQuestLevel <= Trinity::XP::GetGrayLevel(getLevel()))
+ percent *= rate;
+
+ float repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
+
+ if (!for_quest)
+ repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);
+
+ percent += rep > 0 ? repMod : -repMod;
+
+ if (percent <= 0.0f)
+ return 0;
+
+ return int32(rep*percent/100);
+}
+
+//Calculates how many reputation points player gains in victim's enemy factions
+void Player::RewardReputation(Unit *pVictim, float rate)
+{
+ if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
+ return;
+
+ if(((Creature*)pVictim)->IsReputationGainDisabled())
+ return;
+
+ ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
+
+ if(!Rep)
+ return;
+
+ uint32 ChampioningFaction = 0;
+
+ if(GetChampioningFaction())
+ {
+ // support for: Championing - http://www.wowwiki.com/Championing
+
+ Map const *pMap = GetMap();
+ if(pMap && pMap->IsDungeon())
+ {
+ bool Heroic = ((InstanceMap*)pMap)->GetDifficulty() == DUNGEON_DIFFICULTY_HEROIC;
+
+ InstanceTemplate const *pInstance = objmgr.GetInstanceTemplate(pMap->GetId());
+ if(pInstance)
+ {
+ AccessRequirement const *pAccessRequirement = objmgr.GetAccessRequirement(pInstance->access_id);
+ if(pAccessRequirement)
+ {
+ if(!pMap->IsRaid() && ((!Heroic && pAccessRequirement->levelMin == 80) || (Heroic && pAccessRequirement->heroicLevelMin == 80)))
+ ChampioningFaction = GetChampioningFaction();
+ }
+ }
+ }
+ }
+
+ // Favored reputation increase START
+ uint32 zone = GetZoneId();
+ uint32 team = GetTeam();
+ float favored_rep_mult = 0;
+
+ if( (HasAura(32096) || HasAura(32098)) && (zone == 3483 || zone == 3562 || zone == 3836 || zone == 3713 || zone == 3714) ) favored_rep_mult = 0.25; // Thrallmar's Favor and Honor Hold's Favor
+ else if( HasAura(30754) && (Rep->repfaction1 == 609 || Rep->repfaction2 == 609) && !ChampioningFaction ) favored_rep_mult = 0.25; // Cenarion Favor
+
+ if(favored_rep_mult > 0) favored_rep_mult *= 2; // Multiplied by 2 because the reputation is divided by 2 for some reason (See "donerep1 / 2" and "donerep2 / 2") -- if you know why this is done, please update/explain :)
+ // Favored reputation increase END
+
+ if(Rep->repfaction1 && (!Rep->team_dependent || team == ALLIANCE))
+ {
+ int32 donerep1 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue1, ChampioningFaction ? ChampioningFaction : Rep->repfaction1, false);
+ donerep1 = int32(donerep1*(rate + favored_rep_mult));
+ FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(ChampioningFaction ? ChampioningFaction : Rep->repfaction1);
+ uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
+ if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
+ GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
+
+ // Wiki: Team factions value divided by 2 -- Deprecated, see ModifyReputation
+ /*if (factionEntry1 && Rep->is_teamaward1)
+ {
+ FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
+ if(team1_factionEntry)
+ GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
+ }*/
+ }
+
+ if(Rep->repfaction2 && (!Rep->team_dependent || team == HORDE))
+ {
+ int32 donerep2 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue2, ChampioningFaction ? ChampioningFaction : Rep->repfaction2, false);
+ donerep2 = int32(donerep2*(rate + favored_rep_mult));
+ FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(ChampioningFaction ? ChampioningFaction : Rep->repfaction2);
+ uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
+ if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
+ GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
+
+ // Wiki: Team factions value divided by 2 -- Deprecated, see ModifyReputation
+ /*if (factionEntry2 && Rep->is_teamaward2)
+ {
+ FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
+ if(team2_factionEntry)
+ GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
+ }*/
+ }
+}
+
+//Calculate how many reputation points player gain with the quest
+void Player::RewardReputation(Quest const *pQuest)
+{
+ // quest reputation reward/loss
+ for (uint8 i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
+ {
+ if (!pQuest->RewRepFaction[i])
+ continue;
+ if (pQuest->RewRepValue[i])
+ {
+ int32 rep = CalculateReputationGain(GetQuestLevel(pQuest), pQuest->RewRepValue[i], pQuest->RewRepFaction[i], true);
+ if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]))
+ GetReputationMgr().ModifyReputation(factionEntry, rep);
+ }
+ else
+ {
+ uint32 row = 1;
+ int32 field = 0;
+
+ if (pQuest->RewRepValueId[i] < 0)
+ {
+ ++row;
+ field = abs(pQuest->RewRepValueId[i]);
+ }
+ else
+ field = pQuest->RewRepValueId[i];
+ if (const QuestFactionRewEntry *pRow = sQuestFactionRewardStore.LookupEntry(row))
+ {
+ int32 repPoints = pRow->QuestRewFactionValue[field];
+
+ if (!repPoints)
+ continue;
+
+ repPoints = CalculateReputationGain(GetQuestLevel(pQuest), repPoints, pQuest->RewRepFaction[i], true);
+ if (const FactionEntry* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]))
+ GetReputationMgr().ModifyReputation(factionEntry, repPoints);
+ }
+ }
+ }
+
+ // TODO: implement reputation spillover
+}
+
+void Player::UpdateHonorFields()
+{
+ /// called when rewarding honor and at each save
+ uint64 now = time(NULL);
+ uint64 today = uint64(time(NULL) / DAY) * DAY;
+
+ if(m_lastHonorUpdateTime < today)
+ {
+ uint64 yesterday = today - DAY;
+
+ uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
+
+ // update yesterday's contribution
+ if(m_lastHonorUpdateTime >= yesterday )
+ {
+ SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
+
+ // this is the first update today, reset today's contribution
+ SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
+ SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
+ }
+ else
+ {
+ // no honor/kills yesterday or today, reset
+ SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
+ SetUInt32Value(PLAYER_FIELD_KILLS, 0);
+ }
+ }
+
+ m_lastHonorUpdateTime = now;
+}
+
+///Calculate the amount of honor gained based on the victim
+///and the size of the group for which the honor is divided
+///An exact honor value can also be given (overriding the calcs)
+bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor, bool pvptoken)
+{
+ // do not reward honor in arenas, but enable onkill spellproc
+ if(InArena())
+ {
+ if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
+ return false;
+
+ if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
+ return false;
+
+ return true;
+ }
+
+ // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
+ if(HasAura(SPELL_AURA_PLAYER_INACTIVE))
+ return false;
+
+ uint64 victim_guid = 0;
+ uint32 victim_rank = 0;
+ uint32 rank_diff = 0;
+ time_t now = time(NULL);
+
+ // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
+ UpdateHonorFields();
+
+ // do not reward honor in arenas, but return true to enable onkill spellproc
+ if(InBattleGround() && GetBattleGround() && GetBattleGround()->isArena())
+ return true;
+
+ if(honor <= 0)
+ {
+ if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
+ return false;
+
+ victim_guid = uVictim->GetGUID();
+
+ if( uVictim->GetTypeId() == TYPEID_PLAYER )
+ {
+ Player *pVictim = (Player *)uVictim;
+
+ if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
+ return false;
+
+ float f = 1; //need for total kills (?? need more info)
+ uint32 k_grey = 0;
+ uint32 k_level = getLevel();
+ uint32 v_level = pVictim->getLevel();
+
+ {
+ // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
+ // [0] Just name
+ // [1..14] Alliance honor titles and player name
+ // [15..28] Horde honor titles and player name
+ // [29..38] Other title and player name
+ // [39+] Nothing
+ uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
+ // Get Killer titles, CharTitlesEntry::bit_index
+ // Ranks:
+ // title[1..14] -> rank[5..18]
+ // title[15..28] -> rank[5..18]
+ // title[other] -> 0
+ if (victim_title == 0)
+ victim_guid = 0; // Don't show HK: <rank> message, only log.
+ else if (victim_title < 15)
+ victim_rank = victim_title + 4;
+ else if (victim_title < 29)
+ victim_rank = victim_title - 14 + 4;
+ else
+ victim_guid = 0; // Don't show HK: <rank> message, only log.
+ }
+
+ k_grey = Trinity::XP::GetGrayLevel(k_level);
+
+ if(v_level<=k_grey)
+ return false;
+
+ float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
+
+ int32 v_rank =1; //need more info
+
+ honor = ((f * diff_level * (190 + v_rank*10))/6);
+ honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
+
+ // count the number of playerkills in one day
+ ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
+ // and those in a lifetime
+ ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS, 1, true);
+ UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
+ UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
+ UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
+ }
+ else
+ {
+ Creature *cVictim = (Creature *)uVictim;
+
+ if (!cVictim->isRacialLeader())
+ return false;
+
+ honor = 100; // ??? need more info
+ victim_rank = 19; // HK: Leader
+ }
+ }
+
+ if (uVictim != NULL)
+ {
+ honor *= sWorld.getRate(RATE_HONOR);
+
+ if(groupsize > 1)
+ honor /= groupsize;
+
+ // apply honor multiplier from aura (not stacking-get highest)
+ honor = int32(float(honor) * (float(GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN_PCT))+100.0f)/100.0f);
+ honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
+ }
+
+ // honor - for show honor points in log
+ // victim_guid - for show victim name in log
+ // victim_rank [1..4] HK: <dishonored rank>
+ // victim_rank [5..19] HK: <alliance\horde rank>
+ // victim_rank [0,20+] HK: <>
+ WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
+ data << (uint32) honor;
+ data << (uint64) victim_guid;
+ data << (uint32) victim_rank;
+
+ GetSession()->SendPacket(&data);
+
+ // add honor points
+ ModifyHonorPoints(int32(honor));
+
+ ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
+
+ if( sWorld.getConfig(CONFIG_PVP_TOKEN_ENABLE) && pvptoken )
+ {
+ if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
+ return true;
+
+ if(uVictim->GetTypeId() == TYPEID_PLAYER)
+ {
+ // Check if allowed to receive it in current map
+ uint8 MapType = sWorld.getConfig(CONFIG_PVP_TOKEN_MAP_TYPE);
+ if( (MapType == 1 && !InBattleGround() && !HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
+ || (MapType == 2 && !HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
+ || (MapType == 3 && !InBattleGround()) )
+ return true;
+
+ uint32 noSpaceForCount = 0;
+ uint32 itemId = sWorld.getConfig(CONFIG_PVP_TOKEN_ID);
+ int32 count = sWorld.getConfig(CONFIG_PVP_TOKEN_COUNT);
+
+ // check space and find places
+ ItemPosCountVec dest;
+ uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, count, &noSpaceForCount );
+ if( msg != EQUIP_ERR_OK ) // convert to possible store amount
+ count = noSpaceForCount;
+
+ if( count == 0 || dest.empty()) // can't add any
+ {
+ // -- TODO: Send to mailbox if no space
+ ChatHandler(this).PSendSysMessage("You don't have any space in your bags for a token.");
+ return true;
+ }
+
+ Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
+ SendNewItem(item,count,true,false);
+ ChatHandler(this).PSendSysMessage("You have been awarded a token for slaying another player.");
+ }
+ }
+
+ return true;
+}
+
+void Player::ModifyHonorPoints(int32 value)
+{
+ if(value < 0)
+ {
+ if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
+ SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
+ else
+ SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
+ }
+ else
+ SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
+}
+
+void Player::ModifyArenaPoints(int32 value)
+{
+ if(value < 0)
+ {
+ if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
+ SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
+ else
+ SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
+ }
+ else
+ SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
+}
+
+uint32 Player::GetGuildIdFromDB(uint64 guid)
+{
+ QueryResult_AutoPtr result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
+ if(!result)
+ return 0;
+
+ uint32 id = result->Fetch()[0].GetUInt32();
+ return id;
+}
+
+uint32 Player::GetRankFromDB(uint64 guid)
+{
+ QueryResult_AutoPtr result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
+ if( result )
+ {
+ uint32 v = result->Fetch()[0].GetUInt32();
+ return v;
+ }
+ else
+ return 0;
+}
+
+uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
+{
+ QueryResult_AutoPtr 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);
+ if(!result)
+ return 0;
+
+ uint32 id = (*result)[0].GetUInt32();
+ return id;
+}
+
+uint32 Player::GetZoneIdFromDB(uint64 guid)
+{
+ uint32 guidLow = GUID_LOPART(guid);
+ QueryResult_AutoPtr result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
+ if (!result)
+ return 0;
+ Field* fields = result->Fetch();
+ uint32 zone = fields[0].GetUInt32();
+
+ if (!zone)
+ {
+ // stored zone is zero, use generic and slow zone detection
+ result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
+ if( !result )
+ return 0;
+ fields = result->Fetch();
+ uint32 map = fields[0].GetUInt32();
+ float posx = fields[1].GetFloat();
+ float posy = fields[2].GetFloat();
+ float posz = fields[3].GetFloat();
+
+ zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
+
+ if (zone > 0)
+ CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
+ }
+
+ return zone;
+}
+
+uint32 Player::GetLevelFromDB(uint64 guid)
+{
+ QueryResult_AutoPtr result = CharacterDatabase.PQuery("SELECT level FROM characters WHERE guid='%u'", GUID_LOPART(guid));
+ if (!result)
+ return 0;
+
+ Field* fields = result->Fetch();
+ uint8 level = fields[0].GetUInt8();
+
+ return level;
+}
+
+void Player::UpdateArea(uint32 newArea)
+{
+ // FFA_PVP flags are area and not zone id dependent
+ // so apply them accordingly
+ m_areaUpdateId = newArea;
+
+ AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
+ pvpInfo.inFFAPvPArea = area && (area->flags & AREA_FLAG_ARENA);
+ UpdatePvPState(true);
+
+ UpdateAreaDependentAuras(newArea);
+}
+
+void Player::UpdateZone(uint32 newZone, uint32 newArea)
+{
+ if (m_zoneUpdateId != newZone)
+ {
+ sOutdoorPvPMgr.HandlePlayerLeaveZone(this, m_zoneUpdateId);
+ sOutdoorPvPMgr.HandlePlayerEnterZone(this, newZone);
+ SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
+ }
+
+ m_zoneUpdateId = newZone;
+ m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
+
+ // zone changed, so area changed as well, update it
+ UpdateArea(newArea);
+
+ AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
+ if (!zone)
+ return;
+
+ if (sWorld.getConfig(CONFIG_WEATHER))
+ {
+ Weather *wth = sWorld.FindWeather(zone->ID);
+ if (wth)
+ wth->SendWeatherUpdateToPlayer(this);
+ else
+ {
+ if (!sWorld.AddWeather(zone->ID))
+ {
+ // send fine weather packet to remove old zone's weather
+ Weather::SendFineWeatherUpdateToPlayer(this);
+ }
+ }
+ }
+
+ // in PvP, any not controlled zone (except zone->team == 6, default case)
+ // in PvE, only opposition team capital
+ switch (zone->team)
+ {
+ case AREATEAM_ALLY:
+ pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
+ break;
+ case AREATEAM_HORDE:
+ pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
+ break;
+ case AREATEAM_NONE:
+ // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
+ pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround() || zone->flags & AREA_FLAG_OUTDOOR_PVP;
+ break;
+ default: // 6 in fact
+ pvpInfo.inHostileArea = false;
+ break;
+ }
+
+ pvpInfo.inNoPvPArea = false;
+ if(zone->IsSanctuary()) // in sanctuary
+ {
+ SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
+ pvpInfo.inNoPvPArea = true;
+ CombatStopWithPets();
+ }
+ else
+ RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
+
+ if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
+ {
+ SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
+ SetRestType(REST_TYPE_IN_CITY);
+ InnEnter(time(0),GetMapId(),0,0,0);
+ pvpInfo.inNoPvPArea = true;
+ }
+ else // anywhere else
+ {
+ if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
+ {
+ if(GetRestType() == REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
+ {
+ if(GetMapId() != GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
+ {
+ RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
+ SetRestType(REST_TYPE_NO);
+ }
+ }
+ else // not in tavern (leave city then)
+ {
+ RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
+ SetRestType(REST_TYPE_NO);
+ }
+ }
+ }
+
+ UpdatePvPState();
+
+ // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
+ // if player resurrected at teleport this will be applied in resurrect code
+ if (isAlive())
+ DestroyZoneLimitedItem(true, newZone);
+
+ // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
+ AutoUnequipOffhandIfNeed();
+
+ // recent client version not send leave/join channel packets for built-in local channels
+ UpdateLocalChannels(newZone);
+
+ // group update
+ if (GetGroup())
+ SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
+
+ UpdateZoneDependentAuras(newZone);
+}
+
+//If players are too far way of duel flag... then player loose the duel
+void Player::CheckDuelDistance(time_t currTime)
+{
+ if (!duel)
+ return;
+
+ uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
+ GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
+ if (!obj)
+ return;
+
+ if (duel->outOfBound == 0)
+ {
+ if (!IsWithinDistInMap(obj, 50))
+ {
+ duel->outOfBound = currTime;
+
+ WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
+ GetSession()->SendPacket(&data);
+ }
+ }
+ else
+ {
+ if (IsWithinDistInMap(obj, 40))
+ {
+ duel->outOfBound = 0;
+
+ WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
+ GetSession()->SendPacket(&data);
+ }
+ else if (currTime >= (duel->outOfBound+10))
+ DuelComplete(DUEL_FLED);
+ }
+}
+
+bool Player::IsOutdoorPvPActive()
+{
+ return isAlive() && !HasInvisibilityAura() && !HasStealthAura() && (IsPvP() || sWorld.IsPvPRealm()) && !HasUnitMovementFlag(MOVEMENTFLAG_FLYING) && !isInFlight();
+}
+
+void Player::DuelComplete(DuelCompleteType type)
+{
+ // duel not requested
+ if (!duel)
+ return;
+
+ sLog.outDebug("Duel Complete %s %s", GetName(), duel->opponent->GetName());
+
+ WorldPacket data(SMSG_DUEL_COMPLETE, (1));
+ data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
+ GetSession()->SendPacket(&data);
+ duel->opponent->GetSession()->SendPacket(&data);
+
+ if (type != DUEL_INTERUPTED)
+ {
+ data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
+ data << uint8(type == DUEL_WON ? 0 : 1); // 0 = just won; 1 = fled
+ data << duel->opponent->GetName();
+ data << GetName();
+ SendMessageToSet(&data,true);
+ }
+
+ switch (type)
+ {
+ case DUEL_FLED:
+ // if initiator and opponent are on the same team
+ // or initiator and opponent are not PvP enabled, forcibly stop attacking
+ if (duel->initiator->GetTeam() == duel->opponent->GetTeam())
+ {
+ duel->initiator->AttackStop();
+ duel->opponent->AttackStop();
+ }
+ else
+ {
+ if (!duel->initiator->IsPvP())
+ duel->initiator->AttackStop();
+ if (!duel->opponent->IsPvP())
+ duel->opponent->AttackStop();
+ }
+ break;
+ case DUEL_WON:
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
+ if (duel->opponent)
+ {
+ duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
+
+ //Credit for quest Death's Challenge
+ if (getClass() == CLASS_DEATH_KNIGHT && duel->opponent->GetQuestStatus(12733) == QUEST_STATUS_INCOMPLETE)
+ duel->opponent->CastSpell(duel->opponent, 52994, true);
+ }
+ break;
+ }
+
+ //Remove Duel Flag object
+ GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
+ if(obj)
+ duel->initiator->RemoveGameObject(obj,true);
+
+ /* remove auras */
+ AuraApplicationMap &itsAuras = duel->opponent->GetAppliedAuras();
+ for (AuraApplicationMap::iterator i = itsAuras.begin(); i != itsAuras.end();)
+ {
+ Aura const * aura = i->second->GetBase();
+ if (!i->second->IsPositive() && aura->GetCasterGUID() == GetGUID() && aura->GetApplyTime() >= duel->startTime)
+ duel->opponent->RemoveAura(i);
+ else
+ ++i;
+ }
+
+ AuraApplicationMap &myAuras = GetAppliedAuras();
+ for (AuraApplicationMap::iterator i = myAuras.begin(); i != myAuras.end();)
+ {
+ Aura const * aura = i->second->GetBase();
+ if (!i->second->IsPositive() && aura->GetCasterGUID() == duel->opponent->GetGUID() && aura->GetApplyTime() >= duel->startTime)
+ RemoveAura(i);
+ else
+ ++i;
+ }
+
+ // cleanup combo points
+ if(GetComboTarget()==duel->opponent->GetGUID())
+ ClearComboPoints();
+ else if(GetComboTarget()==duel->opponent->GetPetGUID())
+ ClearComboPoints();
+
+ if(duel->opponent->GetComboTarget()==GetGUID())
+ duel->opponent->ClearComboPoints();
+ else if(duel->opponent->GetComboTarget()==GetPetGUID())
+ duel->opponent->ClearComboPoints();
+
+ // Honor points after duel (the winner) - ImpConfig
+ if(uint32 amount = sWorld.getConfig(CONFIG_HONOR_AFTER_DUEL))
+ duel->opponent->RewardHonor(NULL,1,amount);
+
+ //cleanups
+ SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
+ SetUInt32Value(PLAYER_DUEL_TEAM, 0);
+ duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
+ duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
+
+ delete duel->opponent->duel;
+ duel->opponent->duel = NULL;
+ delete duel;
+ duel = NULL;
+}
+
+//---------------------------------------------------------//
+
+void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
+{
+ if(slot >= INVENTORY_SLOT_BAG_END || !item)
+ return;
+
+ ItemPrototype const *proto = item->GetProto();
+
+ if (!proto)
+ return;
+
+ if (proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
+ CorrectMetaGemEnchants(slot, apply);
+
+ // not apply/remove mods for broken item
+ if (item->IsBroken())
+ return;
+
+ sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
+
+ uint8 attacktype = Player::GetAttackBySlot(slot);
+
+ // check disarm only on mod apply to allow remove item mods
+ if (!CanUseAttackType(attacktype) )
+ return;
+
+ if (attacktype < MAX_ATTACK)
+ _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
+
+ _ApplyItemBonuses(proto,slot,apply);
+
+ if (slot==EQUIPMENT_SLOT_RANGED)
+ _ApplyAmmoBonuses();
+
+ ApplyItemEquipSpell(item,apply);
+ ApplyEnchantment(item, apply);
+
+ sLog.outDebug("_ApplyItemMods complete.");
+}
+
+void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply, bool only_level_scale /*= false*/)
+{
+ if (slot >= INVENTORY_SLOT_BAG_END || !proto)
+ return;
+
+ ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : NULL;
+ if (only_level_scale && !ssd)
+ return;
+
+ // req. check at equip, but allow use for extended range if range limit max level, set proper level
+ uint32 ssd_level = getLevel();
+ if (ssd && ssd_level > ssd->MaxLevel)
+ ssd_level = ssd->MaxLevel;
+
+ ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(ssd_level) : NULL;
+ if (only_level_scale && !ssv)
+ return;
+
+ for (uint8 i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
+ {
+ uint32 statType = 0;
+ int32 val = 0;
+ // If set ScalingStatDistribution need get stats and values from it
+ if (ssd && ssv)
+ {
+ if (ssd->StatMod[i] < 0)
+ continue;
+ statType = ssd->StatMod[i];
+ val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[i]) / 10000;
+ }
+ else
+ {
+ if (i >= proto->StatsCount)
+ continue;
+ statType = proto->ItemStat[i].ItemStatType;
+ val = proto->ItemStat[i].ItemStatValue;
+ }
+
+ if(val == 0)
+ continue;
+
+ switch (statType)
+ {
+ case ITEM_MOD_MANA:
+ HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
+ break;
+ case ITEM_MOD_HEALTH: // modify HP
+ HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
+ break;
+ case ITEM_MOD_AGILITY: // modify agility
+ HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
+ ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
+ break;
+ case ITEM_MOD_STRENGTH: //modify strength
+ HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
+ ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
+ break;
+ case ITEM_MOD_INTELLECT: //modify intellect
+ HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
+ ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
+ break;
+ case ITEM_MOD_SPIRIT: //modify spirit
+ HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
+ ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
+ break;
+ case ITEM_MOD_STAMINA: //modify stamina
+ HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
+ ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
+ break;
+ case ITEM_MOD_DEFENSE_SKILL_RATING:
+ ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
+ break;
+ case ITEM_MOD_DODGE_RATING:
+ ApplyRatingMod(CR_DODGE, int32(val), apply);
+ break;
+ case ITEM_MOD_PARRY_RATING:
+ ApplyRatingMod(CR_PARRY, int32(val), apply);
+ break;
+ case ITEM_MOD_BLOCK_RATING:
+ ApplyRatingMod(CR_BLOCK, int32(val), apply);
+ break;
+ case ITEM_MOD_HIT_MELEE_RATING:
+ ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
+ break;
+ case ITEM_MOD_HIT_RANGED_RATING:
+ ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
+ break;
+ case ITEM_MOD_HIT_SPELL_RATING:
+ ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
+ break;
+ case ITEM_MOD_CRIT_MELEE_RATING:
+ ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
+ break;
+ case ITEM_MOD_CRIT_RANGED_RATING:
+ ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
+ break;
+ case ITEM_MOD_CRIT_SPELL_RATING:
+ ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
+ break;
+ case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
+ ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
+ break;
+ case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
+ ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
+ break;
+ case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
+ ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
+ break;
+ case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
+ ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
+ break;
+ case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
+ ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
+ break;
+ case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
+ ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
+ break;
+ case ITEM_MOD_HASTE_MELEE_RATING:
+ ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
+ break;
+ case ITEM_MOD_HASTE_RANGED_RATING:
+ ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
+ break;
+ case ITEM_MOD_HASTE_SPELL_RATING:
+ ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
+ break;
+ case ITEM_MOD_HIT_RATING:
+ ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
+ ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
+ ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
+ break;
+ case ITEM_MOD_CRIT_RATING:
+ ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
+ ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
+ ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
+ break;
+ case ITEM_MOD_HIT_TAKEN_RATING:
+ ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
+ ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
+ ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
+ break;
+ case ITEM_MOD_CRIT_TAKEN_RATING:
+ ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
+ ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
+ ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
+ break;
+ case ITEM_MOD_RESILIENCE_RATING:
+ ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
+ ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
+ ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
+ break;
+ case ITEM_MOD_HASTE_RATING:
+ ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
+ ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
+ ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
+ break;
+ case ITEM_MOD_EXPERTISE_RATING:
+ ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
+ break;
+ case ITEM_MOD_ATTACK_POWER:
+ HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
+ HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
+ break;
+ case ITEM_MOD_RANGED_ATTACK_POWER:
+ HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
+ break;
+// case ITEM_MOD_FERAL_ATTACK_POWER:
+// ApplyFeralAPBonus(int32(val), apply);
+// break;
+ case ITEM_MOD_MANA_REGENERATION:
+ ApplyManaRegenBonus(int32(val), apply);
+ break;
+ case ITEM_MOD_ARMOR_PENETRATION_RATING:
+ ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
+ break;
+ case ITEM_MOD_SPELL_POWER:
+ ApplySpellPowerBonus(int32(val), apply);
+ break;
+ case ITEM_MOD_HEALTH_REGEN:
+ ApplyHealthRegenBonus(int32(val), apply);
+ break;
+ // depricated item mods
+ case ITEM_MOD_SPELL_HEALING_DONE:
+ case ITEM_MOD_SPELL_DAMAGE_DONE:
+ break;
+ }
+ }
+
+ // Apply Spell Power from ScalingStatValue if set
+ if(ssv)
+ {
+ if (int32 spellbonus = ssv->getSpellBonus(proto->ScalingStatValue))
+ ApplySpellPowerBonus(spellbonus, apply);
+ }
+
+ // If set ScalingStatValue armor get it or use item armor
+ uint32 armor = proto->Armor;
+ if (ssv)
+ {
+ if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue))
+ armor = ssvarmor;
+ }
+
+ if (armor)
+ {
+ UnitModifierType modType = TOTAL_VALUE;
+ if (proto->Class == ITEM_CLASS_ARMOR)
+ {
+ switch (proto->SubClass)
+ {
+ case ITEM_SUBCLASS_ARMOR_CLOTH:
+ case ITEM_SUBCLASS_ARMOR_LEATHER:
+ case ITEM_SUBCLASS_ARMOR_MAIL:
+ case ITEM_SUBCLASS_ARMOR_PLATE:
+ case ITEM_SUBCLASS_ARMOR_SHIELD:
+ modType = BASE_VALUE;
+ break;
+ }
+ }
+ HandleStatModifier(UNIT_MOD_ARMOR, modType, float(armor), apply);
+ }
+
+ // Add armor bonus from ArmorDamageModifier if > 0
+ if (proto->ArmorDamageModifier > 0)
+ HandleStatModifier(UNIT_MOD_ARMOR, TOTAL_VALUE, float(proto->ArmorDamageModifier), apply);
+
+ if (proto->Block)
+ HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
+
+ if (proto->HolyRes)
+ HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
+
+ if (proto->FireRes)
+ HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
+
+ if (proto->NatureRes)
+ HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
+
+ if (proto->FrostRes)
+ HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
+
+ if (proto->ShadowRes)
+ HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
+
+ if (proto->ArcaneRes)
+ HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
+
+ WeaponAttackType attType = BASE_ATTACK;
+ float damage = 0.0f;
+
+ if( slot == EQUIPMENT_SLOT_RANGED && (
+ proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
+ proto->InventoryType == INVTYPE_RANGEDRIGHT ))
+ {
+ attType = RANGED_ATTACK;
+ }
+ else if(slot==EQUIPMENT_SLOT_OFFHAND)
+ {
+ attType = OFF_ATTACK;
+ }
+
+ float minDamage = proto->Damage[0].DamageMin;
+ float maxDamage = proto->Damage[0].DamageMax;
+ int32 extraDPS = 0;
+ // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
+ if (ssv)
+ {
+ if ((extraDPS = ssv->getDPSMod(proto->ScalingStatValue)))
+ {
+ float average = extraDPS * proto->Delay / 1000.0f;
+ minDamage = 0.7f * average;
+ maxDamage = 1.3f * average;
+ }
+ }
+ if (minDamage > 0 )
+ {
+ damage = apply ? minDamage : BASE_MINDAMAGE;
+ SetBaseWeaponDamage(attType, MINDAMAGE, damage);
+ //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
+ }
+
+ if (maxDamage > 0 )
+ {
+ damage = apply ? maxDamage : BASE_MAXDAMAGE;
+ SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
+ }
+
+ // Apply feral bonus from ScalingStatValue if set
+ if (ssv)
+ {
+ if (int32 feral_bonus = ssv->getFeralBonus(proto->ScalingStatValue))
+ ApplyFeralAPBonus(feral_bonus, apply);
+ }
+ // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
+ if(getClass() == CLASS_DRUID)
+ {
+ int32 feral_bonus = proto->getFeralBonus(extraDPS);
+ if (feral_bonus > 0)
+ ApplyFeralAPBonus(feral_bonus, apply);
+ }
+
+ if(IsInFeralForm() || !CanUseAttackType(attType))
+ return;
+
+ if (proto->Delay)
+ {
+ if(slot == EQUIPMENT_SLOT_RANGED)
+ SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
+ else if(slot==EQUIPMENT_SLOT_MAINHAND)
+ SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
+ else if(slot==EQUIPMENT_SLOT_OFFHAND)
+ SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
+ }
+
+ if(CanModifyStats() && (damage || proto->Delay))
+ UpdateDamagePhysical(attType);
+}
+
+void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
+{
+ AuraEffectList const& auraCritList = GetAuraEffectsByType(SPELL_AURA_MOD_WEAPON_CRIT_PERCENT);
+ for (AuraEffectList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end(); ++itr)
+ _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
+
+ AuraEffectList const& auraDamageFlatList = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE);
+ for (AuraEffectList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end(); ++itr)
+ _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
+
+ AuraEffectList const& auraDamagePCTList = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
+ for (AuraEffectList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end(); ++itr)
+ _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
+}
+
+void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, AuraEffect const* aura, bool apply)
+{
+ // generic not weapon specific case processes in aura code
+ if (aura->GetSpellProto()->EquippedItemClass == -1)
+ return;
+
+ BaseModGroup mod = BASEMOD_END;
+ switch (attackType)
+ {
+ case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
+ case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
+ case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
+ default: return;
+ }
+
+ if (!item->IsBroken()&&item->IsFitToSpellRequirements(aura->GetSpellProto()))
+ HandleBaseModValue(mod, FLAT_MOD, float (aura->GetAmount()), apply);
+}
+
+void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, AuraEffect const* aura, bool apply)
+{
+ //don't apply mod if item is broken
+ if (item->IsBroken())
+ return;
+
+ // ignore spell mods for not wands
+ if ((aura->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL) == 0 && (getClassMask() & CLASSMASK_WAND_USERS) == 0)
+ return;
+
+ // generic not weapon specific case processes in aura code
+ if (aura->GetSpellProto()->EquippedItemClass == -1)
+ return;
+
+ UnitMods unitMod = UNIT_MOD_END;
+ switch (attackType)
+ {
+ case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
+ case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
+ case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
+ default: return;
+ }
+
+ UnitModifierType unitModType = TOTAL_VALUE;
+ switch (aura->GetAuraType())
+ {
+ case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
+ case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
+ default: return;
+ }
+
+ if (!item->IsBroken()&&item->IsFitToSpellRequirements(aura->GetSpellProto()))
+ {
+ HandleStatModifier(unitMod, unitModType, float(aura->GetAmount()),apply);
+
+ if (unitModType == TOTAL_PCT)
+ ApplyModSignedFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT,aura->GetAmount()/100.0f,apply);
+ else
+ ApplyModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS,aura->GetAmount(),apply);
+ }
+}
+
+void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
+{
+ if(!item)
+ return;
+
+ ItemPrototype const *proto = item->GetProto();
+ if(!proto)
+ return;
+
+ for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
+ {
+ _Spell const& spellData = proto->Spells[i];
+
+ // no spell
+ if (!spellData.SpellId)
+ continue;
+
+ // wrong triggering type
+ if (apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
+ continue;
+
+ // check if it is valid spell
+ SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
+ if (!spellproto)
+ continue;
+
+ ApplyEquipSpell(spellproto,item,apply,form_change);
+ }
+}
+
+void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
+{
+ if (apply)
+ {
+ // Cannot be used in this stance/form
+ if (GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
+ return;
+
+ if (form_change) // check aura active state from other form
+ {
+ AuraApplicationMap const& auras = GetAppliedAuras();
+ for (AuraApplicationMap::const_iterator itr = auras.lower_bound(spellInfo->Id); itr != auras.upper_bound(spellInfo->Id); ++itr)
+ if (!item || itr->second->GetBase()->GetCastItemGUID() == item->GetGUID())
+ return;
+ }
+
+ DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
+
+ CastSpell(this,spellInfo,true,item);
+ }
+ else
+ {
+ if(form_change) // check aura compatibility
+ {
+ // Cannot be used in this stance/form
+ if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
+ return; // and remove only not compatible at form change
+ }
+
+ if (item)
+ RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells, not only at-equipped
+ else
+ RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
+ }
+}
+
+void Player::UpdateEquipSpellsAtFormChange()
+{
+ for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
+ {
+ if(m_items[i] && !m_items[i]->IsBroken())
+ {
+ ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
+ ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
+ }
+ }
+
+ // item set bonuses not dependent from item broken state
+ for (size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
+ {
+ ItemSetEffect* eff = ItemSetEff[setindex];
+ if(!eff)
+ continue;
+
+ for (uint32 y=0; y<8; ++y)
+ {
+ SpellEntry const* spellInfo = eff->spells[y];
+ if(!spellInfo)
+ continue;
+
+ ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
+ ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
+ }
+ }
+}
+void Player::CastItemCombatSpell(Unit *target, WeaponAttackType attType, uint32 procVictim, uint32 procEx)
+{
+ if (!target || !target->isAlive() || target == this)
+ return;
+
+ for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
+ {
+ // If usable, try to cast item spell
+ if (Item * item = GetItemByPos(INVENTORY_SLOT_BAG_0,i))
+ if (!item->IsBroken())
+ if (ItemPrototype const *proto = item->GetProto())
+ {
+ // Additional check for weapons
+ if (proto->Class == ITEM_CLASS_WEAPON)
+ {
+ // offhand item cannot proc from main hand hit etc
+ EquipmentSlots slot;
+ switch (attType)
+ {
+ case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
+ case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
+ case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
+ default: slot = EQUIPMENT_SLOT_END; break;
+ }
+ if (slot != i)
+ continue;
+ // Check if item is useable (forms or disarm)
+ if (attType == BASE_ATTACK)
+ if (!IsUseEquipedWeapon(true))
+ continue;
+ }
+ CastItemCombatSpell(target, attType, procVictim, procEx, item, proto);
+ }
+ }
+}
+
+void Player::CastItemCombatSpell(Unit *target, WeaponAttackType attType, uint32 procVictim, uint32 procEx, Item *item, ItemPrototype const * proto)
+{
+ // Can do effect if any damage done to target
+ if (procVictim & PROC_FLAG_TAKEN_ANY_DAMAGE)
+ //if (damageInfo->procVictim & PROC_FLAG_TAKEN_ANY_DAMAGE)
+ {
+ for (uint8 i = 0; i < 5; ++i)
+ {
+ _Spell const& spellData = proto->Spells[i];
+
+ // no spell
+ if (!spellData.SpellId)
+ continue;
+
+ // wrong triggering type
+ if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
+ continue;
+
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
+ if (!spellInfo)
+ {
+ sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
+ continue;
+ }
+
+ // not allow proc extra attack spell at extra attack
+ if (m_extraAttacks && IsSpellHaveEffect(spellInfo, SPELL_EFFECT_ADD_EXTRA_ATTACKS))
+ return;
+
+ float chance = spellInfo->procChance;
+
+ if (spellData.SpellPPMRate)
+ {
+ if (spellData.SpellId == 52781) // Persuasive Strike
+ {
+ switch (target->GetEntry())
+ {
+ default:
+ return;
+ case 28939:
+ case 28940:
+ case 28610:
+ break;
+ }
+ }
+ uint32 WeaponSpeed = GetAttackTime(attType);
+ chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate, spellInfo);
+ }
+ else if (chance > 100.0f)
+ {
+ chance = GetWeaponProcChance();
+ }
+
+ if (roll_chance_f(chance))
+ CastSpell(target, spellInfo->Id, true, item);
+ }
+ }
+
+ // item combat enchantments
+ for (uint8 e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
+ {
+ uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
+ SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
+ if(!pEnchant) continue;
+ for (uint8 s = 0; s < 3; ++s)
+ {
+ if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
+ continue;
+
+ SpellEnchantProcEntry const* entry = spellmgr.GetSpellEnchantProcEvent(enchant_id);
+
+ if (entry && entry->procEx)
+ {
+ // Check hit/crit/dodge/parry requirement
+ if((entry->procEx & procEx) == 0)
+ continue;
+ }
+ else
+ {
+ // Can do effect if any damage done to target
+ if (!(procVictim & PROC_FLAG_TAKEN_ANY_DAMAGE))
+ //if (!(damageInfo->procVictim & PROC_FLAG_TAKEN_ANY_DAMAGE))
+ continue;
+ }
+
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
+ if (!spellInfo)
+ {
+ sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
+ continue;
+ }
+
+ float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
+
+ if (entry)
+ {
+ if(entry->PPMChance)
+ chance = GetPPMProcChance(proto->Delay, entry->PPMChance, spellInfo);
+ else if(entry->customChance)
+ chance = entry->customChance;
+ }
+
+ // Apply spell mods
+ ApplySpellMod(pEnchant->spellid[s],SPELLMOD_CHANCE_OF_SUCCESS,chance);
+
+ if (roll_chance_f(chance))
+ {
+ if(IsPositiveSpell(pEnchant->spellid[s]))
+ CastSpell(this, pEnchant->spellid[s], true, item);
+ else
+ CastSpell(target, pEnchant->spellid[s], true, item);
+ }
+ }
+ }
+}
+
+void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
+{
+ ItemPrototype const* proto = item->GetProto();
+ // special learning case
+ if (proto->Spells[0].SpellId == 483 || proto->Spells[0].SpellId == 55884)
+ {
+ uint32 learn_spell_id = proto->Spells[0].SpellId;
+ uint32 learning_spell_id = proto->Spells[1].SpellId;
+
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
+ if (!spellInfo)
+ {
+ sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
+ SendEquipError(EQUIP_ERR_NONE,item,NULL);
+ return;
+ }
+
+ Spell *spell = new Spell(this, spellInfo,false);
+ spell->m_CastItem = item;
+ spell->m_cast_count = cast_count; //set count of casts
+ spell->m_currentBasePoints[0] = learning_spell_id;
+ spell->prepare(&targets);
+ return;
+ }
+
+ // use triggered flag only for items with many spell casts and for not first cast
+ uint8 count = 0;
+
+ // item spells casted at use
+ for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
+ {
+ _Spell const& spellData = proto->Spells[i];
+
+ // no spell
+ if (!spellData.SpellId)
+ continue;
+
+ // wrong triggering type
+ if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
+ continue;
+
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
+ if(!spellInfo)
+ {
+ sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
+ continue;
+ }
+
+ Spell *spell = new Spell(this, spellInfo, (count > 0));
+ spell->m_CastItem = item;
+ spell->m_cast_count = cast_count; // set count of casts
+ spell->m_glyphIndex = glyphIndex; // glyph index
+ spell->prepare(&targets);
+
+ ++count;
+ }
+
+ // Item enchantments spells casted at use
+ for (uint8 e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
+ {
+ uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
+ SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
+ if (!pEnchant)
+ continue;
+ for (uint8 s = 0; s < 3; ++s)
+ {
+ if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
+ continue;
+
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
+ if (!spellInfo)
+ {
+ sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
+ continue;
+ }
+
+ Spell *spell = new Spell(this, spellInfo, (count > 0));
+ spell->m_CastItem = item;
+ spell->m_cast_count = cast_count; // set count of casts
+ spell->m_glyphIndex = glyphIndex; // glyph index
+ spell->prepare(&targets);
+
+ ++count;
+ }
+ }
+}
+
+void Player::_RemoveAllItemMods()
+{
+ sLog.outDebug("_RemoveAllItemMods start.");
+
+ for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
+ {
+ if (m_items[i])
+ {
+ ItemPrototype const *proto = m_items[i]->GetProto();
+ if (!proto)
+ continue;
+
+ // item set bonuses not dependent from item broken state
+ if (proto->ItemSet)
+ RemoveItemsSetItem(this,proto);
+
+ if (m_items[i]->IsBroken())
+ continue;
+
+ ApplyItemEquipSpell(m_items[i], false);
+ ApplyEnchantment(m_items[i], false);
+ }
+ }
+
+ for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
+ {
+ if (m_items[i])
+ {
+ if (m_items[i]->IsBroken())
+ continue;
+ ItemPrototype const *proto = m_items[i]->GetProto();
+ if (!proto)
+ continue;
+
+ uint32 attacktype = Player::GetAttackBySlot(i);
+ if (attacktype < MAX_ATTACK)
+ _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
+
+ _ApplyItemBonuses(proto,i, false);
+
+ if (i == EQUIPMENT_SLOT_RANGED)
+ _ApplyAmmoBonuses();
+ }
+ }
+
+ sLog.outDebug("_RemoveAllItemMods complete.");
+}
+
+void Player::_ApplyAllItemMods()
+{
+ sLog.outDebug("_ApplyAllItemMods start.");
+
+ for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
+ {
+ if (m_items[i])
+ {
+ if (m_items[i]->IsBroken())
+ continue;
+
+ ItemPrototype const *proto = m_items[i]->GetProto();
+ if (!proto)
+ continue;
+
+ uint32 attacktype = Player::GetAttackBySlot(i);
+ if (attacktype < MAX_ATTACK)
+ _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
+
+ _ApplyItemBonuses(proto,i, true);
+
+ if (i == EQUIPMENT_SLOT_RANGED)
+ _ApplyAmmoBonuses();
+ }
+ }
+
+ for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
+ {
+ if (m_items[i])
+ {
+ ItemPrototype const *proto = m_items[i]->GetProto();
+ if (!proto)
+ continue;
+
+ // item set bonuses not dependent from item broken state
+ if (proto->ItemSet)
+ AddItemsSetItem(this,m_items[i]);
+
+ if (m_items[i]->IsBroken())
+ continue;
+
+ ApplyItemEquipSpell(m_items[i],true);
+ ApplyEnchantment(m_items[i], true);
+ }
+ }
+
+ sLog.outDebug("_ApplyAllItemMods complete.");
+}
+
+void Player::_ApplyAllLevelScaleItemMods(bool apply)
+{
+ for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
+ {
+ if (m_items[i])
+ {
+ if (m_items[i]->IsBroken())
+ continue;
+
+ ItemPrototype const *proto = m_items[i]->GetProto();
+ if (!proto)
+ continue;
+
+ _ApplyItemBonuses(proto,i, apply, true);
+ }
+ }
+}
+
+void Player::_ApplyAmmoBonuses()
+{
+ // check ammo
+ uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
+ if (!ammo_id)
+ return;
+
+ float currentAmmoDPS;
+
+ ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
+ if (!ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
+ currentAmmoDPS = 0.0f;
+ else
+ currentAmmoDPS = (ammo_proto->Damage[0].DamageMin + ammo_proto->Damage[0].DamageMax) / 2;
+
+ if (currentAmmoDPS == GetAmmoDPS())
+ return;
+
+ m_ammoDPS = currentAmmoDPS;
+
+ if (CanModifyStats())
+ UpdateDamagePhysical(RANGED_ATTACK);
+}
+
+bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
+{
+ if (!ammo_proto)
+ return false;
+
+ // check ranged weapon
+ Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
+ if (!weapon || weapon->IsBroken())
+ return false;
+
+ ItemPrototype const* weapon_proto = weapon->GetProto();
+ if (!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
+ return false;
+
+ // check ammo ws. weapon compatibility
+ switch (weapon_proto->SubClass)
+ {
+ case ITEM_SUBCLASS_WEAPON_BOW:
+ case ITEM_SUBCLASS_WEAPON_CROSSBOW:
+ if (ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
+ return false;
+ break;
+ case ITEM_SUBCLASS_WEAPON_GUN:
+ if (ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
+ return false;
+ break;
+ default:
+ return false;
+ }
+
+ return true;
+}
+
+/* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
+ Called by remove insignia spell effect */
+void Player::RemovedInsignia(Player* looterPlr)
+{
+ if (!GetBattleGroundId())
+ return;
+
+ // If not released spirit, do it !
+ if (m_deathTimer > 0)
+ {
+ m_deathTimer = 0;
+ BuildPlayerRepop();
+ RepopAtGraveyard();
+ }
+
+ Corpse *corpse = GetCorpse();
+ if (!corpse)
+ return;
+
+ // We have to convert player corpse to bones, not to be able to resurrect there
+ // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
+ Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
+ if (!bones)
+ return;
+
+ // Now we must make bones lootable, and send player loot
+ bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
+
+ // We store the level of our player in the gold field
+ // We retrieve this information at Player::SendLoot()
+ bones->loot.gold = getLevel();
+ bones->lootRecipient = looterPlr;
+ looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
+}
+
+void Player::SendLootRelease( uint64 guid )
+{
+ WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
+ data << uint64(guid) << uint8(1);
+ SendDirectMessage( &data );
+}
+
+void Player::SendLoot(uint64 guid, LootType loot_type)
+{
+ if (uint64 lguid = GetLootGUID())
+ m_session->DoLootRelease(lguid);
+
+ Loot *loot = 0;
+ PermissionTypes permission = ALL_PERMISSION;
+
+ sLog.outDebug("Player::SendLoot");
+ if (IS_GAMEOBJECT_GUID(guid))
+ {
+ sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
+ GameObject *go = GetMap()->GetGameObject(guid);
+
+ // not check distance for GO in case owned GO (fishing bobber case, for example)
+ // And permit out of range GO with no owner in case fishing hole
+ if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
+ {
+ SendLootRelease(guid);
+ return;
+ }
+
+ loot = &go->loot;
+
+ if (go->getLootState() == GO_READY)
+ {
+ uint32 lootid = go->GetGOInfo()->GetLootId();
+
+ //TODO: fix this big hack
+ if((go->GetEntry() == BG_AV_OBJECTID_MINE_N || go->GetEntry() == BG_AV_OBJECTID_MINE_S))
+ if( BattleGround *bg = GetBattleGround())
+ if(bg->GetTypeID() == BATTLEGROUND_AV)
+ if(!(((BattleGroundAV*)bg)->PlayerCanDoMineQuest(go->GetEntry(),GetTeam())))
+ {
+ SendLootRelease(guid);
+ return;
+ }
+
+ if (lootid)
+ {
+ sLog.outDebug(" if(lootid)");
+ loot->clear();
+ loot->FillLoot(lootid, LootTemplates_Gameobject, this, false, false, go->GetLootMode());
+ }
+
+ if (loot_type == LOOT_FISHING)
+ go->getFishLoot(loot,this);
+
+ go->SetLootState(GO_ACTIVATED);
+ }
+ }
+ else if (IS_ITEM_GUID(guid))
+ {
+ Item *item = GetItemByGuid(guid);
+
+ if (!item)
+ {
+ SendLootRelease(guid);
+ return;
+ }
+
+ loot = &item->loot;
+
+ if (!item->m_lootGenerated)
+ {
+ item->m_lootGenerated = true;
+ loot->clear();
+
+ switch (loot_type)
+ {
+ case LOOT_DISENCHANTING:
+ loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
+ break;
+ case LOOT_PROSPECTING:
+ loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
+ break;
+ case LOOT_MILLING:
+ loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
+ break;
+ default:
+ loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
+ loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
+ break;
+ }
+ }
+ }
+ else if (IS_CORPSE_GUID(guid)) // remove insignia
+ {
+ Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
+
+ if (!bones || !(loot_type == LOOT_CORPSE || loot_type == LOOT_INSIGNIA) || bones->GetType() != CORPSE_BONES)
+ {
+ SendLootRelease(guid);
+ return;
+ }
+
+ loot = &bones->loot;
+
+ if (!bones->lootForBody)
+ {
+ bones->lootForBody = true;
+ uint32 pLevel = bones->loot.gold;
+ bones->loot.clear();
+ if (BattleGround *bg = GetBattleGround())
+ if (bg->GetTypeID() == BATTLEGROUND_AV)
+ loot->FillLoot(1, LootTemplates_Creature, this, true);
+ // It may need a better formula
+ // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
+ bones->loot.gold = uint32(urand(50, 150) * 0.016f * pow(float(pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY));
+ }
+
+ if (bones->lootRecipient != this)
+ permission = NONE_PERMISSION;
+ }
+ else
+ {
+ Creature *creature = GetMap()->GetCreature(guid);
+
+ // must be in range and creature must be alive for pickpocket and must be dead for another loot
+ if (!creature || creature->isAlive() != (loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
+ {
+ SendLootRelease(guid);
+ return;
+ }
+
+ if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
+ {
+ SendLootRelease(guid);
+ return;
+ }
+
+ loot = &creature->loot;
+
+ if (loot_type == LOOT_PICKPOCKETING)
+ {
+ if (!creature->lootForPickPocketed)
+ {
+ creature->lootForPickPocketed = true;
+ loot->clear();
+
+ if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
+ loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
+
+ // Generate extra money for pick pocket loot
+ const uint32 a = urand(0, creature->getLevel()/2);
+ const uint32 b = urand(0, getLevel()/2);
+ loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
+ }
+ }
+ else
+ {
+ // the player whose group may loot the corpse
+ Player *recipient = creature->GetLootRecipient();
+ if (!recipient)
+ {
+ creature->SetLootRecipient(this);
+ recipient = this;
+ }
+
+ if (creature->lootForPickPocketed)
+ {
+ creature->lootForPickPocketed = false;
+ loot->clear();
+ }
+
+ if (!creature->lootForBody)
+ {
+ creature->lootForBody = true;
+ loot->clear();
+
+ if (uint32 lootid = creature->GetCreatureInfo()->lootid)
+ loot->FillLoot(lootid, LootTemplates_Creature, recipient, false, false, creature->GetLootMode());
+
+ loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
+
+ if (Group* group = recipient->GetGroup())
+ {
+ group->UpdateLooterGuid(creature,true);
+
+ switch (group->GetLootMethod())
+ {
+ case GROUP_LOOT:
+ // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
+ group->GroupLoot(recipient->GetGUID(), loot, creature);
+ break;
+ case NEED_BEFORE_GREED:
+ group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
+ break;
+ case MASTER_LOOT:
+ group->MasterLoot(recipient->GetGUID(), loot, creature);
+ break;
+ default:
+ break;
+ }
+ }
+ }
+
+ // possible only if creature->lootForBody && loot->empty() at spell cast check
+ if (loot_type == LOOT_SKINNING)
+ {
+ loot->clear();
+ loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
+ }
+ // set group rights only for loot_type != LOOT_SKINNING
+ else
+ {
+ if(Group* group = GetGroup())
+ {
+ if (group == recipient->GetGroup())
+ {
+ if (group->GetLootMethod() == FREE_FOR_ALL)
+ permission = ALL_PERMISSION;
+ else if (group->GetLooterGuid() == GetGUID())
+ {
+ if (group->GetLootMethod() == MASTER_LOOT)
+ permission = MASTER_PERMISSION;
+ else
+ permission = ALL_PERMISSION;
+ }
+ else
+ permission = GROUP_PERMISSION;
+ }
+ else
+ permission = NONE_PERMISSION;
+ }
+ else if (recipient == this)
+ permission = ALL_PERMISSION;
+ else
+ permission = NONE_PERMISSION;
+ }
+ }
+ }
+
+ SetLootGUID(guid);
+
+ // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
+ switch (loot_type)
+ {
+ case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
+ case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
+ default: break;
+ }
+
+ // need know merged fishing/corpse loot type for achievements
+ loot->loot_type = loot_type;
+
+ WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
+
+ data << uint64(guid);
+ data << uint8(loot_type);
+ data << LootView(*loot, this, permission);
+
+ SendDirectMessage(&data);
+
+ // add 'this' player as one of the players that are looting 'loot'
+ if (permission != NONE_PERMISSION)
+ loot->AddLooter(GetGUID());
+
+ if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
+ SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
+}
+
+void Player::SendNotifyLootMoneyRemoved()
+{
+ WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
+ GetSession()->SendPacket( &data );
+}
+
+void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
+{
+ WorldPacket data(SMSG_LOOT_REMOVED, 1);
+ data << uint8(lootSlot);
+ GetSession()->SendPacket( &data );
+}
+
+void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
+{
+ WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
+ data << Field;
+ data << Value;
+ GetSession()->SendPacket(&data);
+}
+
+void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
+{
+ // data depends on zoneid/mapid...
+ BattleGround* bg = GetBattleGround();
+ uint16 NumberOfFields = 0;
+ uint32 mapid = GetMapId();
+ OutdoorPvP * pvp = sOutdoorPvPMgr.GetOutdoorPvPToZoneId(zoneid);
+
+ sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map: %u, Zone: %u", mapid, zoneid);
+
+ // may be exist better way to do this...
+ switch (zoneid)
+ {
+ case 0:
+ case 1:
+ case 4:
+ case 8:
+ case 10:
+ case 11:
+ case 12:
+ case 36:
+ case 38:
+ case 40:
+ case 41:
+ case 51:
+ case 267:
+ case 1519:
+ case 1537:
+ case 2257:
+ case 2918:
+ NumberOfFields = 8;
+ break;
+ case 139:
+ NumberOfFields = 41;
+ break;
+ case 1377:
+ NumberOfFields = 15;
+ break;
+ case 2597:
+ NumberOfFields = 83;
+ break;
+ case 3277:
+ NumberOfFields = 16;
+ break;
+ case 3358:
+ case 3820:
+ NumberOfFields = 40;
+ break;
+ case 3483:
+ NumberOfFields = 27;
+ break;
+ case 3518:
+ NumberOfFields = 39;
+ break;
+ case 3519:
+ NumberOfFields = 38;
+ break;
+ case 3521:
+ NumberOfFields = 37;
+ break;
+ case 3698:
+ case 3702:
+ case 3968:
+ NumberOfFields = 11;
+ break;
+ case 4378:
+ NumberOfFields = 11;
+ break;
+ case 3703:
+ NumberOfFields = 11;
+ break;
+ case 4384:
+ NumberOfFields = 30;
+ break;
+ default:
+ NumberOfFields = 12;
+ break;
+ }
+
+ WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
+ data << uint32(mapid); // mapid
+ data << uint32(zoneid); // zone id
+ data << uint32(areaid); // area id, new 2.1.0
+ data << uint16(NumberOfFields); // count of uint64 blocks
+ data << uint32(0x8d8) << uint32(0x0); // 1
+ data << uint32(0x8d7) << uint32(0x0); // 2
+ data << uint32(0x8d6) << uint32(0x0); // 3
+ data << uint32(0x8d5) << uint32(0x0); // 4
+ data << uint32(0x8d4) << uint32(0x0); // 5
+ data << uint32(0x8d3) << uint32(0x0); // 6
+ // 7 1 - Arena season in progress, 0 - end of season
+ data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
+ // 8 Arena season id
+ data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
+
+ if(mapid == 530) // Outland
+ {
+ data << uint32(0x9bf) << uint32(0x0); // 7
+ data << uint32(0x9bd) << uint32(0xF); // 8
+ data << uint32(0x9bb) << uint32(0xF); // 9
+ }
+ switch(zoneid)
+ {
+ case 1:
+ case 11:
+ case 12:
+ case 38:
+ case 40:
+ case 51:
+ case 1519:
+ case 1537:
+ case 2257:
+ break;
+ case 139: // EPL
+ {
+ if(pvp && pvp->GetTypeId() == OUTDOOR_PVP_EP)
+ pvp->FillInitialWorldStates(data);
+ else
+ {
+ data << uint32(0x97a) << uint32(0x0); // 10 2426
+ data << uint32(0x917) << uint32(0x0); // 11 2327
+ data << uint32(0x918) << uint32(0x0); // 12 2328
+ data << uint32(0x97b) << uint32(0x32); // 13 2427
+ data << uint32(0x97c) << uint32(0x32); // 14 2428
+ data << uint32(0x933) << uint32(0x1); // 15 2355
+ data << uint32(0x946) << uint32(0x0); // 16 2374
+ data << uint32(0x947) << uint32(0x0); // 17 2375
+ data << uint32(0x948) << uint32(0x0); // 18 2376
+ data << uint32(0x949) << uint32(0x0); // 19 2377
+ data << uint32(0x94a) << uint32(0x0); // 20 2378
+ data << uint32(0x94b) << uint32(0x0); // 21 2379
+ data << uint32(0x932) << uint32(0x0); // 22 2354
+ data << uint32(0x934) << uint32(0x0); // 23 2356
+ data << uint32(0x935) << uint32(0x0); // 24 2357
+ data << uint32(0x936) << uint32(0x0); // 25 2358
+ data << uint32(0x937) << uint32(0x0); // 26 2359
+ data << uint32(0x938) << uint32(0x0); // 27 2360
+ data << uint32(0x939) << uint32(0x1); // 28 2361
+ data << uint32(0x930) << uint32(0x1); // 29 2352
+ data << uint32(0x93a) << uint32(0x0); // 30 2362
+ data << uint32(0x93b) << uint32(0x0); // 31 2363
+ data << uint32(0x93c) << uint32(0x0); // 32 2364
+ data << uint32(0x93d) << uint32(0x0); // 33 2365
+ data << uint32(0x944) << uint32(0x0); // 34 2372
+ data << uint32(0x945) << uint32(0x0); // 35 2373
+ data << uint32(0x931) << uint32(0x1); // 36 2353
+ data << uint32(0x93e) << uint32(0x0); // 37 2366
+ data << uint32(0x931) << uint32(0x1); // 38 2367 ?? grey horde not in dbc! send for consistency's sake, and to match field count
+ data << uint32(0x940) << uint32(0x0); // 39 2368
+ data << uint32(0x941) << uint32(0x0); // 7 2369
+ data << uint32(0x942) << uint32(0x0); // 8 2370
+ data << uint32(0x943) << uint32(0x0); // 9 2371
+ }
+ }
+ break;
+ case 1377: // Silithus
+ {
+ if (pvp && pvp->GetTypeId() == OUTDOOR_PVP_SI)
+ pvp->FillInitialWorldStates(data);
+ else
+ {
+ // states are always shown
+ data << uint32(2313) << uint32(0x0); // 7 ally silityst gathered
+ data << uint32(2314) << uint32(0x0); // 8 horde silityst gathered
+ data << uint32(2317) << uint32(0x0); // 9 max silithyst
+ }
+ // dunno about these... aq opening event maybe?
+ data << uint32(2322) << uint32(0x0); // 10 sandworm N
+ data << uint32(2323) << uint32(0x0); // 11 sandworm S
+ data << uint32(2324) << uint32(0x0); // 12 sandworm SW
+ data << uint32(2325) << uint32(0x0); // 13 sandworm E
+ }
+ break;
+ case 2597: // AV
+ if (bg && bg->GetTypeID() == BATTLEGROUND_AV)
+ bg->FillInitialWorldStates(data);
+ else
+ {
+ data << uint32(0x7ae) << uint32(0x1); // 7 snowfall n
+ data << uint32(0x532) << uint32(0x1); // 8 frostwolfhut hc
+ data << uint32(0x531) << uint32(0x0); // 9 frostwolfhut ac
+ data << uint32(0x52e) << uint32(0x0); // 10 stormpike firstaid a_a
+ data << uint32(0x571) << uint32(0x0); // 11 east frostwolf tower horde assaulted -unused
+ data << uint32(0x570) << uint32(0x0); // 12 west frostwolf tower horde assaulted - unused
+ data << uint32(0x567) << uint32(0x1); // 13 frostwolfe c
+ data << uint32(0x566) << uint32(0x1); // 14 frostwolfw c
+ data << uint32(0x550) << uint32(0x1); // 15 irondeep (N) ally
+ data << uint32(0x544) << uint32(0x0); // 16 ice grave a_a
+ data << uint32(0x536) << uint32(0x0); // 17 stormpike grave h_c
+ data << uint32(0x535) << uint32(0x1); // 18 stormpike grave a_c
+ data << uint32(0x518) << uint32(0x0); // 19 stoneheart grave a_a
+ data << uint32(0x517) << uint32(0x0); // 20 stoneheart grave h_a
+ data << uint32(0x574) << uint32(0x0); // 21 1396 unk
+ data << uint32(0x573) << uint32(0x0); // 22 iceblood tower horde assaulted -unused
+ data << uint32(0x572) << uint32(0x0); // 23 towerpoint horde assaulted - unused
+ data << uint32(0x56f) << uint32(0x0); // 24 1391 unk
+ data << uint32(0x56e) << uint32(0x0); // 25 iceblood a
+ data << uint32(0x56d) << uint32(0x0); // 26 towerp a
+ data << uint32(0x56c) << uint32(0x0); // 27 frostwolfe a
+ data << uint32(0x56b) << uint32(0x0); // 28 froswolfw a
+ data << uint32(0x56a) << uint32(0x1); // 29 1386 unk
+ data << uint32(0x569) << uint32(0x1); // 30 iceblood c
+ data << uint32(0x568) << uint32(0x1); // 31 towerp c
+ data << uint32(0x565) << uint32(0x0); // 32 stoneh tower a
+ data << uint32(0x564) << uint32(0x0); // 33 icewing tower a
+ data << uint32(0x563) << uint32(0x0); // 34 dunn a
+ data << uint32(0x562) << uint32(0x0); // 35 duns a
+ data << uint32(0x561) << uint32(0x0); // 36 stoneheart bunker alliance assaulted - unused
+ data << uint32(0x560) << uint32(0x0); // 37 icewing bunker alliance assaulted - unused
+ data << uint32(0x55f) << uint32(0x0); // 38 dunbaldar south alliance assaulted - unused
+ data << uint32(0x55e) << uint32(0x0); // 39 dunbaldar north alliance assaulted - unused
+ data << uint32(0x55d) << uint32(0x0); // 40 stone tower d
+ data << uint32(0x3c6) << uint32(0x0); // 41 966 unk
+ data << uint32(0x3c4) << uint32(0x0); // 42 964 unk
+ data << uint32(0x3c2) << uint32(0x0); // 43 962 unk
+ data << uint32(0x516) << uint32(0x1); // 44 stoneheart grave a_c
+ data << uint32(0x515) << uint32(0x0); // 45 stonheart grave h_c
+ data << uint32(0x3b6) << uint32(0x0); // 46 950 unk
+ data << uint32(0x55c) << uint32(0x0); // 47 icewing tower d
+ data << uint32(0x55b) << uint32(0x0); // 48 dunn d
+ data << uint32(0x55a) << uint32(0x0); // 49 duns d
+ data << uint32(0x559) << uint32(0x0); // 50 1369 unk
+ data << uint32(0x558) << uint32(0x0); // 51 iceblood d
+ data << uint32(0x557) << uint32(0x0); // 52 towerp d
+ data << uint32(0x556) << uint32(0x0); // 53 frostwolfe d
+ data << uint32(0x555) << uint32(0x0); // 54 frostwolfw d
+ data << uint32(0x554) << uint32(0x1); // 55 stoneh tower c
+ data << uint32(0x553) << uint32(0x1); // 56 icewing tower c
+ data << uint32(0x552) << uint32(0x1); // 57 dunn c
+ data << uint32(0x551) << uint32(0x1); // 58 duns c
+ data << uint32(0x54f) << uint32(0x0); // 59 irondeep (N) horde
+ data << uint32(0x54e) << uint32(0x0); // 60 irondeep (N) ally
+ data << uint32(0x54d) << uint32(0x1); // 61 mine (S) neutral
+ data << uint32(0x54c) << uint32(0x0); // 62 mine (S) horde
+ data << uint32(0x54b) << uint32(0x0); // 63 mine (S) ally
+ data << uint32(0x545) << uint32(0x0); // 64 iceblood h_a
+ data << uint32(0x543) << uint32(0x1); // 65 iceblod h_c
+ data << uint32(0x542) << uint32(0x0); // 66 iceblood a_c
+ data << uint32(0x540) << uint32(0x0); // 67 snowfall h_a
+ data << uint32(0x53f) << uint32(0x0); // 68 snowfall a_a
+ data << uint32(0x53e) << uint32(0x0); // 69 snowfall h_c
+ data << uint32(0x53d) << uint32(0x0); // 70 snowfall a_c
+ data << uint32(0x53c) << uint32(0x0); // 71 frostwolf g h_a
+ data << uint32(0x53b) << uint32(0x0); // 72 frostwolf g a_a
+ data << uint32(0x53a) << uint32(0x1); // 73 frostwolf g h_c
+ data << uint32(0x539) << uint32(0x0); // 74 frostwolf g a_c
+ data << uint32(0x538) << uint32(0x0); // 75 stormpike grave h_a
+ data << uint32(0x537) << uint32(0x0); // 76 stormpike grave a_a
+ data << uint32(0x534) << uint32(0x0); // 77 frostwolf hut h_a
+ data << uint32(0x533) << uint32(0x0); // 78 frostwolf hut a_a
+ data << uint32(0x530) << uint32(0x0); // 79 stormpike first aid h_a
+ data << uint32(0x52f) << uint32(0x0); // 80 stormpike first aid h_c
+ data << uint32(0x52d) << uint32(0x1); // 81 stormpike first aid a_c
+ }
+ break;
+ case 3277: // WS
+ if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
+ bg->FillInitialWorldStates(data);
+ else
+ {
+ data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
+ data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
+ data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
+ data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
+ data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
+ data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
+ data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
+ data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
+ }
+ break;
+ case 3358: // AB
+ if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
+ bg->FillInitialWorldStates(data);
+ else
+ {
+ data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
+ data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
+ data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
+ data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
+ data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
+ data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
+ data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
+ data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
+ data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
+ data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
+ data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
+ data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
+ data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
+ data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
+ data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
+ data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
+ data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
+ data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
+ data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
+ data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
+ data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
+ data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
+ data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
+ data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
+ data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
+ data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
+ data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
+ data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
+ data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
+ data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
+ data << uint32(0x745) << uint32(0x2); // 37 1861 unk
+ data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
+ }
+ break;
+ case 3820: // EY
+ if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
+ bg->FillInitialWorldStates(data);
+ else
+ {
+ data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
+ data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
+ data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
+ data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
+ data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
+ data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
+ data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
+ data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
+ data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
+ data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
+ data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
+ data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
+ data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
+ data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
+ data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
+ data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
+ data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
+ data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
+ data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
+ data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
+ data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
+ data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
+ data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
+ data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
+ data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
+ data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
+ data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
+ data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
+ data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
+ data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
+ data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
+ data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
+ // and some more ... unknown
+ }
+ break;
+ // any of these needs change! the client remembers the prev setting!
+ // ON EVERY ZONE LEAVE, RESET THE OLD ZONE'S WORLD STATE, BUT AT LEAST THE UI STUFF!
+ case 3483: // Hellfire Peninsula
+ {
+ if(pvp && pvp->GetTypeId() == OUTDOOR_PVP_HP)
+ pvp->FillInitialWorldStates(data);
+ else
+ {
+ data << uint32(0x9ba) << uint32(0x1); // 10 // add ally tower main gui icon // maybe should be sent only on login?
+ data << uint32(0x9b9) << uint32(0x1); // 11 // add horde tower main gui icon // maybe should be sent only on login?
+ data << uint32(0x9b5) << uint32(0x0); // 12 // show neutral broken hill icon // 2485
+ data << uint32(0x9b4) << uint32(0x1); // 13 // show icon above broken hill // 2484
+ data << uint32(0x9b3) << uint32(0x0); // 14 // show ally broken hill icon // 2483
+ data << uint32(0x9b2) << uint32(0x0); // 15 // show neutral overlook icon // 2482
+ data << uint32(0x9b1) << uint32(0x1); // 16 // show the overlook arrow // 2481
+ data << uint32(0x9b0) << uint32(0x0); // 17 // show ally overlook icon // 2480
+ data << uint32(0x9ae) << uint32(0x0); // 18 // horde pvp objectives captured // 2478
+ data << uint32(0x9ac) << uint32(0x0); // 19 // ally pvp objectives captured // 2476
+ data << uint32(2475) << uint32(100); //: ally / horde slider grey area // show only in direct vicinity!
+ data << uint32(2474) << uint32(50); //: ally / horde slider percentage, 100 for ally, 0 for horde // show only in direct vicinity!
+ data << uint32(2473) << uint32(0); //: ally / horde slider display // show only in direct vicinity!
+ data << uint32(0x9a8) << uint32(0x0); // 20 // show the neutral stadium icon // 2472
+ data << uint32(0x9a7) << uint32(0x0); // 21 // show the ally stadium icon // 2471
+ data << uint32(0x9a6) << uint32(0x1); // 22 // show the horde stadium icon // 2470
+ }
+ }
+ break;
+ case 3518:
+ {
+ if(pvp && pvp->GetTypeId() == OUTDOOR_PVP_NA)
+ pvp->FillInitialWorldStates(data);
+ else
+ {
+ data << uint32(2503) << uint32(0x0); // 10
+ data << uint32(2502) << uint32(0x0); // 11
+ data << uint32(2493) << uint32(0x0); // 12
+ data << uint32(2491) << uint32(0x0); // 13
+
+ data << uint32(2495) << uint32(0x0); // 14
+ data << uint32(2494) << uint32(0x0); // 15
+ data << uint32(2497) << uint32(0x0); // 16
+
+ data << uint32(2762) << uint32(0x0); // 17
+ data << uint32(2662) << uint32(0x0); // 18
+ data << uint32(2663) << uint32(0x0); // 19
+ data << uint32(2664) << uint32(0x0); // 20
+
+ data << uint32(2760) << uint32(0x0); // 21
+ data << uint32(2670) << uint32(0x0); // 22
+ data << uint32(2668) << uint32(0x0); // 23
+ data << uint32(2669) << uint32(0x0); // 24
+
+ data << uint32(2761) << uint32(0x0); // 25
+ data << uint32(2667) << uint32(0x0); // 26
+ data << uint32(2665) << uint32(0x0); // 27
+ data << uint32(2666) << uint32(0x0); // 28
+
+ data << uint32(2763) << uint32(0x0); // 29
+ data << uint32(2659) << uint32(0x0); // 30
+ data << uint32(2660) << uint32(0x0); // 31
+ data << uint32(2661) << uint32(0x0); // 32
+
+ data << uint32(2671) << uint32(0x0); // 33
+ data << uint32(2676) << uint32(0x0); // 34
+ data << uint32(2677) << uint32(0x0); // 35
+ data << uint32(2672) << uint32(0x0); // 36
+ data << uint32(2673) << uint32(0x0); // 37
+ }
+ }
+ break;
+ case 3519: // Terokkar Forest
+ {
+ if(pvp && pvp->GetTypeId() == OUTDOOR_PVP_TF)
+ pvp->FillInitialWorldStates(data);
+ else
+ {
+ data << uint32(0xa41) << uint32(0x0); // 10 // 2625 capture bar pos
+ data << uint32(0xa40) << uint32(0x14); // 11 // 2624 capture bar neutral
+ data << uint32(0xa3f) << uint32(0x0); // 12 // 2623 show capture bar
+ data << uint32(0xa3e) << uint32(0x0); // 13 // 2622 horde towers controlled
+ data << uint32(0xa3d) << uint32(0x5); // 14 // 2621 ally towers controlled
+ data << uint32(0xa3c) << uint32(0x0); // 15 // 2620 show towers controlled
+ data << uint32(0xa88) << uint32(0x0); // 16 // 2696 SE Neu
+ data << uint32(0xa87) << uint32(0x0); // 17 // SE Horde
+ data << uint32(0xa86) << uint32(0x0); // 18 // SE Ally
+ data << uint32(0xa85) << uint32(0x0); // 19 //S Neu
+ data << uint32(0xa84) << uint32(0x0); // 20 S Horde
+ data << uint32(0xa83) << uint32(0x0); // 21 S Ally
+ data << uint32(0xa82) << uint32(0x0); // 22 NE Neu
+ data << uint32(0xa81) << uint32(0x0); // 23 NE Horde
+ data << uint32(0xa80) << uint32(0x0); // 24 NE Ally
+ data << uint32(0xa7e) << uint32(0x0); // 25 // 2686 N Neu
+ data << uint32(0xa7d) << uint32(0x0); // 26 N Horde
+ data << uint32(0xa7c) << uint32(0x0); // 27 N Ally
+ data << uint32(0xa7b) << uint32(0x0); // 28 NW Ally
+ data << uint32(0xa7a) << uint32(0x0); // 29 NW Horde
+ data << uint32(0xa79) << uint32(0x0); // 30 NW Neutral
+ data << uint32(0x9d0) << uint32(0x5); // 31 // 2512 locked time remaining seconds first digit
+ data << uint32(0x9ce) << uint32(0x0); // 32 // 2510 locked time remaining seconds second digit
+ data << uint32(0x9cd) << uint32(0x0); // 33 // 2509 locked time remaining minutes
+ data << uint32(0x9cc) << uint32(0x0); // 34 // 2508 neutral locked time show
+ data << uint32(0xad0) << uint32(0x0); // 35 // 2768 horde locked time show
+ data << uint32(0xacf) << uint32(0x1); // 36 // 2767 ally locked time show
+ }
+ }
+ break;
+ case 3521: // Zangarmarsh
+ {
+ if(pvp && pvp->GetTypeId() == OUTDOOR_PVP_ZM)
+ pvp->FillInitialWorldStates(data);
+ else
+ {
+ data << uint32(0x9e1) << uint32(0x0); // 10 //2529
+ data << uint32(0x9e0) << uint32(0x0); // 11
+ data << uint32(0x9df) << uint32(0x0); // 12
+ data << uint32(0xa5d) << uint32(0x1); // 13 //2653
+ data << uint32(0xa5c) << uint32(0x0); // 14 //2652 east beacon neutral
+ data << uint32(0xa5b) << uint32(0x1); // 15 horde
+ data << uint32(0xa5a) << uint32(0x0); // 16 ally
+ data << uint32(0xa59) << uint32(0x1); // 17 // 2649 Twin spire graveyard horde 12???
+ data << uint32(0xa58) << uint32(0x0); // 18 ally 14 ???
+ data << uint32(0xa57) << uint32(0x0); // 19 neutral 7???
+ data << uint32(0xa56) << uint32(0x0); // 20 // 2646 west beacon neutral
+ data << uint32(0xa55) << uint32(0x1); // 21 horde
+ data << uint32(0xa54) << uint32(0x0); // 22 ally
+ data << uint32(0x9e7) << uint32(0x0); // 23 // 2535
+ data << uint32(0x9e6) << uint32(0x0); // 24
+ data << uint32(0x9e5) << uint32(0x0); // 25
+ data << uint32(0xa00) << uint32(0x0); // 26 // 2560
+ data << uint32(0x9ff) << uint32(0x1); // 27
+ data << uint32(0x9fe) << uint32(0x0); // 28
+ data << uint32(0x9fd) << uint32(0x0); // 29
+ data << uint32(0x9fc) << uint32(0x1); // 30
+ data << uint32(0x9fb) << uint32(0x0); // 31
+ data << uint32(0xa62) << uint32(0x0); // 32 // 2658
+ data << uint32(0xa61) << uint32(0x1); // 33
+ data << uint32(0xa60) << uint32(0x1); // 34
+ data << uint32(0xa5f) << uint32(0x0); // 35
+ }
+ }
+ break;
+ case 3698: // Nagrand Arena
+ if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
+ bg->FillInitialWorldStates(data);
+ else
+ {
+ data << uint32(0xa0f) << uint32(0x0); // 7
+ data << uint32(0xa10) << uint32(0x0); // 8
+ data << uint32(0xa11) << uint32(0x0); // 9 show
+ }
+ break;
+ case 3702: // Blade's Edge Arena
+ if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
+ bg->FillInitialWorldStates(data);
+ else
+ {
+ data << uint32(0x9f0) << uint32(0x0); // 7 gold
+ data << uint32(0x9f1) << uint32(0x0); // 8 green
+ data << uint32(0x9f3) << uint32(0x0); // 9 show
+ }
+ break;
+ case 3968: // Ruins of Lordaeron
+ if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
+ bg->FillInitialWorldStates(data);
+ else
+ {
+ data << uint32(0xbb8) << uint32(0x0); // 7 gold
+ data << uint32(0xbb9) << uint32(0x0); // 8 green
+ data << uint32(0xbba) << uint32(0x0); // 9 show
+ }
+ break;
+ case 4378: // Dalaran Sewers
+ if (bg && bg->GetTypeID() == BATTLEGROUND_DS)
+ bg->FillInitialWorldStates(data);
+ else
+ {
+ data << uint32(3601) << uint32(0x0); // 7 gold
+ data << uint32(3600) << uint32(0x0); // 8 green
+ data << uint32(3610) << uint32(0x0); // 9 show
+ }
+ break;
+ case 3703: // Shattrath City
+ case 4384: // SA
+ if (bg && bg->GetTypeID() == BATTLEGROUND_SA)
+ bg->FillInitialWorldStates(data);
+ else
+ {
+ // 1-3 A defend, 4-6 H defend, 7-9 unk defend, 1 - ok, 2 - half destroyed, 3 - destroyed
+ data << uint32(0xf09) << uint32(0x0); // 7 3849 Gate of Temple
+ data << uint32(0xe36) << uint32(0x0); // 8 3638 Gate of Yellow Moon
+ data << uint32(0xe27) << uint32(0x0); // 9 3623 Gate of Green Emerald
+ data << uint32(0xe24) << uint32(0x0); // 10 3620 Gate of Blue Sapphire
+ data << uint32(0xe21) << uint32(0x0); // 11 3617 Gate of Red Sun
+ data << uint32(0xe1e) << uint32(0x0); // 12 3614 Gate of Purple Ametyst
+
+ data << uint32(0xdf3) << uint32(0x0); // 13 3571 bonus timer (1 - on, 0 - off)
+ data << uint32(0xded) << uint32(0x0); // 14 3565 Horde Attacker
+ data << uint32(0xdec) << uint32(0x0); // 15 3564 Alliance Attacker
+ // End Round (timer), better explain this by example, eg. ends in 19:59 -> A:BC
+ data << uint32(0xde9) << uint32(0x0); // 16 3561 C
+ data << uint32(0xde8) << uint32(0x0); // 17 3560 B
+ data << uint32(0xde7) << uint32(0x0); // 18 3559 A
+ data << uint32(0xe35) << uint32(0x0); // 19 3637 East g - Horde control
+ data << uint32(0xe34) << uint32(0x0); // 20 3636 West g - Horde control
+ data << uint32(0xe33) << uint32(0x0); // 21 3635 South g - Horde control
+ data << uint32(0xe32) << uint32(0x0); // 22 3634 East g - Alliance control
+ data << uint32(0xe31) << uint32(0x0); // 23 3633 West g - Alliance control
+ data << uint32(0xe30) << uint32(0x0); // 24 3632 South g - Alliance control
+ data << uint32(0xe2f) << uint32(0x0); // 25 3631 Chamber of Ancients - Horde control
+ data << uint32(0xe2e) << uint32(0x0); // 26 3630 Chamber of Ancients - Alliance control
+ data << uint32(0xe2d) << uint32(0x0); // 27 3629 Beach1 - Horde control
+ data << uint32(0xe2c) << uint32(0x0); // 28 3628 Beach2 - Horde control
+ data << uint32(0xe2b) << uint32(0x0); // 29 3627 Beach1 - Alliance control
+ data << uint32(0xe2a) << uint32(0x0); // 30 3626 Beach2 - Alliance control
+ // and many unks...
+ }
+ break;
+ case 4406: // Ring of Valor
+ if (bg && bg->GetTypeID() == BATTLEGROUND_RV)
+ bg->FillInitialWorldStates(data);
+ else
+ {
+ data << uint32(0xe10) << uint32(0x0); // 7 gold
+ data << uint32(0xe11) << uint32(0x0); // 8 green
+ data << uint32(0xe1a) << uint32(0x0); // 9 show
+ }
+ break;
+ default:
+ data << uint32(0x914) << uint32(0x0); // 7
+ data << uint32(0x913) << uint32(0x0); // 8
+ data << uint32(0x912) << uint32(0x0); // 9
+ data << uint32(0x915) << uint32(0x0); // 10
+ break;
+ }
+ GetSession()->SendPacket(&data);
+}
+
+uint32 Player::GetXPRestBonus(uint32 xp)
+{
+ uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
+
+ if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
+ rested_bonus = xp;
+
+ SetRestBonus( GetRestBonus() - rested_bonus);
+
+ sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
+ return rested_bonus;
+}
+
+void Player::SetBindPoint(uint64 guid)
+{
+ WorldPacket data(SMSG_BINDER_CONFIRM, 8);
+ data << uint64(guid);
+ GetSession()->SendPacket( &data );
+}
+
+void Player::SendTalentWipeConfirm(uint64 guid)
+{
+ WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
+ data << uint64(guid);
+ uint32 cost = sWorld.getConfig(CONFIG_NO_RESET_TALENT_COST) ? 0 : resetTalentsCost();
+ data << cost;
+ GetSession()->SendPacket( &data );
+}
+
+void Player::SendPetSkillWipeConfirm()
+{
+ Pet* pet = GetPet();
+ if (!pet)
+ return;
+ WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
+ data << pet->GetGUID();
+ data << uint32(pet->resetTalentsCost());
+ GetSession()->SendPacket( &data );
+}
+
+/*********************************************************/
+/*** STORAGE SYSTEM ***/
+/*********************************************************/
+
+void Player::SetVirtualItemSlot( uint8 i, Item* item)
+{
+ assert(i < 3);
+ if (i < 2 && item)
+ {
+ if (!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
+ return;
+ uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
+ if (charges == 0)
+ return;
+ if (charges > 1)
+ item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
+ else if (charges <= 1)
+ {
+ ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
+ item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
+ }
+ }
+}
+
+void Player::SetSheath( SheathState sheathed )
+{
+ switch (sheathed)
+ {
+ case SHEATH_STATE_UNARMED: // no prepared weapon
+ SetVirtualItemSlot(0,NULL);
+ SetVirtualItemSlot(1,NULL);
+ SetVirtualItemSlot(2,NULL);
+ break;
+ case SHEATH_STATE_MELEE: // prepared melee weapon
+ {
+ SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
+ SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
+ SetVirtualItemSlot(2,NULL);
+ }; break;
+ case SHEATH_STATE_RANGED: // prepared ranged weapon
+ SetVirtualItemSlot(0,NULL);
+ SetVirtualItemSlot(1,NULL);
+ SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
+ break;
+ default:
+ SetVirtualItemSlot(0,NULL);
+ SetVirtualItemSlot(1,NULL);
+ SetVirtualItemSlot(2,NULL);
+ break;
+ }
+ Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
+}
+
+uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
+{
+ uint8 pClass = getClass();
+
+ uint8 slots[4];
+ slots[0] = NULL_SLOT;
+ slots[1] = NULL_SLOT;
+ slots[2] = NULL_SLOT;
+ slots[3] = NULL_SLOT;
+ switch (proto->InventoryType)
+ {
+ case INVTYPE_HEAD:
+ slots[0] = EQUIPMENT_SLOT_HEAD;
+ break;
+ case INVTYPE_NECK:
+ slots[0] = EQUIPMENT_SLOT_NECK;
+ break;
+ case INVTYPE_SHOULDERS:
+ slots[0] = EQUIPMENT_SLOT_SHOULDERS;
+ break;
+ case INVTYPE_BODY:
+ slots[0] = EQUIPMENT_SLOT_BODY;
+ break;
+ case INVTYPE_CHEST:
+ slots[0] = EQUIPMENT_SLOT_CHEST;
+ break;
+ case INVTYPE_ROBE:
+ slots[0] = EQUIPMENT_SLOT_CHEST;
+ break;
+ case INVTYPE_WAIST:
+ slots[0] = EQUIPMENT_SLOT_WAIST;
+ break;
+ case INVTYPE_LEGS:
+ slots[0] = EQUIPMENT_SLOT_LEGS;
+ break;
+ case INVTYPE_FEET:
+ slots[0] = EQUIPMENT_SLOT_FEET;
+ break;
+ case INVTYPE_WRISTS:
+ slots[0] = EQUIPMENT_SLOT_WRISTS;
+ break;
+ case INVTYPE_HANDS:
+ slots[0] = EQUIPMENT_SLOT_HANDS;
+ break;
+ case INVTYPE_FINGER:
+ slots[0] = EQUIPMENT_SLOT_FINGER1;
+ slots[1] = EQUIPMENT_SLOT_FINGER2;
+ break;
+ case INVTYPE_TRINKET:
+ slots[0] = EQUIPMENT_SLOT_TRINKET1;
+ slots[1] = EQUIPMENT_SLOT_TRINKET2;
+ break;
+ case INVTYPE_CLOAK:
+ slots[0] = EQUIPMENT_SLOT_BACK;
+ break;
+ case INVTYPE_WEAPON:
+ {
+ slots[0] = EQUIPMENT_SLOT_MAINHAND;
+
+ // suggest offhand slot only if know dual wielding
+ // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
+ if (CanDualWield())
+ slots[1] = EQUIPMENT_SLOT_OFFHAND;
+ break;
+ };
+ case INVTYPE_SHIELD:
+ slots[0] = EQUIPMENT_SLOT_OFFHAND;
+ break;
+ case INVTYPE_RANGED:
+ slots[0] = EQUIPMENT_SLOT_RANGED;
+ break;
+ case INVTYPE_2HWEAPON:
+ slots[0] = EQUIPMENT_SLOT_MAINHAND;
+ if (Item *mhWeapon = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND))
+ if (ItemPrototype const *mhWeaponProto = mhWeapon->GetProto())
+ if (mhWeaponProto->SubClass == ITEM_SUBCLASS_WEAPON_POLEARM || mhWeaponProto->SubClass == ITEM_SUBCLASS_WEAPON_STAFF)
+ {
+ const_cast<Player *>(this)->AutoUnequipOffhandIfNeed(true);
+ break;
+ }
+ if (CanDualWield() && CanTitanGrip() && proto->SubClass != ITEM_SUBCLASS_WEAPON_POLEARM && proto->SubClass != ITEM_SUBCLASS_WEAPON_STAFF)
+ slots[1] = EQUIPMENT_SLOT_OFFHAND;
+ break;
+ case INVTYPE_TABARD:
+ slots[0] = EQUIPMENT_SLOT_TABARD;
+ break;
+ case INVTYPE_WEAPONMAINHAND:
+ slots[0] = EQUIPMENT_SLOT_MAINHAND;
+ break;
+ case INVTYPE_WEAPONOFFHAND:
+ slots[0] = EQUIPMENT_SLOT_OFFHAND;
+ break;
+ case INVTYPE_HOLDABLE:
+ slots[0] = EQUIPMENT_SLOT_OFFHAND;
+ break;
+ case INVTYPE_THROWN:
+ slots[0] = EQUIPMENT_SLOT_RANGED;
+ break;
+ case INVTYPE_RANGEDRIGHT:
+ slots[0] = EQUIPMENT_SLOT_RANGED;
+ break;
+ case INVTYPE_BAG:
+ slots[0] = INVENTORY_SLOT_BAG_START + 0;
+ slots[1] = INVENTORY_SLOT_BAG_START + 1;
+ slots[2] = INVENTORY_SLOT_BAG_START + 2;
+ slots[3] = INVENTORY_SLOT_BAG_START + 3;
+ break;
+ case INVTYPE_RELIC:
+ {
+ switch(proto->SubClass)
+ {
+ case ITEM_SUBCLASS_ARMOR_LIBRAM:
+ if (pClass == CLASS_PALADIN)
+ slots[0] = EQUIPMENT_SLOT_RANGED;
+ break;
+ case ITEM_SUBCLASS_ARMOR_IDOL:
+ if (pClass == CLASS_DRUID)
+ slots[0] = EQUIPMENT_SLOT_RANGED;
+ break;
+ case ITEM_SUBCLASS_ARMOR_TOTEM:
+ if (pClass == CLASS_SHAMAN)
+ slots[0] = EQUIPMENT_SLOT_RANGED;
+ break;
+ case ITEM_SUBCLASS_ARMOR_MISC:
+ if (pClass == CLASS_WARLOCK)
+ slots[0] = EQUIPMENT_SLOT_RANGED;
+ break;
+ case ITEM_SUBCLASS_ARMOR_SIGIL:
+ if (pClass == CLASS_DEATH_KNIGHT)
+ slots[0] = EQUIPMENT_SLOT_RANGED;
+ break;
+ }
+ break;
+ }
+ default:
+ return NULL_SLOT;
+ }
+
+ if (slot != NULL_SLOT)
+ {
+ if (swap || !GetItemByPos(INVENTORY_SLOT_BAG_0, slot))
+ for (uint8 i = 0; i < 4; ++i)
+ if (slots[i] == slot)
+ return slot;
+ }
+ else
+ {
+ // search free slot at first
+ for (uint8 i = 0; i < 4; ++i)
+ if (slots[i] != NULL_SLOT && !GetItemByPos(INVENTORY_SLOT_BAG_0, slots[i]))
+ // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
+ if(slots[i] != EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
+ return slots[i];
+
+ // if not found free and can swap return first appropriate from used
+ for (uint8 i = 0; i < 4; ++i)
+ if (slots[i] != NULL_SLOT && swap)
+ return slots[i];
+ }
+
+ // no free position
+ return NULL_SLOT;
+}
+
+uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
+{
+ uint32 tempcount = 0;
+
+ uint8 res = EQUIP_ERR_OK;
+
+ for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
+ if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
+ if (pItem->GetEntry() == item)
+ {
+ uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
+ if (ires == EQUIP_ERR_OK)
+ {
+ tempcount += pItem->GetCount();
+ if (tempcount >= count)
+ return EQUIP_ERR_OK;
+ }
+ else
+ res = ires;
+ }
+
+ for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
+ if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i))
+ if (pItem->GetEntry() == item)
+ {
+ tempcount += pItem->GetCount();
+ if (tempcount >= count)
+ return EQUIP_ERR_OK;
+ }
+
+ for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
+ if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i))
+ if (pItem->GetEntry() == item)
+ {
+ tempcount += pItem->GetCount();
+ if(tempcount >= count)
+ return EQUIP_ERR_OK;
+ }
+
+ for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
+ if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i))
+ for (uint32 j = 0; j < pBag->GetBagSize(); ++j)
+ if (Item *pItem = GetItemByPos(i, j))
+ if (pItem->GetEntry() == item)
+ {
+ tempcount += pItem->GetCount();
+ if (tempcount >= count)
+ return EQUIP_ERR_OK;
+ }
+
+ // not found req. item count and have unequippable items
+ return res;
+}
+
+uint32 Player::GetItemCount(uint32 item, bool inBankAlso, Item* skipItem) const
+{
+ uint32 count = 0;
+ for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
+ if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i))
+ if (pItem != skipItem && pItem->GetEntry() == item)
+ count += pItem->GetCount();
+
+ for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
+ if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i))
+ if (pItem != skipItem && pItem->GetEntry() == item)
+ count += pItem->GetCount();
+
+ for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
+ if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
+ count += pBag->GetItemCount(item,skipItem);
+
+ if(skipItem && skipItem->GetProto()->GemProperties)
+ for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
+ if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i))
+ if (pItem != skipItem && pItem->GetProto()->Socket[0].Color)
+ count += pItem->GetGemCountWithID(item);
+
+ if (inBankAlso)
+ {
+ for (uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
+ if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i))
+ if (pItem != skipItem && pItem->GetEntry() == item)
+ count += pItem->GetCount();
+
+ for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
+ if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i))
+ count += pBag->GetItemCount(item,skipItem);
+
+ if (skipItem && skipItem->GetProto()->GemProperties)
+ for (uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
+ if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
+ if (pItem != skipItem && pItem->GetProto()->Socket[0].Color)
+ count += pItem->GetGemCountWithID(item);
+ }
+
+ return count;
+}
+
+Item* Player::GetItemByGuid( uint64 guid ) const
+{
+ for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
+ if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
+ if (pItem->GetGUID() == guid)
+ return pItem;
+
+ for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
+ if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i))
+ if (pItem->GetGUID() == guid)
+ return pItem;
+
+ for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
+ if (Bag *pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
+ for (uint32 j = 0; j < pBag->GetBagSize(); ++j)
+ if (Item* pItem = pBag->GetItemByPos(j))
+ if (pItem->GetGUID() == guid)
+ return pItem;
+
+ for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
+ if (Bag *pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
+ for (uint32 j = 0; j < pBag->GetBagSize(); ++j)
+ if (Item* pItem = pBag->GetItemByPos(j))
+ if (pItem->GetGUID() == guid)
+ return pItem;
+
+ return NULL;
+}
+
+Item* Player::GetItemByPos( uint16 pos ) const
+{
+ uint8 bag = pos >> 8;
+ uint8 slot = pos & 255;
+ return GetItemByPos( bag, slot );
+}
+
+Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
+{
+ if (bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || (slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END) ))
+ return m_items[slot];
+ else if ((bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
+ || (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END))
+ {
+ if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag))
+ return pBag->GetItemByPos(slot);
+ }
+ return NULL;
+}
+
+Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable /*= false*/) const
+{
+ uint16 slot;
+ switch (attackType)
+ {
+ case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
+ case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
+ case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
+ default: return NULL;
+ }
+
+ Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, slot);
+ if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
+ return NULL;
+
+ if (!useable)
+ return item;
+
+ if (item->IsBroken() || IsInFeralForm())
+ return NULL;
+
+ return item;
+}
+
+Item* Player::GetShield(bool useable) const
+{
+ Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
+ if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
+ return NULL;
+
+ if (!useable)
+ return item;
+
+ if (item->IsBroken())
+ return NULL;
+
+ return item;
+}
+
+uint8 Player::GetAttackBySlot( uint8 slot )
+{
+ switch(slot)
+ {
+ case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
+ case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
+ case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
+ default: return MAX_ATTACK;
+ }
+}
+
+bool Player::IsInventoryPos( uint8 bag, uint8 slot )
+{
+ if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
+ return true;
+ if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
+ return true;
+ if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
+ return true;
+ if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
+ return true;
+ return false;
+}
+
+bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
+{
+ if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
+ return true;
+ if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
+ return true;
+ return false;
+}
+
+bool Player::IsBankPos( uint8 bag, uint8 slot )
+{
+ if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
+ return true;
+ if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
+ return true;
+ if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
+ return true;
+ return false;
+}
+
+bool Player::IsBagPos( uint16 pos )
+{
+ uint8 bag = pos >> 8;
+ uint8 slot = pos & 255;
+ if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
+ return true;
+ if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
+ return true;
+ return false;
+}
+
+bool Player::IsValidPos( uint8 bag, uint8 slot )
+{
+ // post selected
+ if(bag == NULL_BAG)
+ return true;
+
+ if (bag == INVENTORY_SLOT_BAG_0)
+ {
+ // any post selected
+ if (slot == NULL_SLOT)
+ return true;
+
+ // equipment
+ if (slot < EQUIPMENT_SLOT_END)
+ return true;
+
+ // bag equip slots
+ if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
+ return true;
+
+ // backpack slots
+ if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
+ return true;
+
+ // keyring slots
+ if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
+ return true;
+
+ // bank main slots
+ if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
+ return true;
+
+ // bank bag slots
+ if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
+ return true;
+
+ return false;
+ }
+
+ // bag content slots
+ if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
+ {
+ Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
+ if(!pBag)
+ return false;
+
+ // any post selected
+ if (slot == NULL_SLOT)
+ return true;
+
+ return slot < pBag->GetBagSize();
+ }
+
+ // bank bag content slots
+ if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
+ {
+ Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
+ if(!pBag)
+ return false;
+
+ // any post selected
+ if (slot == NULL_SLOT)
+ return true;
+
+ return slot < pBag->GetBagSize();
+ }
+
+ // where this?
+ return false;
+}
+
+bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
+{
+ uint32 tempcount = 0;
+ for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
+ {
+ Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
+ if( pItem && pItem->GetEntry() == item )
+ {
+ tempcount += pItem->GetCount();
+ if( tempcount >= count )
+ return true;
+ }
+ }
+ for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
+ {
+ Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
+ if( pItem && pItem->GetEntry() == item )
+ {
+ tempcount += pItem->GetCount();
+ if( tempcount >= count )
+ return true;
+ }
+ }
+ for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
+ {
+ if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ {
+ for (uint32 j = 0; j < pBag->GetBagSize(); j++)
+ {
+ Item* pItem = GetItemByPos( i, j );
+ if( pItem && pItem->GetEntry() == item )
+ {
+ tempcount += pItem->GetCount();
+ if( tempcount >= count )
+ return true;
+ }
+ }
+ }
+ }
+
+ if(inBankAlso)
+ {
+ for (uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
+ {
+ Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
+ if( pItem && pItem->GetEntry() == item )
+ {
+ tempcount += pItem->GetCount();
+ if( tempcount >= count )
+ return true;
+ }
+ }
+ for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
+ {
+ if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ {
+ for (uint32 j = 0; j < pBag->GetBagSize(); j++)
+ {
+ Item* pItem = GetItemByPos( i, j );
+ if( pItem && pItem->GetEntry() == item )
+ {
+ tempcount += pItem->GetCount();
+ if( tempcount >= count )
+ return true;
+ }
+ }
+ }
+ }
+ }
+
+ return false;
+}
+
+bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
+{
+ uint32 tempcount = 0;
+ for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
+ {
+ if(i == except_slot)
+ continue;
+
+ Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
+ if( pItem && pItem->GetEntry() == item)
+ {
+ tempcount += pItem->GetCount();
+ if( tempcount >= count )
+ return true;
+ }
+ }
+
+ ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
+ if (pProto && pProto->GemProperties)
+ {
+ for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
+ {
+ if(i == except_slot)
+ continue;
+
+ Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
+ if( pItem && pItem->GetProto()->Socket[0].Color)
+ {
+ tempcount += pItem->GetGemCountWithID(item);
+ if( tempcount >= count )
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
+
+bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
+{
+ uint32 tempcount = 0;
+ for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
+ {
+ if(i == except_slot)
+ continue;
+
+ Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
+ if (!pItem)
+ continue;
+
+ ItemPrototype const *pProto = pItem->GetProto();
+ if (!pProto)
+ continue;
+
+ if (pProto->ItemLimitCategory == limitCategory)
+ {
+ tempcount += pItem->GetCount();
+ if( tempcount >= count )
+ return true;
+ }
+
+ if( pProto->Socket[0].Color)
+ {
+ tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
+ if( tempcount >= count )
+ return true;
+ }
+ }
+
+ return false;
+}
+
+uint8 Player::CountItemWithLimitCategory(uint32 limitCategory, Item* skipItem) const
+{
+ uint8 tempcount = 0;
+ for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
+ {
+ Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
+ if (!pItem)
+ continue;
+
+ if (pItem == skipItem)
+ continue;
+
+ ItemPrototype const *pProto = pItem->GetProto();
+ if (pProto && pProto->ItemLimitCategory == limitCategory)
+ tempcount += pItem->GetCount();
+ }
+
+ for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
+ {
+ Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
+ if (!pItem)
+ continue;
+
+ if (pItem == skipItem)
+ continue;
+
+ ItemPrototype const *pProto = pItem->GetProto();
+ if (pProto && pProto->ItemLimitCategory == limitCategory)
+ tempcount += pItem->GetCount();
+ }
+
+ for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
+ {
+ Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
+ if (!pBag)
+ continue;
+
+ for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
+ {
+ Item *pItem = GetItemByPos( i, j );
+
+ if (!pItem)
+ continue;
+
+ if (pItem == skipItem)
+ continue;
+
+ if (pItem->GetProto()->ItemLimitCategory == limitCategory)
+ tempcount += pItem->GetCount();
+ }
+ }
+
+ for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
+ {
+ Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
+ if (!pItem)
+ continue;
+
+ if (pItem == skipItem)
+ continue;
+
+ ItemPrototype const *pProto = pItem->GetProto();
+ if (pProto && pProto->ItemLimitCategory == limitCategory)
+ tempcount += pItem->GetCount();
+ }
+
+ for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
+ {
+ Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
+ if (!pBag)
+ continue;
+
+ for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
+ {
+ Item *pItem = GetItemByPos( i, j );
+
+ if(!pItem)
+ continue;
+
+ if(pItem == skipItem)
+ continue;
+
+ if(pItem->GetProto()->ItemLimitCategory == limitCategory)
+ tempcount += pItem->GetCount();
+ }
+ }
+
+ return tempcount;
+}
+
+uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
+{
+ ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
+ if (!pProto)
+ {
+ if(no_space_count)
+ *no_space_count = count;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+ }
+
+ if (pItem && pItem->m_lootGenerated)
+ return EQUIP_ERR_ALREADY_LOOTED;
+
+ // no maximum
+ if (pProto->MaxCount <= 0 && pProto->ItemLimitCategory == 0 || pProto->MaxCount == 2147483647)
+ return EQUIP_ERR_OK;
+
+ uint32 curcount;
+ if (pProto->ItemLimitCategory)
+ curcount = CountItemWithLimitCategory(pProto->ItemLimitCategory,pItem);
+ else
+ curcount = GetItemCount(pProto->ItemId,true,pItem);
+
+ if ((curcount + count > uint32(pProto->MaxCount)) && !(pProto->ItemLimitCategory))
+ {
+ if (no_space_count)
+ *no_space_count = count +curcount - pProto->MaxCount;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+ }
+
+ if (pProto->ItemLimitCategory && pProto->Class!=ITEM_CLASS_GEM) // gem have equip check (maybe sort by bonding?)
+ {
+ ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(pProto->ItemLimitCategory);
+ if (!limitEntry)
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+
+ if (curcount + count > limitEntry->maxCount)
+ {
+ if (no_space_count)
+ *no_space_count = count + curcount - limitEntry->maxCount;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; // attempt add too many limit category items
+ }
+ }
+
+ return EQUIP_ERR_OK;
+}
+
+bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
+{
+ Item *pItem;
+ for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
+ {
+ pItem = GetUseableItemByPos( INVENTORY_SLOT_BAG_0, i );
+ if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
+ return true;
+ }
+ for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
+ {
+ pItem = GetUseableItemByPos( INVENTORY_SLOT_BAG_0, i );
+ if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
+ return true;
+ }
+ for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
+ {
+ if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ {
+ for (uint32 j = 0; j < pBag->GetBagSize(); ++j)
+ {
+ pItem = GetUseableItemByPos( i, j );
+ if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
+{
+ Item* pItem2 = GetItemByPos( bag, slot );
+
+ // ignore move item (this slot will be empty at move)
+ if (pItem2==pSrcItem)
+ pItem2 = NULL;
+
+ uint32 need_space;
+
+ // empty specific slot - check item fit to slot
+ if (!pItem2 || swap)
+ {
+ if (bag == INVENTORY_SLOT_BAG_0)
+ {
+ // keyring case
+ if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
+ return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
+
+ // currencytoken case
+ if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
+ return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
+
+ // prevent cheating
+ if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
+ return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
+ }
+ else
+ {
+ Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
+ if (!pBag)
+ return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
+
+ ItemPrototype const* pBagProto = pBag->GetProto();
+ if (!pBagProto)
+ return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
+
+ if (slot >= pBagProto->ContainerSlots)
+ return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
+
+ if (!ItemCanGoIntoBag(pProto,pBagProto))
+ return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
+ }
+
+ // non empty stack with space
+ need_space = pProto->GetMaxStackSize();
+ }
+ // non empty slot, check item type
+ else
+ {
+ // check item type
+ if (pItem2->GetEntry() != pProto->ItemId)
+ return EQUIP_ERR_ITEM_CANT_STACK;
+
+ // check free space
+ if (pItem2->GetCount() >= pProto->GetMaxStackSize())
+ return EQUIP_ERR_ITEM_CANT_STACK;
+
+ // free stack space or infinity
+ need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
+ }
+
+ if (need_space > count)
+ need_space = count;
+
+ ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
+ if (!newPosition.isContainedIn(dest))
+ {
+ dest.push_back(newPosition);
+ count -= need_space;
+ }
+ return EQUIP_ERR_OK;
+}
+
+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
+{
+ // skip specific bag already processed in first called _CanStoreItem_InBag
+ if (bag==skip_bag)
+ return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
+
+ Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
+ if (!pBag)
+ return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
+
+ ItemPrototype const* pBagProto = pBag->GetProto();
+ if (!pBagProto)
+ return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
+
+ // specialized bag mode or non-specilized
+ if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER))
+ return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
+
+ if (!ItemCanGoIntoBag(pProto,pBagProto))
+ return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
+
+ for (uint32 j = 0; j < pBag->GetBagSize(); j++)
+ {
+ // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
+ if (j==skip_slot)
+ continue;
+
+ Item* pItem2 = GetItemByPos( bag, j );
+
+ // ignore move item (this slot will be empty at move)
+ if (pItem2==pSrcItem)
+ pItem2 = NULL;
+
+ // if merge skip empty, if !merge skip non-empty
+ if ((pItem2!=NULL)!=merge)
+ continue;
+
+ if (pItem2)
+ {
+ if (pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
+ {
+ uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
+ if(need_space > count)
+ need_space = count;
+
+ ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
+ if (!newPosition.isContainedIn(dest))
+ {
+ dest.push_back(newPosition);
+ count -= need_space;
+
+ if (count==0)
+ return EQUIP_ERR_OK;
+ }
+ }
+ }
+ else
+ {
+ uint32 need_space = pProto->GetMaxStackSize();
+ if (need_space > count)
+ need_space = count;
+
+ ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
+ if (!newPosition.isContainedIn(dest))
+ {
+ dest.push_back(newPosition);
+ count -= need_space;
+
+ if (count==0)
+ return EQUIP_ERR_OK;
+ }
+ }
+ }
+ return EQUIP_ERR_OK;
+}
+
+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
+{
+ for (uint32 j = slot_begin; j < slot_end; j++)
+ {
+ // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
+ if (INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
+ continue;
+
+ Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
+
+ // ignore move item (this slot will be empty at move)
+ if (pItem2==pSrcItem)
+ pItem2 = NULL;
+
+ // if merge skip empty, if !merge skip non-empty
+ if ((pItem2!=NULL)!=merge)
+ continue;
+
+ if (pItem2)
+ {
+ if (pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
+ {
+ uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
+ if (need_space > count)
+ need_space = count;
+ ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
+ if (!newPosition.isContainedIn(dest))
+ {
+ dest.push_back(newPosition);
+ count -= need_space;
+
+ if (count==0)
+ return EQUIP_ERR_OK;
+ }
+ }
+ }
+ else
+ {
+ uint32 need_space = pProto->GetMaxStackSize();
+ if (need_space > count)
+ need_space = count;
+
+ ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
+ if (!newPosition.isContainedIn(dest))
+ {
+ dest.push_back(newPosition);
+ count -= need_space;
+
+ if (count==0)
+ return EQUIP_ERR_OK;
+ }
+ }
+ }
+ return EQUIP_ERR_OK;
+}
+
+uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
+{
+ sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
+
+ ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
+ if (!pProto)
+ {
+ if (no_space_count)
+ *no_space_count = count;
+ return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
+ }
+
+ if (pItem && pItem->IsBindedNotWith(this))
+ {
+ if (no_space_count)
+ *no_space_count = count;
+ return EQUIP_ERR_DONT_OWN_THAT_ITEM;
+ }
+
+ // check count of items (skip for auto move for same player from bank)
+ uint32 no_similar_count = 0; // can't store this amount similar items
+ uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
+ if (res!=EQUIP_ERR_OK)
+ {
+ if (count==no_similar_count)
+ {
+ if (no_space_count)
+ *no_space_count = no_similar_count;
+ return res;
+ }
+ count -= no_similar_count;
+ }
+
+ // in specific slot
+ if (bag != NULL_BAG && slot != NULL_SLOT)
+ {
+ res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
+ if (res!=EQUIP_ERR_OK)
+ {
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return res;
+ }
+
+ if (count==0)
+ {
+ if (no_similar_count==0)
+ return EQUIP_ERR_OK;
+
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+ }
+ }
+
+ // not specific slot or have space for partly store only in specific slot
+
+ // in specific bag
+ if (bag != NULL_BAG)
+ {
+ // search stack in bag for merge to
+ if (pProto->Stackable != 1)
+ {
+ if (bag == INVENTORY_SLOT_BAG_0) // inventory
+ {
+ res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
+ if (res!=EQUIP_ERR_OK)
+ {
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return res;
+ }
+
+ if (count==0)
+ {
+ if (no_similar_count==0)
+ return EQUIP_ERR_OK;
+
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+ }
+
+ res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
+ if (res!=EQUIP_ERR_OK)
+ {
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return res;
+ }
+
+ if (count==0)
+ {
+ if (no_similar_count==0)
+ return EQUIP_ERR_OK;
+
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+ }
+ }
+ else // equipped bag
+ {
+ // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
+ res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
+ if (res!=EQUIP_ERR_OK)
+ res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
+
+ if (res!=EQUIP_ERR_OK)
+ {
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return res;
+ }
+
+ if (count==0)
+ {
+ if (no_similar_count==0)
+ return EQUIP_ERR_OK;
+
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+ }
+ }
+ }
+
+ // search free slot in bag for place to
+ if(bag == INVENTORY_SLOT_BAG_0) // inventory
+ {
+ // search free slot - keyring case
+ if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
+ {
+ uint32 keyringSize = GetMaxKeyringSize();
+ res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
+ if (res!=EQUIP_ERR_OK)
+ {
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return res;
+ }
+
+ if (count==0)
+ {
+ if (no_similar_count==0)
+ return EQUIP_ERR_OK;
+
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+ }
+
+ res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
+ if (res!=EQUIP_ERR_OK)
+ {
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return res;
+ }
+
+ if (count==0)
+ {
+ if (no_similar_count==0)
+ return EQUIP_ERR_OK;
+
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+ }
+ }
+ else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
+ {
+ res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
+ if (res!=EQUIP_ERR_OK)
+ {
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return res;
+ }
+
+ if (count==0)
+ {
+ if (no_similar_count==0)
+ return EQUIP_ERR_OK;
+
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+ }
+ }
+
+ res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
+ if (res!=EQUIP_ERR_OK)
+ {
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return res;
+ }
+
+ if (count==0)
+ {
+ if (no_similar_count==0)
+ return EQUIP_ERR_OK;
+
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+ }
+ }
+ else // equipped bag
+ {
+ res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
+ if (res!=EQUIP_ERR_OK)
+ res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
+
+ if (res!=EQUIP_ERR_OK)
+ {
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return res;
+ }
+
+ if (count==0)
+ {
+ if (no_similar_count==0)
+ return EQUIP_ERR_OK;
+
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+ }
+ }
+ }
+
+ // not specific bag or have space for partly store only in specific bag
+
+ // search stack for merge to
+ if (pProto->Stackable != 1)
+ {
+ res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
+ if (res!=EQUIP_ERR_OK)
+ {
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return res;
+ }
+
+ if (count==0)
+ {
+ if (no_similar_count==0)
+ return EQUIP_ERR_OK;
+
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+ }
+
+ res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
+ if (res!=EQUIP_ERR_OK)
+ {
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return res;
+ }
+
+ if (count==0)
+ {
+ if (no_similar_count==0)
+ return EQUIP_ERR_OK;
+
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+ }
+
+ if (pProto->BagFamily)
+ {
+ for (uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
+ {
+ res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
+ if (res!=EQUIP_ERR_OK)
+ continue;
+
+ if (count==0)
+ {
+ if (no_similar_count==0)
+ return EQUIP_ERR_OK;
+
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+ }
+ }
+ }
+
+ for (uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
+ {
+ res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
+ if (res!=EQUIP_ERR_OK)
+ continue;
+
+ if (count==0)
+ {
+ if (no_similar_count==0)
+ return EQUIP_ERR_OK;
+
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+ }
+ }
+ }
+
+ // search free slot - special bag case
+ if (pProto->BagFamily)
+ {
+ if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
+ {
+ uint32 keyringSize = GetMaxKeyringSize();
+ res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
+ if (res!=EQUIP_ERR_OK)
+ {
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return res;
+ }
+
+ if (count==0)
+ {
+ if (no_similar_count==0)
+ return EQUIP_ERR_OK;
+
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+ }
+ }
+ else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
+ {
+ res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
+ if (res!=EQUIP_ERR_OK)
+ {
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return res;
+ }
+
+ if (count==0)
+ {
+ if (no_similar_count==0)
+ return EQUIP_ERR_OK;
+
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+ }
+ }
+
+ for (uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
+ {
+ res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
+ if (res!=EQUIP_ERR_OK)
+ continue;
+
+ if (count==0)
+ {
+ if (no_similar_count==0)
+ return EQUIP_ERR_OK;
+
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+ }
+ }
+ }
+
+ // search free slot
+ res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
+ if (res!=EQUIP_ERR_OK)
+ {
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return res;
+ }
+
+ if (count==0)
+ {
+ if (no_similar_count==0)
+ return EQUIP_ERR_OK;
+
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+ }
+
+ for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
+ {
+ res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
+ if (res!=EQUIP_ERR_OK)
+ continue;
+
+ if (count==0)
+ {
+ if (no_similar_count==0)
+ return EQUIP_ERR_OK;
+
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+ return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
+ }
+ }
+
+ if (no_space_count)
+ *no_space_count = count + no_similar_count;
+
+ return EQUIP_ERR_INVENTORY_FULL;
+}
+
+//////////////////////////////////////////////////////////////////////////
+uint8 Player::CanStoreItems( Item **pItems,int count) const
+{
+ Item *pItem2;
+
+ // fill space table
+ int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
+ int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
+ int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
+ int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
+
+ memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
+ memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
+ memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
+ memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
+
+ for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
+ {
+ pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
+
+ if (pItem2 && !pItem2->IsInTrade())
+ {
+ inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
+ }
+ }
+
+ for (uint8 i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
+ {
+ pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
+
+ if (pItem2 && !pItem2->IsInTrade())
+ {
+ inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
+ }
+ }
+
+ for (uint8 i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; i++)
+ {
+ pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
+
+ if (pItem2 && !pItem2->IsInTrade())
+ {
+ inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
+ }
+ }
+
+ for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
+ {
+ if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ {
+ for (uint32 j = 0; j < pBag->GetBagSize(); j++)
+ {
+ pItem2 = GetItemByPos( i, j );
+ if (pItem2 && !pItem2->IsInTrade())
+ {
+ inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
+ }
+ }
+ }
+ }
+
+ // check free space for all items
+ for (int k = 0; k < count; ++k)
+ {
+ Item *pItem = pItems[k];
+
+ // no item
+ if (!pItem) continue;
+
+ sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
+ ItemPrototype const *pProto = pItem->GetProto();
+
+ // strange item
+ if( !pProto )
+ return EQUIP_ERR_ITEM_NOT_FOUND;
+
+ // item it 'bind'
+ if(pItem->IsBindedNotWith(this))
+ return EQUIP_ERR_DONT_OWN_THAT_ITEM;
+
+ Bag *pBag;
+ ItemPrototype const *pBagProto;
+
+ // item is 'one item only'
+ uint8 res = CanTakeMoreSimilarItems(pItem);
+ if(res != EQUIP_ERR_OK)
+ return res;
+
+ // search stack for merge to
+ if( pProto->Stackable != 1 )
+ {
+ bool b_found = false;
+
+ for (int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
+ {
+ pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
+ if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
+ {
+ inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
+ b_found = true;
+ break;
+ }
+ }
+ if (b_found) continue;
+
+ for (int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
+ {
+ pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
+ if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
+ {
+ inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
+ b_found = true;
+ break;
+ }
+ }
+ if (b_found) continue;
+
+ for (int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
+ {
+ pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
+ if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
+ {
+ inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
+ b_found = true;
+ break;
+ }
+ }
+ if (b_found) continue;
+
+ for (int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
+ {
+ pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
+ if( pBag && ItemCanGoIntoBag(pItem->GetProto(), pBag->GetProto()))
+ {
+ for (uint32 j = 0; j < pBag->GetBagSize(); j++)
+ {
+ pItem2 = GetItemByPos( t, j );
+ if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
+ {
+ inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
+ b_found = true;
+ break;
+ }
+ }
+ }
+ }
+ if (b_found) continue;
+ }
+
+ // special bag case
+ if( pProto->BagFamily )
+ {
+ bool b_found = false;
+ if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
+ {
+ uint32 keyringSize = GetMaxKeyringSize();
+ for (uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
+ {
+ if( inv_keys[t-KEYRING_SLOT_START] == 0 )
+ {
+ inv_keys[t-KEYRING_SLOT_START] = 1;
+ b_found = true;
+ break;
+ }
+ }
+ }
+
+ if (b_found) continue;
+
+ if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
+ {
+ for (uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
+ {
+ if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
+ {
+ inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
+ b_found = true;
+ break;
+ }
+ }
+ }
+
+ if (b_found) continue;
+
+ for (int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
+ {
+ pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
+ if( pBag )
+ {
+ pBagProto = pBag->GetProto();
+
+ // not plain container check
+ if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
+ ItemCanGoIntoBag(pProto,pBagProto) )
+ {
+ for (uint32 j = 0; j < pBag->GetBagSize(); j++)
+ {
+ if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
+ {
+ inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
+ b_found = true;
+ break;
+ }
+ }
+ }
+ }
+ }
+ if (b_found) continue;
+ }
+
+ // search free slot
+ bool b_found = false;
+ for (int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
+ {
+ if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
+ {
+ inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
+ b_found = true;
+ break;
+ }
+ }
+ if (b_found) continue;
+
+ // search free slot in bags
+ for (int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
+ {
+ pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
+ if( pBag )
+ {
+ pBagProto = pBag->GetProto();
+
+ // special bag already checked
+ if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
+ continue;
+
+ for (uint32 j = 0; j < pBag->GetBagSize(); j++)
+ {
+ if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
+ {
+ inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
+ b_found = true;
+ break;
+ }
+ }
+ }
+ }
+
+ // no free slot found?
+ if (!b_found)
+ return EQUIP_ERR_INVENTORY_FULL;
+ }
+
+ return EQUIP_ERR_OK;
+}
+
+//////////////////////////////////////////////////////////////////////////
+uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
+{
+ dest = 0;
+ Item *pItem = Item::CreateItem( item, 1, this );
+ if( pItem )
+ {
+ uint8 result = CanEquipItem(slot, dest, pItem, swap );
+ delete pItem;
+ return result;
+ }
+
+ return EQUIP_ERR_ITEM_NOT_FOUND;
+}
+
+uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
+{
+ dest = 0;
+ if( pItem )
+ {
+ sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
+ ItemPrototype const *pProto = pItem->GetProto();
+ if( pProto )
+ {
+ if(pItem->IsBindedNotWith(this))
+ return EQUIP_ERR_DONT_OWN_THAT_ITEM;
+
+ // check count of items (skip for auto move for same player from bank)
+ uint8 res = CanTakeMoreSimilarItems(pItem);
+ if(res != EQUIP_ERR_OK)
+ return res;
+
+ // check this only in game
+ if(not_loading)
+ {
+ // May be here should be more stronger checks; STUNNED checked
+ // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
+ if (hasUnitState(UNIT_STAT_STUNNED))
+ return EQUIP_ERR_YOU_ARE_STUNNED;
+
+ // do not allow equipping gear except weapons, offhands, projectiles, relics in
+ // - combat
+ // - in-progress arenas
+ if( !pProto->CanChangeEquipStateInCombat() )
+ {
+ if( isInCombat() )
+ return EQUIP_ERR_NOT_IN_COMBAT;
+
+ if(BattleGround* bg = GetBattleGround())
+ if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
+ return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
+ }
+
+ if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
+ return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
+
+ if(IsNonMeleeSpellCasted(false))
+ return EQUIP_ERR_CANT_DO_RIGHT_NOW;
+ }
+
+ ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0;
+ // 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)
+ if (ssd && ssd->MaxLevel < DEFAULT_MAX_LEVEL && ssd->MaxLevel < getLevel())
+ return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
+
+ uint8 eslot = FindEquipSlot( pProto, slot, swap );
+ if (eslot == NULL_SLOT)
+ return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
+
+ uint8 msg = CanUseItem(pItem , not_loading);
+ if (msg != EQUIP_ERR_OK)
+ return msg;
+ if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
+ return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
+
+ // if swap ignore item (equipped also)
+ if (uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
+ return res2;
+
+ // check unique-equipped special item classes
+ if (pProto->Class == ITEM_CLASS_QUIVER)
+ {
+ for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
+ {
+ if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
+ {
+ if (pBag != pItem)
+ {
+ if (ItemPrototype const* pBagProto = pBag->GetProto())
+ {
+ if (pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot))
+ return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
+ ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
+ : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
+ }
+ }
+ }
+ }
+ }
+
+ uint32 type = pProto->InventoryType;
+
+ if (eslot == EQUIPMENT_SLOT_OFFHAND)
+ {
+ if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
+ {
+ if (!CanDualWield())
+ return EQUIP_ERR_CANT_DUAL_WIELD;
+ }
+ else if (type == INVTYPE_2HWEAPON)
+ {
+ if (!CanDualWield() || !CanTitanGrip())
+ return EQUIP_ERR_CANT_DUAL_WIELD;
+ }
+
+ if (IsTwoHandUsed())
+ return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
+ }
+
+ // equip two-hand weapon case (with possible unequip 2 items)
+ if (type == INVTYPE_2HWEAPON)
+ {
+ if (eslot == EQUIPMENT_SLOT_OFFHAND)
+ {
+ if (!CanTitanGrip())
+ return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
+ }
+ else if (eslot != EQUIPMENT_SLOT_MAINHAND)
+ return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
+
+ if (!CanTitanGrip())
+ {
+ // offhand item must can be stored in inventory for offhand item and it also must be unequipped
+ Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
+ ItemPosCountVec off_dest;
+ if (offItem && (!not_loading ||
+ CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
+ CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ))
+ return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
+ }
+ }
+ dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
+ return EQUIP_ERR_OK;
+ }
+ }
+
+ return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
+}
+
+uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
+{
+ // Applied only to equipped items and bank bags
+ if(!IsEquipmentPos(pos) && !IsBagPos(pos))
+ return EQUIP_ERR_OK;
+
+ Item* pItem = GetItemByPos(pos);
+
+ // Applied only to existed equipped item
+ if( !pItem )
+ return EQUIP_ERR_OK;
+
+ sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
+
+ ItemPrototype const *pProto = pItem->GetProto();
+ if( !pProto )
+ return EQUIP_ERR_ITEM_NOT_FOUND;
+
+ // do not allow unequipping gear except weapons, offhands, projectiles, relics in
+ // - combat
+ // - in-progress arenas
+ if( !pProto->CanChangeEquipStateInCombat() )
+ {
+ if( isInCombat() )
+ return EQUIP_ERR_NOT_IN_COMBAT;
+
+ if(BattleGround* bg = GetBattleGround())
+ if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
+ return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
+ }
+
+ if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
+ return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
+
+ return EQUIP_ERR_OK;
+}
+
+uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
+{
+ if (!pItem)
+ return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
+
+ if (pItem->m_lootGenerated)
+ {
+ GetSession()->DoLootRelease(GetLootGUID());
+ return EQUIP_ERR_OK;
+ }
+
+ uint32 count = pItem->GetCount();
+
+ sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
+ ItemPrototype const *pProto = pItem->GetProto();
+ if (!pProto)
+ return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
+
+ if (pItem->IsBindedNotWith(this))
+ return EQUIP_ERR_DONT_OWN_THAT_ITEM;
+
+ // check count of items (skip for auto move for same player from bank)
+ uint8 res = CanTakeMoreSimilarItems(pItem);
+ if (res != EQUIP_ERR_OK)
+ return res;
+
+ // in specific slot
+ if (bag != NULL_BAG && slot != NULL_SLOT)
+ {
+ if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
+ {
+ if (!pItem->IsBag())
+ return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
+
+ if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
+ return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
+
+ if (uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK)
+ return cantuse;
+ }
+
+ res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
+ if (res!=EQUIP_ERR_OK)
+ return res;
+
+ if (count==0)
+ return EQUIP_ERR_OK;
+ }
+
+ // not specific slot or have space for partly store only in specific slot
+
+ // in specific bag
+ if( bag != NULL_BAG )
+ {
+ if( pProto->InventoryType == INVTYPE_BAG )
+ {
+ Bag *pBag = (Bag*)pItem;
+ if( pBag && !pBag->IsEmpty() )
+ return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
+ }
+
+ // search stack in bag for merge to
+ if( pProto->Stackable != 1 )
+ {
+ if( bag == INVENTORY_SLOT_BAG_0 )
+ {
+ res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
+ if(res!=EQUIP_ERR_OK)
+ return res;
+
+ if(count==0)
+ return EQUIP_ERR_OK;
+ }
+ else
+ {
+ res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
+ if(res!=EQUIP_ERR_OK)
+ res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
+
+ if(res!=EQUIP_ERR_OK)
+ return res;
+
+ if(count==0)
+ return EQUIP_ERR_OK;
+ }
+ }
+
+ // search free slot in bag
+ if( bag == INVENTORY_SLOT_BAG_0 )
+ {
+ res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
+ if(res!=EQUIP_ERR_OK)
+ return res;
+
+ if(count==0)
+ return EQUIP_ERR_OK;
+ }
+ else
+ {
+ res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
+ if(res != EQUIP_ERR_OK)
+ res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
+
+ if(res != EQUIP_ERR_OK)
+ return res;
+
+ if(count == 0)
+ return EQUIP_ERR_OK;
+ }
+ }
+
+ // not specific bag or have space for partly store only in specific bag
+
+ // search stack for merge to
+ if( pProto->Stackable != 1 )
+ {
+ // in slots
+ res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
+ if(res != EQUIP_ERR_OK)
+ return res;
+
+ if(count == 0)
+ return EQUIP_ERR_OK;
+
+ // in special bags
+ if( pProto->BagFamily )
+ {
+ for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
+ {
+ res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
+ if(res!=EQUIP_ERR_OK)
+ continue;
+
+ if(count==0)
+ return EQUIP_ERR_OK;
+ }
+ }
+
+ for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
+ {
+ res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
+ if(res!=EQUIP_ERR_OK)
+ continue;
+
+ if(count==0)
+ return EQUIP_ERR_OK;
+ }
+ }
+
+ // search free place in special bag
+ if( pProto->BagFamily )
+ {
+ for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
+ {
+ res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
+ if(res!=EQUIP_ERR_OK)
+ continue;
+
+ if(count==0)
+ return EQUIP_ERR_OK;
+ }
+ }
+
+ // search free space
+ res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
+ if(res!=EQUIP_ERR_OK)
+ return res;
+
+ if(count==0)
+ return EQUIP_ERR_OK;
+
+ for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
+ {
+ res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
+ if(res!=EQUIP_ERR_OK)
+ continue;
+
+ if(count==0)
+ return EQUIP_ERR_OK;
+ }
+ return EQUIP_ERR_BANK_FULL;
+}
+
+uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
+{
+ if (pItem)
+ {
+ sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
+
+ if (!isAlive() && not_loading)
+ return EQUIP_ERR_YOU_ARE_DEAD;
+
+ //if (isStunned())
+ // return EQUIP_ERR_YOU_ARE_STUNNED;
+
+ ItemPrototype const *pProto = pItem->GetProto();
+ if (pProto)
+ {
+ if (pItem->IsBindedNotWith(this))
+ return EQUIP_ERR_DONT_OWN_THAT_ITEM;
+
+ if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0)
+ return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
+
+ if (pItem->GetSkill() != 0)
+ {
+ bool allowEquip = false;
+ uint32 itemSkill = pItem->GetSkill();
+ // Armor that is binded to account can "morph" from plate to mail, etc. if skill is not learned yet.
+ if (pProto->Quality == ITEM_QUALITY_HEIRLOOM && pProto->Class == ITEM_CLASS_ARMOR && !HasSkill(itemSkill))
+ {
+ // TODO: when you right-click already equipped item it throws EQUIP_ERR_NO_REQUIRED_PROFICIENCY.
+
+ // In fact it's a visual bug, everything works properly... I need sniffs of operations with
+ // binded to account items from off server.
+
+ switch (this->getClass())
+ {
+ case CLASS_HUNTER:
+ case CLASS_SHAMAN:
+ allowEquip = (itemSkill == SKILL_MAIL);
+ break;
+ case CLASS_PALADIN:
+ allowEquip = (itemSkill == SKILL_PLATE_MAIL);
+ break;
+ }
+ }
+ if (!allowEquip && GetSkillValue(itemSkill) == 0)
+ return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
+ }
+
+ if (pProto->RequiredSkill != 0)
+ {
+ if (GetSkillValue( pProto->RequiredSkill ) == 0)
+ return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
+
+ if (GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank)
+ return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
+ }
+
+ if (pProto->RequiredSpell != 0 && !HasSpell(pProto->RequiredSpell))
+ return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
+
+ if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
+ return EQUIP_ERR_CANT_EQUIP_REPUTATION;
+
+ if (getLevel() < pProto->RequiredLevel)
+ return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
+
+ return EQUIP_ERR_OK;
+ }
+ }
+ return EQUIP_ERR_ITEM_NOT_FOUND;
+}
+
+bool Player::CanUseItem( ItemPrototype const *pProto )
+{
+ // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
+
+ if( pProto )
+ {
+ if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
+ return false;
+ if( pProto->RequiredSkill != 0 )
+ {
+ if( GetSkillValue( pProto->RequiredSkill ) == 0 )
+ return false;
+ else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
+ return false;
+ }
+ if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
+ return false;
+ if( getLevel() < pProto->RequiredLevel )
+ return false;
+ return true;
+ }
+ return false;
+}
+
+uint8 Player::CanUseAmmo( uint32 item ) const
+{
+ sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
+ if( !isAlive() )
+ return EQUIP_ERR_YOU_ARE_DEAD;
+ //if( isStunned() )
+ // return EQUIP_ERR_YOU_ARE_STUNNED;
+ ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
+ if( pProto )
+ {
+ if( pProto->InventoryType!= INVTYPE_AMMO )
+ return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
+ if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
+ return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
+ if( pProto->RequiredSkill != 0 )
+ {
+ if( GetSkillValue( pProto->RequiredSkill ) == 0 )
+ return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
+ else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
+ return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
+ }
+ if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
+ return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
+ /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
+ return EQUIP_ERR_CANT_EQUIP_REPUTATION;
+ */
+ if( getLevel() < pProto->RequiredLevel )
+ return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
+
+ // Requires No Ammo
+ if(HasAura(46699))
+ return EQUIP_ERR_BAG_FULL6;
+
+ return EQUIP_ERR_OK;
+ }
+ return EQUIP_ERR_ITEM_NOT_FOUND;
+}
+
+void Player::SetAmmo( uint32 item )
+{
+ if(!item)
+ return;
+
+ // already set
+ if( GetUInt32Value(PLAYER_AMMO_ID) == item )
+ return;
+
+ // check ammo
+ if(item)
+ {
+ uint8 msg = CanUseAmmo( item );
+ if( msg != EQUIP_ERR_OK )
+ {
+ SendEquipError( msg, NULL, NULL );
+ return;
+ }
+ }
+
+ SetUInt32Value(PLAYER_AMMO_ID, item);
+
+ _ApplyAmmoBonuses();
+}
+
+void Player::RemoveAmmo()
+{
+ SetUInt32Value(PLAYER_AMMO_ID, 0);
+
+ m_ammoDPS = 0.0f;
+
+ if(CanModifyStats())
+ UpdateDamagePhysical(RANGED_ATTACK);
+}
+
+// Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
+Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
+{
+ uint32 count = 0;
+ for (ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
+ count += itr->count;
+
+ Item *pItem = Item::CreateItem( item, count, this );
+ if( pItem )
+ {
+ ItemAddedQuestCheck( item, count );
+ if(randomPropertyId)
+ pItem->SetItemRandomProperties(randomPropertyId);
+ pItem = StoreItem( dest, pItem, update );
+ }
+ return pItem;
+}
+
+Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
+{
+ if( !pItem )
+ return NULL;
+
+ Item* lastItem = pItem;
+ uint32 entry = pItem->GetEntry();
+ for (ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end();)
+ {
+ uint16 pos = itr->pos;
+ uint32 count = itr->count;
+
+ ++itr;
+
+ if(itr == dest.end())
+ {
+ lastItem = _StoreItem(pos,pItem,count,false,update);
+ break;
+ }
+
+ lastItem = _StoreItem(pos,pItem,count,true,update);
+ }
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
+ return lastItem;
+}
+
+// Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
+Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
+{
+ if( !pItem )
+ return NULL;
+
+ uint8 bag = pos >> 8;
+ uint8 slot = pos & 255;
+
+ sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u, guid = %u", bag, slot, pItem->GetEntry(), count, pItem->GetGUIDLow());
+
+ Item *pItem2 = GetItemByPos( bag, slot );
+
+ if (!pItem2)
+ {
+ if (clone)
+ pItem = pItem->CloneItem(count, this);
+ else
+ pItem->SetCount(count);
+
+ if (!pItem)
+ return NULL;
+
+ if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
+ pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
+ (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
+ pItem->SetBinding( true );
+
+ if (bag == INVENTORY_SLOT_BAG_0)
+ {
+ m_items[slot] = pItem;
+ SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
+ pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
+ pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
+
+ pItem->SetSlot( slot );
+ pItem->SetContainer( NULL );
+
+ // need update known currency
+ if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
+ UpdateKnownCurrencies(pItem->GetEntry(), true);
+
+ if (IsInWorld() && update)
+ {
+ pItem->AddToWorld();
+ pItem->SendUpdateToPlayer( this );
+ }
+
+ pItem->SetState(ITEM_CHANGED, this);
+ }
+ else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
+ {
+ pBag->StoreItem( slot, pItem, update );
+ if( IsInWorld() && update )
+ {
+ pItem->AddToWorld();
+ pItem->SendUpdateToPlayer( this );
+ }
+ pItem->SetState(ITEM_CHANGED, this);
+ pBag->SetState(ITEM_CHANGED, this);
+ }
+
+ AddEnchantmentDurations(pItem);
+ AddItemDurations(pItem);
+
+ return pItem;
+ }
+ else
+ {
+ if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
+ pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
+ (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
+ pItem2->SetBinding( true );
+
+ pItem2->SetCount( pItem2->GetCount() + count );
+ if (IsInWorld() && update)
+ pItem2->SendUpdateToPlayer( this );
+
+ if (!clone)
+ {
+ // delete item (it not in any slot currently)
+ if (IsInWorld() && update)
+ {
+ pItem->RemoveFromWorld();
+ pItem->DestroyForPlayer( this );
+ }
+
+ RemoveEnchantmentDurations(pItem);
+ RemoveItemDurations(pItem);
+
+ pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
+ pItem->SetState(ITEM_REMOVED, this);
+ }
+
+ // AddItemDurations(pItem2); - pItem2 already have duration listed for player
+ AddEnchantmentDurations(pItem2);
+
+ pItem2->SetState(ITEM_CHANGED, this);
+
+ return pItem2;
+ }
+}
+
+Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
+{
+ if (Item *pItem = Item::CreateItem( item, 1, this ))
+ {
+ ItemAddedQuestCheck( item, 1 );
+ return EquipItem( pos, pItem, update );
+ }
+
+ return NULL;
+}
+
+Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
+{
+ AddEnchantmentDurations(pItem);
+ AddItemDurations(pItem);
+
+ uint8 bag = pos >> 8;
+ uint8 slot = pos & 255;
+
+ Item *pItem2 = GetItemByPos( bag, slot );
+
+ if( !pItem2 )
+ {
+ VisualizeItem( slot, pItem);
+
+ if(isAlive())
+ {
+ ItemPrototype const *pProto = pItem->GetProto();
+
+ // item set bonuses applied only at equip and removed at unequip, and still active for broken items
+ if(pProto && pProto->ItemSet)
+ AddItemsSetItem(this, pItem);
+
+ _ApplyItemMods(pItem, slot, true);
+
+ if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
+ {
+ uint32 cooldownSpell = 6119;
+
+ if (getClass() == CLASS_ROGUE)
+ cooldownSpell = 6123;
+
+ SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
+
+ if (!spellProto)
+ sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
+ else
+ {
+ m_weaponChangeTimer = spellProto->StartRecoveryTime;
+
+ WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
+ data << uint64(GetGUID());
+ data << uint8(1);
+ data << uint32(cooldownSpell);
+ data << uint32(0);
+ GetSession()->SendPacket(&data);
+ }
+ }
+ }
+
+ if( IsInWorld() && update )
+ {
+ pItem->AddToWorld();
+ pItem->SendUpdateToPlayer( this );
+ }
+
+ ApplyEquipCooldown(pItem);
+
+ // update expertise and armor penetration - passive auras may need it
+
+ if( slot == EQUIPMENT_SLOT_MAINHAND )
+ UpdateExpertise(BASE_ATTACK);
+
+ else if( slot == EQUIPMENT_SLOT_OFFHAND )
+ UpdateExpertise(OFF_ATTACK);
+
+ switch(slot)
+ {
+ case EQUIPMENT_SLOT_MAINHAND:
+ case EQUIPMENT_SLOT_OFFHAND:
+ case EQUIPMENT_SLOT_RANGED:
+ RecalculateRating(CR_ARMOR_PENETRATION);
+ default:
+ break;
+ }
+ }
+ else
+ {
+ pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
+ if( IsInWorld() && update )
+ pItem2->SendUpdateToPlayer( this );
+
+ // delete item (it not in any slot currently)
+ //pItem->DeleteFromDB();
+ if( IsInWorld() && update )
+ {
+ pItem->RemoveFromWorld();
+ pItem->DestroyForPlayer( this );
+ }
+
+ RemoveEnchantmentDurations(pItem);
+ RemoveItemDurations(pItem);
+
+ pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
+ pItem->SetState(ITEM_REMOVED, this);
+ pItem2->SetState(ITEM_CHANGED, this);
+
+ ApplyEquipCooldown(pItem2);
+
+ return pItem2;
+ }
+
+ // only for full equip instead adding to stack
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, pItem->GetEntry(), slot);
+
+ return pItem;
+}
+
+void Player::QuickEquipItem( uint16 pos, Item *pItem)
+{
+ if( pItem )
+ {
+ AddEnchantmentDurations(pItem);
+ AddItemDurations(pItem);
+
+ uint8 slot = pos & 255;
+ VisualizeItem( slot, pItem);
+
+ if( IsInWorld() )
+ {
+ pItem->AddToWorld();
+ pItem->SendUpdateToPlayer( this );
+ }
+
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, pItem->GetEntry(), slot);
+ }
+}
+
+void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
+{
+ if(pItem)
+ {
+ SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
+ SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
+ SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT));
+ }
+ else
+ {
+ SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
+ SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
+ }
+}
+
+void Player::VisualizeItem( uint8 slot, Item *pItem)
+{
+ if(!pItem)
+ return;
+
+ // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
+ if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
+ pItem->SetBinding( true );
+
+ sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
+
+ m_items[slot] = pItem;
+ SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
+ pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
+ pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
+ pItem->SetSlot( slot );
+ pItem->SetContainer( NULL );
+
+ if( slot < EQUIPMENT_SLOT_END )
+ SetVisibleItemSlot(slot, pItem);
+
+ pItem->SetState(ITEM_CHANGED, this);
+}
+
+void Player::RemoveItem(uint8 bag, uint8 slot, bool update)
+{
+ // note: removeitem does not actually change the item
+ // it only takes the item out of storage temporarily
+ // note2: if removeitem is to be used for delinking
+ // the item must be removed from the player's updatequeue
+
+ Item *pItem = GetItemByPos(bag, slot);
+ if (pItem)
+ {
+ sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
+
+ RemoveEnchantmentDurations(pItem);
+ RemoveItemDurations(pItem);
+
+ if (bag == INVENTORY_SLOT_BAG_0)
+ {
+ if (slot < INVENTORY_SLOT_BAG_END)
+ {
+ ItemPrototype const *pProto = pItem->GetProto();
+ // item set bonuses applied only at equip and removed at unequip, and still active for broken items
+
+ if(pProto && pProto->ItemSet)
+ RemoveItemsSetItem(this, pProto);
+
+ _ApplyItemMods(pItem, slot, false);
+
+ // remove item dependent auras and casts (only weapon and armor slots)
+ if(slot < EQUIPMENT_SLOT_END)
+ {
+ RemoveItemDependentAurasAndCasts(pItem);
+
+ // remove held enchantments, update expertise
+ if (slot == EQUIPMENT_SLOT_MAINHAND)
+ {
+ if (pItem->GetItemSuffixFactor())
+ {
+ pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
+ pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
+ }
+ else
+ {
+ pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
+ pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
+ }
+
+ UpdateExpertise(BASE_ATTACK);
+ }
+ else if (slot == EQUIPMENT_SLOT_OFFHAND)
+ UpdateExpertise(OFF_ATTACK);
+ // update armor penetration - passive auras may need it
+ switch(slot)
+ {
+ case EQUIPMENT_SLOT_MAINHAND:
+ case EQUIPMENT_SLOT_OFFHAND:
+ case EQUIPMENT_SLOT_RANGED:
+ RecalculateRating(CR_ARMOR_PENETRATION);
+ default:
+ break;
+ }
+ }
+ }
+ // need update known currency
+ else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
+ UpdateKnownCurrencies(pItem->GetEntry(), false);
+
+ m_items[slot] = NULL;
+ SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
+
+ if (slot < EQUIPMENT_SLOT_END)
+ SetVisibleItemSlot(slot, NULL);
+ }
+ else
+ {
+ if (Bag *pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, bag))
+ pBag->RemoveItem(slot, update);
+ }
+ pItem->SetUInt64Value(ITEM_FIELD_CONTAINED, 0);
+ // pItem->SetUInt64Value(ITEM_FIELD_OWNER, 0); not clear owner at remove (it will be set at store). This used in mail and auction code
+ pItem->SetSlot(NULL_SLOT);
+ if(IsInWorld() && update)
+ pItem->SendUpdateToPlayer(this);
+ }
+}
+
+// Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
+void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
+{
+ if(Item* it = GetItemByPos(bag,slot))
+ {
+ ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
+ RemoveItem(bag, slot, update);
+ it->RemoveFromUpdateQueueOf(this);
+ if(it->IsInWorld())
+ {
+ it->RemoveFromWorld();
+ it->DestroyForPlayer(this);
+ }
+ }
+}
+
+// Common operation need to add item from inventory without delete in trade, guild bank, mail....
+void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
+{
+ // update quest counters
+ ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
+
+ // store item
+ Item* pLastItem = StoreItem(dest, pItem, update);
+
+ // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
+ if(pLastItem == pItem)
+ {
+ // update owner for last item (this can be original item with wrong owner
+ if(pLastItem->GetOwnerGUID() != GetGUID())
+ pLastItem->SetOwnerGUID(GetGUID());
+
+ // if this original item then it need create record in inventory
+ // in case trade we already have item in other player inventory
+ pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
+ }
+}
+
+void Player::DestroyItem(uint8 bag, uint8 slot, bool update)
+{
+ Item *pItem = GetItemByPos(bag, slot);
+ if(pItem)
+ {
+ sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
+
+ // start from destroy contained items (only equipped bag can have its)
+ if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
+ {
+ for (uint8 i = 0; i < MAX_BAG_SIZE; ++i)
+ DestroyItem(slot, i, update);
+ }
+
+ if (pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
+ CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
+
+ RemoveEnchantmentDurations(pItem);
+ RemoveItemDurations(pItem);
+
+ ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
+
+ if (bag == INVENTORY_SLOT_BAG_0)
+ {
+ SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
+
+ // equipment and equipped bags can have applied bonuses
+ if (slot < INVENTORY_SLOT_BAG_END)
+ {
+ ItemPrototype const *pProto = pItem->GetProto();
+
+ // item set bonuses applied only at equip and removed at unequip, and still active for broken items
+ if (pProto && pProto->ItemSet)
+ RemoveItemsSetItem(this, pProto);
+
+ _ApplyItemMods(pItem, slot, false);
+ }
+
+ if ( slot < EQUIPMENT_SLOT_END )
+ {
+ // remove item dependent auras and casts (only weapon and armor slots)
+ RemoveItemDependentAurasAndCasts(pItem);
+
+ // update expertise and armor penetration - passive auras may need it
+ switch (slot)
+ {
+ case EQUIPMENT_SLOT_MAINHAND:
+ case EQUIPMENT_SLOT_OFFHAND:
+ case EQUIPMENT_SLOT_RANGED:
+ RecalculateRating(CR_ARMOR_PENETRATION);
+ default:
+ break;
+ }
+
+ if (slot == EQUIPMENT_SLOT_MAINHAND)
+ UpdateExpertise(BASE_ATTACK);
+ else if (slot == EQUIPMENT_SLOT_OFFHAND)
+ UpdateExpertise(OFF_ATTACK);
+
+ // equipment visual show
+ SetVisibleItemSlot(slot, NULL);
+ }
+ // need update known currency
+ else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
+ UpdateKnownCurrencies(pItem->GetEntry(), false);
+
+ m_items[slot] = NULL;
+ }
+ else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
+ pBag->RemoveItem(slot, update);
+
+ if (IsInWorld() && update)
+ {
+ pItem->RemoveFromWorld();
+ pItem->DestroyForPlayer(this);
+ }
+
+ //pItem->SetOwnerGUID(0);
+ pItem->SetUInt64Value(ITEM_FIELD_CONTAINED, 0);
+ pItem->SetSlot(NULL_SLOT);
+ pItem->SetState(ITEM_REMOVED, this);
+ }
+}
+
+void Player::DestroyItemCount(uint32 item, uint32 count, bool update, bool unequip_check)
+{
+ sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
+ uint32 remcount = 0;
+
+ // in inventory
+ for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
+ {
+ if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ {
+ if (pItem->GetEntry() == item)
+ {
+ if (pItem->GetCount() + remcount <= count)
+ {
+ // all items in inventory can unequipped
+ remcount += pItem->GetCount();
+ DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
+
+ if (remcount >= count)
+ return;
+ }
+ else
+ {
+ ItemRemovedQuestCheck(pItem->GetEntry(), count - remcount);
+ pItem->SetCount(pItem->GetCount() - count + remcount);
+ if (IsInWorld() & update)
+ pItem->SendUpdateToPlayer( this );
+ pItem->SetState(ITEM_CHANGED, this);
+ return;
+ }
+ }
+ }
+ }
+
+ for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
+ {
+ if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ {
+ if (pItem->GetEntry() == item)
+ {
+ if (pItem->GetCount() + remcount <= count)
+ {
+ // all keys can be unequipped
+ remcount += pItem->GetCount();
+ DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
+
+ if (remcount >= count)
+ return;
+ }
+ else
+ {
+ ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
+ pItem->SetCount( pItem->GetCount() - count + remcount );
+ if (IsInWorld() & update)
+ pItem->SendUpdateToPlayer( this );
+ pItem->SetState(ITEM_CHANGED, this);
+ return;
+ }
+ }
+ }
+ }
+
+ // in inventory bags
+ for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
+ {
+ if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ {
+ for (uint32 j = 0; j < pBag->GetBagSize(); j++)
+ {
+ if(Item* pItem = pBag->GetItemByPos(j))
+ {
+ if (pItem->GetEntry() == item)
+ {
+ // all items in bags can be unequipped
+ if (pItem->GetCount() + remcount <= count)
+ {
+ remcount += pItem->GetCount();
+ DestroyItem( i, j, update );
+
+ if (remcount >= count)
+ return;
+ }
+ else
+ {
+ ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
+ pItem->SetCount( pItem->GetCount() - count + remcount );
+ if (IsInWorld() && update)
+ pItem->SendUpdateToPlayer( this );
+ pItem->SetState(ITEM_CHANGED, this);
+ return;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // in equipment and bag list
+ for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
+ {
+ if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ {
+ if (pItem && pItem->GetEntry() == item)
+ {
+ if (pItem->GetCount() + remcount <= count)
+ {
+ if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
+ {
+ remcount += pItem->GetCount();
+ DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
+
+ if (remcount >= count)
+ return;
+ }
+ }
+ else
+ {
+ ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
+ pItem->SetCount( pItem->GetCount() - count + remcount );
+ if (IsInWorld() & update)
+ pItem->SendUpdateToPlayer( this );
+ pItem->SetState(ITEM_CHANGED, this);
+ return;
+ }
+ }
+ }
+ }
+}
+
+void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
+{
+ sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
+
+ // in inventory
+ for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
+ if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
+ DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
+
+ for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
+ if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
+ DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
+
+ // in inventory bags
+ for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
+ if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ for (uint32 j = 0; j < pBag->GetBagSize(); j++)
+ if (Item* pItem = pBag->GetItemByPos(j))
+ if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
+ DestroyItem(i, j, update);
+
+ // in equipment and bag list
+ for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
+ if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
+ DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
+}
+
+void Player::DestroyConjuredItems( bool update )
+{
+ // used when entering arena
+ // destroys all conjured items
+ sLog.outDebug( "STORAGE: DestroyConjuredItems" );
+
+ // in inventory
+ for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
+ if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ if (pItem->IsConjuredConsumable())
+ DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
+
+ // in inventory bags
+ for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
+ if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ for (uint32 j = 0; j < pBag->GetBagSize(); j++)
+ if (Item* pItem = pBag->GetItemByPos(j))
+ if (pItem->IsConjuredConsumable())
+ DestroyItem( i, j, update);
+
+ // in equipment and bag list
+ for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
+ if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ if (pItem->IsConjuredConsumable())
+ DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
+}
+
+Item* Player::GetItemByEntry(uint32 entry) const
+{
+ // in inventory
+ for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
+ {
+ if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ if (pItem->GetEntry() == entry)
+ return pItem;
+ }
+
+
+ for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
+ {
+ if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ {
+ for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
+ {
+ if (Item* pItem = pBag->GetItemByPos(j))
+ if (pItem->GetEntry()==entry)
+ return pItem;
+ }
+ }
+ }
+
+
+ for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
+ {
+ if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ if (pItem->GetEntry()==entry)
+ return pItem;
+ }
+
+ return NULL;
+}
+
+void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
+{
+ if(!pItem)
+ return;
+
+ sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
+
+ if( pItem->GetCount() <= count )
+ {
+ count -= pItem->GetCount();
+
+ DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
+ }
+ else
+ {
+ ItemRemovedQuestCheck( pItem->GetEntry(), count);
+ pItem->SetCount( pItem->GetCount() - count );
+ count = 0;
+ if( IsInWorld() & update )
+ pItem->SendUpdateToPlayer( this );
+ pItem->SetState(ITEM_CHANGED, this);
+ }
+}
+
+void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
+{
+ uint8 srcbag = src >> 8;
+ uint8 srcslot = src & 255;
+
+ uint8 dstbag = dst >> 8;
+ uint8 dstslot = dst & 255;
+
+ Item *pSrcItem = GetItemByPos( srcbag, srcslot );
+ if( !pSrcItem )
+ {
+ SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
+ return;
+ }
+
+ // not let split all items (can be only at cheating)
+ if(pSrcItem->GetCount() == count)
+ {
+ SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
+ return;
+ }
+
+ // not let split more existed items (can be only at cheating)
+ if(pSrcItem->GetCount() < count)
+ {
+ SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
+ return;
+ }
+
+ if(pSrcItem->m_lootGenerated) // prevent split looting item (item
+ {
+ //best error message found for attempting to split while looting
+ SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
+ return;
+ }
+
+ sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
+ Item *pNewItem = pSrcItem->CloneItem( count, this );
+ if( !pNewItem )
+ {
+ SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
+ return;
+ }
+
+ if( IsInventoryPos( dst ) )
+ {
+ // change item amount before check (for unique max count check)
+ pSrcItem->SetCount( pSrcItem->GetCount() - count );
+
+ ItemPosCountVec dest;
+ uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
+ if( msg != EQUIP_ERR_OK )
+ {
+ delete pNewItem;
+ pSrcItem->SetCount( pSrcItem->GetCount() + count );
+ SendEquipError( msg, pSrcItem, NULL );
+ return;
+ }
+
+ if( IsInWorld() )
+ pSrcItem->SendUpdateToPlayer( this );
+ pSrcItem->SetState(ITEM_CHANGED, this);
+ StoreItem( dest, pNewItem, true);
+ }
+ else if( IsBankPos ( dst ) )
+ {
+ // change item amount before check (for unique max count check)
+ pSrcItem->SetCount( pSrcItem->GetCount() - count );
+
+ ItemPosCountVec dest;
+ uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
+ if( msg != EQUIP_ERR_OK )
+ {
+ delete pNewItem;
+ pSrcItem->SetCount( pSrcItem->GetCount() + count );
+ SendEquipError( msg, pSrcItem, NULL );
+ return;
+ }
+
+ if( IsInWorld() )
+ pSrcItem->SendUpdateToPlayer( this );
+ pSrcItem->SetState(ITEM_CHANGED, this);
+ BankItem( dest, pNewItem, true);
+ }
+ else if( IsEquipmentPos ( dst ) )
+ {
+ // change item amount before check (for unique max count check), provide space for splitted items
+ pSrcItem->SetCount( pSrcItem->GetCount() - count );
+
+ uint16 dest;
+ uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
+ if( msg != EQUIP_ERR_OK )
+ {
+ delete pNewItem;
+ pSrcItem->SetCount( pSrcItem->GetCount() + count );
+ SendEquipError( msg, pSrcItem, NULL );
+ return;
+ }
+
+ if( IsInWorld() )
+ pSrcItem->SendUpdateToPlayer( this );
+ pSrcItem->SetState(ITEM_CHANGED, this);
+ EquipItem( dest, pNewItem, true);
+ AutoUnequipOffhandIfNeed();
+ }
+}
+
+void Player::SwapItem( uint16 src, uint16 dst )
+{
+ uint8 srcbag = src >> 8;
+ uint8 srcslot = src & 255;
+
+ uint8 dstbag = dst >> 8;
+ uint8 dstslot = dst & 255;
+
+ Item *pSrcItem = GetItemByPos( srcbag, srcslot );
+ Item *pDstItem = GetItemByPos( dstbag, dstslot );
+
+ if( !pSrcItem )
+ return;
+
+ sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
+
+ if(!isAlive() )
+ {
+ SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
+ return;
+ }
+
+ // SRC checks
+
+ if(pSrcItem->m_lootGenerated) // prevent swap looting item
+ {
+ //best error message found for attempting to swap while looting
+ SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
+ return;
+ }
+
+ // check unequip potability for equipped items and bank bags
+ if(IsEquipmentPos ( src ) || IsBagPos ( src ))
+ {
+ // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
+ uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || (pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty()));
+ if(msg != EQUIP_ERR_OK)
+ {
+ SendEquipError( msg, pSrcItem, pDstItem );
+ return;
+ }
+ }
+
+ // prevent put equipped/bank bag in self
+ if( IsBagPos ( src ) && srcslot == dstbag)
+ {
+ SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
+ return;
+ }
+
+ // DST checks
+
+ if (pDstItem)
+ {
+ if(pDstItem->m_lootGenerated) // prevent swap looting item
+ {
+ //best error message found for attempting to swap while looting
+ SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
+ return;
+ }
+
+ // check unequip potability for equipped items and bank bags
+ if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
+ {
+ // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
+ uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || (pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty()));
+ if(msg != EQUIP_ERR_OK)
+ {
+ SendEquipError( msg, pSrcItem, pDstItem );
+ return;
+ }
+ }
+ }
+
+ // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
+ // or swap empty bag with another empty or not empty bag (with items exchange)
+
+ // Move case
+ if( !pDstItem )
+ {
+ if( IsInventoryPos( dst ) )
+ {
+ ItemPosCountVec dest;
+ uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
+ if( msg != EQUIP_ERR_OK )
+ {
+ SendEquipError( msg, pSrcItem, NULL );
+ return;
+ }
+
+ RemoveItem(srcbag, srcslot, true);
+ StoreItem( dest, pSrcItem, true);
+ }
+ else if( IsBankPos ( dst ) )
+ {
+ ItemPosCountVec dest;
+ uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
+ if( msg != EQUIP_ERR_OK )
+ {
+ SendEquipError( msg, pSrcItem, NULL );
+ return;
+ }
+
+ RemoveItem(srcbag, srcslot, true);
+ BankItem( dest, pSrcItem, true);
+ }
+ else if( IsEquipmentPos ( dst ) )
+ {
+ uint16 dest;
+ uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
+ if( msg != EQUIP_ERR_OK )
+ {
+ SendEquipError( msg, pSrcItem, NULL );
+ return;
+ }
+
+ RemoveItem(srcbag, srcslot, true);
+ EquipItem(dest, pSrcItem, true);
+ AutoUnequipOffhandIfNeed();
+ }
+
+ return;
+ }
+
+ // attempt merge to / fill target item
+ if(!pSrcItem->IsBag() && !pDstItem->IsBag())
+ {
+ uint8 msg;
+ ItemPosCountVec sDest;
+ uint16 eDest;
+ if( IsInventoryPos( dst ) )
+ msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
+ else if( IsBankPos ( dst ) )
+ msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
+ else if( IsEquipmentPos ( dst ) )
+ msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
+ else
+ return;
+
+ // can be merge/fill
+ if(msg == EQUIP_ERR_OK)
+ {
+ if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
+ {
+ RemoveItem(srcbag, srcslot, true);
+
+ if( IsInventoryPos( dst ) )
+ StoreItem( sDest, pSrcItem, true);
+ else if( IsBankPos ( dst ) )
+ BankItem( sDest, pSrcItem, true);
+ else if( IsEquipmentPos ( dst ) )
+ {
+ EquipItem( eDest, pSrcItem, true);
+ AutoUnequipOffhandIfNeed();
+ }
+ }
+ else
+ {
+ pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
+ pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
+ pSrcItem->SetState(ITEM_CHANGED, this);
+ pDstItem->SetState(ITEM_CHANGED, this);
+ if( IsInWorld() )
+ {
+ pSrcItem->SendUpdateToPlayer( this );
+ pDstItem->SendUpdateToPlayer( this );
+ }
+ }
+ return;
+ }
+ }
+
+ // impossible merge/fill, do real swap
+ uint8 msg;
+
+ // check src->dest move possibility
+ ItemPosCountVec sDest;
+ uint16 eDest = 0;
+ if( IsInventoryPos( dst ) )
+ msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
+ else if( IsBankPos( dst ) )
+ msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
+ else if( IsEquipmentPos( dst ) )
+ {
+ msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
+ if( msg == EQUIP_ERR_OK )
+ msg = CanUnequipItem( eDest, true );
+ }
+
+ if( msg != EQUIP_ERR_OK )
+ {
+ SendEquipError( msg, pSrcItem, pDstItem );
+ return;
+ }
+
+ // check dest->src move possibility
+ ItemPosCountVec sDest2;
+ uint16 eDest2 = 0;
+ if( IsInventoryPos( src ) )
+ msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
+ else if( IsBankPos( src ) )
+ msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
+ else if( IsEquipmentPos( src ) )
+ {
+ msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
+ if( msg == EQUIP_ERR_OK )
+ msg = CanUnequipItem( eDest2, true);
+ }
+
+ if( msg != EQUIP_ERR_OK )
+ {
+ SendEquipError( msg, pDstItem, pSrcItem );
+ return;
+ }
+
+ // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
+ if(pSrcItem->IsBag() && pDstItem->IsBag())
+ {
+ Bag* emptyBag = NULL;
+ Bag* fullBag = NULL;
+ if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
+ {
+ emptyBag = (Bag*)pSrcItem;
+ fullBag = (Bag*)pDstItem;
+ }
+ else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
+ {
+ emptyBag = (Bag*)pDstItem;
+ fullBag = (Bag*)pSrcItem;
+ }
+
+ // bag swap (with items exchange) case
+ if(emptyBag && fullBag)
+ {
+ ItemPrototype const* emptyProto = emptyBag->GetProto();
+
+ uint32 count = 0;
+
+ for (uint32 i=0; i < fullBag->GetBagSize(); ++i)
+ {
+ Item *bagItem = fullBag->GetItemByPos(i);
+ if (!bagItem)
+ continue;
+
+ ItemPrototype const* bagItemProto = bagItem->GetProto();
+ if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emptyProto))
+ {
+ // one from items not go to empty target bag
+ SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
+ return;
+ }
+
+ ++count;
+ }
+
+ if (count > emptyBag->GetBagSize())
+ {
+ // too small targeted bag
+ SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
+ return;
+ }
+
+ // Items swap
+ count = 0; // will pos in new bag
+ for (uint32 i = 0; i< fullBag->GetBagSize(); ++i)
+ {
+ Item *bagItem = fullBag->GetItemByPos(i);
+ if (!bagItem)
+ continue;
+
+ fullBag->RemoveItem(i, true);
+ emptyBag->StoreItem(count, bagItem, true);
+ bagItem->SetState(ITEM_CHANGED, this);
+
+ ++count;
+ }
+ }
+ }
+
+ // now do moves, remove...
+ RemoveItem(dstbag, dstslot, false);
+ RemoveItem(srcbag, srcslot, false);
+
+ // add to dest
+ if (IsInventoryPos(dst))
+ StoreItem(sDest, pSrcItem, true);
+ else if (IsBankPos(dst))
+ BankItem(sDest, pSrcItem, true);
+ else if (IsEquipmentPos(dst))
+ EquipItem(eDest, pSrcItem, true);
+
+ // add to src
+ if (IsInventoryPos(src))
+ StoreItem(sDest2, pDstItem, true);
+ else if (IsBankPos(src))
+ BankItem(sDest2, pDstItem, true);
+ else if (IsEquipmentPos(src))
+ EquipItem(eDest2, pDstItem, true);
+
+ // if player is moving bags and is looting an item inside this bag
+ // release the loot
+ if (GetLootGUID())
+ {
+ bool released = false;
+ if (IsBagPos(src))
+ {
+ Bag* bag = (Bag*)pSrcItem;
+ for(int i=0; i < bag->GetBagSize(); ++i)
+ {
+ if (Item *bagItem = bag->GetItemByPos(i))
+ {
+ if (bagItem->m_lootGenerated)
+ {
+ m_session->DoLootRelease(GetLootGUID());
+ released = true; // so we don't need to look at dstBag
+ break;
+ }
+ }
+ }
+ }
+
+ if (!released && IsBagPos(dst) && pDstItem)
+ {
+ Bag* bag = (Bag*)pDstItem;
+ for(int i=0; i < bag->GetBagSize(); ++i)
+ {
+ if (Item *bagItem = bag->GetItemByPos(i))
+ {
+ if (bagItem->m_lootGenerated)
+ {
+ m_session->DoLootRelease(GetLootGUID());
+ released = true; // not realy needed here
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ AutoUnequipOffhandIfNeed();
+}
+
+void Player::AddItemToBuyBackSlot( Item *pItem )
+{
+ if (pItem)
+ {
+ uint32 slot = m_currentBuybackSlot;
+ // if current back slot non-empty search oldest or free
+ if (m_items[slot])
+ {
+ uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
+ uint32 oldest_slot = BUYBACK_SLOT_START;
+
+ for (uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
+ {
+ // found empty
+ if (!m_items[i])
+ {
+ slot = i;
+ break;
+ }
+
+ uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
+
+ if (oldest_time > i_time)
+ {
+ oldest_time = i_time;
+ oldest_slot = i;
+ }
+ }
+
+ // find oldest
+ slot = oldest_slot;
+ }
+
+ RemoveItemFromBuyBackSlot( slot, true );
+ sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
+
+ m_items[slot] = pItem;
+ time_t base = time(NULL);
+ uint32 etime = uint32(base - m_logintime + (30 * 3600));
+ uint32 eslot = slot - BUYBACK_SLOT_START;
+
+ SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID() );
+ if (ItemPrototype const *pProto = pItem->GetProto())
+ SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
+ else
+ SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
+ SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
+
+ // move to next (for non filled list is move most optimized choice)
+ if (m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
+ ++m_currentBuybackSlot;
+ }
+}
+
+Item* Player::GetItemFromBuyBackSlot( uint32 slot )
+{
+ sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
+ if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
+ return m_items[slot];
+ return NULL;
+}
+
+void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
+{
+ sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
+ if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
+ {
+ Item *pItem = m_items[slot];
+ if (pItem)
+ {
+ pItem->RemoveFromWorld();
+ if(del)
+ pItem->SetState(ITEM_REMOVED, this);
+ }
+
+ m_items[slot] = NULL;
+
+ uint32 eslot = slot - BUYBACK_SLOT_START;
+ SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0);
+ SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0);
+ SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0);
+
+ // if current backslot is filled set to now free slot
+ if(m_items[m_currentBuybackSlot])
+ m_currentBuybackSlot = slot;
+ }
+}
+
+void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
+{
+ sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
+ WorldPacket data(SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18));
+ data << uint8(msg);
+
+ if (msg != EQUIP_ERR_OK)
+ {
+ data << uint64(pItem ? pItem->GetGUID() : 0);
+ data << uint64(pItem2 ? pItem2->GetGUID() : 0);
+ data << uint8(0); // not 0 there...
+
+ if (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
+ {
+ uint8 level = 0;
+
+ if (pItem)
+ if (ItemPrototype const* proto = pItem->GetProto())
+ level = proto->RequiredLevel;
+
+ data << uint32(level); // new 2.4.0
+ }
+ }
+ GetSession()->SendPacket(&data);
+}
+
+void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
+{
+ sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
+ WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
+ data << uint64(pCreature ? pCreature->GetGUID() : 0);
+ data << uint32(item);
+ if (param > 0)
+ data << uint32(param);
+ data << uint8(msg);
+ GetSession()->SendPacket(&data);
+}
+
+void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
+{
+ sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
+ WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
+ data << uint64(pCreature ? pCreature->GetGUID() : 0);
+ data << uint64(guid);
+ if (param > 0)
+ data << uint32(param);
+ data << uint8(msg);
+ GetSession()->SendPacket(&data);
+}
+
+void Player::ClearTrade()
+{
+ tradeGold = 0;
+ acceptTrade = false;
+ for (uint8 i = 0; i < TRADE_SLOT_COUNT; i++)
+ tradeItems[i] = 0;
+}
+
+void Player::TradeCancel(bool sendback)
+{
+ if (pTrader)
+ {
+ // send yellow "Trade canceled" message to both traders
+ WorldSession* ws;
+ ws = GetSession();
+ if (sendback)
+ ws->SendCancelTrade();
+ ws = pTrader->GetSession();
+ if (!ws->PlayerLogout())
+ ws->SendCancelTrade();
+
+ // cleanup
+ ClearTrade();
+ pTrader->ClearTrade();
+ // prevent loss of reference
+ pTrader->pTrader = NULL;
+ pTrader = NULL;
+ }
+}
+
+void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
+{
+ if (m_itemDuration.empty())
+ return;
+
+ sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
+
+ for (ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end();)
+ {
+ Item* item = *itr;
+ ++itr; // current element can be erased in UpdateDuration
+
+ if ((realtimeonly && item->GetProto()->Duration < 0) || !realtimeonly)
+ item->UpdateDuration(this,time);
+ }
+}
+
+void Player::UpdateEnchantTime(uint32 time)
+{
+ for (EnchantDurationList::iterator itr = m_enchantDuration.begin(),next; itr != m_enchantDuration.end(); itr=next)
+ {
+ assert(itr->item);
+ next = itr;
+ if (!itr->item->GetEnchantmentId(itr->slot))
+ {
+ next = m_enchantDuration.erase(itr);
+ }
+ else if (itr->leftduration <= time)
+ {
+ ApplyEnchantment(itr->item, itr->slot, false, false);
+ itr->item->ClearEnchantment(itr->slot);
+ next = m_enchantDuration.erase(itr);
+ }
+ else if (itr->leftduration > time)
+ {
+ itr->leftduration -= time;
+ ++next;
+ }
+ }
+}
+
+void Player::AddEnchantmentDurations(Item *item)
+{
+ for (int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
+ {
+ if (!item->GetEnchantmentId(EnchantmentSlot(x)))
+ continue;
+
+ uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
+ if (duration > 0)
+ AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
+ }
+}
+
+void Player::RemoveEnchantmentDurations(Item *item)
+{
+ for (EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
+ {
+ if (itr->item == item)
+ {
+ // save duration in item
+ item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
+ itr = m_enchantDuration.erase(itr);
+ }
+ else
+ ++itr;
+ }
+}
+
+void Player::RemoveArenaEnchantments(EnchantmentSlot slot)
+{
+ // remove enchantments from equipped items first to clean up the m_enchantDuration list
+ for (EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
+ {
+ next = itr;
+ if (itr->slot == slot)
+ {
+ if (itr->item && itr->item->GetEnchantmentId(slot))
+ {
+ // Poisons and DK runes are enchants which are allowed on arenas
+ if (spellmgr.IsArenaAllowedEnchancment(itr->item->GetEnchantmentId(slot)))
+ {
+ ++next;
+ continue;
+ }
+ // remove from stats
+ ApplyEnchantment(itr->item, slot, false, false);
+ // remove visual
+ itr->item->ClearEnchantment(slot);
+ }
+ // remove from update list
+ next = m_enchantDuration.erase(itr);
+ }
+ else
+ ++next;
+ }
+
+ // remove enchants from inventory items
+ // NOTE: no need to remove these from stats, since these aren't equipped
+ // in inventory
+ for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
+ if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
+ if (pItem->GetEnchantmentId(slot))
+ pItem->ClearEnchantment(slot);
+
+ // in inventory bags
+ for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
+ if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ for (uint32 j = 0; j < pBag->GetBagSize(); j++)
+ if (Item* pItem = pBag->GetItemByPos(j))
+ if (pItem->GetEnchantmentId(slot))
+ pItem->ClearEnchantment(slot);
+}
+
+// duration == 0 will remove item enchant
+void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
+{
+ if (!item)
+ return;
+
+ if (slot >= MAX_ENCHANTMENT_SLOT)
+ return;
+
+ for (EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
+ {
+ if (itr->item == item && itr->slot == slot)
+ {
+ itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
+ m_enchantDuration.erase(itr);
+ break;
+ }
+ }
+ if (item && duration > 0 )
+ {
+ GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
+ m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
+ }
+}
+
+void Player::ApplyEnchantment(Item *item,bool apply)
+{
+ for (uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
+ ApplyEnchantment(item, EnchantmentSlot(slot), apply);
+}
+
+void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
+{
+ if (!item)
+ return;
+
+ if (!item->IsEquipped())
+ return;
+
+ if (!CanUseAttackType(Player::GetAttackBySlot(item->GetSlot())))
+ return;
+
+ if (slot >= MAX_ENCHANTMENT_SLOT)
+ return;
+
+ uint32 enchant_id = item->GetEnchantmentId(slot);
+ if (!enchant_id)
+ return;
+
+ SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
+ if (!pEnchant)
+ return;
+
+ if (!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
+ return;
+
+ if ((pEnchant->requiredLevel) > ((Player*)this)->getLevel())
+ return;
+
+ if ((pEnchant->requiredSkill) > 0)
+ {
+ if ((pEnchant->requiredSkillValue) > (((Player*)this)->GetSkillValue(pEnchant->requiredSkill)))
+ return;
+ }
+
+ if (!item->IsBroken())
+ {
+ for (int s = 0; s < 3; ++s)
+ {
+ uint32 enchant_display_type = pEnchant->type[s];
+ uint32 enchant_amount = pEnchant->amount[s];
+ uint32 enchant_spell_id = pEnchant->spellid[s];
+
+ switch(enchant_display_type)
+ {
+ case ITEM_ENCHANTMENT_TYPE_NONE:
+ break;
+ case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
+ // processed in Player::CastItemCombatSpell
+ break;
+ case ITEM_ENCHANTMENT_TYPE_DAMAGE:
+ if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
+ HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
+ else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
+ HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
+ else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
+ HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
+ break;
+ case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
+ if (enchant_spell_id)
+ {
+ if (apply)
+ {
+ int32 basepoints = 0;
+ // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
+ if (item->GetItemRandomPropertyId())
+ {
+ ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
+ if (item_rand)
+ {
+ // Search enchant_amount
+ for (int k = 0; k < 3; ++k)
+ {
+ if(item_rand->enchant_id[k] == enchant_id)
+ {
+ basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
+ break;
+ }
+ }
+ }
+ }
+ // Cast custom spell vs all equal basepoints getted from enchant_amount
+ if (basepoints)
+ CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
+ else
+ CastSpell(this, enchant_spell_id, true, item);
+ }
+ else
+ RemoveAurasDueToItemSpell(item, enchant_spell_id);
+ }
+ break;
+ case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
+ if (!enchant_amount)
+ {
+ ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
+ if(item_rand)
+ {
+ for (int k = 0; k < 3; ++k)
+ {
+ if(item_rand->enchant_id[k] == enchant_id)
+ {
+ enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
+ break;
+ }
+ }
+ }
+ }
+
+ HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
+ break;
+ case ITEM_ENCHANTMENT_TYPE_STAT:
+ {
+ if (!enchant_amount)
+ {
+ ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
+ if(item_rand_suffix)
+ {
+ for (int k = 0; k < 3; ++k)
+ {
+ if(item_rand_suffix->enchant_id[k] == enchant_id)
+ {
+ enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
+ break;
+ }
+ }
+ }
+ }
+
+ sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
+ switch (enchant_spell_id)
+ {
+ case ITEM_MOD_MANA:
+ sLog.outDebug("+ %u MANA",enchant_amount);
+ HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
+ break;
+ case ITEM_MOD_HEALTH:
+ sLog.outDebug("+ %u HEALTH",enchant_amount);
+ HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
+ break;
+ case ITEM_MOD_AGILITY:
+ sLog.outDebug("+ %u AGILITY",enchant_amount);
+ HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
+ ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
+ break;
+ case ITEM_MOD_STRENGTH:
+ sLog.outDebug("+ %u STRENGTH",enchant_amount);
+ HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
+ ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
+ break;
+ case ITEM_MOD_INTELLECT:
+ sLog.outDebug("+ %u INTELLECT",enchant_amount);
+ HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
+ ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
+ break;
+ case ITEM_MOD_SPIRIT:
+ sLog.outDebug("+ %u SPIRIT",enchant_amount);
+ HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
+ ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
+ break;
+ case ITEM_MOD_STAMINA:
+ sLog.outDebug("+ %u STAMINA",enchant_amount);
+ HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
+ ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
+ break;
+ case ITEM_MOD_DEFENSE_SKILL_RATING:
+ ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
+ sLog.outDebug("+ %u DEFENCE", enchant_amount);
+ break;
+ case ITEM_MOD_DODGE_RATING:
+ ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
+ sLog.outDebug("+ %u DODGE", enchant_amount);
+ break;
+ case ITEM_MOD_PARRY_RATING:
+ ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
+ sLog.outDebug("+ %u PARRY", enchant_amount);
+ break;
+ case ITEM_MOD_BLOCK_RATING:
+ ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
+ sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
+ break;
+ case ITEM_MOD_HIT_MELEE_RATING:
+ ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
+ sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
+ break;
+ case ITEM_MOD_HIT_RANGED_RATING:
+ ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
+ sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
+ break;
+ case ITEM_MOD_HIT_SPELL_RATING:
+ ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
+ sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
+ break;
+ case ITEM_MOD_CRIT_MELEE_RATING:
+ ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
+ sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
+ break;
+ case ITEM_MOD_CRIT_RANGED_RATING:
+ ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
+ sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
+ break;
+ case ITEM_MOD_CRIT_SPELL_RATING:
+ ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
+ sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
+ break;
+// Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
+// in Enchantments
+// case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
+// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
+// break;
+// case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
+// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
+// break;
+// case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
+// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
+// break;
+// case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
+// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
+// break;
+// case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
+// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
+// break;
+// case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
+// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
+// break;
+// case ITEM_MOD_HASTE_MELEE_RATING:
+// ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
+// break;
+// case ITEM_MOD_HASTE_RANGED_RATING:
+// ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
+// break;
+ case ITEM_MOD_HASTE_SPELL_RATING:
+ ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
+ break;
+ case ITEM_MOD_HIT_RATING:
+ ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
+ ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
+ ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
+ sLog.outDebug("+ %u HIT", enchant_amount);
+ break;
+ case ITEM_MOD_CRIT_RATING:
+ ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
+ ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
+ ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
+ sLog.outDebug("+ %u CRITICAL", enchant_amount);
+ break;
+// Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
+// case ITEM_MOD_HIT_TAKEN_RATING:
+// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
+// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
+// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
+// break;
+// case ITEM_MOD_CRIT_TAKEN_RATING:
+// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
+// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
+// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
+// break;
+ case ITEM_MOD_RESILIENCE_RATING:
+ ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
+ ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
+ ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
+ sLog.outDebug("+ %u RESILIENCE", enchant_amount);
+ break;
+ case ITEM_MOD_HASTE_RATING:
+ ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
+ ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
+ ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
+ sLog.outDebug("+ %u HASTE", enchant_amount);
+ break;
+ case ITEM_MOD_EXPERTISE_RATING:
+ ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
+ sLog.outDebug("+ %u EXPERTISE", enchant_amount);
+ break;
+ case ITEM_MOD_ATTACK_POWER:
+ HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
+ HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
+ sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
+ break;
+ case ITEM_MOD_RANGED_ATTACK_POWER:
+ HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
+ sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
+ break;
+// case ITEM_MOD_FERAL_ATTACK_POWER:
+// ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
+ sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
+ break;
+ case ITEM_MOD_MANA_REGENERATION:
+ ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
+ sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
+ break;
+ case ITEM_MOD_ARMOR_PENETRATION_RATING:
+ ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
+ sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
+ break;
+ case ITEM_MOD_SPELL_POWER:
+ ((Player*)this)->ApplySpellPowerBonus(enchant_amount, apply);
+ sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
+ break;
+ case ITEM_MOD_HEALTH_REGEN:
+ ((Player*)this)->ApplyHealthRegenBonus(enchant_amount, apply);
+ sLog.outDebug("+ %u HEALTH_REGENERATION", enchant_amount);
+ break;
+ case ITEM_MOD_SPELL_HEALING_DONE: // deprecated
+ case ITEM_MOD_SPELL_DAMAGE_DONE: // deprecated
+ default:
+ break;
+ }
+ break;
+ }
+ case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
+ {
+ if(getClass() == CLASS_SHAMAN)
+ {
+ float addValue = 0.0f;
+ if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
+ {
+ addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
+ HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
+ }
+ else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
+ {
+ addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
+ HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
+ }
+ }
+ break;
+ }
+ case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
+ // processed in Player::CastItemUseSpell
+ break;
+ case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
+ // nothing do..
+ break;
+ default:
+ sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
+ break;
+ } /*switch(enchant_display_type)*/
+ } /*for*/
+ }
+
+ // visualize enchantment at player and equipped items
+ if(slot == PERM_ENCHANTMENT_SLOT)
+ SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
+
+ if(slot == TEMP_ENCHANTMENT_SLOT)
+ SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
+
+ if(apply_dur)
+ {
+ if(apply)
+ {
+ // set duration
+ uint32 duration = item->GetEnchantmentDuration(slot);
+ if(duration > 0)
+ AddEnchantmentDuration(item, slot, duration);
+ }
+ else
+ {
+ // duration == 0 will remove EnchantDuration
+ AddEnchantmentDuration(item, slot, 0);
+ }
+ }
+}
+
+void Player::SendEnchantmentDurations()
+{
+ for (EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
+ {
+ GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
+ }
+}
+
+void Player::SendItemDurations()
+{
+ for (ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
+ {
+ (*itr)->SendTimeUpdate(this);
+ }
+}
+
+void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
+{
+ if(!item) // prevent crash
+ return;
+
+ // last check 2.0.10
+ WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
+ data << uint64(GetGUID()); // player GUID
+ data << uint32(received); // 0=looted, 1=from npc
+ data << uint32(created); // 0=received, 1=created
+ data << uint32(1); // always 0x01 (probably meant to be count of listed items)
+ data << uint8(item->GetBagSlot()); // bagslot
+ // item slot, but when added to stack: 0xFFFFFFFF
+ data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
+ data << uint32(item->GetEntry()); // item id
+ data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
+ data << int32(item->GetItemRandomPropertyId()); // random item property id
+ data << uint32(count); // count of items
+ data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
+
+ if (broadcast && GetGroup())
+ GetGroup()->BroadcastPacket(&data, true);
+ else
+ GetSession()->SendPacket(&data);
+}
+
+/*********************************************************/
+/*** GOSSIP SYSTEM ***/
+/*********************************************************/
+
+void Player::PrepareGossipMenu(WorldObject *pSource, uint32 menuId)
+{
+ PlayerMenu* pMenu = PlayerTalkClass;
+ pMenu->ClearMenus();
+
+ pMenu->GetGossipMenu().SetMenuId(menuId);
+
+ GossipMenuItemsMapBounds pMenuItemBounds = objmgr.GetGossipMenuItemsMapBounds(menuId);
+
+ // if default menuId and no menu options exist for this, use options from default options
+ if (pMenuItemBounds.first == pMenuItemBounds.second && menuId == GetDefaultGossipMenuForSource(pSource))
+ pMenuItemBounds = objmgr.GetGossipMenuItemsMapBounds(0);
+
+ for(GossipMenuItemsMap::const_iterator itr = pMenuItemBounds.first; itr != pMenuItemBounds.second; ++itr)
+ {
+ bool bCanTalk = true;
+
+ if (itr->second.cond_1 && !objmgr.IsPlayerMeetToCondition(this, itr->second.cond_1))
+ continue;
+
+ if (itr->second.cond_2 && !objmgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
+ continue;
+
+ if (itr->second.cond_3 && !objmgr.IsPlayerMeetToCondition(this, itr->second.cond_3))
+ continue;
+
+ if (pSource->GetTypeId() == TYPEID_UNIT)
+ {
+ Creature *pCreature = (Creature*)pSource;
+
+ uint32 npcflags = pCreature->GetUInt32Value(UNIT_NPC_FLAGS);
+
+ if (!(itr->second.npc_option_npcflag & npcflags))
+ continue;
+
+ switch(itr->second.option_id)
+ {
+ case GOSSIP_OPTION_QUESTGIVER:
+ PrepareQuestMenu(pSource->GetGUID());
+ bCanTalk = false;
+ break;
+ case GOSSIP_OPTION_ARMORER:
+ bCanTalk = false; // added in special mode
+ break;
+ case GOSSIP_OPTION_SPIRITHEALER:
+ if (!isDead())
+ bCanTalk = false;
+ break;
+ case GOSSIP_OPTION_VENDOR:
+ {
+ VendorItemData const* vItems = pCreature->GetVendorItems();
+ if (!vItems || vItems->Empty())
+ {
+ sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", pCreature->GetGUIDLow(), pCreature->GetEntry());
+ bCanTalk = false;
+ }
+ break;
+ }
+ case GOSSIP_OPTION_TRAINER:
+ if (!pCreature->isCanTrainingOf(this, false))
+ bCanTalk = false;
+ break;
+ case GOSSIP_OPTION_LEARNDUALSPEC:
+ if(!(GetSpecsCount() == 1 && pCreature->isCanTrainingAndResetTalentsOf(this) && !(getLevel() < sWorld.getConfig(CONFIG_MIN_DUALSPEC_LEVEL))))
+ bCanTalk = false;
+ break;
+ case GOSSIP_OPTION_UNLEARNTALENTS:
+ if (!pCreature->isCanTrainingAndResetTalentsOf(this))
+ bCanTalk = false;
+ break;
+ case GOSSIP_OPTION_UNLEARNPETSKILLS:
+ if (!GetPet() || GetPet()->getPetType() != HUNTER_PET || GetPet()->m_spells.size() <= 1 || pCreature->GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || pCreature->GetCreatureInfo()->trainer_class != CLASS_HUNTER)
+ bCanTalk = false;
+ break;
+ case GOSSIP_OPTION_TAXIVENDOR:
+ if (GetSession()->SendLearnNewTaxiNode(pCreature))
+ return;
+ break;
+ case GOSSIP_OPTION_BATTLEFIELD:
+ if (!pCreature->isCanInteractWithBattleMaster(this, false))
+ bCanTalk = false;
+ break;
+ case GOSSIP_OPTION_STABLEPET:
+ if (getClass() != CLASS_HUNTER)
+ bCanTalk = false;
+ break;
+ case GOSSIP_OPTION_GOSSIP:
+ case GOSSIP_OPTION_SPIRITGUIDE:
+ case GOSSIP_OPTION_INNKEEPER:
+ case GOSSIP_OPTION_BANKER:
+ case GOSSIP_OPTION_PETITIONER:
+ case GOSSIP_OPTION_TABARDDESIGNER:
+ case GOSSIP_OPTION_AUCTIONEER:
+ break; // no checks
+ case GOSSIP_OPTION_OUTDOORPVP:
+ if (!sOutdoorPvPMgr.CanTalkTo(this, pCreature, itr->second))
+ bCanTalk = false;
+ break;
+ default:
+ sLog.outErrorDb("Creature entry %u have unknown gossip option %u for menu %u", pCreature->GetEntry(), itr->second.option_id, itr->second.menu_id);
+ bCanTalk = false;
+ break;
+ }
+ }
+ else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
+ {
+ GameObject *pGo = (GameObject*)pSource;
+
+ switch(itr->second.option_id)
+ {
+ case GOSSIP_OPTION_QUESTGIVER:
+ if (pGo->GetGoType() == GAMEOBJECT_TYPE_QUESTGIVER)
+ PrepareQuestMenu(pSource->GetGUID());
+ bCanTalk = false;
+ break;
+ case GOSSIP_OPTION_GOSSIP:
+ if (pGo->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER && pGo->GetGoType() != GAMEOBJECT_TYPE_GOOBER)
+ bCanTalk = false;
+ break;
+ default:
+ bCanTalk = false;
+ break;
+ }
+ }
+
+ if (bCanTalk)
+ {
+ std::string strOptionText = itr->second.option_text;
+ std::string strBoxText = itr->second.box_text;
+
+ int loc_idx = GetSession()->GetSessionDbLocaleIndex();
+
+ if (loc_idx >= 0)
+ {
+ uint32 idxEntry = MAKE_PAIR32(menuId, itr->second.id);
+
+ if (GossipMenuItemsLocale const *no = objmgr.GetGossipMenuItemsLocale(idxEntry))
+ {
+ if (no->OptionText.size() > (size_t)loc_idx && !no->OptionText[loc_idx].empty())
+ strOptionText = no->OptionText[loc_idx];
+
+ if (no->BoxText.size() > (size_t)loc_idx && !no->BoxText[loc_idx].empty())
+ strBoxText = no->BoxText[loc_idx];
+ }
+ }
+
+ pMenu->GetGossipMenu().AddMenuItem(itr->second.option_icon, strOptionText, 0, itr->second.option_id, strBoxText, itr->second.box_money, itr->second.box_coded);
+ pMenu->GetGossipMenu().AddGossipMenuItemData(itr->second.action_menu_id, itr->second.action_poi_id, itr->second.action_script_id);
+ }
+ }
+
+ // some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
+ /*if (pMenu->Empty())
+ {
+ if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
+ {
+ // output error message if need
+ pCreature->isCanTrainingOf(this, true);
+ }
+
+ if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
+ {
+ // output error message if need
+ pCreature->isCanInteractWithBattleMaster(this, true);
+ }
+ }*/
+}
+
+void Player::SendPreparedGossip(WorldObject *pSource)
+{
+ if (!pSource)
+ return;
+
+ if (pSource->GetTypeId() == TYPEID_UNIT)
+ {
+ // in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
+ if (!((Creature*)pSource)->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_GOSSIP) && !PlayerTalkClass->GetQuestMenu().Empty())
+ {
+ SendPreparedQuest(pSource->GetGUID());
+ return;
+ }
+ }
+ else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
+ {
+ // probably need to find a better way here
+ if (!PlayerTalkClass->GetGossipMenu().GetMenuId() && !PlayerTalkClass->GetQuestMenu().Empty())
+ {
+ SendPreparedQuest(pSource->GetGUID());
+ return;
+ }
+ }
+
+ // in case non empty gossip menu (that not included quests list size) show it
+ // (quest entries from quest menu will be included in list)
+
+ uint32 textId = GetGossipTextId(pSource);
+
+ if (uint32 menuId = PlayerTalkClass->GetGossipMenu().GetMenuId())
+ textId = GetGossipTextId(menuId);
+
+ PlayerTalkClass->SendGossipMenu(textId, pSource->GetGUID());
+}
+
+void Player::OnGossipSelect(WorldObject* pSource, uint32 gossipListId, uint32 menuId)
+{
+ GossipMenu& gossipmenu = PlayerTalkClass->GetGossipMenu();
+
+ if (gossipListId >= gossipmenu.MenuItemCount())
+ return;
+
+ // if not same, then something funky is going on
+ if (menuId != gossipmenu.GetMenuId())
+ return;
+
+ uint32 gossipOptionId = gossipmenu.GetItem(gossipListId).m_gOptionId;
+ uint64 guid = pSource->GetGUID();
+
+ if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
+ {
+ if (gossipOptionId > GOSSIP_OPTION_QUESTGIVER)
+ {
+ sLog.outError("Player guid %u request invalid gossip option for GameObject entry %u", GetGUIDLow(), pSource->GetEntry());
+ return;
+ }
+ }
+
+ GossipMenuItemData pMenuData = gossipmenu.GetItemData(gossipListId);
+
+ switch(gossipOptionId)
+ {
+ case GOSSIP_OPTION_GOSSIP:
+ {
+ if (pMenuData.m_gAction_menu)
+ {
+ PrepareGossipMenu(pSource, pMenuData.m_gAction_menu);
+ SendPreparedGossip(pSource);
+ }
+
+ if (pMenuData.m_gAction_poi)
+ PlayerTalkClass->SendPointOfInterest(pMenuData.m_gAction_poi);
+
+ if (pMenuData.m_gAction_script)
+ {
+ if (pSource->GetTypeId() == TYPEID_UNIT)
+ GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, this, pSource);
+ else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
+ GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, pSource, this);
+ }
+ break;
+ }
+ case GOSSIP_OPTION_OUTDOORPVP:
+ sOutdoorPvPMgr.HandleGossipOption(this, pSource->GetGUID(), gossipListId);
+ break;
+ case GOSSIP_OPTION_SPIRITHEALER:
+ if (isDead())
+ ((Creature*)pSource)->CastSpell(((Creature*)pSource),17251,true,NULL,NULL,GetGUID());
+ break;
+ case GOSSIP_OPTION_QUESTGIVER:
+ PrepareQuestMenu(guid);
+ SendPreparedQuest(guid);
+ break;
+ case GOSSIP_OPTION_VENDOR:
+ case GOSSIP_OPTION_ARMORER:
+ GetSession()->SendListInventory(guid);
+ break;
+ case GOSSIP_OPTION_STABLEPET:
+ GetSession()->SendStablePet(guid);
+ break;
+ case GOSSIP_OPTION_TRAINER:
+ GetSession()->SendTrainerList(guid);
+ break;
+ case GOSSIP_OPTION_LEARNDUALSPEC:
+ if(GetSpecsCount() == 1 && !(getLevel() < sWorld.getConfig(CONFIG_MIN_DUALSPEC_LEVEL)))
+ {
+ if (GetMoney() < 10000000)
+ {
+ SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
+ PlayerTalkClass->CloseGossip();
+ break;
+ }
+ else
+ {
+ ModifyMoney(-10000000);
+
+ // Cast spells that teach dual spec
+ // Both are also ImplicitTarget self and must be cast by player
+ this->CastSpell(this, 63680, true, NULL, NULL, this->GetGUID());
+ this->CastSpell(this, 63624, true, NULL, NULL, this->GetGUID());
+
+ // Should show another Gossip text with "Congratulations..."
+ PlayerTalkClass->CloseGossip();
+ }
+ }
+ break;
+ case GOSSIP_OPTION_UNLEARNTALENTS:
+ PlayerTalkClass->CloseGossip();
+ SendTalentWipeConfirm(guid);
+ break;
+ case GOSSIP_OPTION_UNLEARNPETSKILLS:
+ PlayerTalkClass->CloseGossip();
+ SendPetSkillWipeConfirm();
+ break;
+ case GOSSIP_OPTION_TAXIVENDOR:
+ GetSession()->SendTaxiMenu(((Creature*)pSource));
+ break;
+ case GOSSIP_OPTION_INNKEEPER:
+ PlayerTalkClass->CloseGossip();
+ SetBindPoint(guid);
+ break;
+ case GOSSIP_OPTION_BANKER:
+ GetSession()->SendShowBank(guid);
+ break;
+ case GOSSIP_OPTION_PETITIONER:
+ PlayerTalkClass->CloseGossip();
+ GetSession()->SendPetitionShowList(guid);
+ break;
+ case GOSSIP_OPTION_TABARDDESIGNER:
+ PlayerTalkClass->CloseGossip();
+ GetSession()->SendTabardVendorActivate(guid);
+ break;
+ case GOSSIP_OPTION_AUCTIONEER:
+ GetSession()->SendAuctionHello(guid, ((Creature*)pSource));
+ break;
+ case GOSSIP_OPTION_SPIRITGUIDE:
+ PrepareGossipMenu(pSource);
+ SendPreparedGossip(pSource);
+ break;
+ case GOSSIP_OPTION_BATTLEFIELD:
+ {
+ BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(pSource->GetEntry());
+
+ if (bgTypeId == BATTLEGROUND_TYPE_NONE)
+ {
+ sLog.outError("a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUIDLow());
+ return;
+ }
+
+ GetSession()->SendBattlegGroundList(guid, bgTypeId);
+ break;
+ }
+ }
+}
+
+uint32 Player::GetGossipTextId(WorldObject *pSource)
+{
+ if (!pSource || pSource->GetTypeId() != TYPEID_UNIT || !((Creature*)pSource)->GetDBTableGUIDLow())
+ return DEFAULT_GOSSIP_MESSAGE;
+
+ if (uint32 pos = objmgr.GetNpcGossip(((Creature*)pSource)->GetDBTableGUIDLow()))
+ return pos;
+
+ return DEFAULT_GOSSIP_MESSAGE;
+}
+
+uint32 Player::GetGossipTextId(uint32 menuId)
+{
+ uint32 textId = DEFAULT_GOSSIP_MESSAGE;
+
+ if (!menuId)
+ return textId;
+
+ GossipMenusMapBounds pMenuBounds = objmgr.GetGossipMenusMapBounds(menuId);
+
+ for(GossipMenusMap::const_iterator itr = pMenuBounds.first; itr != pMenuBounds.second; ++itr)
+ {
+ if (objmgr.IsPlayerMeetToCondition(this, itr->second.cond_1) && objmgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
+ textId = itr->second.text_id;
+ }
+
+ return textId;
+}
+
+uint32 Player::GetDefaultGossipMenuForSource(WorldObject *pSource)
+{
+ if (pSource->GetTypeId() == TYPEID_UNIT)
+ return ((Creature*)pSource)->GetCreatureInfo()->GossipMenuId;
+ else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
+ return((GameObject*)pSource)->GetGOInfo()->GetGossipMenuId();
+
+ return 0;
+}
+
+/*********************************************************/
+/*** QUEST SYSTEM ***/
+/*********************************************************/
+
+void Player::PrepareQuestMenu( uint64 guid )
+{
+ Object *pObject;
+ QuestRelations* pObjectQR;
+ QuestRelations* pObjectQIR;
+
+ // pets also can have quests
+ Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
+ if( pCreature )
+ {
+ pObject = (Object*)pCreature;
+ pObjectQR = &objmgr.mCreatureQuestRelations;
+ pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
+ }
+ else
+ {
+ //we should obtain map pointer from GetMap() in 99% of cases. Special case
+ //only for quests which cast teleport spells on player
+ Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
+ ASSERT(_map);
+ GameObject *pGameObject = _map->GetGameObject(guid);
+ if( pGameObject )
+ {
+ pObject = (Object*)pGameObject;
+ pObjectQR = &objmgr.mGOQuestRelations;
+ pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
+ }
+ else
+ return;
+ }
+
+ QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
+ qm.ClearMenu();
+
+ for (QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
+ {
+ uint32 quest_id = i->second;
+ QuestStatus status = GetQuestStatus( quest_id );
+ if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
+ qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
+ else if ( status == QUEST_STATUS_INCOMPLETE )
+ qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
+ //else if (status == QUEST_STATUS_AVAILABLE )
+ // qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
+ }
+
+ for (QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
+ {
+ uint32 quest_id = i->second;
+ Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
+ if(!pQuest) continue;
+
+ QuestStatus status = GetQuestStatus( quest_id );
+
+ if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
+ qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
+ else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
+ qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
+ }
+}
+
+void Player::SendPreparedQuest(uint64 guid)
+{
+ QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
+ if (questMenu.Empty())
+ return;
+
+ QuestMenuItem const& qmi0 = questMenu.GetItem(0);
+
+ uint32 status = qmi0.m_qIcon;
+
+ // single element case
+ if (questMenu.MenuItemCount() == 1)
+ {
+ // Auto open -- maybe also should verify there is no greeting
+ uint32 quest_id = qmi0.m_qId;
+ Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
+
+ if (pQuest)
+ {
+ if (status == DIALOG_STATUS_UNK2 && !GetQuestRewardStatus(quest_id))
+ PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
+ else if (status == DIALOG_STATUS_UNK2)
+ PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
+ // Send completable on repeatable and autoCompletable quest if player don't have quest
+ // TODO: verify if check for !pQuest->IsDaily() is really correct (possibly not)
+ else if (pQuest->IsAutoComplete() && pQuest->IsRepeatable() && !pQuest->IsDaily())
+ PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanCompleteRepeatableQuest(pQuest), true);
+ else
+ PlayerTalkClass->SendQuestGiverQuestDetails(pQuest, guid, true);
+ }
+ }
+ // multiply entries
+ else
+ {
+ QEmote qe;
+ qe._Delay = 0;
+ qe._Emote = 0;
+ std::string title = "";
+
+ // need pet case for some quests
+ Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
+ if (pCreature)
+ {
+ uint32 textid = GetGossipTextId(pCreature);
+ GossipText const* gossiptext = objmgr.GetGossipText(textid);
+ if (!gossiptext)
+ {
+ qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
+ qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
+ title = "";
+ }
+ else
+ {
+ qe = gossiptext->Options[0].Emotes[0];
+
+ if(!gossiptext->Options[0].Text_0.empty())
+ {
+ title = gossiptext->Options[0].Text_0;
+
+ int loc_idx = GetSession()->GetSessionDbLocaleIndex();
+ if (loc_idx >= 0)
+ {
+ NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
+ if (nl)
+ {
+ if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
+ title = nl->Text_0[0][loc_idx];
+ }
+ }
+ }
+ else
+ {
+ title = gossiptext->Options[0].Text_1;
+
+ int loc_idx = GetSession()->GetSessionDbLocaleIndex();
+ if (loc_idx >= 0)
+ {
+ NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
+ if (nl)
+ {
+ if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
+ title = nl->Text_1[0][loc_idx];
+ }
+ }
+ }
+ }
+ }
+ PlayerTalkClass->SendQuestGiverQuestList(qe, title, guid);
+ }
+}
+
+bool Player::IsActiveQuest( uint32 quest_id ) const
+{
+ QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
+
+ return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
+}
+
+Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
+{
+ Object *pObject;
+ QuestRelations* pObjectQR;
+ QuestRelations* pObjectQIR;
+
+ Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
+ if( pCreature )
+ {
+ pObject = (Object*)pCreature;
+ pObjectQR = &objmgr.mCreatureQuestRelations;
+ pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
+ }
+ else
+ {
+ //we should obtain map pointer from GetMap() in 99% of cases. Special case
+ //only for quests which cast teleport spells on player
+ Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
+ ASSERT(_map);
+ GameObject *pGameObject = _map->GetGameObject(guid);
+ if( pGameObject )
+ {
+ pObject = (Object*)pGameObject;
+ pObjectQR = &objmgr.mGOQuestRelations;
+ pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
+ }
+ else
+ return NULL;
+ }
+
+ uint32 nextQuestID = pQuest->GetNextQuestInChain();
+ for (QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
+ {
+ if (itr->second == nextQuestID)
+ return objmgr.GetQuestTemplate(nextQuestID);
+ }
+
+ return NULL;
+}
+
+bool Player::CanSeeStartQuest( Quest const *pQuest )
+{
+ if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
+ SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
+ SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
+ SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
+ {
+ return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
+ }
+
+ return false;
+}
+
+bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
+{
+ return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
+ && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
+ && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
+ && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
+ && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
+ && SatisfyQuestDay( pQuest, msg );
+}
+
+bool Player::CanAddQuest( Quest const *pQuest, bool msg )
+{
+ if( !SatisfyQuestLog( msg ) )
+ return false;
+
+ uint32 srcitem = pQuest->GetSrcItemId();
+ if( srcitem > 0 )
+ {
+ uint32 count = pQuest->GetSrcItemCount();
+ ItemPosCountVec dest;
+ uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
+
+ // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
+ if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
+ return true;
+ else if( msg2 != EQUIP_ERR_OK )
+ {
+ SendEquipError( msg2, NULL, NULL );
+ return false;
+ }
+ }
+ return true;
+}
+
+bool Player::CanCompleteQuest( uint32 quest_id )
+{
+ if( quest_id )
+ {
+ QuestStatusData& q_status = mQuestStatus[quest_id];
+ if( q_status.m_status == QUEST_STATUS_COMPLETE )
+ return false; // not allow re-complete quest
+
+ Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
+
+ if(!qInfo)
+ return false;
+
+ // auto complete quest
+ if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
+ return true;
+
+ if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
+ {
+
+ if ( qInfo->HasFlag( QUEST_TRINITY_FLAGS_DELIVER ) )
+ {
+ for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; i++)
+ {
+ if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
+ return false;
+ }
+ }
+
+ if ( qInfo->HasFlag(QUEST_TRINITY_FLAGS_KILL_OR_CAST | QUEST_TRINITY_FLAGS_SPEAKTO) )
+ {
+ for (uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
+ {
+ if( qInfo->ReqCreatureOrGOId[i] == 0 )
+ continue;
+
+ if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
+ return false;
+ }
+ }
+
+ if ( qInfo->HasFlag( QUEST_TRINITY_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
+ return false;
+
+ if ( qInfo->HasFlag( QUEST_TRINITY_FLAGS_TIMED ) && q_status.m_timer == 0 )
+ return false;
+
+ if ( qInfo->GetRewOrReqMoney() < 0 )
+ {
+ if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
+ return false;
+ }
+
+ uint32 repFacId = qInfo->GetRepObjectiveFaction();
+ if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
+ return false;
+
+ uint32 repFacId2 = qInfo->GetRepObjectiveFaction2();
+ if ( repFacId2 && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue2() )
+ return false;
+
+ return true;
+ }
+ }
+ return false;
+}
+
+bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
+{
+ // Solve problem that player don't have the quest and try complete it.
+ // if repeatable she must be able to complete event if player don't have it.
+ // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
+ if( !CanTakeQuest(pQuest, false) )
+ return false;
+
+ if (pQuest->HasFlag( QUEST_TRINITY_FLAGS_DELIVER) )
+ for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; i++)
+ if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
+ return false;
+
+ if( !CanRewardQuest(pQuest, false) )
+ return false;
+
+ return true;
+}
+
+bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
+{
+ // not auto complete quest and not completed quest (only cheating case, then ignore without message)
+ if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
+ return false;
+
+ // daily quest can't be rewarded (25 daily quest already completed)
+ if(!SatisfyQuestDay(pQuest,true))
+ return false;
+
+ // rewarded and not repeatable quest (only cheating case, then ignore without message)
+ if(GetQuestRewardStatus(pQuest->GetQuestId()))
+ return false;
+
+ // prevent receive reward with quest items in bank
+ if ( pQuest->HasFlag( QUEST_TRINITY_FLAGS_DELIVER ) )
+ {
+ for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; i++)
+ {
+ if( pQuest->ReqItemCount[i]!= 0 &&
+ GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
+ {
+ if(msg)
+ SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
+ return false;
+ }
+ }
+ }
+
+ // prevent receive reward with low money and GetRewOrReqMoney() < 0
+ if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
+ return false;
+
+ return true;
+}
+
+bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
+{
+ // prevent receive reward with quest items in bank or for not completed quest
+ if(!CanRewardQuest(pQuest,msg))
+ return false;
+
+ if ( pQuest->GetRewChoiceItemsCount() > 0 )
+ {
+ if( pQuest->RewChoiceItemId[reward] )
+ {
+ ItemPosCountVec dest;
+ uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
+ if( res != EQUIP_ERR_OK )
+ {
+ SendEquipError( res, NULL, NULL );
+ return false;
+ }
+ }
+ }
+
+ if ( pQuest->GetRewItemsCount() > 0 )
+ {
+ for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
+ {
+ if( pQuest->RewItemId[i] )
+ {
+ ItemPosCountVec dest;
+ uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
+ if( res != EQUIP_ERR_OK )
+ {
+ SendEquipError( res, NULL, NULL );
+ return false;
+ }
+ }
+ }
+ }
+
+ return true;
+}
+
+void Player::AddQuest( Quest const *pQuest, Object *questGiver )
+{
+ uint16 log_slot = FindQuestSlot( 0 );
+ assert(log_slot < MAX_QUEST_LOG_SIZE);
+
+ uint32 quest_id = pQuest->GetQuestId();
+
+ // if not exist then created with set uState==NEW and rewarded=false
+ QuestStatusData& questStatusData = mQuestStatus[quest_id];
+
+ // check for repeatable quests status reset
+ questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
+ questStatusData.m_explored = false;
+
+ if ( pQuest->HasFlag( QUEST_TRINITY_FLAGS_DELIVER ) )
+ {
+ for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
+ questStatusData.m_itemcount[i] = 0;
+ }
+
+ if ( pQuest->HasFlag(QUEST_TRINITY_FLAGS_KILL_OR_CAST | QUEST_TRINITY_FLAGS_SPEAKTO) )
+ {
+ for (uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
+ questStatusData.m_creatureOrGOcount[i] = 0;
+ }
+
+ GiveQuestSourceItem( pQuest );
+ AdjustQuestReqItemCount( pQuest, questStatusData );
+
+ if( pQuest->GetRepObjectiveFaction() )
+ if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
+ GetReputationMgr().SetVisible(factionEntry);
+
+ if( pQuest->GetRepObjectiveFaction2() )
+ if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction2()))
+ GetReputationMgr().SetVisible(factionEntry);
+
+ uint32 qtime = 0;
+ if( pQuest->HasFlag( QUEST_TRINITY_FLAGS_TIMED ) )
+ {
+ uint32 limittime = pQuest->GetLimitTime();
+
+ // shared timed quest
+ if(questGiver && questGiver->GetTypeId() == TYPEID_PLAYER)
+ limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
+
+ AddTimedQuest( quest_id );
+ questStatusData.m_timer = limittime * IN_MILISECONDS;
+ qtime = static_cast<uint32>(time(NULL)) + limittime;
+ }
+ else
+ questStatusData.m_timer = 0;
+
+ SetQuestSlot(log_slot, quest_id, qtime);
+
+ if (questStatusData.uState != QUEST_NEW)
+ questStatusData.uState = QUEST_CHANGED;
+
+ //starting initial quest script
+ if(questGiver && pQuest->GetQuestStartScript()!=0)
+ GetMap()->ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
+
+ // Some spells applied at quest activation
+ SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,true);
+ if(saBounds.first != saBounds.second)
+ {
+ uint32 zone, area;
+ GetZoneAndAreaId(zone,area);
+
+ for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
+ if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
+ if( !HasAura(itr->second->spellId) )
+ CastSpell(this,itr->second->spellId,true);
+ }
+
+ UpdateForQuestWorldObjects();
+}
+
+void Player::CompleteQuest( uint32 quest_id )
+{
+ if( quest_id )
+ {
+ SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
+
+ uint16 log_slot = FindQuestSlot( quest_id );
+ if( log_slot < MAX_QUEST_LOG_SIZE)
+ SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
+
+ if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
+ {
+ if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
+ RewardQuest(qInfo,0,this,false);
+ else
+ SendQuestComplete( quest_id );
+ }
+ }
+}
+
+void Player::IncompleteQuest( uint32 quest_id )
+{
+ if( quest_id )
+ {
+ SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
+
+ uint16 log_slot = FindQuestSlot( quest_id );
+ if( log_slot < MAX_QUEST_LOG_SIZE)
+ RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
+ }
+}
+
+void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
+{
+ //this THING should be here to protect code from quest, which cast on player far teleport as a reward
+ //should work fine, cause far teleport will be executed in Player::Update()
+ SetCanDelayTeleport(true);
+
+ uint32 quest_id = pQuest->GetQuestId();
+
+ for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
+ if (pQuest->ReqItemId[i])
+ DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
+
+ for (uint8 i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i)
+ {
+ if (pQuest->ReqSourceId[i])
+ {
+ uint32 count = pQuest->ReqSourceCount[i];
+ DestroyItemCount(pQuest->ReqSourceId[i], count ? count : 9999, true);
+ }
+ }
+
+ RemoveTimedQuest(quest_id);
+
+ if (pQuest->GetRewChoiceItemsCount() > 0)
+ {
+ if (uint32 itemId = pQuest->RewChoiceItemId[reward])
+ {
+ ItemPosCountVec dest;
+ if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK)
+ {
+ Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
+ SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
+ }
+ }
+ }
+
+ if (pQuest->GetRewItemsCount() > 0)
+ {
+ for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
+ {
+ if (uint32 itemId = pQuest->RewItemId[i])
+ {
+ ItemPosCountVec dest;
+ if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewItemCount[i] ) == EQUIP_ERR_OK)
+ {
+ Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
+ SendNewItem(item, pQuest->RewItemCount[i], true, false);
+ }
+ }
+ }
+ }
+
+ RewardReputation(pQuest);
+
+ uint16 log_slot = FindQuestSlot(quest_id);
+ if (log_slot < MAX_QUEST_LOG_SIZE)
+ SetQuestSlot(log_slot, 0);
+
+ QuestStatusData& q_status = mQuestStatus[quest_id];
+
+ // Not give XP in case already completed once repeatable quest
+ uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
+
+ // handle SPELL_AURA_MOD_XP_QUEST_PCT auras
+ Unit::AuraEffectList const& ModXPPctAuras = GetAuraEffectsByType(SPELL_AURA_MOD_XP_QUEST_PCT);
+ for (Unit::AuraEffectList::const_iterator i = ModXPPctAuras.begin(); i != ModXPPctAuras.end(); ++i)
+ XP = uint32(XP*(1.0f + (*i)->GetAmount() / 100.0f));
+
+ if (getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
+ GiveXP(XP, NULL);
+ else
+ {
+ uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
+ ModifyMoney(money);
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
+ }
+
+ // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
+ if (pQuest->GetRewOrReqMoney())
+ {
+ ModifyMoney(pQuest->GetRewOrReqMoney());
+
+ if (pQuest->GetRewOrReqMoney() > 0)
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
+ }
+
+ // honor reward
+ if (pQuest->GetRewHonorableKills())
+ RewardHonor(NULL, 0, Trinity::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
+
+ // title reward
+ if (pQuest->GetCharTitleId())
+ {
+ if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
+ SetTitle(titleEntry);
+ }
+
+ if (pQuest->GetBonusTalents())
+ {
+ m_questRewardTalentCount+=pQuest->GetBonusTalents();
+ InitTalentForLevel();
+ }
+
+ // Send reward mail
+ if (uint32 mail_template_id = pQuest->GetRewMailTemplateId())
+ MailDraft(mail_template_id).SendMailTo(this, questGiver, MAIL_CHECK_MASK_NONE, pQuest->GetRewMailDelaySecs());
+
+ if (pQuest->IsDaily())
+ {
+ SetDailyQuestStatus(quest_id);
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
+ }
+
+ if (!pQuest->IsRepeatable())
+ SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
+ else
+ SetQuestStatus(quest_id, QUEST_STATUS_NONE);
+
+ q_status.m_rewarded = true;
+ if (q_status.uState != QUEST_NEW)
+ q_status.uState = QUEST_CHANGED;
+
+ if (announce)
+ SendQuestReward( pQuest, XP, questGiver );
+
+ // cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data)
+ if (pQuest->GetRewSpellCast() > 0)
+ CastSpell( this, pQuest->GetRewSpellCast(), true);
+ else if ( pQuest->GetRewSpell() > 0)
+ CastSpell( this, pQuest->GetRewSpell(), true);
+
+ if (pQuest->GetZoneOrSort() > 0)
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
+
+ uint32 zone = 0;
+ uint32 area = 0;
+
+ // remove auras from spells with quest reward state limitations
+ SpellAreaForQuestMapBounds saEndBounds = spellmgr.GetSpellAreaForQuestEndMapBounds(quest_id);
+ if(saEndBounds.first != saEndBounds.second)
+ {
+ GetZoneAndAreaId(zone,area);
+
+ for (SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
+ if(!itr->second->IsFitToRequirements(this,zone,area))
+ RemoveAurasDueToSpell(itr->second->spellId);
+ }
+
+ // Some spells applied at quest reward
+ SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,false);
+ if(saBounds.first != saBounds.second)
+ {
+ if(!zone || !area)
+ GetZoneAndAreaId(zone,area);
+
+ for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
+ if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
+ if( !HasAura(itr->second->spellId) )
+ CastSpell(this,itr->second->spellId,true);
+ }
+
+ //lets remove flag for delayed teleports
+ SetCanDelayTeleport(false);
+}
+
+void Player::FailQuest(uint32 questId)
+{
+ if (Quest const* pQuest = objmgr.GetQuestTemplate(questId))
+ {
+ SetQuestStatus(questId, QUEST_STATUS_FAILED);
+
+ uint16 log_slot = FindQuestSlot(questId);
+
+ if (log_slot < MAX_QUEST_LOG_SIZE)
+ {
+ SetQuestSlotTimer(log_slot, 1);
+ SetQuestSlotState(log_slot, QUEST_STATE_FAIL);
+ }
+
+ if (pQuest->HasFlag(QUEST_TRINITY_FLAGS_TIMED))
+ {
+ QuestStatusData& q_status = mQuestStatus[questId];
+
+ RemoveTimedQuest(questId);
+ q_status.m_timer = 0;
+
+ SendQuestTimerFailed(questId);
+ }
+ else
+ SendQuestFailed(questId);
+
+ // Destroy quest items on quest failure.
+ for (uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
+ if (pQuest->ReqItemId[i] > 0 && pQuest->ReqItemCount[i] > 0)
+ // Destroy items recieved on starting the quest.
+ DestroyItemCount(pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true, true);
+ for (uint8 i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i)
+ if (pQuest->ReqSourceId[i] > 0 && pQuest->ReqSourceCount[i] > 0)
+ // Destroy items recieved during the quest.
+ DestroyItemCount(pQuest->ReqSourceId[i], pQuest->ReqSourceCount[i], true, true);
+ }
+}
+
+bool Player::SatisfyQuestSkillOrClass(Quest const* qInfo, bool msg)
+{
+ int32 zoneOrSort = qInfo->GetZoneOrSort();
+ int32 skillOrClass = qInfo->GetSkillOrClass();
+
+ // skip zone zoneOrSort and 0 case skillOrClass
+ if (zoneOrSort >= 0 && skillOrClass == 0)
+ return true;
+
+ int32 questSort = -zoneOrSort;
+ uint8 reqSortClass = ClassByQuestSort(questSort);
+
+ // check class sort cases in zoneOrSort
+ if( reqSortClass != 0 && getClass() != reqSortClass)
+ {
+ if (msg)
+ SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
+ return false;
+ }
+
+ // check class
+ if (skillOrClass < 0)
+ {
+ uint8 reqClass = -int32(skillOrClass);
+ if (getClass() != reqClass)
+ {
+ if (msg)
+ SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
+ return false;
+ }
+ }
+ // check skill
+ else if(skillOrClass > 0)
+ {
+ uint32 reqSkill = skillOrClass;
+ if(GetSkillValue(reqSkill) < qInfo->GetRequiredSkillValue())
+ {
+ if (msg)
+ SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool Player::SatisfyQuestLevel(Quest const* qInfo, bool msg)
+{
+ if (getLevel() < qInfo->GetMinLevel())
+ {
+ if(msg)
+ SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
+ return false;
+ }
+ return true;
+}
+
+bool Player::SatisfyQuestLog(bool msg)
+{
+ // exist free slot
+ if (FindQuestSlot(0) < MAX_QUEST_LOG_SIZE)
+ return true;
+
+ if (msg)
+ {
+ WorldPacket data(SMSG_QUESTLOG_FULL, 0);
+ GetSession()->SendPacket(&data);
+ sLog.outDebug("WORLD: Sent QUEST_LOG_FULL_MESSAGE");
+ }
+ return false;
+}
+
+bool Player::SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg)
+{
+ // No previous quest (might be first quest in a series)
+ if (qInfo->prevQuests.empty())
+ return true;
+
+ for (Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter)
+ {
+ uint32 prevId = abs(*iter);
+
+ QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
+ Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
+
+ if (qPrevInfo && i_prevstatus != mQuestStatus.end())
+ {
+ // If any of the positive previous quests completed, return true
+ if (*iter > 0 && i_prevstatus->second.m_rewarded)
+ {
+ // skip one-from-all exclusive group
+ if (qPrevInfo->GetExclusiveGroup() >= 0)
+ return true;
+
+ // each-from-all exclusive group ( < 0)
+ // can be start if only all quests in prev quest exclusive group completed and rewarded
+ ObjectMgr::ExclusiveQuestGroups::iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
+ ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
+
+ assert(iter2 != end); // always must be found if qPrevInfo->ExclusiveGroup != 0
+
+ for (; iter2 != end; ++iter2)
+ {
+ uint32 exclude_Id = iter2->second;
+
+ // skip checked quest id, only state of other quests in group is interesting
+ if (exclude_Id == prevId)
+ continue;
+
+ QuestStatusMap::iterator i_exstatus = mQuestStatus.find(exclude_Id);
+
+ // alternative quest from group also must be completed and rewarded(reported)
+ if (i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded)
+ {
+ if (msg)
+ SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
+ return false;
+ }
+ }
+ return true;
+ }
+ // If any of the negative previous quests active, return true
+ if (*iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
+ || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
+ {
+ // skip one-from-all exclusive group
+ if (qPrevInfo->GetExclusiveGroup() >= 0)
+ return true;
+
+ // each-from-all exclusive group ( < 0)
+ // can be start if only all quests in prev quest exclusive group active
+ ObjectMgr::ExclusiveQuestGroups::iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
+ ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
+
+ assert(iter2 != end); // always must be found if qPrevInfo->ExclusiveGroup != 0
+
+ for (; iter2 != end; ++iter2)
+ {
+ uint32 exclude_Id = iter2->second;
+
+ // skip checked quest id, only state of other quests in group is interesting
+ if (exclude_Id == prevId)
+ continue;
+
+ QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
+
+ // alternative quest from group also must be active
+ if (i_exstatus == mQuestStatus.end() ||
+ i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
+ (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)))
+ {
+ if (msg)
+ SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
+ return false;
+ }
+ }
+ return true;
+ }
+ }
+ }
+
+ // Has only positive prev. quests in non-rewarded state
+ // and negative prev. quests in non-active state
+ if (msg)
+ SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
+
+ return false;
+}
+
+bool Player::SatisfyQuestRace(Quest const* qInfo, bool msg)
+{
+ uint32 reqraces = qInfo->GetRequiredRaces();
+ if (reqraces == 0)
+ return true;
+ if ((reqraces & getRaceMask()) == 0)
+ {
+ if (msg)
+ SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
+ return false;
+ }
+ return true;
+}
+
+bool Player::SatisfyQuestReputation(Quest const* qInfo, bool msg)
+{
+ uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
+ if (fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
+ {
+ if (msg)
+ SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
+ return false;
+ }
+
+ uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
+ if (fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
+ {
+ if (msg)
+ SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
+ return false;
+ }
+
+ return true;
+}
+
+bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
+{
+ QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
+ if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
+ {
+ if( msg )
+ SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
+ return false;
+ }
+ return true;
+}
+
+bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg)
+{
+ if (!m_timedquests.empty() && qInfo->HasFlag(QUEST_TRINITY_FLAGS_TIMED))
+ {
+ if (msg)
+ SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED);
+ return false;
+ }
+ return true;
+}
+
+bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
+{
+ // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
+ if(qInfo->GetExclusiveGroup() <= 0)
+ return true;
+
+ ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
+ ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
+
+ assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
+
+ for (; iter != end; ++iter)
+ {
+ uint32 exclude_Id = iter->second;
+
+ // skip checked quest id, only state of other quests in group is interesting
+ if(exclude_Id == qInfo->GetQuestId())
+ continue;
+
+ // not allow have daily quest if daily quest from exclusive group already recently completed
+ Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
+ if( !SatisfyQuestDay(Nquest, false) )
+ {
+ if( msg )
+ SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
+ return false;
+ }
+
+ QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
+
+ // alternative quest already started or completed
+ if( i_exstatus != mQuestStatus.end()
+ && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
+ {
+ if( msg )
+ SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
+ return false;
+ }
+ }
+ return true;
+}
+
+bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
+{
+ if(!qInfo->GetNextQuestInChain())
+ return true;
+
+ // next quest in chain already started or completed
+ QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
+ if( itr != mQuestStatus.end()
+ && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
+ {
+ if( msg )
+ SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
+ return false;
+ }
+
+ // check for all quests further up the chain
+ // only necessary if there are quest chains with more than one quest that can be skipped
+ //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
+ return true;
+}
+
+bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
+{
+ // No previous quest in chain
+ if( qInfo->prevChainQuests.empty())
+ return true;
+
+ for (Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
+ {
+ uint32 prevId = *iter;
+
+ QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
+
+ if( i_prevstatus != mQuestStatus.end() )
+ {
+ // If any of the previous quests in chain active, return false
+ if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
+ || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
+ {
+ if( msg )
+ SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
+ return false;
+ }
+ }
+
+ // check for all quests further down the chain
+ // only necessary if there are quest chains with more than one quest that can be skipped
+ //if( !SatisfyQuestPrevChain( prevId, msg ) )
+ // return false;
+ }
+
+ // No previous quest in chain active
+ return true;
+}
+
+bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
+{
+ if(!qInfo->IsDaily())
+ return true;
+
+ bool have_slot = false;
+ for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
+ {
+ uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
+ if(qInfo->GetQuestId()==id)
+ return false;
+
+ if(!id)
+ have_slot = true;
+ }
+
+ if(!have_slot)
+ {
+ if( msg )
+ SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
+ return false;
+ }
+
+ return true;
+}
+
+bool Player::GiveQuestSourceItem( Quest const *pQuest )
+{
+ uint32 srcitem = pQuest->GetSrcItemId();
+ if( srcitem > 0 )
+ {
+ uint32 count = pQuest->GetSrcItemCount();
+ if( count <= 0 )
+ count = 1;
+
+ ItemPosCountVec dest;
+ uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
+ if( msg == EQUIP_ERR_OK )
+ {
+ Item * item = StoreNewItem(dest, srcitem, true);
+ SendNewItem(item, count, true, false);
+ return true;
+ }
+ // player already have max amount required item, just report success
+ else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
+ return true;
+ else
+ SendEquipError( msg, NULL, NULL );
+ return false;
+ }
+
+ return true;
+}
+
+bool Player::TakeQuestSourceItem(uint32 quest_id, bool msg)
+{
+ Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
+ if (qInfo)
+ {
+ uint32 srcitem = qInfo->GetSrcItemId();
+ if (srcitem > 0)
+ {
+ uint32 count = qInfo->GetSrcItemCount();
+ if (count <= 0)
+ count = 1;
+
+ // exist one case when destroy source quest item not possible:
+ // non un-equippable item (equipped non-empty bag, for example)
+ uint8 res = CanUnequipItems(srcitem,count);
+ if (res != EQUIP_ERR_OK)
+ {
+ if (msg)
+ SendEquipError(res, NULL, NULL);
+ return false;
+ }
+
+ DestroyItemCount(srcitem, count, true, true);
+ }
+ }
+ return true;
+}
+
+bool Player::GetQuestRewardStatus(uint32 quest_id) const
+{
+ Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
+ if (qInfo)
+ {
+ // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
+ QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
+ if(itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
+ && !qInfo->IsRepeatable())
+ return itr->second.m_rewarded;
+
+ return false;
+ }
+ return false;
+}
+
+QuestStatus Player::GetQuestStatus(uint32 quest_id) const
+{
+ if (quest_id)
+ {
+ QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
+ if (itr != mQuestStatus.end())
+ return itr->second.m_status;
+ }
+ return QUEST_STATUS_NONE;
+}
+
+bool Player::CanShareQuest(uint32 quest_id) const
+{
+ Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
+ if (qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE))
+ {
+ QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
+ if (itr != mQuestStatus.end())
+ return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
+ }
+ return false;
+}
+
+void Player::SetQuestStatus(uint32 quest_id, QuestStatus status)
+{
+ if (Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
+ {
+ QuestStatusData& q_status = mQuestStatus[quest_id];
+
+ q_status.m_status = status;
+
+ if (q_status.uState != QUEST_NEW)
+ q_status.uState = QUEST_CHANGED;
+ }
+
+ UpdateForQuestWorldObjects();
+}
+
+// not used in Trinity, but used in scripting code
+uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
+{
+ Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
+ if (!qInfo)
+ return 0;
+
+ for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
+ if ( qInfo->ReqCreatureOrGOId[j] == entry )
+ return mQuestStatus[quest_id].m_creatureOrGOcount[j];
+
+ return 0;
+}
+
+void Player::AdjustQuestReqItemCount(Quest const* pQuest, QuestStatusData& questStatusData)
+{
+ if (pQuest->HasFlag( QUEST_TRINITY_FLAGS_DELIVER))
+ {
+ for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
+ {
+ uint32 reqitemcount = pQuest->ReqItemCount[i];
+ if (reqitemcount != 0)
+ {
+ uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
+
+ questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
+ if (questStatusData.uState != QUEST_NEW)
+ questStatusData.uState = QUEST_CHANGED;
+ }
+ }
+ }
+}
+
+uint16 Player::FindQuestSlot( uint32 quest_id ) const
+{
+ for (uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
+ if (GetQuestSlotQuestId(i) == quest_id)
+ return i;
+
+ return MAX_QUEST_LOG_SIZE;
+}
+
+void Player::AreaExploredOrEventHappens(uint32 questId)
+{
+ if (questId)
+ {
+ uint16 log_slot = FindQuestSlot(questId);
+ if (log_slot < MAX_QUEST_LOG_SIZE)
+ {
+ QuestStatusData& q_status = mQuestStatus[questId];
+
+ if (!q_status.m_explored)
+ {
+ q_status.m_explored = true;
+ if (q_status.uState != QUEST_NEW)
+ q_status.uState = QUEST_CHANGED;
+ }
+ }
+ if (CanCompleteQuest(questId))
+ CompleteQuest(questId);
+ }
+}
+
+//not used in Trinityd, function for external script library
+void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
+{
+ if (Group *pGroup = GetGroup())
+ {
+ for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
+ {
+ Player *pGroupGuy = itr->getSource();
+
+ // for any leave or dead (with not released body) group member at appropriate distance
+ if (pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse())
+ pGroupGuy->AreaExploredOrEventHappens(questId);
+ }
+ }
+ else
+ AreaExploredOrEventHappens(questId);
+}
+
+void Player::ItemAddedQuestCheck( uint32 entry, uint32 count)
+{
+ for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
+ {
+ uint32 questid = GetQuestSlotQuestId(i);
+ if (questid == 0)
+ continue;
+
+ QuestStatusData& q_status = mQuestStatus[questid];
+
+ if (q_status.m_status != QUEST_STATUS_INCOMPLETE)
+ continue;
+
+ Quest const* qInfo = objmgr.GetQuestTemplate(questid);
+ if( !qInfo || !qInfo->HasFlag(QUEST_TRINITY_FLAGS_DELIVER))
+ continue;
+
+ for (uint8 j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
+ {
+ uint32 reqitem = qInfo->ReqItemId[j];
+ if (reqitem == entry)
+ {
+ uint32 reqitemcount = qInfo->ReqItemCount[j];
+ uint32 curitemcount = q_status.m_itemcount[j];
+ if (curitemcount < reqitemcount)
+ {
+ uint32 additemcount = curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount;
+ q_status.m_itemcount[j] += additemcount;
+ if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
+
+ SendQuestUpdateAddItem(qInfo, j, additemcount);
+ }
+ if ( CanCompleteQuest( questid))
+ CompleteQuest( questid );
+ return;
+ }
+ }
+ }
+ UpdateForQuestWorldObjects();
+}
+
+void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count)
+{
+ for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
+ {
+ uint32 questid = GetQuestSlotQuestId(i);
+ if(!questid)
+ continue;
+ Quest const* qInfo = objmgr.GetQuestTemplate(questid);
+ if (!qInfo)
+ continue;
+ if( !qInfo->HasFlag(QUEST_TRINITY_FLAGS_DELIVER))
+ continue;
+
+ for (uint8 j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
+ {
+ uint32 reqitem = qInfo->ReqItemId[j];
+ if (reqitem == entry)
+ {
+ QuestStatusData& q_status = mQuestStatus[questid];
+
+ uint32 reqitemcount = qInfo->ReqItemCount[j];
+ uint32 curitemcount;
+ if (q_status.m_status != QUEST_STATUS_COMPLETE)
+ curitemcount = q_status.m_itemcount[j];
+ else
+ curitemcount = GetItemCount(entry,true);
+ if (curitemcount < reqitemcount + count)
+ {
+ uint32 remitemcount = curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount;
+ q_status.m_itemcount[j] = curitemcount - remitemcount;
+ if (q_status.uState != QUEST_NEW)
+ q_status.uState = QUEST_CHANGED;
+
+ IncompleteQuest(questid);
+ }
+ return;
+ }
+ }
+ }
+ UpdateForQuestWorldObjects();
+}
+
+void Player::KilledMonster(CreatureInfo const* cInfo, uint64 guid)
+{
+ if (cInfo->Entry)
+ KilledMonsterCredit(cInfo->Entry,guid);
+
+ for (uint8 i = 0; i < MAX_KILL_CREDIT; ++i)
+ if (cInfo->KillCredit[i])
+ KilledMonsterCredit(cInfo->KillCredit[i],guid);
+}
+
+void Player::KilledMonsterCredit(uint32 entry, uint64 guid)
+{
+ uint32 addkillcount = 1;
+ uint32 real_entry = entry;
+ if (guid)
+ {
+ Creature *killed = GetMap()->GetCreature(guid);
+ if (killed && killed->GetEntry())
+ real_entry = killed->GetEntry();
+ }
+
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, real_entry, addkillcount);
+ for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
+ {
+ uint32 questid = GetQuestSlotQuestId(i);
+ if (!questid)
+ continue;
+
+ Quest const* qInfo = objmgr.GetQuestTemplate(questid);
+ if (!qInfo)
+ continue;
+ // just if !ingroup || !noraidgroup || raidgroup
+ QuestStatusData& q_status = mQuestStatus[questid];
+ if(q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
+ {
+ if (qInfo->HasFlag( QUEST_TRINITY_FLAGS_KILL_OR_CAST))
+ {
+ for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
+ {
+ // skip GO activate objective or none
+ if (qInfo->ReqCreatureOrGOId[j] <= 0)
+ continue;
+
+ // skip Cast at creature objective
+ if (qInfo->ReqSpell[j] != 0)
+ continue;
+
+ uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
+
+ if (reqkill == entry)
+ {
+ uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
+ uint32 curkillcount = q_status.m_creatureOrGOcount[j];
+ if (curkillcount < reqkillcount)
+ {
+ q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
+ if (q_status.uState != QUEST_NEW)
+ q_status.uState = QUEST_CHANGED;
+
+ SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
+ }
+ if (CanCompleteQuest(questid))
+ CompleteQuest(questid);
+
+ // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
+ continue;
+ }
+ }
+ }
+ }
+ }
+}
+
+void Player::CastedCreatureOrGO(uint32 entry, uint64 guid, uint32 spell_id)
+{
+ bool isCreature = IS_CRE_OR_VEH_GUID(guid);
+
+ uint32 addCastCount = 1;
+ for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
+ {
+ uint32 questid = GetQuestSlotQuestId(i);
+ if(!questid)
+ continue;
+
+ Quest const* qInfo = objmgr.GetQuestTemplate(questid);
+ if (!qInfo)
+ continue;
+
+ QuestStatusData& q_status = mQuestStatus[questid];
+
+ if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
+ {
+ if (qInfo->HasFlag( QUEST_TRINITY_FLAGS_KILL_OR_CAST))
+ {
+ for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
+ {
+ // skip kill creature objective (0) or wrong spell casts
+ if (qInfo->ReqSpell[j] != spell_id)
+ continue;
+
+ uint32 reqTarget = 0;
+
+ if (isCreature)
+ {
+ // creature activate objectives
+ if (qInfo->ReqCreatureOrGOId[j] > 0)
+ {
+ // checked at quest_template loading
+ reqTarget = qInfo->ReqCreatureOrGOId[j];
+ if (reqTarget != entry) // if entry doesn't match, check for killcredits referenced in template
+ {
+ CreatureInfo const *cinfo = objmgr.GetCreatureTemplate(entry);
+ for (uint8 i = 0; i < MAX_KILL_CREDIT; ++i)
+ if (cinfo->KillCredit[i] == reqTarget)
+ entry = cinfo->KillCredit[i];
+ }
+ }
+ }
+ else
+ {
+ // GO activate objective
+ if (qInfo->ReqCreatureOrGOId[j] < 0)
+ // checked at quest_template loading
+ reqTarget = - qInfo->ReqCreatureOrGOId[j];
+ }
+
+ // other not this creature/GO related objectives
+ if (reqTarget != entry)
+ continue;
+
+ uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
+ uint32 curCastCount = q_status.m_creatureOrGOcount[j];
+ if (curCastCount < reqCastCount)
+ {
+ q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
+ if (q_status.uState != QUEST_NEW)
+ q_status.uState = QUEST_CHANGED;
+
+ SendQuestUpdateAddCreatureOrGo(qInfo, guid, j, curCastCount, addCastCount);
+ }
+
+ if (CanCompleteQuest(questid))
+ CompleteQuest(questid);
+
+ // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
+ break;
+ }
+ }
+ }
+ }
+}
+
+void Player::TalkedToCreature(uint32 entry, uint64 guid)
+{
+ uint32 addTalkCount = 1;
+ for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
+ {
+ uint32 questid = GetQuestSlotQuestId(i);
+ if (!questid)
+ continue;
+
+ Quest const* qInfo = objmgr.GetQuestTemplate(questid);
+ if (!qInfo)
+ continue;
+
+ QuestStatusData& q_status = mQuestStatus[questid];
+
+ if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
+ {
+ if (qInfo->HasFlag(QUEST_TRINITY_FLAGS_KILL_OR_CAST | QUEST_TRINITY_FLAGS_SPEAKTO))
+ {
+ for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
+ {
+ // skip spell casts and Gameobject objectives
+ if (qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
+ continue;
+
+ uint32 reqTarget = 0;
+
+ if (qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
+ // checked at quest_template loading
+ reqTarget = qInfo->ReqCreatureOrGOId[j];
+ else
+ continue;
+
+ if (reqTarget == entry)
+ {
+ uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
+ uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
+ if (curTalkCount < reqTalkCount)
+ {
+ q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
+ if (q_status.uState != QUEST_NEW)
+ q_status.uState = QUEST_CHANGED;
+
+ SendQuestUpdateAddCreatureOrGo(qInfo, guid, j, curTalkCount, addTalkCount);
+ }
+ if (CanCompleteQuest(questid))
+ CompleteQuest(questid);
+
+ // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
+ continue;
+ }
+ }
+ }
+ }
+ }
+}
+
+void Player::MoneyChanged( uint32 count )
+{
+ for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
+ {
+ uint32 questid = GetQuestSlotQuestId(i);
+ if (!questid)
+ continue;
+
+ Quest const* qInfo = objmgr.GetQuestTemplate(questid);
+ if (qInfo && qInfo->GetRewOrReqMoney() < 0)
+ {
+ QuestStatusData& q_status = mQuestStatus[questid];
+
+ if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
+ {
+ if (int32(count) >= -qInfo->GetRewOrReqMoney())
+ {
+ if (CanCompleteQuest(questid))
+ CompleteQuest(questid);
+ }
+ }
+ else if (q_status.m_status == QUEST_STATUS_COMPLETE)
+ {
+ if (int32(count) < -qInfo->GetRewOrReqMoney())
+ IncompleteQuest(questid);
+ }
+ }
+ }
+}
+
+void Player::ReputationChanged(FactionEntry const* factionEntry)
+{
+ for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
+ {
+ if(uint32 questid = GetQuestSlotQuestId(i))
+ {
+ if (Quest const* qInfo = objmgr.GetQuestTemplate(questid))
+ {
+ if (qInfo->GetRepObjectiveFaction() == factionEntry->ID)
+ {
+ QuestStatusData& q_status = mQuestStatus[questid];
+ if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
+ {
+ if (GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
+ if (CanCompleteQuest(questid))
+ CompleteQuest(questid);
+ }
+ else if(q_status.m_status == QUEST_STATUS_COMPLETE)
+ {
+ if (GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
+ IncompleteQuest(questid);
+ }
+ }
+ }
+ }
+ }
+}
+
+void Player::ReputationChanged2(FactionEntry const* factionEntry)
+{
+ for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
+ {
+ if(uint32 questid = GetQuestSlotQuestId(i))
+ {
+ if (Quest const* qInfo = objmgr.GetQuestTemplate(questid))
+ {
+ if (qInfo->GetRepObjectiveFaction2() == factionEntry->ID)
+ {
+ QuestStatusData& q_status = mQuestStatus[questid];
+ if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
+ {
+ if (GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue2())
+ if (CanCompleteQuest(questid))
+ CompleteQuest(questid);
+ }
+ else if(q_status.m_status == QUEST_STATUS_COMPLETE)
+ {
+ if (GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue2())
+ IncompleteQuest(questid);
+ }
+ }
+ }
+ }
+ }
+}
+
+bool Player::HasQuestForItem(uint32 itemid) const
+{
+ for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
+ {
+ uint32 questid = GetQuestSlotQuestId(i);
+ if (questid == 0)
+ continue;
+
+ QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
+ if(qs_itr == mQuestStatus.end())
+ continue;
+
+ QuestStatusData const& q_status = qs_itr->second;
+
+ if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
+ {
+ Quest const* qinfo = objmgr.GetQuestTemplate(questid);
+ if (!qinfo)
+ continue;
+
+ // hide quest if player is in raid-group and quest is no raid quest
+ if (GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
+ if (!InBattleGround()) //there are two ways.. we can make every bg-quest a raidquest, or add this code here.. i don't know if this can be exploited by other quests, but i think all other quests depend on a specific area.. but keep this in mind, if something strange happens later
+ continue;
+
+ // There should be no mixed ReqItem/ReqSource drop
+ // This part for ReqItem drop
+ for (uint8 j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
+ {
+ if (itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j])
+ return true;
+ }
+ // This part - for ReqSource
+ for (uint8 j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
+ {
+ // examined item is a source item
+ if (qinfo->ReqSourceId[j] == itemid)
+ {
+ ItemPrototype const *pProto = objmgr.GetItemPrototype(itemid);
+
+ // 'unique' item
+ if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
+ return true;
+
+ // allows custom amount drop when not 0
+ if (qinfo->ReqSourceCount[j])
+ {
+ if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
+ return true;
+ } else if (GetItemCount(itemid,true) < pProto->Stackable)
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+}
+
+void Player::SendQuestComplete(uint32 quest_id)
+{
+ if(quest_id)
+ {
+ WorldPacket data(SMSG_QUESTUPDATE_COMPLETE, 4);
+ data << uint32(quest_id);
+ GetSession()->SendPacket(&data);
+ sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id);
+ }
+}
+
+void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
+{
+ uint32 questid = pQuest->GetQuestId();
+ sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
+ gameeventmgr.HandleQuestComplete(questid);
+ WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
+ data << uint32(questid);
+
+ if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
+ {
+ data << uint32(XP);
+ data << uint32(pQuest->GetRewOrReqMoney());
+ }
+ else
+ {
+ data << uint32(0);
+ data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
+ }
+
+ data << uint32(10*Trinity::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
+ data << uint32(pQuest->GetBonusTalents()); // bonus talents
+ data << uint32(0);
+ GetSession()->SendPacket( &data );
+
+ if (pQuest->GetQuestCompleteScript() != 0)
+ GetMap()->ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
+}
+
+void Player::SendQuestFailed( uint32 quest_id )
+{
+ if( quest_id )
+ {
+ WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
+ data << uint32(quest_id);
+ data << uint32(0); // failed reason (4 for inventory is full)
+ GetSession()->SendPacket( &data );
+ sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
+ }
+}
+
+void Player::SendQuestTimerFailed( uint32 quest_id )
+{
+ if( quest_id )
+ {
+ WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
+ data << uint32(quest_id);
+ GetSession()->SendPacket( &data );
+ sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
+ }
+}
+
+void Player::SendCanTakeQuestResponse( uint32 msg )
+{
+ WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
+ data << uint32(msg);
+ GetSession()->SendPacket( &data );
+ sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
+}
+
+void Player::SendQuestConfirmAccept(const Quest* pQuest, Player* pReceiver)
+{
+ if (pReceiver)
+ {
+ std::string strTitle = pQuest->GetTitle();
+
+ int loc_idx = pReceiver->GetSession()->GetSessionDbLocaleIndex();
+
+ if (loc_idx >= 0)
+ {
+ if (const QuestLocale* pLocale = objmgr.GetQuestLocale(pQuest->GetQuestId()))
+ {
+ if (pLocale->Title.size() > loc_idx && !pLocale->Title[loc_idx].empty())
+ strTitle = pLocale->Title[loc_idx];
+ }
+ }
+
+ WorldPacket data(SMSG_QUEST_CONFIRM_ACCEPT, (4 + strTitle.size() + 8));
+ data << uint32(pQuest->GetQuestId());
+ data << strTitle;
+ data << uint64(GetGUID());
+ pReceiver->GetSession()->SendPacket(&data);
+
+ sLog.outDebug("WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT");
+ }
+}
+
+void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
+{
+ if( pPlayer )
+ {
+ WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
+ data << uint64(pPlayer->GetGUID());
+ data << uint8(msg); // valid values: 0-8
+ GetSession()->SendPacket( &data );
+ sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
+ }
+}
+
+void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
+{
+ WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
+ sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
+ //data << pQuest->ReqItemId[item_idx];
+ //data << count;
+ GetSession()->SendPacket( &data );
+}
+
+void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
+{
+ assert(old_count + add_count < 65536 && "mob/GO count store in 16 bits 2^16 = 65536 (0..65536)");
+
+ int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
+ if (entry < 0)
+ // client expected gameobject template id in form (id|0x80000000)
+ entry = (-entry) | 0x80000000;
+
+ WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
+ sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
+ data << uint32(pQuest->GetQuestId());
+ data << uint32(entry);
+ data << uint32(old_count + add_count);
+ data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
+ data << uint64(guid);
+ GetSession()->SendPacket(&data);
+
+ uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
+ if( log_slot < MAX_QUEST_LOG_SIZE)
+ SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
+}
+
+/*********************************************************/
+/*** LOAD SYSTEM ***/
+/*********************************************************/
+
+bool Player::MinimalLoadFromDB( QueryResult_AutoPtr result, uint32 guid )
+{
+ if (!result)
+ {
+ // 0 1 2 3 4 5 6 7 8 9 10 11
+ result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login, zone, level FROM characters WHERE guid = '%u'",guid);
+ if (!result)
+ return false;
+ }
+
+ Field *fields = result->Fetch();
+
+ if (!LoadValues( fields[1].GetString()))
+ {
+ sLog.outError("Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
+ return false;
+ }
+
+ // overwrite possible wrong/corrupted guid
+ SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
+
+ m_name = fields[2].GetCppString();
+
+ Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
+ Map *map = MapManager::Instance().CreateMap(fields[6].GetUInt32(), this, 0);
+ SetMap(map);
+
+ // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
+ // this must help in case next save after mass player load after server startup
+ m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
+
+ // the instance id is not needed at character enum
+
+ m_Played_time[PLAYED_TIME_TOTAL] = fields[7].GetUInt32();
+ m_Played_time[PLAYED_TIME_LEVEL] = fields[8].GetUInt32();
+
+ m_atLoginFlags = fields[9].GetUInt32();
+
+ // I don't see these used anywhere ..
+ /*_LoadGroup();
+
+ _LoadBoundInstances();*/
+
+ for (uint8 i = 0; i < PLAYER_SLOTS_COUNT; i++)
+ m_items[i] = NULL;
+
+ if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
+ m_deathState = DEAD;
+
+ return true;
+}
+
+void Player::_LoadDeclinedNames(QueryResult_AutoPtr result)
+{
+ if(!result)
+ return;
+
+ if(m_declinedname)
+ delete m_declinedname;
+
+ m_declinedname = new DeclinedName;
+ Field *fields = result->Fetch();
+ for (uint8 i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
+ m_declinedname->name[i] = fields[i].GetCppString();
+}
+
+void Player::_LoadArenaTeamInfo(QueryResult_AutoPtr result)
+{
+ // arenateamid, played_week, played_season, personal_rating
+ memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32) * MAX_ARENA_SLOT * ARENA_TEAM_END);
+ if (!result)
+ return;
+
+ do
+ {
+ Field *fields = result->Fetch();
+
+ uint32 arenateamid = fields[0].GetUInt32();
+ uint32 played_week = fields[1].GetUInt32();
+ uint32 played_season = fields[2].GetUInt32();
+ uint32 wons_season = fields[3].GetUInt32();
+ uint32 personal_rating = fields[4].GetUInt32();
+
+ ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
+ if(!aTeam)
+ {
+ sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u", arenateamid);
+ continue;
+ }
+ uint8 arenaSlot = aTeam->GetSlot();
+
+ m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_ID] = arenateamid; // TeamID
+ m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_TYPE] = aTeam->GetType(); // team type
+ 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
+ m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_GAMES_WEEK] = played_week; // Played Week
+ m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_GAMES_SEASON] = played_season; // Played Season
+ m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_WINS_SEASON] = wons_season; // wins season
+ m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_PERSONAL_RATING] = personal_rating; // Personal Rating
+
+ }while (result->NextRow());
+}
+
+void Player::_LoadEquipmentSets(QueryResult_AutoPtr result)
+{
+ // 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));
+ if (!result)
+ return;
+
+ uint32 count = 0;
+ do
+ {
+ Field *fields = result->Fetch();
+
+ EquipmentSet eqSet;
+
+ eqSet.Guid = fields[0].GetUInt64();
+ uint32 index = fields[1].GetUInt32();
+ eqSet.Name = fields[2].GetCppString();
+ eqSet.IconName = fields[3].GetCppString();
+ eqSet.state = EQUIPMENT_SET_UNCHANGED;
+
+ for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
+ eqSet.Items[i] = fields[4+i].GetUInt32();
+
+ m_EquipmentSets[index] = eqSet;
+
+ ++count;
+
+ if(count >= MAX_EQUIPMENT_SET_INDEX) // client limit
+ break;
+ } while (result->NextRow());
+}
+
+void Player::_LoadBGData(QueryResult_AutoPtr result)
+{
+ if (!result)
+ return;
+
+ // Expecting only one row
+ Field *fields = result->Fetch();
+ /* bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
+ m_bgData.bgInstanceID = fields[0].GetUInt32();
+ m_bgData.bgTeam = fields[1].GetUInt32();
+ m_bgData.joinPos = WorldLocation(fields[6].GetUInt32(), // Map
+ fields[2].GetFloat(), // X
+ fields[3].GetFloat(), // Y
+ fields[4].GetFloat(), // Z
+ fields[5].GetFloat()); // Orientation
+ m_bgData.taxiPath[0] = fields[7].GetUInt32();
+ m_bgData.taxiPath[1] = fields[8].GetUInt32();
+ m_bgData.mountSpell = fields[9].GetUInt32();
+}
+
+bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
+{
+ QueryResult_AutoPtr result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
+ if(!result)
+ return false;
+
+ Field *fields = result->Fetch();
+
+ x = fields[0].GetFloat();
+ y = fields[1].GetFloat();
+ z = fields[2].GetFloat();
+ o = fields[3].GetFloat();
+ mapid = fields[4].GetUInt32();
+ in_flight = !fields[5].GetCppString().empty();
+
+ return true;
+}
+
+bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
+{
+ QueryResult_AutoPtr result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
+ if( !result )
+ return false;
+
+ Field *fields = result->Fetch();
+
+ data = StrSplit(fields[0].GetCppString(), " ");
+
+ return true;
+}
+
+uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
+{
+ if(index >= data.size())
+ return 0;
+
+ return (uint32)atoi(data[index].c_str());
+}
+
+float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
+{
+ float result;
+ uint32 temp = Player::GetUInt32ValueFromArray(data,index);
+ memcpy(&result, &temp, sizeof(result));
+
+ return result;
+}
+
+uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
+{
+ Tokens data;
+ if(!LoadValuesArrayFromDB(data,guid))
+ return 0;
+
+ return GetUInt32ValueFromArray(data,index);
+}
+
+float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
+{
+ float result;
+ uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
+ memcpy(&result, &temp, sizeof(result));
+
+ return result;
+}
+
+bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
+{
+ //// 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 41 42 43
+ //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, instance_id, speccount, activespec FROM characters WHERE guid = '%u'", guid);
+ QueryResult_AutoPtr result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
+
+ if(!result)
+ {
+ sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
+ return false;
+ }
+
+ Field *fields = result->Fetch();
+
+ uint32 dbAccountId = fields[1].GetUInt32();
+
+ // check if the character's account in the db and the logged in account match.
+ // player should be able to load/delete character only with correct account!
+ if( dbAccountId != GetSession()->GetAccountId() )
+ {
+ sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
+ return false;
+ }
+
+ Object::_Create( guid, 0, HIGHGUID_PLAYER );
+
+ m_name = fields[3].GetCppString();
+
+ // check name limitations
+ if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS ||
+ (GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name)))
+ {
+ CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
+ return false;
+ }
+
+ if(!LoadValues( fields[2].GetString()))
+ {
+ sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid));
+ return false;
+ }
+
+ // overwrite possible wrong/corrupted guid
+ SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
+
+ // overwrite some data fields
+ uint32 bytes0 = GetUInt32Value(UNIT_FIELD_BYTES_0) & 0xFF000000;
+ bytes0 |= fields[4].GetUInt8(); // race
+ bytes0 |= fields[5].GetUInt8() << 8; // class
+ bytes0 |= fields[6].GetUInt8() << 16; // gender
+ SetUInt32Value(UNIT_FIELD_BYTES_0, bytes0);
+
+ SetUInt32Value(UNIT_FIELD_LEVEL, fields[7].GetUInt8());
+ SetUInt32Value(PLAYER_XP, fields[8].GetUInt32());
+ SetUInt32Value(PLAYER_FIELD_COINAGE, fields[9].GetUInt32());
+ SetUInt32Value(PLAYER_BYTES, fields[10].GetUInt32());
+ SetUInt32Value(PLAYER_BYTES_2, fields[11].GetUInt32());
+ SetUInt32Value(PLAYER_BYTES_3, (GetUInt32Value(PLAYER_BYTES_3) & ~1) | fields[6].GetUInt8());
+ SetUInt32Value(PLAYER_FLAGS, fields[12].GetUInt32());
+
+ InitDisplayIds();
+
+ // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
+ for (uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
+ {
+ SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0 );
+ SetVisibleItemSlot(slot, NULL);
+
+ if (m_items[slot])
+ {
+ delete m_items[slot];
+ m_items[slot] = NULL;
+ }
+ }
+
+ // update money limits
+ if(GetMoney() > MAX_MONEY_AMOUNT)
+ SetMoney(MAX_MONEY_AMOUNT);
+
+ sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
+ outDebugValues();
+
+ //Need to call it to initialize m_team (m_team can be calculated from race)
+ //Other way is to saves m_team into characters table.
+ setFactionForRace(getRace());
+
+ // load home bind and check in same time class/race pair, it used later for restore broken positions
+ if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
+ return false;
+
+ InitPrimaryProfessions(); // to max set before any spell loaded
+
+ // init saved position, and fix it later if problematic
+ uint32 transGUID = fields[31].GetUInt32();
+ Relocate(fields[13].GetFloat(),fields[14].GetFloat(),fields[15].GetFloat(),fields[17].GetFloat());
+ uint32 mapId = fields[16].GetUInt32();
+ uint32 instanceId = fields[41].GetFloat();
+
+ uint32 difficulty = fields[39].GetUInt32();
+ if(difficulty >= MAX_DUNGEON_DIFFICULTY)
+ difficulty = DUNGEON_DIFFICULTY_NORMAL;
+ SetDungeonDifficulty(Difficulty(difficulty)); // may be changed in _LoadGroup
+ std::string taxi_nodes = fields[38].GetCppString();
+
+#define RelocateToHomebind(){ mapId = m_homebindMapId; instanceId = 0; Relocate(m_homebindX, m_homebindY, m_homebindZ); }
+
+ _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
+
+ _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
+
+ uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[40].GetUInt32();
+ if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
+ arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
+
+ SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
+
+ // check arena teams integrity
+ for (uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
+ {
+ uint32 arena_team_id = GetArenaTeamId(arena_slot);
+ if(!arena_team_id)
+ continue;
+
+ if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
+ if(at->HaveMember(GetGUID()))
+ continue;
+
+ // arena team not exist or not member, cleanup fields
+ for (int j = 0; j < 6; ++j)
+ SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arena_slot * ARENA_TEAM_END) + j, 0);
+ }
+
+ _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
+ _LoadBGData(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBGDATA));
+
+ MapEntry const * mapEntry = sMapStore.LookupEntry(mapId);
+ if(!mapEntry || !IsPositionValid())
+ {
+ sLog.outError("Player (guidlow %d) have invalid coordinates (MapId: %u X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",guid,mapId,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
+ RelocateToHomebind();
+ }
+ // Player was saved in Arena or Bg
+ else if (mapEntry && mapEntry->IsBattleGroundOrArena())
+ {
+ BattleGround *currentBg = NULL;
+ if(m_bgData.bgInstanceID) //saved in BattleGround
+ currentBg = sBattleGroundMgr.GetBattleGround(m_bgData.bgInstanceID, BATTLEGROUND_TYPE_NONE);
+
+ bool player_at_bg = currentBg && currentBg->IsPlayerInBattleGround(GetGUID());
+
+ if(player_at_bg && currentBg->GetStatus() != STATUS_WAIT_LEAVE)
+ {
+ BattleGroundQueueTypeId bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
+ AddBattleGroundQueueId(bgQueueTypeId);
+
+ m_bgData.bgTypeID = currentBg->GetTypeID();
+
+ //join player to battleground group
+ currentBg->EventPlayerLoggedIn(this, GetGUID());
+ currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), m_bgData.bgTeam);
+
+ SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
+ }
+ // Bg was not found - go to Entry Point
+ else
+ {
+ // leave bg
+ if (player_at_bg)
+ currentBg->RemovePlayerAtLeave(GetGUID(), false, true);
+
+ // Do not look for instance if bg not found
+ const WorldLocation& _loc = GetBattleGroundEntryPoint();
+ mapId = _loc.GetMapId(); instanceId = 0;
+
+ if(mapId == MAPID_INVALID) // Battleground Entry Point not found (???)
+ {
+ sLog.outError("Player (guidlow %d) was in BG in database, but BG was not found, and entry point was invalid! Teleport to default race/class locations.",guid);
+ RelocateToHomebind();
+ }
+ else
+ Relocate(&_loc);
+
+ // We are not in BG anymore
+ m_bgData.bgInstanceID = 0;
+ }
+ }
+ // currently we do not support transport in bg
+ else if (transGUID)
+ {
+ // There are no transports on instances
+ instanceId = 0;
+
+ m_movementInfo.t_x = fields[27].GetFloat();
+ m_movementInfo.t_y = fields[28].GetFloat();
+ m_movementInfo.t_z = fields[29].GetFloat();
+ m_movementInfo.t_o = fields[30].GetFloat();
+
+ if( !Trinity::IsValidMapCoord(
+ GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
+ GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
+ // transport size limited
+ m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
+ {
+ sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
+ guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
+ GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
+
+ RelocateToHomebind();
+ }
+ else
+ {
+ for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
+ {
+ if( (*iter)->GetGUIDLow() == transGUID)
+ {
+ m_transport = *iter;
+ m_transport->AddPassenger(this);
+ mapId = (m_transport->GetMapId());
+ break;
+ }
+ }
+ if(!m_transport)
+ {
+ sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
+ guid,transGUID);
+
+ RelocateToHomebind();
+ }
+ }
+ }
+ // currently we do not support taxi in instance
+ else if (!taxi_nodes.empty())
+ {
+ instanceId = 0;
+
+ // Not finish taxi flight path
+ if(m_bgData.HasTaxiPath())
+ {
+ for (int i = 0; i < 2; ++i)
+ m_taxi.AddTaxiDestination(m_bgData.taxiPath[i]);
+ }
+ else if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
+ {
+ // problems with taxi path loading
+ TaxiNodesEntry const* nodeEntry = NULL;
+ if(uint32 node_id = m_taxi.GetTaxiSource())
+ nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
+
+ if(!nodeEntry) // don't know taxi start node, to homebind
+ {
+ sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
+ RelocateToHomebind();
+ }
+ else // have start node, to it
+ {
+ sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
+ mapId = nodeEntry->map_id;
+ Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
+ }
+ m_taxi.ClearTaxiDestinations();
+ }
+
+ if (uint32 node_id = m_taxi.GetTaxiSource())
+ {
+ // save source node as recall coord to prevent recall and fall from sky
+ TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
+ if (nodeEntry && nodeEntry->map_id == GetMapId())
+ {
+ assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
+ mapId = nodeEntry->map_id;
+ Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
+ }
+
+ // flight will started later
+ }
+ }
+
+ // Map could be changed before
+ mapEntry = sMapStore.LookupEntry(mapId);
+ // client without expansion support
+ if(mapEntry && GetSession()->Expansion() < mapEntry->Expansion())
+ {
+ sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), mapId);
+ RelocateToHomebind();
+ }
+
+ // fix crash (because of if(Map *map = _FindMap(instanceId)) in MapInstanced::CreateInstance)
+ if(instanceId)
+ if(InstanceSave * save = GetInstanceSave(mapId, mapEntry->IsRaid()))
+ if(save->GetInstanceId() != instanceId)
+ instanceId = 0;
+
+ // NOW player must have valid map
+ // load the player's map here if it's not already loaded
+ Map *map = MapManager::Instance().CreateMap(mapId, this, instanceId);
+
+ if (!map)
+ {
+ instanceId = 0;
+ AreaTrigger const* at = objmgr.GetGoBackTrigger(mapId);
+ if(at)
+ {
+ sLog.outError("Player (guidlow %d) is teleported to gobacktrigger (Map: %u X: %f Y: %f Z: %f O: %f).",guid,mapId,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
+ Relocate(at->target_X, at->target_Y, at->target_Z, GetOrientation());
+ mapId = at->target_mapId;
+ }
+ else
+ {
+ sLog.outError("Player (guidlow %d) is teleported to home (Map: %u X: %f Y: %f Z: %f O: %f).",guid,mapId,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
+ RelocateToHomebind();
+ }
+
+ map = MapManager::Instance().CreateMap(mapId, this, 0);
+ if(!map)
+ {
+ PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
+ mapId = info->mapId;
+ Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
+ sLog.outError("ERROR: Player (guidlow %d) have invalid coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",guid,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
+ map = MapManager::Instance().CreateMap(mapId, this, 0);
+ if (!map)
+ {
+ sLog.outError("ERROR: Player (guidlow %d) has invalid default map coordinates (X: %f Y: %f Z: %f O: %f). or instance couldn't be created",guid,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
+ return false;
+ }
+ }
+ }
+
+ // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
+ if(instanceId && !sInstanceSaveManager.GetInstanceSave(instanceId))
+ {
+ AreaTrigger const* at = objmgr.GetMapEntranceTrigger(mapId);
+ if(at)
+ Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
+ else
+ {
+ 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(), mapId);
+ RelocateToHomebind();
+ }
+ }
+
+ SetMap(map);
+
+ // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
+ // this must help in case next save after mass player load after server startup
+ m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
+
+ SaveRecallPosition();
+
+ time_t now = time(NULL);
+ time_t logoutTime = time_t(fields[23].GetUInt64());
+
+ // since last logout (in seconds)
+ uint32 time_diff = uint32(now - logoutTime); //uint64 is excessive for a time_diff in seconds.. uint32 allows for 136~ year difference.
+
+ // set value, including drunk invisibility detection
+ // calculate sobering. after 15 minutes logged out, the player will be sober again
+ float soberFactor;
+ if (time_diff > 15*MINUTE)
+ soberFactor = 0;
+ else
+ soberFactor = 1-time_diff/(15.0f*MINUTE);
+ uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
+ SetDrunkValue(newDrunkenValue);
+
+ m_rest_bonus = fields[22].GetFloat();
+ //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
+ float bubble0 = 0.031;
+ //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
+ float bubble1 = 0.125;
+
+ if (time_diff > 0)
+ {
+ float bubble = fields[24].GetUInt32() > 0
+ ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
+ : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
+
+ SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
+ }
+
+ m_cinematic = fields[19].GetUInt32();
+ m_Played_time[PLAYED_TIME_TOTAL]= fields[20].GetUInt32();
+ m_Played_time[PLAYED_TIME_LEVEL]= fields[21].GetUInt32();
+
+ m_resetTalentsCost = fields[25].GetUInt32();
+ m_resetTalentsTime = time_t(fields[26].GetUInt64());
+
+ // reserve some flags
+ uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
+
+ if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM))
+ SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
+
+ m_taxi.LoadTaxiMask(fields[18].GetString()); // must be before InitTaxiNodesForLevel
+
+ uint32 extraflags = fields[32].GetUInt32();
+
+ m_stableSlots = fields[33].GetUInt32();
+ if (m_stableSlots > MAX_PET_STABLES)
+ {
+ sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
+ m_stableSlots = MAX_PET_STABLES;
+ }
+
+ m_atLoginFlags = fields[34].GetUInt32();
+
+ // Honor system
+ // Update Honor kills data
+ m_lastHonorUpdateTime = logoutTime;
+ UpdateHonorFields();
+
+ m_deathExpireTime = (time_t)fields[37].GetUInt64();
+ if (m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
+ m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
+
+ // clear channel spell data (if saved at channel spell casting)
+ SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
+ SetUInt32Value(UNIT_CHANNEL_SPELL,0);
+
+ // clear charm/summon related fields
+ SetUInt64Value(UNIT_FIELD_SUMMONEDBY, 0);
+ SetUInt64Value(UNIT_FIELD_CHARMEDBY, 0);
+ SetUInt64Value(UNIT_FIELD_CHARM, 0);
+ SetUInt64Value(UNIT_FIELD_SUMMON, 0);
+ SetUInt64Value(PLAYER_FARSIGHT, 0);
+ SetCreatorGUID(0);
+
+ RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVE);
+
+ // reset some aura modifiers before aura apply
+ SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
+ SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
+
+ // make sure the unit is considered out of combat for proper loading
+ ClearInCombat();
+
+ // make sure the unit is considered not in duel for proper loading
+ SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
+ SetUInt32Value(PLAYER_DUEL_TEAM, 0);
+
+ // remember loaded power/health values to restore after stats initialization and modifier applying
+ uint32 savedHealth = GetHealth();
+ uint32 savedPower[MAX_POWERS];
+ for (uint8 i = 0; i < MAX_POWERS; ++i)
+ savedPower[i] = GetPower(Powers(i));
+
+ // reset stats before loading any modifiers
+ InitStatsForLevel();
+ InitGlyphsForLevel();
+ InitTaxiNodesForLevel();
+ InitRunes();
+
+ // load skills after InitStatsForLevel because it triggering aura apply also
+ _LoadSkills(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSKILLS));
+
+ // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
+
+ //mails are loaded only when needed ;-) - when player in game click on mailbox.
+ //_LoadMail();
+
+ m_specsCount = fields[42].GetUInt8();
+ m_activeSpec = fields[43].GetUInt8();
+
+ // sanity check
+ if (m_specsCount > MAX_TALENT_SPECS || m_activeSpec > MAX_TALENT_SPEC ||
+ m_specsCount < MIN_TALENT_SPECS || m_activeSpec < MIN_TALENT_SPEC)
+ {
+ m_activeSpec = 0;
+ sLog.outError("Player %s(GUID: %u) has SpecCount = %u and ActiveSpec = %u.", GetName(), GetGUIDLow(), m_specsCount, m_activeSpec);
+ }
+
+ _LoadTalents(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTALENTS));
+ _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
+
+ _LoadGlyphs(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGLYPHS));
+ _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
+ _LoadGlyphAuras();
+ // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
+ if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
+ m_deathState = DEAD;
+
+ // after spell load, learn rewarded spell if need also
+ _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
+ _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
+
+ // after spell and quest load
+ InitTalentForLevel();
+ learnDefaultSpells();
+
+ // must be before inventory (some items required reputation check)
+ m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
+
+ _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
+
+ // update items with duration and realtime
+ UpdateItemDuration(time_diff, true);
+
+ _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS), true);
+
+ // unread mails and next delivery time, actual mails not loaded
+ _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
+
+ m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
+
+ // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
+ // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
+ if (uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
+ if(!HasTitle(curTitle))
+ SetUInt32Value(PLAYER_CHOSEN_TITLE, 0);
+
+ // has to be called after last Relocate() in Player::LoadFromDB
+ SetFallInformation(0, GetPositionZ());
+
+ _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
+
+ // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
+ // Do now before stats re-calculation cleanup for ghost state unexpected auras
+ if (!isAlive())
+ RemoveAllAurasOnDeath();
+
+ //apply all stat bonuses from items and auras
+ SetCanModifyStats(true);
+ UpdateAllStats();
+
+ // restore remembered power/health values (but not more max values)
+ SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
+ for (uint8 i = 0; i < MAX_POWERS; ++i)
+ SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
+
+ sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
+ outDebugValues();
+
+ // GM state
+ if (GetSession()->GetSecurity() > SEC_PLAYER)
+ {
+ switch (sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
+ {
+ default:
+ case 0: break; // disable
+ case 1: SetGameMaster(true); break; // enable
+ case 2: // save state
+ if(extraflags & PLAYER_EXTRA_GM_ON)
+ SetGameMaster(true);
+ break;
+ }
+
+ switch (sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
+ {
+ default:
+ case 0: SetGMVisible(false); break; // invisible
+ case 1: break; // visible
+ case 2: // save state
+ if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
+ SetGMVisible(false);
+ break;
+ }
+
+ /*switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
+ {
+ default:
+ case 0: break; // disable
+ case 1: SetAcceptTicket(true); break; // enable
+ case 2: // save state
+ if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
+ SetAcceptTicket(true);
+ break;
+ }*/
+
+ switch (sWorld.getConfig(CONFIG_GM_CHAT))
+ {
+ default:
+ case 0: break; // disable
+ case 1: SetGMChat(true); break; // enable
+ case 2: // save state
+ if(extraflags & PLAYER_EXTRA_GM_CHAT)
+ SetGMChat(true);
+ break;
+ }
+
+ switch (sWorld.getConfig(CONFIG_GM_WISPERING_TO))
+ {
+ default:
+ case 0: break; // disable
+ case 1: SetAcceptWhispers(true); break; // enable
+ case 2: // save state
+ if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
+ SetAcceptWhispers(true);
+ break;
+ }
+ }
+
+ _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
+
+ m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
+ m_achievementMgr.CheckAllAchievementCriteria();
+
+ _LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
+
+ return true;
+}
+
+bool Player::isAllowedToLoot(Creature* creature)
+{
+ if (creature->isDead() && !creature->IsDamageEnoughForLootingAndReward())
+ return false;
+
+ if (Player* recipient = creature->GetLootRecipient())
+ {
+ if (recipient == this)
+ return true;
+ if (Group* otherGroup = recipient->GetGroup())
+ {
+ Group* thisGroup = GetGroup();
+ if (!thisGroup)
+ return false;
+ return thisGroup == otherGroup;
+ }
+ return false;
+ }
+ else
+ // prevent other players from looting if the recipient got disconnected
+ return !creature->hasLootRecipient();
+}
+
+void Player::_LoadActions(QueryResult_AutoPtr result, bool startup)
+{
+ if (result)
+ {
+ do
+ {
+ Field *fields = result->Fetch();
+
+ uint8 button = fields[0].GetUInt8();
+ uint32 action = fields[1].GetUInt32();
+ uint8 type = fields[2].GetUInt8();
+
+ if(ActionButton* ab = addActionButton(button, action, type))
+ {
+ ab->uState = ACTIONBUTTON_UNCHANGED;
+ if(!startup) // Switching specs
+ ab->canRemoveByClient = false;
+ }
+ else
+ {
+ sLog.outError( " ...at loading, and will deleted in DB also");
+
+ // Will deleted in DB at next save (it can create data until save but marked as deleted)
+ m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
+ }
+ }
+ while (result->NextRow());
+ }
+}
+
+void Player::_LoadAuras(QueryResult_AutoPtr result, uint32 timediff)
+{
+ sLog.outDebug("Loading auras for player %u",GetGUIDLow());
+
+ //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_mask,recalculate_mask,stackcount,amount0,amount1,amount2,base_amount0,base_amount1,base_amount2,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
+
+ if (result)
+ {
+ do
+ {
+ int32 damage[3];
+ int32 baseDamage[3];
+ Field *fields = result->Fetch();
+ uint64 caster_guid = fields[0].GetUInt64();
+ uint32 spellid = fields[1].GetUInt32();
+ uint8 effmask = fields[2].GetUInt8();
+ uint8 recalculatemask = fields[3].GetUInt8();
+ uint8 stackcount = fields[4].GetUInt8();
+ damage[0] = fields[5].GetInt32();
+ damage[1] = fields[6].GetInt32();
+ damage[2] = fields[7].GetInt32();
+ baseDamage[0] = fields[8].GetInt32();
+ baseDamage[1] = fields[9].GetInt32();
+ baseDamage[2] = fields[10].GetInt32();
+ int32 maxduration = fields[11].GetInt32();
+ int32 remaintime = fields[12].GetInt32();
+ uint8 remaincharges = fields[13].GetUInt8();
+
+ SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
+ if (!spellproto)
+ {
+ sLog.outError("Unknown aura (spellid %u), ignore.",spellid);
+ continue;
+ }
+
+ // negative effects should continue counting down after logout
+ if (remaintime != -1 && !IsPositiveSpell(spellid))
+ {
+ if (remaintime/IN_MILISECONDS <= int32(timediff))
+ continue;
+
+ remaintime -= timediff*IN_MILISECONDS;
+ }
+
+ // prevent wrong values of remaincharges
+ if (spellproto->procCharges)
+ {
+ if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
+ remaincharges = spellproto->procCharges;
+ }
+ else
+ remaincharges = 0;
+
+ if (Aura * aura = Aura::TryCreate(spellproto, effmask, this, NULL, &baseDamage[0], NULL, caster_guid))
+ {
+ if (!aura->CanBeSaved())
+ {
+ aura->Remove();
+ continue;
+ }
+ aura->SetLoadedState(maxduration,remaintime,remaincharges,stackcount,recalculatemask,&damage[0]);
+ aura->ApplyForTargets();
+ sLog.outDetail("Added aura spellid %u, effectmask %u", spellproto->Id, effmask);
+ }
+ }
+ while (result->NextRow());
+ }
+
+ if (getClass() == CLASS_WARRIOR && !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT))
+ CastSpell(this, 2457, true);
+}
+
+void Player::_LoadGlyphAuras()
+{
+ for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
+ {
+ if (uint32 glyph = GetGlyph(i))
+ {
+ if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
+ {
+ if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
+ {
+ if (gp->TypeFlags == gs->TypeFlags)
+ {
+ CastSpell(this, gp->SpellId, true);
+ continue;
+ }
+ else
+ sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
+ }
+ else
+ sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
+ }
+ else
+ sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
+
+ // On any error remove glyph
+ SetGlyph(i, 0);
+ }
+ }
+}
+
+void Player::LoadCorpse()
+{
+ if (isAlive())
+ ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
+ else
+ {
+ if (Corpse *corpse = GetCorpse())
+ ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
+ else
+ //Prevent Dead Player login without corpse
+ ResurrectPlayer(0.5f);
+ }
+}
+
+void Player::_LoadInventory(QueryResult_AutoPtr result, uint32 timediff)
+{
+ //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());
+ std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
+ //NOTE: the "order by `bag`" is important because it makes sure
+ //the bagMap is filled before items in the bags are loaded
+ //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
+ //expected to be equipped before offhand items (TODO: fixme)
+
+ uint32 zone = GetZoneId();
+
+ if (result)
+ {
+ std::list<Item*> problematicItems;
+
+ // prevent items from being added to the queue when stored
+ m_itemUpdateQueueBlocked = true;
+ do
+ {
+ Field *fields = result->Fetch();
+ uint32 bag_guid = fields[1].GetUInt32();
+ uint8 slot = fields[2].GetUInt8();
+ uint32 item_guid = fields[3].GetUInt32();
+ uint32 item_id = fields[4].GetUInt32();
+
+ ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
+
+ if (!proto)
+ {
+ CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
+ CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
+ sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
+ continue;
+ }
+
+ Item *item = NewItemOrBag(proto);
+
+ if (!item->LoadFromDB(item_guid, GetGUID(), result))
+ {
+ sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
+ CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
+ item->FSetState(ITEM_REMOVED);
+ item->SaveToDB(); // it also deletes item object !
+ continue;
+ }
+
+ // not allow have in alive state item limited to another map/zone
+ if (isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone))
+ {
+ CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
+ item->FSetState(ITEM_REMOVED);
+ item->SaveToDB(); // it also deletes item object !
+ continue;
+ }
+
+ // "Conjured items disappear if you are logged out for more than 15 minutes"
+ if (timediff > 15*MINUTE && item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED))
+ {
+ CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
+ item->FSetState(ITEM_REMOVED);
+ item->SaveToDB(); // it also deletes item object !
+ continue;
+ }
+
+ bool success = true;
+
+ if (!bag_guid)
+ {
+ // the item is not in a bag
+ item->SetContainer(NULL);
+ item->SetSlot(slot);
+
+ if (IsInventoryPos(INVENTORY_SLOT_BAG_0, slot))
+ {
+ ItemPosCountVec dest;
+ if (CanStoreItem(INVENTORY_SLOT_BAG_0, slot, dest, item, false) == EQUIP_ERR_OK)
+ item = StoreItem(dest, item, true);
+ else
+ success = false;
+ }
+ else if (IsEquipmentPos(INVENTORY_SLOT_BAG_0, slot))
+ {
+ uint16 dest;
+ if (CanEquipItem(slot, dest, item, false, false) == EQUIP_ERR_OK)
+ QuickEquipItem(dest, item);
+ else
+ success = false;
+ }
+ else if (IsBankPos(INVENTORY_SLOT_BAG_0, slot))
+ {
+ ItemPosCountVec dest;
+ if (CanBankItem(INVENTORY_SLOT_BAG_0, slot, dest, item, false, false) == EQUIP_ERR_OK)
+ item = BankItem(dest, item, true);
+ else
+ success = false;
+ }
+
+ if (success)
+ {
+ // store bags that may contain items in them
+ if (item->IsBag() && IsBagPos(item->GetPos()))
+ bagMap[item_guid] = (Bag*)item;
+ }
+ }
+ else
+ {
+ item->SetSlot(NULL_SLOT);
+ // the item is in a bag, find the bag
+ std::map<uint64, Bag*>::iterator itr = bagMap.find(bag_guid);
+ if (itr != bagMap.end())
+ {
+ ItemPosCountVec dest;
+ uint8 result = CanStoreItem(itr->second->GetSlot(), slot, dest, item);
+ if (result == EQUIP_ERR_OK)
+ itr->second->StoreItem(slot, item, true);
+ else
+ {
+ sLog.outError("Player::_LoadInventory: Player %s has item (GUID: %u Entry: %u) can't be loaded to inventory (Bag GUID: %u Slot: %u) by reason %u.", GetName(),item_guid, item_id, bag_guid, slot, result);
+ success = false;
+ }
+ }
+ else
+ success = false;
+ }
+
+ // item's state may have changed after stored
+ if (success)
+ item->SetState(ITEM_UNCHANGED, this);
+ else
+ {
+ 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);
+ CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
+ problematicItems.push_back(item);
+ }
+ } while (result->NextRow());
+
+ m_itemUpdateQueueBlocked = false;
+
+ // send by mail problematic items
+ while (!problematicItems.empty())
+ {
+ std::string subject = GetSession()->GetTrinityString(LANG_NOT_EQUIPPED_ITEM);
+
+ // fill mail
+ MailDraft draft(subject);
+
+ for (uint8 i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
+ {
+ Item* item = problematicItems.front();
+ problematicItems.pop_front();
+
+ draft.AddItem(item);
+ }
+
+ draft.SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM));
+ }
+ }
+ //if(isAlive())
+ _ApplyAllItemMods();
+}
+
+// load mailed item which should receive current player
+void Player::_LoadMailedItems(Mail *mail)
+{
+ // data needs to be at first place for Item::LoadFromDB
+ QueryResult_AutoPtr 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);
+ if (!result)
+ return;
+
+ do
+ {
+ Field *fields = result->Fetch();
+ uint32 item_guid_low = fields[1].GetUInt32();
+ uint32 item_template = fields[2].GetUInt32();
+
+ mail->AddItem(item_guid_low, item_template);
+
+ ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
+
+ if (!proto)
+ {
+ 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);
+ CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
+ CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
+ continue;
+ }
+
+ Item *item = NewItemOrBag(proto);
+
+ if (!item->LoadFromDB(item_guid_low, 0, result))
+ {
+ sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
+ CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
+ item->FSetState(ITEM_REMOVED);
+ item->SaveToDB(); // it also deletes item object !
+ continue;
+ }
+
+ AddMItem(item);
+ } while (result->NextRow());
+}
+
+void Player::_LoadMailInit(QueryResult_AutoPtr resultUnread, QueryResult_AutoPtr resultDelivery)
+{
+ //set a count of unread mails
+ //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);
+ if (resultUnread)
+ {
+ Field *fieldMail = resultUnread->Fetch();
+ unReadMails = fieldMail[0].GetUInt8();
+ }
+
+ // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
+ //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
+ if (resultDelivery)
+ {
+ Field *fieldMail = resultDelivery->Fetch();
+ m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
+ }
+}
+
+void Player::_LoadMail()
+{
+ m_mail.clear();
+ //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
+ QueryResult_AutoPtr 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());
+ if (result)
+ {
+ do
+ {
+ Field *fields = result->Fetch();
+ Mail *m = new Mail;
+ m->messageID = fields[0].GetUInt32();
+ m->messageType = fields[1].GetUInt8();
+ m->sender = fields[2].GetUInt32();
+ m->receiver = fields[3].GetUInt32();
+ m->subject = fields[4].GetCppString();
+ m->itemTextId = fields[5].GetUInt32();
+ bool has_items = fields[6].GetBool();
+ m->expire_time = (time_t)fields[7].GetUInt64();
+ m->deliver_time = (time_t)fields[8].GetUInt64();
+ m->money = fields[9].GetUInt32();
+ m->COD = fields[10].GetUInt32();
+ m->checked = fields[11].GetUInt32();
+ m->stationery = fields[12].GetUInt8();
+ m->mailTemplateId = fields[13].GetInt16();
+
+ if (m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
+ {
+ sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
+ m->mailTemplateId = 0;
+ }
+
+ m->state = MAIL_STATE_UNCHANGED;
+
+ if (has_items)
+ _LoadMailedItems(m);
+
+ m_mail.push_back(m);
+ } while (result->NextRow());
+ }
+ m_mailsLoaded = true;
+}
+
+void Player::LoadPet()
+{
+ //fixme: the pet should still be loaded if the player is not in world
+ // just not added to the map
+ if (IsInWorld())
+ {
+ Pet *pet = new Pet(this);
+ if (!pet->LoadPetFromDB(this,0,0,true))
+ delete pet;
+ }
+}
+
+void Player::_LoadQuestStatus(QueryResult_AutoPtr result)
+{
+ mQuestStatus.clear();
+
+ uint16 slot = 0;
+
+ //// 0 1 2 3 4 5 6 7 8 9 10 11 12
+ //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());
+
+ if (result)
+ {
+ do
+ {
+ Field *fields = result->Fetch();
+
+ uint32 quest_id = fields[0].GetUInt32();
+ // used to be new, no delete?
+ Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
+ if (pQuest)
+ {
+ // find or create
+ QuestStatusData& questStatusData = mQuestStatus[quest_id];
+
+ uint32 qstatus = fields[1].GetUInt32();
+ if (qstatus < MAX_QUEST_STATUS)
+ questStatusData.m_status = QuestStatus(qstatus);
+ else
+ {
+ questStatusData.m_status = QUEST_STATUS_NONE;
+ sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
+ }
+
+ questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
+ questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
+
+ time_t quest_time = time_t(fields[4].GetUInt64());
+
+ if (pQuest->HasFlag(QUEST_TRINITY_FLAGS_TIMED) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE)
+ {
+ AddTimedQuest(quest_id);
+
+ if (quest_time <= sWorld.GetGameTime())
+ questStatusData.m_timer = 1;
+ else
+ questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
+ }
+ else
+ quest_time = 0;
+
+ questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
+ questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
+ questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
+ questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
+ questStatusData.m_itemcount[0] = fields[9].GetUInt32();
+ questStatusData.m_itemcount[1] = fields[10].GetUInt32();
+ questStatusData.m_itemcount[2] = fields[11].GetUInt32();
+ questStatusData.m_itemcount[3] = fields[12].GetUInt32();
+
+ questStatusData.uState = QUEST_UNCHANGED;
+
+ // add to quest log
+ if (slot < MAX_QUEST_LOG_SIZE &&
+ ((questStatusData.m_status == QUEST_STATUS_INCOMPLETE ||
+ questStatusData.m_status == QUEST_STATUS_COMPLETE ||
+ questStatusData.m_status == QUEST_STATUS_FAILED) &&
+ (!questStatusData.m_rewarded || pQuest->IsRepeatable())))
+ {
+ SetQuestSlot(slot, quest_id, quest_time);
+
+ if (questStatusData.m_status == QUEST_STATUS_COMPLETE)
+ SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
+
+ if (questStatusData.m_status == QUEST_STATUS_FAILED)
+ SetQuestSlotState(slot, QUEST_STATE_FAIL);
+
+ for (uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
+ if (questStatusData.m_creatureOrGOcount[idx])
+ SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]);
+
+ ++slot;
+ }
+
+ if (questStatusData.m_rewarded)
+ {
+ // learn rewarded spell if unknown
+ learnQuestRewardedSpells(pQuest);
+
+ // set rewarded title if any
+ if (pQuest->GetCharTitleId())
+ {
+ if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
+ SetTitle(titleEntry);
+ }
+
+ if(pQuest->GetBonusTalents())
+ m_questRewardTalentCount += pQuest->GetBonusTalents();
+ }
+
+ sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
+ }
+ }
+ while (result->NextRow());
+ }
+
+ // clear quest log tail
+ for (uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i)
+ SetQuestSlot(i, 0);
+}
+
+void Player::_LoadDailyQuestStatus(QueryResult_AutoPtr result)
+{
+ for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
+ SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
+
+ //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
+
+ if (result)
+ {
+ uint32 quest_daily_idx = 0;
+
+ do
+ {
+ if (quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
+ {
+ sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
+ break;
+ }
+
+ Field *fields = result->Fetch();
+
+ uint32 quest_id = fields[0].GetUInt32();
+
+ // save _any_ from daily quest times (it must be after last reset anyway)
+ m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
+
+ Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
+ if (!pQuest)
+ continue;
+
+ SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
+ ++quest_daily_idx;
+
+ sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
+ }
+ while (result->NextRow());
+ }
+
+ m_DailyQuestChanged = false;
+}
+
+void Player::_LoadSpells(QueryResult_AutoPtr result)
+{
+ //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
+
+ if (result)
+ {
+ do
+ {
+ Field *fields = result->Fetch();
+
+ addSpell(fields[0].GetUInt32(), fields[1].GetBool(), false, false, fields[2].GetBool());
+ }
+ while (result->NextRow());
+ }
+}
+
+void Player::_LoadGroup(QueryResult_AutoPtr result)
+{
+ //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
+ if (result)
+ {
+ uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
+ if (Group* group = objmgr.GetGroupByLeader(leaderGuid))
+ {
+ uint8 subgroup = group->GetMemberGroup(GetGUID());
+ SetGroup(group, subgroup);
+ if (getLevel() >= LEVELREQUIREMENT_HEROIC)
+ {
+ // the group leader may change the instance difficulty while the player is offline
+ SetDungeonDifficulty(group->GetDungeonDifficulty());
+ SetRaidDifficulty(group->GetRaidDifficulty());
+ }
+ }
+ }
+}
+
+void Player::_LoadBoundInstances(QueryResult_AutoPtr result)
+{
+ for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
+ m_boundInstances[i].clear();
+
+ Group *group = GetGroup();
+
+ //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));
+ if (result)
+ {
+ do
+ {
+ Field *fields = result->Fetch();
+ bool perm = fields[1].GetBool();
+ uint32 mapId = fields[2].GetUInt32();
+ uint32 instanceId = fields[0].GetUInt32();
+ uint8 difficulty = fields[3].GetUInt8();
+
+ time_t resetTime = (time_t)fields[4].GetUInt64();
+ // the resettime for normal instances is only saved when the InstanceSave is unloaded
+ // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
+ // and in that case it is not used
+
+ MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
+ if (!mapEntry || !mapEntry->IsDungeon())
+ {
+ sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
+ CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
+ continue;
+ }
+
+ if(difficulty >= MAX_DIFFICULTY)
+ {
+ sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
+ CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
+ continue;
+ }
+
+ MapDifficulty const* mapDiff = GetMapDifficultyData(mapId,Difficulty(difficulty));
+ if(!mapDiff)
+ {
+ sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
+ CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
+ continue;
+ }
+
+
+ if (!perm && group)
+ {
+ 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);
+ CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
+ continue;
+ }
+
+ // since non permanent binds are always solo bind, they can always be reset
+ if (InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, Difficulty(difficulty), resetTime, !perm, true))
+ BindToInstance(save, perm, true);
+ } while (result->NextRow());
+ }
+}
+
+InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty)
+{
+ // some instances only have one difficulty
+ MapDifficulty const* mapDiff = GetMapDifficultyData(mapid,difficulty);
+ if(!mapDiff)
+ return NULL;
+
+ BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
+ if (itr != m_boundInstances[difficulty].end())
+ return &itr->second;
+ else
+ return NULL;
+}
+
+InstanceSave * Player::GetInstanceSave(uint32 mapid, bool raid)
+{
+ InstancePlayerBind *pBind = GetBoundInstance(mapid, GetDifficulty(raid));
+ InstanceSave *pSave = pBind ? pBind->save : NULL;
+ if (!pBind || !pBind->perm)
+ if(Group *group = GetGroup())
+ if(InstanceGroupBind *groupBind = group->GetBoundInstance(this))
+ pSave = groupBind->save;
+
+ return pSave;
+}
+
+void Player::UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload)
+{
+ BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
+ UnbindInstance(itr, difficulty, unload);
+}
+
+void Player::UnbindInstance(BoundInstancesMap::iterator &itr, Difficulty difficulty, bool unload)
+{
+ if (itr != m_boundInstances[difficulty].end())
+ {
+ if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
+ itr->second.save->RemovePlayer(this); // save can become invalid
+ m_boundInstances[difficulty].erase(itr++);
+ }
+}
+
+InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
+{
+ if(save)
+ {
+ InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
+ if (bind.save)
+ {
+ // update the save when the group kills a boss
+ if (permanent != bind.perm || save != bind.save)
+ 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());
+ }
+ else
+ if (!load)
+ CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
+
+ if (bind.save != save)
+ {
+ if(bind.save)
+ bind.save->RemovePlayer(this);
+ save->AddPlayer(this);
+ }
+
+ if (permanent)
+ save->SetCanReset(false);
+
+ bind.save = save;
+ bind.perm = permanent;
+ 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());
+ return &bind;
+ }
+ else
+ return NULL;
+}
+
+void Player::SendRaidInfo()
+{
+ uint32 counter = 0;
+
+ WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
+
+ size_t p_counter = data.wpos();
+ data << uint32(counter); // placeholder
+
+ time_t now = time(NULL);
+
+ for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
+ {
+ for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
+ {
+ if(itr->second.perm)
+ {
+ InstanceSave *save = itr->second.save;
+ data << uint32(save->GetMapId()); // map id
+ data << uint32(save->GetDifficulty()); // difficulty
+ data << uint64(save->GetInstanceId()); // instance id
+ data << uint8(1); // expired = 0
+ data << uint8(0); // extended = 1
+ data << uint32(save->GetResetTime() - now); // reset time
+ ++counter;
+ }
+ }
+ }
+ data.put<uint32>(p_counter, counter);
+ GetSession()->SendPacket(&data);
+}
+
+/*
+- called on every successful teleportation to a map
+*/
+void Player::SendSavedInstances()
+{
+ bool hasBeenSaved = false;
+ WorldPacket data;
+
+ for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
+ {
+ for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
+ {
+ if (itr->second.perm) // only permanent binds are sent
+ {
+ hasBeenSaved = true;
+ break;
+ }
+ }
+ }
+
+ //Send opcode 811. true or false means, whether you have current raid/heroic instances
+ data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
+ data << uint32(hasBeenSaved);
+ GetSession()->SendPacket(&data);
+
+ if (!hasBeenSaved)
+ return;
+
+ for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
+ {
+ for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
+ {
+ if (itr->second.perm)
+ {
+ data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
+ data << uint32(itr->second.save->GetMapId());
+ GetSession()->SendPacket(&data);
+ }
+ }
+ }
+}
+
+/// convert the player's binds to the group
+void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
+{
+ bool has_binds = false;
+ bool has_solo = false;
+
+ if(player)
+ {
+ player_guid = player->GetGUID();
+ if (!group)
+ group = player->GetGroup();
+ }
+ assert(player_guid);
+
+ // copy all binds to the group, when changing leader it's assumed the character
+ // will not have any solo binds
+
+ if (player)
+ {
+ for (uint8 i = 0; i < MAX_DIFFICULTY; ++i)
+ {
+ for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
+ {
+ has_binds = true;
+ if (group)
+ group->BindToInstance(itr->second.save, itr->second.perm, true);
+ // permanent binds are not removed
+ if (!itr->second.perm)
+ {
+ // increments itr in call
+ player->UnbindInstance(itr, Difficulty(i), true);
+ has_solo = true;
+ }
+ else
+ ++itr;
+ }
+ }
+ }
+
+ // if the player's not online we don't know what binds it has
+ 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));
+ // the following should not get executed when changing leaders
+ if(!player || has_solo)
+ CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
+}
+
+bool Player::Satisfy(AccessRequirement const *ar, uint32 target_map, bool report)
+{
+ if (!isGameMaster() && ar)
+ {
+ uint8 LevelMin = 0;
+ uint8 LevelMax = 0;
+
+ if (!sWorld.getConfig(CONFIG_INSTANCE_IGNORE_LEVEL))
+ {
+ if (ar->levelMin && getLevel() < ar->levelMin)
+ LevelMin = ar->levelMin;
+ if(ar->heroicLevelMin && GetDungeonDifficulty() == DUNGEON_DIFFICULTY_HEROIC && getLevel() < ar->heroicLevelMin)
+ LevelMin = ar->heroicLevelMin;
+ if (ar->levelMax && getLevel() > ar->levelMax)
+ LevelMax = ar->levelMax;
+ }
+
+ uint32 missingItem = 0;
+ if (ar->item)
+ {
+ if (!HasItemCount(ar->item, 1) &&
+ (!ar->item2 || !HasItemCount(ar->item2, 1)))
+ missingItem = ar->item;
+ }
+ else if(ar->item2 && !HasItemCount(ar->item2, 1))
+ missingItem = ar->item2;
+
+ MapEntry const* mapEntry = sMapStore.LookupEntry(target_map);
+ if(!mapEntry)
+ return false;
+
+ bool isNormalTargetMap = mapEntry->IsRaid()
+ ? (GetRaidDifficulty() == RAID_DIFFICULTY_10MAN_NORMAL)
+ : (GetDungeonDifficulty() == DUNGEON_DIFFICULTY_NORMAL);
+
+ uint32 missingKey = 0;
+ uint32 missingHeroicQuest = 0;
+ if(!isNormalTargetMap)
+ {
+ if (ar->heroicKey)
+ {
+ if (!HasItemCount(ar->heroicKey, 1) &&
+ (!ar->heroicKey2 || !HasItemCount(ar->heroicKey2, 1)))
+ missingKey = ar->heroicKey;
+ }
+ else if (ar->heroicKey2 && !HasItemCount(ar->heroicKey2, 1))
+ missingKey = ar->heroicKey2;
+
+ if (ar->heroicQuest && !GetQuestRewardStatus(ar->heroicQuest))
+ missingHeroicQuest = ar->heroicQuest;
+ }
+
+ uint32 missingQuest = 0;
+ if(ar->quest && !GetQuestRewardStatus(ar->quest))
+ missingQuest = ar->quest;
+
+ if (LevelMin || LevelMax || missingItem || missingKey || missingQuest || missingHeroicQuest)
+ {
+ if (report)
+ {
+ if (missingItem)
+ GetSession()->SendAreaTriggerMessage(GetSession()->GetTrinityString(LANG_LEVEL_MINREQUIRED_AND_ITEM), LevelMin, objmgr.GetItemPrototype(missingItem)->Name1);
+ else if (missingKey)
+ SendTransferAborted(target_map, TRANSFER_ABORT_DIFFICULTY, isNormalTargetMap ? DUNGEON_DIFFICULTY_NORMAL : DUNGEON_DIFFICULTY_HEROIC);
+ else if (missingHeroicQuest)
+ GetSession()->SendAreaTriggerMessage(ar->heroicQuestFailedText.c_str());
+ else if (missingQuest)
+ GetSession()->SendAreaTriggerMessage(ar->questFailedText.c_str());
+ else if (LevelMin)
+ GetSession()->SendAreaTriggerMessage(GetSession()->GetTrinityString(LANG_LEVEL_MINREQUIRED), LevelMin);
+ }
+ return false;
+ }
+ }
+ return true;
+}
+
+bool Player::_LoadHomeBind(QueryResult_AutoPtr result)
+{
+ PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
+ if (!info)
+ {
+ sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
+ return false;
+ }
+
+ bool ok = false;
+ //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
+ if (result)
+ {
+ Field *fields = result->Fetch();
+ m_homebindMapId = fields[0].GetUInt32();
+ m_homebindZoneId = fields[1].GetUInt16();
+ m_homebindX = fields[2].GetFloat();
+ m_homebindY = fields[3].GetFloat();
+ m_homebindZ = fields[4].GetFloat();
+
+ MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
+
+ // accept saved data only for valid position (and non instanceable), and accessable
+ if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
+ !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
+ ok = true;
+ else
+ CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
+ }
+
+ if (!ok)
+ {
+ m_homebindMapId = info->mapId;
+ m_homebindZoneId = info->zoneId;
+ m_homebindX = info->positionX;
+ m_homebindY = info->positionY;
+ m_homebindZ = info->positionZ;
+
+ 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);
+ }
+
+ DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
+ m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
+
+ return true;
+}
+
+/*********************************************************/
+/*** SAVE SYSTEM ***/
+/*********************************************************/
+
+void Player::SaveToDB()
+{
+ // delay auto save at any saves (manual, in code, or autosave)
+ m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
+
+ //lets allow only players in world to be saved
+ if (IsBeingTeleportedFar())
+ {
+ ScheduleDelayedOperation(DELAYED_SAVE_PLAYER);
+ return;
+ }
+
+ // first save/honor gain after midnight will also update the player's honor fields
+ UpdateHonorFields();
+
+ sLog.outDebug("The value of player %s at save: ", m_name.c_str());
+ outDebugValues();
+
+ std::string sql_name = m_name;
+ CharacterDatabase.escape_string(sql_name);
+
+ std::ostringstream ss;
+ ss << "REPLACE INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags,"
+ "map, instance_id, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
+ "taximask, online, 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, "
+ "death_expire_time, taxi_path, arena_pending_points, latency, speccount, activespec) VALUES ("
+ << GetGUIDLow() << ", "
+ << GetSession()->GetAccountId() << ", '"
+ << sql_name << "', "
+ << uint32(getRace()) << ", "
+ << uint32(getClass()) << ", "
+ << uint32(getGender()) << ", "
+ << uint32(getLevel()) << ", "
+ << GetUInt32Value(PLAYER_XP) << ", "
+ << GetMoney() << ", "
+ << GetUInt32Value(PLAYER_BYTES) << ", "
+ << GetUInt32Value(PLAYER_BYTES_2) << ", "
+ << GetUInt32Value(PLAYER_FLAGS) << ", ";
+
+ if (!IsBeingTeleported())
+ {
+ ss << GetMapId() << ", "
+ << (uint32)GetInstanceId() << ", "
+ << (uint32)GetDungeonDifficulty() << ", "
+ << finiteAlways(GetPositionX()) << ", "
+ << finiteAlways(GetPositionY()) << ", "
+ << finiteAlways(GetPositionZ()) << ", "
+ << finiteAlways(GetOrientation()) << ", '";
+ }
+ else
+ {
+ ss << GetTeleportDest().GetMapId() << ", "
+ << (uint32)0 << ", "
+ << (uint32)GetDungeonDifficulty() << ", "
+ << finiteAlways(GetTeleportDest().GetPositionX()) << ", "
+ << finiteAlways(GetTeleportDest().GetPositionY()) << ", "
+ << finiteAlways(GetTeleportDest().GetPositionZ()) << ", "
+ << finiteAlways(GetTeleportDest().GetOrientation()) << ", '";
+ }
+
+ uint16 i;
+ for (i = 0; i < m_valuesCount; ++i)
+ ss << GetUInt32Value(i) << " ";
+
+ ss << "', ";
+
+ ss << m_taxi << ", "; // string with TaxiMaskSize numbers
+
+ ss << (IsInWorld() ? 1 : 0) << ", ";
+
+ ss << m_cinematic << ", ";
+
+ ss << m_Played_time[PLAYED_TIME_TOTAL] << ", ";
+ ss << m_Played_time[PLAYED_TIME_LEVEL] << ", ";
+
+ ss << finiteAlways(m_rest_bonus) << ", ";
+ ss << (uint64)time(NULL) << ", ";
+ ss << (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0) << ", ";
+ //save, far from tavern/city
+ //save, but in tavern/city
+ ss << m_resetTalentsCost << ", ";
+ ss << (uint64)m_resetTalentsTime << ", ";
+
+ ss << finiteAlways(m_movementInfo.t_x) << ", ";
+ ss << finiteAlways(m_movementInfo.t_y) << ", ";
+ ss << finiteAlways(m_movementInfo.t_z) << ", ";
+ ss << finiteAlways(m_movementInfo.t_o) << ", ";
+ if (m_transport)
+ ss << m_transport->GetGUIDLow();
+ else
+ ss << "0";
+ ss << ", ";
+
+ ss << m_ExtraFlags << ", ";
+
+ ss << uint32(m_stableSlots) << ", "; // to prevent save uint8 as char
+
+ ss << uint32(m_atLoginFlags) << ", ";
+
+ ss << GetZoneId() << ", ";
+
+ ss << (uint64)m_deathExpireTime << ", '";
+
+ ss << m_taxi.SaveTaxiDestinationsToString() << "', ";
+ ss << "'0', "; // arena_pending_points
+ ss << GetSession()->GetLatency();
+ ss << ", ";
+ ss << uint32(m_specsCount);
+ ss << ", ";
+ ss << uint32(m_activeSpec);
+ ss << ")";
+
+ CharacterDatabase.BeginTransaction();
+
+ CharacterDatabase.Execute( ss.str().c_str() );
+
+ if (m_mailsUpdated) //save mails only when needed
+ _SaveMail();
+
+ _SaveBGData();
+ _SaveInventory();
+ _SaveQuestStatus();
+ _SaveDailyQuestStatus();
+ _SaveTalents();
+ _SaveSpells();
+ _SaveSpellCooldowns();
+ _SaveActions();
+ _SaveAuras();
+ _SaveSkills();
+ m_achievementMgr.SaveToDB();
+ m_reputationMgr.SaveToDB();
+ _SaveEquipmentSets();
+ GetSession()->SaveTutorialsData(); // changed only while character in game
+ _SaveGlyphs();
+
+ CharacterDatabase.CommitTransaction();
+
+ // save pet (hunter pet level and experience and all type pets health/mana).
+ if (Pet* pet = GetPet())
+ pet->SavePetToDB(PET_SAVE_AS_CURRENT);
+}
+
+// fast save function for item/money cheating preventing - save only inventory and money state
+void Player::SaveInventoryAndGoldToDB()
+{
+ _SaveInventory();
+ SaveGoldToDB();
+}
+
+void Player::SaveGoldToDB()
+{
+ CharacterDatabase.PExecute("UPDATE characters SET money = '%u' WHERE guid = '%u'", GetMoney(), GetGUIDLow());
+}
+
+void Player::_SaveActions()
+{
+ for (ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end();)
+ {
+ switch (itr->second.uState)
+ {
+ case ACTIONBUTTON_NEW:
+ CharacterDatabase.PExecute("INSERT INTO character_action (guid,spec,button,action,type) VALUES ('%u', '%u', '%u', '%u', '%u')",
+ GetGUIDLow(), (uint32)m_activeSpec, (uint32)itr->first, (uint32)itr->second.GetAction(), (uint32)itr->second.GetType() );
+ itr->second.uState = ACTIONBUTTON_UNCHANGED;
+ ++itr;
+ break;
+ case ACTIONBUTTON_CHANGED:
+ CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u' WHERE guid = '%u' AND button = '%u' AND spec = '%u'",
+ (uint32)itr->second.GetAction(), (uint32)itr->second.GetType(), GetGUIDLow(), (uint32)itr->first, (uint32)m_activeSpec);
+ itr->second.uState = ACTIONBUTTON_UNCHANGED;
+ ++itr;
+ break;
+ case ACTIONBUTTON_DELETED:
+ CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u' and spec = '%u'", GetGUIDLow(), (uint32)itr->first, (uint32)m_activeSpec );
+ m_actionButtons.erase(itr++);
+ break;
+ default:
+ ++itr;
+ break;
+ }
+ }
+}
+
+void Player::_SaveAuras()
+{
+ CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
+
+ for (AuraMap::const_iterator itr = m_ownedAuras.begin(); itr != m_ownedAuras.end() ; ++itr)
+ {
+ if (!itr->second->CanBeSaved())
+ continue;
+
+ Aura * aura = itr->second;
+
+ int32 damage[MAX_SPELL_EFFECTS];
+ int32 baseDamage[MAX_SPELL_EFFECTS];
+ uint8 effMask = 0;
+ uint8 recalculateMask = 0;
+ for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
+ {
+ if (aura->GetEffect(i))
+ {
+ baseDamage[i] = aura->GetEffect(i)->GetBaseAmount();
+ damage[i] = aura->GetEffect(i)->GetAmount();
+ effMask |= (1<<i);
+ if (aura->GetEffect(i)->CanBeRecalculated())
+ recalculateMask |= (1<<i);
+ }
+ else
+ {
+ baseDamage[i] = NULL;
+ damage[i] = NULL;
+ }
+ }
+
+ CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_mask,recalculate_mask,stackcount,amount0,amount1,amount2,base_amount0,base_amount1,base_amount2,maxduration,remaintime,remaincharges) "
+ "VALUES ('%u', '" UI64FMTD "', '%u', '%u', '%u', '%u', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%u')",
+ GetGUIDLow(), itr->second->GetCasterGUID(), itr->second->GetId(), effMask, recalculateMask,
+ itr->second->GetStackAmount(), damage[0], damage[1], damage[2], baseDamage[0], baseDamage[1], baseDamage[2],
+ itr->second->GetMaxDuration(), itr->second->GetDuration(),itr->second->GetCharges());
+ }
+}
+
+void Player::_SaveInventory()
+{
+ // force items in buyback slots to new state
+ // and remove those that aren't already
+ for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
+ {
+ Item *item = m_items[i];
+ if (!item || item->GetState() == ITEM_NEW)
+ continue;
+ CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
+ CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
+ m_items[i]->FSetState(ITEM_NEW);
+ }
+
+ // update enchantment durations
+ for (EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
+ itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
+
+ // if no changes
+ if (m_itemUpdateQueue.empty())
+ return;
+
+ // do not save if the update queue is corrupt
+ bool error = false;
+ for (size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
+ {
+ Item *item = m_itemUpdateQueue[i];
+ if(!item || item->GetState() == ITEM_REMOVED) continue;
+ Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
+
+ if (test == NULL)
+ {
+ sLog.outCrash("Player(GUID: %u Name: %s)::_SaveInventory - the bag(%d) and slot(%d) values for the item with guid %d (state %d) are incorrect, the player doesn't have an item at that position!", GetGUIDLow(), GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow(), (int32)item->GetState());
+ //error = true;
+ //now some items in bags cannot be saved but after cleansup they appear again
+ }
+ else if (test != item)
+ {
+ 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());
+ error = true;
+ }
+ }
+
+ if (error)
+ {
+ sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
+ ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
+ return;
+ }
+
+ for (size_t i = 0; i < m_itemUpdateQueue.size(); i++)
+ {
+ Item *item = m_itemUpdateQueue[i];
+ if(!item) continue;
+
+ Bag *container = item->GetContainer();
+ uint32 bag_guid = container ? container->GetGUIDLow() : 0;
+
+ switch(item->GetState())
+ {
+ case ITEM_NEW:
+ 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());
+ break;
+ case ITEM_CHANGED:
+ 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());
+ break;
+ case ITEM_REMOVED:
+ CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
+ break;
+ case ITEM_UNCHANGED:
+ break;
+ }
+
+ item->SaveToDB(); // item have unchanged inventory record and can be save standalone
+ }
+ m_itemUpdateQueue.clear();
+}
+
+void Player::_SaveMail()
+{
+ if (!m_mailsLoaded)
+ return;
+
+ for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
+ {
+ Mail *m = (*itr);
+ if (m->state == MAIL_STATE_CHANGED)
+ {
+ 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'",
+ m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
+ if(m->removedItems.size())
+ {
+ for (std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
+ CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
+ m->removedItems.clear();
+ }
+ m->state = MAIL_STATE_UNCHANGED;
+ }
+ else if (m->state == MAIL_STATE_DELETED)
+ {
+ if (m->HasItems())
+ for (std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
+ CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
+ if (m->itemTextId)
+ CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
+ CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
+ CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
+ }
+ }
+
+ //deallocate deleted mails...
+ for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();)
+ {
+ if ((*itr)->state == MAIL_STATE_DELETED)
+ {
+ Mail* m = *itr;
+ m_mail.erase(itr);
+ delete m;
+ itr = m_mail.begin();
+ }
+ else
+ ++itr;
+ }
+
+ m_mailsUpdated = false;
+}
+
+void Player::_SaveQuestStatus()
+{
+ // we don't need transactions here.
+ for (QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
+ {
+ switch (i->second.uState)
+ {
+ case QUEST_NEW :
+ CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
+ "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
+ 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]);
+ break;
+ case QUEST_CHANGED :
+ 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' ",
+ 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 );
+ break;
+ case QUEST_UNCHANGED:
+ break;
+ };
+ i->second.uState = QUEST_UNCHANGED;
+ }
+}
+
+void Player::_SaveDailyQuestStatus()
+{
+ if(!m_DailyQuestChanged)
+ return;
+
+ m_DailyQuestChanged = false;
+
+ // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
+
+ // we don't need transactions here.
+ CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
+ for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
+ if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
+ CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" UI64FMTD "')",
+ GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
+}
+
+void Player::_SaveSkills()
+{
+ // we don't need transactions here.
+ for( SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); )
+ {
+ if(itr->second.uState == SKILL_UNCHANGED)
+ {
+ ++itr;
+ continue;
+ }
+
+ if(itr->second.uState == SKILL_DELETED)
+ {
+ CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), itr->first );
+ mSkillStatus.erase(itr++);
+ continue;
+ }
+
+ uint32 valueData = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos));
+ uint16 value = SKILL_VALUE(valueData);
+ uint16 max = SKILL_MAX(valueData);
+
+ switch (itr->second.uState)
+ {
+ case SKILL_NEW:
+ CharacterDatabase.PExecute("INSERT INTO character_skills (guid, skill, value, max) VALUES ('%u', '%u', '%u', '%u')",
+ GetGUIDLow(), itr->first, value, max);
+ break;
+ case SKILL_CHANGED:
+ CharacterDatabase.PExecute("UPDATE character_skills SET value = '%u',max = '%u'WHERE guid = '%u' AND skill = '%u' ",
+ value, max, GetGUIDLow(), itr->first );
+ break;
+ };
+ itr->second.uState = SKILL_UNCHANGED;
+
+ ++itr;
+ }
+}
+
+void Player::_SaveSpells()
+{
+ for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
+ {
+ if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
+ CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
+
+ // add only changed/new not dependent spells
+ if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
+ 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);
+
+ if (itr->second->state == PLAYERSPELL_REMOVED)
+ {
+ delete itr->second;
+ m_spells.erase(itr++);
+ }
+ else
+ {
+ itr->second->state = PLAYERSPELL_UNCHANGED;
+ ++itr;
+ }
+
+ }
+}
+
+void Player::outDebugValues() const
+{
+ if(!sLog.IsOutDebug()) // optimize disabled debug output
+ return;
+
+ sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
+ sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
+ sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
+ sLog.outDebug("STAMINA is: \t\t%f",GetStat(STAT_STAMINA));
+ sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
+ sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
+ sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
+ sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
+ sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
+ sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
+ sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
+ sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
+}
+
+/*********************************************************/
+/*** FLOOD FILTER SYSTEM ***/
+/*********************************************************/
+
+void Player::UpdateSpeakTime()
+{
+ // ignore chat spam protection for GMs in any mode
+ if(GetSession()->GetSecurity() > SEC_PLAYER)
+ return;
+
+ time_t current = time (NULL);
+ if(m_speakTime > current)
+ {
+ uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
+ if(!max_count)
+ return;
+
+ ++m_speakCount;
+ if(m_speakCount >= max_count)
+ {
+ // prevent overwrite mute time, if message send just before mutes set, for example.
+ time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
+ if(GetSession()->m_muteTime < new_mute)
+ GetSession()->m_muteTime = new_mute;
+
+ m_speakCount = 0;
+ }
+ }
+ else
+ m_speakCount = 0;
+
+ m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
+}
+
+bool Player::CanSpeak() const
+{
+ return GetSession()->m_muteTime <= time (NULL);
+}
+
+/*********************************************************/
+/*** LOW LEVEL FUNCTIONS:Notifiers ***/
+/*********************************************************/
+
+void Player::SendAttackSwingNotInRange()
+{
+ WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
+ GetSession()->SendPacket( &data );
+}
+
+void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
+{
+ std::ostringstream ss;
+ ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
+ << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
+ << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
+ << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
+ sLog.outDebug(ss.str().c_str());
+ CharacterDatabase.Execute(ss.str().c_str());
+}
+
+void Player::SaveDataFieldToDB()
+{
+ std::ostringstream ss;
+ ss<<"UPDATE characters SET data='";
+
+ for (uint16 i = 0; i < m_valuesCount; i++ )
+ {
+ ss << GetUInt32Value(i) << " ";
+ }
+ ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
+
+ CharacterDatabase.Execute(ss.str().c_str());
+}
+
+bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
+{
+ std::ostringstream ss2;
+ ss2<<"UPDATE characters SET data='";
+ uint32 i=0;
+ for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
+ {
+ ss2<<tokens[i]<<" ";
+ }
+ ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
+
+ return CharacterDatabase.Execute(ss2.str().c_str());
+}
+
+void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
+{
+ char buf[11];
+ snprintf(buf,11,"%u",value);
+
+ if(index >= tokens.size())
+ return;
+
+ tokens[index] = buf;
+}
+
+void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
+{
+ Tokens tokens;
+ if(!LoadValuesArrayFromDB(tokens,guid))
+ return;
+
+ if(index >= tokens.size())
+ return;
+
+ char buf[11];
+ snprintf(buf,11,"%u",value);
+ tokens[index] = buf;
+
+ SaveValuesArrayInDB(tokens,guid);
+}
+
+void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
+{
+ uint32 temp;
+ memcpy(&temp, &value, sizeof(value));
+ Player::SetUInt32ValueInDB(index, temp, guid);
+}
+
+void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
+{
+ // 0
+ QueryResult_AutoPtr result = CharacterDatabase.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
+ if(!result)
+ return;
+
+ Field* fields = result->Fetch();
+
+ uint32 player_bytes2 = fields[0].GetUInt32();
+ player_bytes2 &= ~0xFF;
+ player_bytes2 |= facialHair;
+
+ 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));
+}
+
+void Player::SendAttackSwingDeadTarget()
+{
+ WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
+ GetSession()->SendPacket( &data );
+}
+
+void Player::SendAttackSwingCantAttack()
+{
+ WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
+ GetSession()->SendPacket( &data );
+}
+
+void Player::SendAttackSwingCancelAttack()
+{
+ WorldPacket data(SMSG_CANCEL_COMBAT, 0);
+ GetSession()->SendPacket( &data );
+}
+
+void Player::SendAttackSwingBadFacingAttack()
+{
+ WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
+ GetSession()->SendPacket( &data );
+}
+
+void Player::SendAutoRepeatCancel(Unit *target)
+{
+ WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, target->GetPackGUID().size());
+ data.append(target->GetPackGUID()); // may be it's target guid
+ GetSession()->SendPacket( &data );
+}
+
+void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
+{
+ WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
+ data << Area;
+ data << Experience;
+ GetSession()->SendPacket(&data);
+}
+
+void Player::SendDungeonDifficulty(bool IsInGroup)
+{
+ uint8 val = 0x00000001;
+ WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
+ data << (uint32)GetDungeonDifficulty();
+ data << uint32(val);
+ data << uint32(IsInGroup);
+ GetSession()->SendPacket(&data);
+}
+
+void Player::SendRaidDifficulty(bool IsInGroup)
+{
+ uint8 val = 0x00000001;
+ WorldPacket data(MSG_SET_RAID_DIFFICULTY, 12);
+ data << uint32(GetRaidDifficulty());
+ data << uint32(val);
+ data << uint32(IsInGroup);
+ GetSession()->SendPacket(&data);
+}
+
+void Player::SendResetFailedNotify(uint32 mapid)
+{
+ WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
+ data << uint32(mapid);
+ GetSession()->SendPacket(&data);
+}
+
+/// Reset all solo instances and optionally send a message on success for each
+void Player::ResetInstances(uint8 method, bool isRaid)
+{
+ // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
+
+ // we assume that when the difficulty changes, all instances that can be reset will be
+ Difficulty diff = GetDifficulty(isRaid);
+
+ for (BoundInstancesMap::iterator itr = m_boundInstances[diff].begin(); itr != m_boundInstances[diff].end(); )
+ {
+ InstanceSave *p = itr->second.save;
+ const MapEntry *entry = sMapStore.LookupEntry(itr->first);
+ if(!entry || entry->IsRaid() != isRaid || !p->CanReset())
+ {
+ ++itr;
+ continue;
+ }
+
+ if(method == INSTANCE_RESET_ALL)
+ {
+ // the "reset all instances" method can only reset normal maps
+ if(entry->map_type == MAP_RAID || diff == DUNGEON_DIFFICULTY_HEROIC)
+ {
+ ++itr;
+ continue;
+ }
+ }
+
+ // if the map is loaded, reset it
+ Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
+ if(map && map->IsDungeon())
+ if(!((InstanceMap*)map)->Reset(method))
+ {
+ ++itr;
+ continue;
+ }
+
+ // since this is a solo instance there should not be any players inside
+ if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
+ SendResetInstanceSuccess(p->GetMapId());
+
+ p->DeleteFromDB();
+ m_boundInstances[diff].erase(itr++);
+
+ // the following should remove the instance save from the manager and delete it as well
+ p->RemovePlayer(this);
+ }
+}
+
+void Player::SendResetInstanceSuccess(uint32 MapId)
+{
+ WorldPacket data(SMSG_INSTANCE_RESET, 4);
+ data << MapId;
+ GetSession()->SendPacket(&data);
+}
+
+void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
+{
+ // TODO: find what other fail reasons there are besides players in the instance
+ WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
+ data << reason;
+ data << MapId;
+ GetSession()->SendPacket(&data);
+}
+
+/*********************************************************/
+/*** Update timers ***/
+/*********************************************************/
+
+///checks the 15 afk reports per 5 minutes limit
+void Player::UpdateAfkReport(time_t currTime)
+{
+ if(m_bgData.bgAfkReportedTimer <= currTime)
+ {
+ m_bgData.bgAfkReportedCount = 0;
+ m_bgData.bgAfkReportedTimer = currTime+5*MINUTE;
+ }
+}
+
+void Player::UpdateContestedPvP(uint32 diff)
+{
+ if(!m_contestedPvPTimer||isInCombat())
+ return;
+ if(m_contestedPvPTimer <= diff)
+ {
+ ResetContestedPvP();
+ }
+ else
+ m_contestedPvPTimer -= diff;
+}
+
+void Player::UpdatePvPFlag(time_t currTime)
+{
+ if(!IsPvP())
+ return;
+ if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
+ return;
+
+ UpdatePvP(false);
+}
+
+void Player::UpdateDuelFlag(time_t currTime)
+{
+ if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
+ return;
+
+ SetUInt32Value(PLAYER_DUEL_TEAM, 1);
+ duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
+
+ duel->startTimer = 0;
+ duel->startTime = currTime;
+ duel->opponent->duel->startTimer = 0;
+ duel->opponent->duel->startTime = currTime;
+}
+
+Pet* Player::GetPet() const
+{
+ if(uint64 pet_guid = GetPetGUID())
+ {
+ if(!IS_PET_GUID(pet_guid))
+ return NULL;
+
+ Pet* pet = ObjectAccessor::GetPet(pet_guid);
+
+ if (!pet)
+ return NULL;
+
+ if(IsInWorld() && pet)
+ return pet;
+
+ //there may be a guardian in slot
+ //sLog.outError("Player::GetPet: Pet %u not exist.",GUID_LOPART(pet_guid));
+ //const_cast<Player*>(this)->SetPetGUID(0);
+ }
+
+ return NULL;
+}
+
+void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
+{
+ if(!pet)
+ pet = GetPet();
+
+ if(pet)
+ {
+ sLog.outDebug("RemovePet %u, %u, %u", pet->GetEntry(), mode, returnreagent);
+
+ if(pet->m_removed)
+ return;
+ }
+
+ if(returnreagent && (pet || m_temporaryUnsummonedPetNumber) && !InBattleGround())
+ {
+ //returning of reagents only for players, so best done here
+ uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
+
+ if(spellInfo)
+ {
+ for (uint32 i = 0; i < 7; ++i)
+ {
+ if(spellInfo->Reagent[i] > 0)
+ {
+ ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
+ uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
+ if( msg == EQUIP_ERR_OK )
+ {
+ Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
+ if(IsInWorld())
+ SendNewItem(item,spellInfo->ReagentCount[i],true,false);
+ }
+ }
+ }
+ }
+ m_temporaryUnsummonedPetNumber = 0;
+ }
+
+ if(!pet || pet->GetOwnerGUID()!=GetGUID())
+ return;
+
+ pet->CombatStop();
+
+ if(returnreagent)
+ {
+ switch(pet->GetEntry())
+ {
+ //warlock pets except imp are removed(?) when logging out
+ case 1860:
+ case 1863:
+ case 417:
+ case 17252:
+ mode = PET_SAVE_NOT_IN_SLOT;
+ break;
+ }
+ }
+
+ // only if current pet in slot
+ pet->SavePetToDB(mode);
+
+ SetMinion(pet, false);
+
+ pet->AddObjectToRemoveList();
+ pet->m_removed = true;
+
+ if(pet->isControlled())
+ {
+ WorldPacket data(SMSG_PET_SPELLS, 8);
+ data << uint64(0);
+ GetSession()->SendPacket(&data);
+
+ if(GetGroup())
+ SetGroupUpdateFlag(GROUP_UPDATE_PET);
+ }
+}
+
+void Player::StopCastingCharm()
+{
+ Unit* charm = GetCharm();
+ if(!charm)
+ return;
+
+ if(charm->GetTypeId() == TYPEID_UNIT)
+ {
+ if(((Creature*)charm)->HasUnitTypeMask(UNIT_MASK_PUPPET))
+ ((Puppet*)charm)->UnSummon();
+ else if(charm->IsVehicle())
+ ExitVehicle();
+ }
+ if(GetCharmGUID())
+ charm->RemoveCharmAuras();
+
+ if(GetCharmGUID())
+ {
+ sLog.outCrash("Player %s (GUID: " UI64FMTD " is not able to uncharm unit (GUID: " UI64FMTD " Entry: %u, Type: %u)", GetName(), GetGUID(), GetCharmGUID(), charm->GetEntry(), charm->GetTypeId());
+ if(charm->GetCharmerGUID())
+ {
+ sLog.outCrash("Charmed unit has charmer guid " UI64FMTD, charm->GetCharmerGUID());
+ assert(false);
+ }
+ else
+ SetCharm(charm, false);
+ }
+}
+
+void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
+{
+ *data << (uint8)msgtype;
+ *data << (uint32)language;
+ *data << (uint64)GetGUID();
+ *data << (uint32)language; //language 2.1.0 ?
+ *data << (uint64)GetGUID();
+ *data << (uint32)(text.length()+1);
+ *data << text;
+ *data << (uint8)chatTag();
+}
+
+void Player::Say(const std::string& text, const uint32 language)
+{
+ WorldPacket data(SMSG_MESSAGECHAT, 200);
+ BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
+ SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
+
+ if(sWorld.getConfig(CONFIG_CHATLOG_PUBLIC))
+ sLog.outChat("[SAY] Player %s says (language %u): %s",
+ GetName(), language, text.c_str());
+}
+
+void Player::Yell(const std::string& text, const uint32 language)
+{
+ WorldPacket data(SMSG_MESSAGECHAT, 200);
+ BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
+ SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
+
+ if(sWorld.getConfig(CONFIG_CHATLOG_PUBLIC))
+ sLog.outChat("[YELL] Player %s yells (language %u): %s",
+ GetName(), language, text.c_str());
+}
+
+void Player::TextEmote(const std::string& text)
+{
+ WorldPacket data(SMSG_MESSAGECHAT, 200);
+ BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
+ SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT));
+
+ if(sWorld.getConfig(CONFIG_CHATLOG_PUBLIC))
+ sLog.outChat("[TEXTEMOTE] Player %s emotes: %s",
+ GetName(), text.c_str());
+}
+
+void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
+{
+ if (language != LANG_ADDON) // if not addon data
+ language = LANG_UNIVERSAL; // whispers should always be readable
+
+ Player *rPlayer = objmgr.GetPlayer(receiver);
+
+ if(sWorld.getConfig(CONFIG_CHATLOG_WHISPER))
+ sLog.outChat("[WHISPER] Player %s tells %s: %s",
+ GetName(), rPlayer->GetName(), text.c_str());
+
+ // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
+ if(!rPlayer->isDND() || isGameMaster())
+ {
+ WorldPacket data(SMSG_MESSAGECHAT, 200);
+ BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
+ rPlayer->GetSession()->SendPacket(&data);
+
+ // not send confirmation for addon messages
+ if (language != LANG_ADDON)
+ {
+ data.Initialize(SMSG_MESSAGECHAT, 200);
+ rPlayer->BuildPlayerChat(&data, CHAT_MSG_WHISPER_INFORM, text, language);
+ GetSession()->SendPacket(&data);
+ }
+ }
+ else
+ {
+ // announce to player that player he is whispering to is dnd and cannot receive his message
+ ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
+ }
+
+ if(!isAcceptWhispers() && !isGameMaster() && !rPlayer->isGameMaster())
+ {
+ SetAcceptWhispers(true);
+ ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
+ }
+
+ // announce to player that player he is whispering to is afk
+ if(rPlayer->isAFK())
+ ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
+
+ // if player whisper someone, auto turn of dnd to be able to receive an answer
+ if(isDND() && !rPlayer->isGameMaster())
+ ToggleDND();
+}
+
+void Player::PetSpellInitialize()
+{
+ Pet* pet = GetPet();
+
+ if(!pet)
+ return;
+
+ sLog.outDebug("Pet Spells Groups");
+
+ CharmInfo *charmInfo = pet->GetCharmInfo();
+
+ WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
+ data << uint64(pet->GetGUID());
+ data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
+ data << uint32(0);
+ data << uint8(pet->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
+
+ // action bar loop
+ charmInfo->BuildActionBar(&data);
+
+ size_t spellsCountPos = data.wpos();
+
+ // spells count
+ uint8 addlist = 0;
+ data << uint8(addlist); // placeholder
+
+ if (pet->IsPermanentPetFor(this))
+ {
+ // spells loop
+ for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
+ {
+ if(itr->second.state == PETSPELL_REMOVED)
+ continue;
+
+ data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first,itr->second.active));
+ ++addlist;
+ }
+ }
+
+ data.put<uint8>(spellsCountPos, addlist);
+
+ uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
+ data << uint8(cooldownsCount);
+
+ time_t curTime = time(NULL);
+
+ for (CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
+ {
+ time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
+
+ data << uint32(itr->first); // spellid
+ data << uint16(0); // spell category?
+ data << uint32(cooldown); // cooldown
+ data << uint32(0); // category cooldown
+ }
+
+ for (CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
+ {
+ time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
+
+ data << uint32(itr->first); // spellid
+ data << uint16(0); // spell category?
+ data << uint32(0); // cooldown
+ data << uint32(cooldown); // category cooldown
+ }
+
+ data.hexlike();
+
+ GetSession()->SendPacket(&data);
+}
+
+void Player::PossessSpellInitialize()
+{
+ Unit* charm = GetCharm();
+ if(!charm)
+ return;
+
+ CharmInfo *charmInfo = charm->GetCharmInfo();
+
+ if(!charmInfo)
+ {
+ sLog.outError("Player::PossessSpellInitialize(): charm ("UI64FMTD") has no charminfo!", charm->GetGUID());
+ return;
+ }
+
+ WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
+ data << uint64(charm->GetGUID());
+ data << uint16(0);
+ data << uint32(0);
+ data << uint32(0);
+
+ charmInfo->BuildActionBar(&data);
+
+ data << uint8(0); // spells count
+ data << uint8(0); // cooldowns count
+
+ GetSession()->SendPacket(&data);
+}
+
+void Player::VehicleSpellInitialize()
+{
+ Creature* veh = GetVehicleCreatureBase();
+ if(!veh)
+ return;
+
+ // GetPosition_ is not a member of 'Vehicle', SetPosition is a member of 'Player': SetPosition(GetVehicle()->GetPositionX(), GetVehicle()->GetPositionY(), GetVehicle()->GetPositionZ(), GetVehicle()->GetOrientation());
+
+ // GetPosition_ is not a member of 'Vehicle', SetPosition is a member of 'Player': SetPosition(GetVehicle()->GetPositionX(), GetVehicle()->GetPositionY(), GetVehicle()->GetPositionZ(), GetVehicle()->GetOrientation());
+
+ WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*10+1+1);
+ data << uint64(veh->GetGUID());
+ data << uint16(0);
+ data << uint32(0);
+ data << uint32(0x00000101);
+
+ for (uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
+ {
+ uint32 spellId = ((Creature*)veh)->m_spells[i];
+ if(!spellId)
+ continue;
+
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
+ if(!spellInfo)
+ continue;
+
+ if(IsPassiveSpell(spellId))
+ {
+ veh->CastSpell(veh, spellId, true);
+ data << uint16(0) << uint8(0) << uint8(i+8);
+ }
+ else
+ data << uint32(MAKE_UNIT_ACTION_BUTTON(spellId,i+8));
+ }
+
+ for (uint32 i = CREATURE_MAX_SPELLS; i < MAX_SPELL_CONTROL_BAR; ++i)
+ data << uint16(0) << uint8(0) << uint8(i+8);
+
+ data << uint8(0);
+ data << uint8(0);
+ GetSession()->SendPacket(&data);
+}
+
+void Player::CharmSpellInitialize()
+{
+ Unit* charm = GetFirstControlled();
+ if(!charm)
+ return;
+
+ CharmInfo *charmInfo = charm->GetCharmInfo();
+ if(!charmInfo)
+ {
+ sLog.outError("Player::CharmSpellInitialize(): the player's charm ("UI64FMTD") has no charminfo!", charm->GetGUID());
+ return;
+ }
+
+ uint8 addlist = 0;
+ if(charm->GetTypeId() != TYPEID_PLAYER)
+ {
+ CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
+ //if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
+ {
+ for (uint32 i = 0; i < MAX_SPELL_CHARM; ++i)
+ {
+ if(charmInfo->GetCharmSpell(i)->GetAction())
+ ++addlist;
+ }
+ }
+ }
+
+ WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1);
+ data << uint64(charm->GetGUID());
+ data << uint16(0);
+ data << uint32(0);
+
+ if(charm->GetTypeId() != TYPEID_PLAYER)
+ data << uint8(((Creature*)charm)->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
+ else
+ data << uint8(0) << uint8(0) << uint16(0);
+
+ charmInfo->BuildActionBar(&data);
+
+ data << uint8(addlist);
+
+ if(addlist)
+ {
+ for (uint32 i = 0; i < MAX_SPELL_CHARM; ++i)
+ {
+ CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
+ if(cspell->GetAction())
+ data << uint32(cspell->packedData);
+ }
+ }
+
+ data << uint8(0); // cooldowns count
+
+ GetSession()->SendPacket(&data);
+}
+
+void Player::SendRemoveControlBar()
+{
+ WorldPacket data(SMSG_PET_SPELLS, 8);
+ data << uint64(0);
+ GetSession()->SendPacket(&data);
+}
+
+bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell * spell)
+{
+ if (!mod || !spellInfo)
+ return false;
+
+ // Mod out of charges
+ if (spell && mod->charges == -1 && spell->m_appliedMods.find(mod->ownerAura) == spell->m_appliedMods.end())
+ return false;
+
+ return spellmgr.IsAffectedByMod(spellInfo, mod);
+}
+
+void Player::AddSpellMod(SpellModifier* mod, bool apply)
+{
+ sLog.outDebug("Player::AddSpellMod %d", mod->spellId);
+ uint16 Opcode = (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
+
+ int i = 0;
+ flag96 _mask = 0;
+ for (int eff = 0; eff < 96; ++eff)
+ {
+ if (eff != 0 && eff%32 == 0)
+ _mask[i++] = 0;
+
+ _mask[i] = uint32(1) << (eff-(32*i));
+ if (mod->mask & _mask)
+ {
+ int32 val = 0;
+ for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
+ {
+ if ((*itr)->type == mod->type && (*itr)->mask & _mask)
+ val += (*itr)->value;
+ }
+ val += apply ? mod->value : -(mod->value);
+ WorldPacket data(Opcode, (1+1+4));
+ data << uint8(eff);
+ data << uint8(mod->op);
+ data << int32(val);
+ SendDirectMessage(&data);
+ }
+ }
+
+ if (apply)
+ m_spellMods[mod->op].push_back(mod);
+ else
+ {
+ m_spellMods[mod->op].remove(mod);
+ // mods bound to aura will be removed in AuraEffect::~AuraEffect
+ if (!mod->ownerAura)
+ delete mod;
+ }
+}
+
+// Restore spellmods in case of failed cast
+void Player::RestoreSpellMods(Spell * spell)
+{
+ if (!spell || spell->m_appliedMods.empty())
+ return;
+
+ for (uint8 i=0; i<MAX_SPELLMOD; ++i)
+ {
+ for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end(); ++itr)
+ {
+ SpellModifier *mod = *itr;
+
+ // spellmods without aura set cannot be charged
+ if (!mod->ownerAura || !mod->ownerAura->GetCharges())
+ continue;
+
+ // check if mod affected this spell
+ Spell::UsedSpellMods::iterator iterMod = spell->m_appliedMods.find(mod->ownerAura);
+ if (iterMod == spell->m_appliedMods.end())
+ continue;
+
+ // remove from list
+ spell->m_appliedMods.erase(iterMod);
+
+ // add mod charges back to mod
+ if (mod->charges == -1)
+ mod->charges = 1;
+ else
+ mod->charges++;
+
+ // Do not set more spellmods than avalible
+ if (mod->ownerAura->GetCharges() < mod->charges)
+ mod->charges = mod->ownerAura->GetCharges();
+
+ // Skip this check for now - aura charges may change due to various reason
+ // TODO: trac these changes correctly
+ //assert (mod->ownerAura->GetCharges() <= mod->charges);
+ }
+ }
+}
+
+void Player::RemoveSpellMods(Spell * spell)
+{
+ if (!spell)
+ return;
+ std::set <Aura *> checkedSpells;
+
+ AuraEffectList const & auraList = GetAuraEffectsByType(SPELL_AURA_ABILITY_IGNORE_AURASTATE);
+ for (AuraEffectList::const_iterator itr = auraList.begin(); itr != auraList.end();)
+ {
+ AuraEffect * aurEff = *itr;
+ Aura * aura = aurEff->GetBase();
+ ++itr;
+ if (!aura->GetCharges())
+ continue;
+
+ SpellEntry const * spellInfo = aura->GetSpellProto();
+
+ if (spellInfo->SpellFamilyName != spell->m_spellInfo->SpellFamilyName ||
+ checkedSpells.find(aura) != checkedSpells.end())
+ continue;
+
+ if (spell->m_spellInfo->SpellFamilyFlags & spellInfo->EffectSpellClassMask[aurEff->GetEffIndex()]
+ // this is for fingers of frost, look at spell::finish part, a charge will be taken by the triggering spell
+ && aura->GetDuration() != aura->GetMaxDuration())
+ {
+ checkedSpells.insert(aura);
+ spell->m_appliedMods.erase(aura);
+ if (aura->DropCharge())
+ itr = auraList.begin();
+ }
+ }
+
+ if (spell->m_appliedMods.empty())
+ return;
+
+ for (uint8 i=0; i<MAX_SPELLMOD; ++i)
+ {
+ for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
+ {
+ SpellModifier *mod = *itr;
+ ++itr;
+
+ // spellmods without aura set cannot be charged
+ if (!mod->ownerAura || !mod->ownerAura->GetCharges())
+ continue;
+
+ // check if mod affected this spell
+ Spell::UsedSpellMods::iterator iterMod = spell->m_appliedMods.find(mod->ownerAura);
+ if (iterMod == spell->m_appliedMods.end())
+ continue;
+
+ // remove from list
+ spell->m_appliedMods.erase(iterMod);
+
+ if (mod->ownerAura->DropCharge())
+ itr = m_spellMods[i].begin();
+ }
+ }
+}
+
+void Player::DropModCharge(SpellModifier * mod, Spell * spell)
+{
+ if (spell && mod->ownerAura && mod->charges > 0 )
+ {
+ --mod->charges;
+ if (mod->charges == 0)
+ {
+ mod->charges = -1;
+ }
+ spell->m_appliedMods.insert(mod->ownerAura);
+ }
+}
+
+void Player::SetSpellModTakingSpell(Spell * spell, bool apply)
+{
+ if (!spell || (m_spellModTakingSpell && m_spellModTakingSpell != spell))
+ return;
+
+ if (apply && spell->getState() == SPELL_STATE_FINISHED)
+ return;
+
+ m_spellModTakingSpell = apply ? spell : NULL;
+}
+
+// send Proficiency
+void Player::SendProficiency(uint8 pr1, uint32 pr2)
+{
+ WorldPacket data(SMSG_SET_PROFICIENCY, 8);
+ data << pr1 << pr2;
+ GetSession()->SendPacket (&data);
+}
+
+void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
+{
+ QueryResult_AutoPtr result = QueryResult_AutoPtr(NULL);
+ if(type==10)
+ result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
+ else
+ result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
+ if(result)
+ {
+ 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.
+ { // and SendPetitionQueryOpcode reads data from the DB
+ Field *fields = result->Fetch();
+ uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
+ uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
+
+ // send update if charter owner in game
+ Player* owner = objmgr.GetPlayer(ownerguid);
+ if(owner)
+ owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
+
+ } while ( result->NextRow() );
+
+ if(type==10)
+ CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
+ else
+ CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
+ }
+
+ CharacterDatabase.BeginTransaction();
+ if(type == 10)
+ {
+ CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
+ CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
+ }
+ else
+ {
+ CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
+ CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
+ }
+ CharacterDatabase.CommitTransaction();
+}
+
+void Player::LeaveAllArenaTeams(uint64 guid)
+{
+ QueryResult_AutoPtr 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));
+ if(!result)
+ return;
+
+ do
+ {
+ Field *fields = result->Fetch();
+ uint32 at_id = fields[0].GetUInt32();
+ if(at_id != 0)
+ {
+ ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
+ if(at)
+ at->DelMember(guid);
+ }
+ } while (result->NextRow());
+}
+
+void Player::SetRestBonus (float rest_bonus_new)
+{
+ // Prevent resting on max level
+ if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
+ rest_bonus_new = 0;
+
+ if(rest_bonus_new < 0)
+ rest_bonus_new = 0;
+
+ float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
+
+ if(rest_bonus_new > rest_bonus_max)
+ m_rest_bonus = rest_bonus_max;
+ else
+ m_rest_bonus = rest_bonus_new;
+
+ // update data for client
+ if(m_rest_bonus>10)
+ SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
+ else if(m_rest_bonus<=1)
+ SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
+
+ //RestTickUpdate
+ SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
+}
+
+void Player::HandleStealthedUnitsDetection()
+{
+ std::list<Unit*> stealthedUnits;
+ Trinity::AnyStealthedCheck u_check;
+ Trinity::UnitListSearcher<Trinity::AnyStealthedCheck > searcher(this, stealthedUnits, u_check);
+ VisitNearbyObject(GetMap()->GetVisibilityDistance(), searcher);
+
+ for (std::list<Unit*>::const_iterator i = stealthedUnits.begin(); i != stealthedUnits.end(); ++i)
+ {
+ if((*i)==this)
+ continue;
+
+ bool hasAtClient = HaveAtClient((*i));
+ bool hasDetected = canSeeOrDetect(*i, true);
+
+ if (hasDetected)
+ {
+ if(!hasAtClient)
+ {
+ (*i)->SendUpdateToPlayer(this);
+ m_clientGUIDs.insert((*i)->GetGUID());
+
+ #ifdef TRINITY_DEBUG
+ if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
+ sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
+ #endif
+
+ // target aura duration for caster show only if target exist at caster client
+ // send data at target visibility change (adding to client)
+ SendInitialVisiblePackets(*i);
+ }
+ }
+ else
+ {
+ if(hasAtClient)
+ {
+ (*i)->DestroyForPlayer(this);
+ m_clientGUIDs.erase((*i)->GetGUID());
+ }
+ }
+ }
+}
+
+bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
+{
+ if(nodes.size() < 2)
+ return false;
+
+ // not let cheating with start flight in time of logout process || while in combat || has type state: stunned || has type state: root
+ if(GetSession()->isLogingOut() || isInCombat() || hasUnitState(UNIT_STAT_STUNNED) || hasUnitState(UNIT_STAT_ROOT))
+ {
+ WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
+ data << uint32(ERR_TAXIPLAYERBUSY);
+ GetSession()->SendPacket(&data);
+ return false;
+ }
+
+ if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
+ return false;
+
+ // taximaster case
+ if(npc)
+ {
+ // not let cheating with start flight mounted
+ if(IsMounted())
+ {
+ WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
+ data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
+ GetSession()->SendPacket(&data);
+ return false;
+ }
+
+ if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
+ {
+ WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
+ data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
+ GetSession()->SendPacket(&data);
+ return false;
+ }
+
+ // 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
+ if(IsNonMeleeSpellCasted(false))
+ {
+ WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
+ data << uint32(ERR_TAXIPLAYERBUSY);
+ GetSession()->SendPacket(&data);
+ return false;
+ }
+ }
+ // cast case or scripted call case
+ else
+ {
+ RemoveAurasByType(SPELL_AURA_MOUNTED);
+
+ if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
+ RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
+
+ if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
+ if (spell->m_spellInfo->Id != spellid)
+ InterruptSpell(CURRENT_GENERIC_SPELL,false);
+
+ InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false);
+
+ if (Spell* spell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
+ if (spell->m_spellInfo->Id != spellid)
+ InterruptSpell(CURRENT_CHANNELED_SPELL,true);
+ }
+
+ uint32 sourcenode = nodes[0];
+
+ // starting node too far away (cheat?)
+ TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
+ if (!node)
+ {
+ WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
+ data << uint32(ERR_TAXINOSUCHPATH);
+ GetSession()->SendPacket(&data);
+ return false;
+ }
+
+ // check node starting pos data set case if provided
+ if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
+ {
+ if (node->map_id != GetMapId() ||
+ (node->x - GetPositionX())*(node->x - GetPositionX())+
+ (node->y - GetPositionY())*(node->y - GetPositionY())+
+ (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
+ (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
+ {
+ WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
+ data << uint32(ERR_TAXITOOFARAWAY);
+ GetSession()->SendPacket(&data);
+ return false;
+ }
+ }
+ // node must have pos if taxi master case (npc != NULL)
+ else if (npc)
+ {
+ WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
+ data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
+ GetSession()->SendPacket(&data);
+ return false;
+ }
+
+ // Prepare to flight start now
+
+ // stop combat at start taxi flight if any
+ CombatStop();
+
+ StopCastingCharm();
+ StopCastingBindSight();
+ ExitVehicle();
+
+ // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
+ TradeCancel(true);
+
+ // clean not finished taxi path if any
+ m_taxi.ClearTaxiDestinations();
+
+ // 0 element current node
+ m_taxi.AddTaxiDestination(sourcenode);
+
+ // fill destinations path tail
+ uint32 sourcepath = 0;
+ uint32 totalcost = 0;
+
+ uint32 prevnode = sourcenode;
+ uint32 lastnode = 0;
+
+ for (uint32 i = 1; i < nodes.size(); ++i)
+ {
+ uint32 path, cost;
+
+ lastnode = nodes[i];
+ objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
+
+ if(!path)
+ {
+ m_taxi.ClearTaxiDestinations();
+ return false;
+ }
+
+ totalcost += cost;
+
+ if(prevnode == sourcenode)
+ sourcepath = path;
+
+ m_taxi.AddTaxiDestination(lastnode);
+
+ prevnode = lastnode;
+ }
+
+ // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
+ //
+ // Hack-Fix for Alliance not being able to use Acherus taxi. There is
+ // only one mount ID for both sides. Probably not good to use 315 in case DBC nodes
+ // change but I couldn't find a suitable alternative. OK to use class because only DK
+ // can use this taxi.
+ uint32 mount_display_id = objmgr.GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL || (sourcenode == 315 && getClass() == CLASS_DEATH_KNIGHT));
+
+ // in spell case allow 0 model
+ if ((mount_display_id == 0 && spellid == 0) || sourcepath == 0)
+ {
+ WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
+ data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
+ GetSession()->SendPacket(&data);
+ m_taxi.ClearTaxiDestinations();
+ return false;
+ }
+
+ uint32 money = GetMoney();
+
+ if (npc)
+ totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
+
+ if(money < totalcost)
+ {
+ WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
+ data << uint32(ERR_TAXINOTENOUGHMONEY);
+ GetSession()->SendPacket(&data);
+ m_taxi.ClearTaxiDestinations();
+ return false;
+ }
+
+ //Checks and preparations done, DO FLIGHT
+ ModifyMoney(-(int32)totalcost);
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
+
+ // prevent stealth flight
+ //RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TALK);
+
+ if (sWorld.getConfig(CONFIG_INSTANT_TAXI))
+ {
+ TaxiNodesEntry const* lastnode = sTaxiNodesStore.LookupEntry(nodes[nodes.size()-1]);
+ m_taxi.ClearTaxiDestinations();
+ TeleportTo(lastnode->map_id, lastnode->x, lastnode->y, lastnode->z, GetOrientation());
+ return false;
+ }
+ else
+ {
+ WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
+ data << uint32(ERR_TAXIOK);
+ GetSession()->SendPacket(&data);
+ sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
+ GetSession()->SendDoFlight(mount_display_id, sourcepath);
+ }
+ return true;
+}
+
+bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ )
+{
+ TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
+ if(!entry)
+ return false;
+
+ std::vector<uint32> nodes;
+
+ nodes.resize(2);
+ nodes[0] = entry->from;
+ nodes[1] = entry->to;
+
+ return ActivateTaxiPathTo(nodes,NULL,spellid);
+}
+
+void Player::CleanupAfterTaxiFlight()
+{
+ m_taxi.ClearTaxiDestinations(); // not destinations, clear source node
+ Unmount();
+ RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_TAXI_FLIGHT);
+ getHostilRefManager().setOnlineOfflineState(true);
+}
+
+void Player::ContinueTaxiFlight()
+{
+ uint32 sourceNode = m_taxi.GetTaxiSource();
+ if (!sourceNode)
+ return;
+
+ sLog.outDebug( "WORLD: Restart character %u taxi flight", GetGUIDLow() );
+
+ uint32 mountDisplayId = objmgr.GetTaxiMountDisplayId(sourceNode, GetTeam(),true);
+ uint32 path = m_taxi.GetCurrentTaxiPath();
+
+ // search appropriate start path node
+ uint32 startNode = 0;
+
+ TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];
+
+ float distPrev = MAP_SIZE*MAP_SIZE;
+ float distNext =
+ (nodeList[0].x-GetPositionX())*(nodeList[0].x-GetPositionX())+
+ (nodeList[0].y-GetPositionY())*(nodeList[0].y-GetPositionY())+
+ (nodeList[0].z-GetPositionZ())*(nodeList[0].z-GetPositionZ());
+
+ for (uint32 i = 1; i < nodeList.size(); ++i)
+ {
+ TaxiPathNode const& node = nodeList[i];
+ TaxiPathNode const& prevNode = nodeList[i-1];
+
+ // skip nodes at another map
+ if(node.mapid != GetMapId())
+ continue;
+
+ distPrev = distNext;
+
+ distNext =
+ (node.x-GetPositionX())*(node.x-GetPositionX())+
+ (node.y-GetPositionY())*(node.y-GetPositionY())+
+ (node.z-GetPositionZ())*(node.z-GetPositionZ());
+
+ float distNodes =
+ (node.x-prevNode.x)*(node.x-prevNode.x)+
+ (node.y-prevNode.y)*(node.y-prevNode.y)+
+ (node.z-prevNode.z)*(node.z-prevNode.z);
+
+ if(distNext + distPrev < distNodes)
+ {
+ startNode = i;
+ break;
+ }
+ }
+
+ GetSession()->SendDoFlight(mountDisplayId, path, startNode);
+}
+
+void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
+{
+ // last check 2.0.10
+ WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
+ data << GetGUID();
+ data << uint8(0x0); // flags (0x1, 0x2)
+ time_t curTime = time(NULL);
+ for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
+ {
+ if (itr->second->state == PLAYERSPELL_REMOVED)
+ continue;
+ uint32 unSpellId = itr->first;
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
+ if (!spellInfo)
+ {
+ ASSERT(spellInfo);
+ continue;
+ }
+
+ // Not send cooldown for this spells
+ if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
+ continue;
+
+ if(spellInfo->PreventionType != SPELL_PREVENTION_TYPE_SILENCE)
+ continue;
+
+ if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
+ {
+ data << uint32(unSpellId);
+ data << uint32(unTimeMs); // in m.secs
+ AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
+ }
+ }
+ GetSession()->SendPacket(&data);
+}
+
+void Player::InitDataForForm(bool reapplyMods)
+{
+ SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
+ if(ssEntry && ssEntry->attackSpeed)
+ {
+ SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
+ SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
+ SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
+ }
+ else
+ SetRegularAttackTime();
+
+ switch(m_form)
+ {
+ case FORM_GHOUL:
+ case FORM_CAT:
+ {
+ if(getPowerType()!=POWER_ENERGY)
+ setPowerType(POWER_ENERGY);
+ break;
+ }
+ case FORM_BEAR:
+ case FORM_DIREBEAR:
+ {
+ if(getPowerType()!=POWER_RAGE)
+ setPowerType(POWER_RAGE);
+ break;
+ }
+ default: // 0, for example
+ {
+ ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
+ if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
+ setPowerType(Powers(cEntry->powerType));
+ break;
+ }
+ }
+
+ // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
+ if (!reapplyMods)
+ UpdateEquipSpellsAtFormChange();
+
+ UpdateAttackPowerAndDamage();
+ UpdateAttackPowerAndDamage(true);
+}
+
+void Player::InitDisplayIds()
+{
+ PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
+ if(!info)
+ {
+ sLog.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
+ return;
+ }
+
+ uint8 gender = getGender();
+ switch(gender)
+ {
+ case GENDER_FEMALE:
+ SetDisplayId(info->displayId_f );
+ SetNativeDisplayId(info->displayId_f );
+ break;
+ case GENDER_MALE:
+ SetDisplayId(info->displayId_m );
+ SetNativeDisplayId(info->displayId_m );
+ break;
+ default:
+ sLog.outError("Invalid gender %u for player",gender);
+ return;
+ }
+}
+
+// Return true is the bought item has a max count to force refresh of window by caller
+bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint8 bag, uint8 slot)
+{
+ // cheating attempt
+ if (count < 1) count = 1;
+
+ // cheating attempt
+ if(slot > MAX_BAG_SIZE && slot !=NULL_SLOT)
+ return false;
+
+ if (!isAlive())
+ return false;
+
+ ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
+ if (!pProto)
+ {
+ SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
+ return false;
+ }
+
+ Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
+ if (!pCreature)
+ {
+ sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
+ SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
+ return false;
+ }
+
+ VendorItemData const* vItems = pCreature->GetVendorItems();
+ if(!vItems || vItems->Empty())
+ {
+ SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
+ return false;
+ }
+
+ size_t vendor_slot = vItems->FindItemSlot(item);
+ if (vendor_slot >= vItems->GetItemCount())
+ {
+ SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
+ return false;
+ }
+
+ VendorItem const* crItem = vItems->m_items[vendor_slot];
+
+ // check current item amount if it limited
+ if (crItem->maxcount != 0)
+ {
+ if (pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
+ {
+ SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
+ return false;
+ }
+ }
+
+ if (pProto->RequiredReputationFaction && (uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank))
+ {
+ SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
+ return false;
+ }
+ else if (!pProto->RequiredReputationFaction && pProto->RequiredReputationRank > 0)
+ {
+ if (uint32(GetReputationRank(pCreature->getFactionTemplateEntry()->faction)) < pProto->RequiredReputationRank)
+ {
+ SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
+ return false;
+ }
+ }
+
+ if (crItem->ExtendedCost)
+ {
+ ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
+ if (!iece)
+ {
+ sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
+ return false;
+ }
+
+ // honor points price
+ if (GetHonorPoints() < (iece->reqhonorpoints * count))
+ {
+ SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
+ return false;
+ }
+
+ // arena points price
+ if (GetArenaPoints() < (iece->reqarenapoints * count))
+ {
+ SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
+ return false;
+ }
+
+ // item base price
+ for (uint8 i = 0; i < 5; ++i)
+ {
+ if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
+ {
+ SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
+ return false;
+ }
+ }
+
+ // check for personal arena rating requirement
+ if( GetMaxPersonalArenaRatingRequirement(iece->reqarenaslot) < iece->reqpersonalarenarating )
+ {
+ // probably not the proper equip err
+ SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
+ return false;
+ }
+ }
+
+ int32 price = pProto->BuyPrice * count;
+
+ // reputation discount
+ price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
+
+ if (GetMoney() < price)
+ {
+ SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
+ return false;
+ }
+
+ if ((bag == NULL_BAG && slot == NULL_SLOT) || IsInventoryPos(bag, slot))
+ {
+ ItemPosCountVec dest;
+ uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
+ if (msg != EQUIP_ERR_OK)
+ {
+ SendEquipError( msg, NULL, NULL );
+ return false;
+ }
+
+ ModifyMoney( -(int32)price );
+ uint32 arenaPoints = 0;
+ uint32 honorPoints = 0;
+ uint32 extendedCost[5] = {0,0,0,0,0};
+ uint32 extendedCostCount[5] = {0,0,0,0,0};
+
+ if (crItem->ExtendedCost) // case for new honor system
+ {
+ ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
+ if (iece->reqhonorpoints)
+ {
+ honorPoints = iece->reqhonorpoints * count;
+ ModifyHonorPoints( - int32(honorPoints) );
+ }
+ if (iece->reqarenapoints)
+ {
+ arenaPoints = iece->reqarenapoints * count;
+ ModifyArenaPoints( - int32(arenaPoints) );
+ }
+ for (uint8 i = 0; i < 5; ++i)
+ {
+ if (iece->reqitem[i])
+ {
+ DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
+ extendedCost[i] = iece->reqitem[i];
+ extendedCostCount[i] = iece->reqitemcount[i];
+ }
+ }
+ }
+
+ if (Item *it = StoreNewItem( dest, item, true ))
+ {
+ uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
+
+ WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
+ data << uint64(pCreature->GetGUID());
+ data << uint32(vendor_slot+1); // numbered from 1 at client
+ data << int32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
+ data << uint32(count);
+ GetSession()->SendPacket(&data);
+ SendNewItem(it, pProto->BuyCount*count, true, false, false);
+
+ // Item Refund system, only works for non stackable items with extendedcost
+ if(count == 1 && crItem->ExtendedCost )
+ {
+ it->SetPaidArenaPoints(arenaPoints);
+ it->SetPaidHonorPoints(honorPoints);
+ it->SetRefundExpiryTime( time(NULL)+(HOUR*2) );
+ for (uint8 i = 0; i < 5; ++i)
+ it->SetPaidExtendedCost(i, extendedCost[i], extendedCostCount[i]);
+ }
+ }
+ }
+ else if (IsEquipmentPos(bag, slot))
+ {
+ if (pProto->BuyCount * count != 1)
+ {
+ SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
+ return false;
+ }
+
+ uint16 dest;
+ uint8 msg = CanEquipNewItem( slot, dest, item, false );
+ if (msg != EQUIP_ERR_OK)
+ {
+ SendEquipError( msg, NULL, NULL );
+ return false;
+ }
+
+ ModifyMoney( -(int32)price );
+ if (crItem->ExtendedCost) // case for new honor system
+ {
+ ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
+ if (iece->reqhonorpoints)
+ ModifyHonorPoints( - int32(iece->reqhonorpoints));
+ if (iece->reqarenapoints)
+ ModifyArenaPoints( - int32(iece->reqarenapoints));
+ for (uint8 i = 0; i < 5; ++i)
+ {
+ if(iece->reqitem[i])
+ DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
+ }
+ }
+
+ if (Item *it = EquipNewItem( dest, item, true ))
+ {
+ uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
+
+ WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
+ data << uint64(pCreature->GetGUID());
+ data << uint32(vendor_slot + 1); // numbered from 1 at client
+ data << int32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
+ data << uint32(count);
+ GetSession()->SendPacket(&data);
+
+ SendNewItem(it, pProto->BuyCount*count, true, false, false);
+
+ AutoUnequipOffhandIfNeed();
+ }
+ }
+ else
+ {
+ SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
+ return false;
+ }
+
+ return crItem->maxcount != 0;
+}
+
+uint32 Player::GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot)
+{
+ // returns the maximal personal arena rating that can be used to purchase items requiring this condition
+ // the personal rating of the arena team must match the required limit as well
+ // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
+ uint32 max_personal_rating = 0;
+ for (uint8 i = minarenaslot; i < MAX_ARENA_SLOT; ++i)
+ {
+ if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
+ {
+ uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * ARENA_TEAM_END) + ARENA_TEAM_PERSONAL_RATING);
+ uint32 t_rating = at->GetRating();
+ p_rating = p_rating < t_rating ? p_rating : t_rating;
+ if(max_personal_rating < p_rating)
+ max_personal_rating = p_rating;
+ }
+ }
+ return max_personal_rating;
+}
+
+void Player::UpdateHomebindTime(uint32 time)
+{
+ // GMs never get homebind timer online
+ if (m_InstanceValid || isGameMaster())
+ {
+ if(m_HomebindTimer) // instance valid, but timer not reset
+ {
+ // hide reminder
+ WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
+ data << uint32(0);
+ data << uint32(0);
+ GetSession()->SendPacket(&data);
+ }
+ // instance is valid, reset homebind timer
+ m_HomebindTimer = 0;
+ }
+ else if (m_HomebindTimer > 0)
+ {
+ if (time >= m_HomebindTimer)
+ {
+ // teleport to nearest graveyard
+ SetPhaseMask(1,true);
+ RepopAtGraveyard();
+ }
+ else
+ m_HomebindTimer -= time;
+ }
+ else
+ {
+ // instance is invalid, start homebind timer
+ m_HomebindTimer = 60000;
+ // send message to player
+ WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
+ data << uint32(m_HomebindTimer);
+ data << uint32(1);
+ GetSession()->SendPacket(&data);
+ sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
+ SetPhaseMask(2,true);
+ }
+}
+
+void Player::UpdatePvPState(bool onlyFFA)
+{
+ // TODO: should we always synchronize UNIT_FIELD_BYTES_2, 1 of controller and controlled?
+ if(!pvpInfo.inNoPvPArea && !isGameMaster()
+ && (pvpInfo.inFFAPvPArea || sWorld.IsFFAPvPRealm()))
+ {
+ if(!HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
+ {
+ SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
+ for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
+ (*itr)->SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
+ }
+ }
+ else if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
+ {
+ RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
+ for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
+ (*itr)->RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
+ }
+
+ if(onlyFFA)
+ return;
+
+ if(pvpInfo.inHostileArea) // in hostile area
+ {
+ if(!IsPvP() || pvpInfo.endTimer != 0)
+ UpdatePvP(true, true);
+ }
+ else // in friendly area
+ {
+ if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
+ pvpInfo.endTimer = time(0); // start toggle-off
+ }
+}
+
+void Player::UpdatePvP(bool state, bool override)
+{
+ if(!state || override)
+ {
+ SetPvP(state);
+ pvpInfo.endTimer = 0;
+ }
+ else
+ {
+ if(pvpInfo.endTimer != 0)
+ pvpInfo.endTimer = time(NULL);
+ else
+ SetPvP(state);
+ }
+}
+
+void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
+{
+ // init cooldown values
+ uint32 cat = 0;
+ int32 rec = -1;
+ int32 catrec = -1;
+
+ // some special item spells without correct cooldown in SpellInfo
+ // cooldown information stored in item prototype
+ // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
+
+ if(itemId)
+ {
+ if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
+ {
+ for (uint8 idx = 0; idx < 5; ++idx)
+ {
+ if(proto->Spells[idx].SpellId == spellInfo->Id)
+ {
+ cat = proto->Spells[idx].SpellCategory;
+ rec = proto->Spells[idx].SpellCooldown;
+ catrec = proto->Spells[idx].SpellCategoryCooldown;
+ break;
+ }
+ }
+ }
+ }
+
+ // if no cooldown found above then base at DBC data
+ if(rec < 0 && catrec < 0)
+ {
+ cat = spellInfo->Category;
+ rec = spellInfo->RecoveryTime;
+ catrec = spellInfo->CategoryRecoveryTime;
+ }
+
+ time_t curTime = time(NULL);
+
+ time_t catrecTime;
+ time_t recTime;
+
+ // overwrite time for selected category
+ if(infinityCooldown)
+ {
+ // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
+ // but not allow ignore until reset or re-login
+ catrecTime = catrec > 0 ? curTime+infinityCooldownDelay : 0;
+ recTime = rec > 0 ? curTime+infinityCooldownDelay : catrecTime;
+ }
+ else
+ {
+ // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
+ // prevent 0 cooldowns set by another way
+ if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != 75))
+ rec = GetAttackTime(RANGED_ATTACK);
+
+ // Now we have cooldown data (if found any), time to apply mods
+ if(rec > 0)
+ ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
+
+ if(catrec > 0)
+ ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
+
+ // replace negative cooldowns by 0
+ if (rec < 0) rec = 0;
+ if (catrec < 0) catrec = 0;
+
+ // no cooldown after applying spell mods
+ if( rec == 0 && catrec == 0)
+ return;
+
+ catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
+ recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
+ }
+
+ // self spell cooldown
+ if(recTime > 0)
+ AddSpellCooldown(spellInfo->Id, itemId, recTime);
+
+ // category spells
+ if (cat && catrec > 0)
+ {
+ SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
+ if(i_scstore != sSpellCategoryStore.end())
+ {
+ for (SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
+ {
+ if(*i_scset == spellInfo->Id) // skip main spell, already handled above
+ continue;
+
+ AddSpellCooldown(*i_scset, itemId, catrecTime);
+ }
+ }
+ }
+}
+
+void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
+{
+ SpellCooldown sc;
+ sc.end = end_time;
+ sc.itemid = itemid;
+ m_spellCooldowns[spellid] = sc;
+}
+
+void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
+{
+ // start cooldowns at server side, if any
+ AddSpellAndCategoryCooldowns(spellInfo,itemId,spell);
+
+ // Send activate cooldown timer (possible 0) at client side
+ WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
+ data << uint32(spellInfo->Id);
+ data << uint64(GetGUID());
+ SendDirectMessage(&data);
+}
+
+void Player::UpdatePotionCooldown(Spell* spell)
+{
+ // no potion used i combat or still in combat
+ if(!m_lastPotionId || isInCombat())
+ return;
+
+ // Call not from spell cast, send cooldown event for item spells if no in combat
+ if(!spell)
+ {
+ // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
+ if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
+ for (uint8 idx = 0; idx < 5; ++idx)
+ if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
+ if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
+ SendCooldownEvent(spellInfo,m_lastPotionId);
+ }
+ // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
+ else
+ SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
+
+ m_lastPotionId = 0;
+}
+
+ //slot to be excluded while counting
+bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
+{
+ if(!enchantmentcondition)
+ return true;
+
+ SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
+
+ if(!Condition)
+ return true;
+
+ uint8 curcount[4] = {0, 0, 0, 0};
+
+ //counting current equipped gem colors
+ for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
+ {
+ if (i == slot)
+ continue;
+ Item *pItem2 = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
+ if (pItem2 && !pItem2->IsBroken() && pItem2->GetProto()->Socket[0].Color)
+ {
+ for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
+ {
+ uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
+ if(!enchant_id)
+ continue;
+
+ SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
+ if(!enchantEntry)
+ continue;
+
+ uint32 gemid = enchantEntry->GemID;
+ if(!gemid)
+ continue;
+
+ ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
+ if(!gemProto)
+ continue;
+
+ GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
+ if(!gemProperty)
+ continue;
+
+ uint8 GemColor = gemProperty->color;
+
+ for (uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
+ {
+ if(tmpcolormask & GemColor)
+ ++curcount[b];
+ }
+ }
+ }
+ }
+
+ bool activate = true;
+
+ for (uint8 i = 0; i < 5; i++)
+ {
+ if(!Condition->Color[i])
+ continue;
+
+ uint32 _cur_gem = curcount[Condition->Color[i] - 1];
+
+ // if have <CompareColor> use them as count, else use <value> from Condition
+ uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
+
+ switch(Condition->Comparator[i])
+ {
+ case 2: // requires less <color> than (<value> || <comparecolor>) gems
+ activate &= (_cur_gem < _cmp_gem) ? true : false;
+ break;
+ case 3: // requires more <color> than (<value> || <comparecolor>) gems
+ activate &= (_cur_gem > _cmp_gem) ? true : false;
+ break;
+ case 5: // requires at least <color> than (<value> || <comparecolor>) gems
+ activate &= (_cur_gem >= _cmp_gem) ? true : false;
+ break;
+ }
+ }
+
+ 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");
+
+ return activate;
+}
+
+void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
+{
+ //cycle all equipped items
+ for (uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
+ {
+ //enchants for the slot being socketed are handled by Player::ApplyItemMods
+ if(slot == exceptslot)
+ continue;
+
+ Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
+
+ if(!pItem || !pItem->GetProto()->Socket[0].Color)
+ continue;
+
+ for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
+ {
+ uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
+ if(!enchant_id)
+ continue;
+
+ SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
+ if(!enchantEntry)
+ continue;
+
+ uint32 condition = enchantEntry->EnchantmentCondition;
+ if(condition)
+ {
+ //was enchant active with/without item?
+ bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
+ //should it now be?
+ if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
+ {
+ // ignore item gem conditions
+ //if state changed, (dis)apply enchant
+ ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
+ }
+ }
+ }
+ }
+}
+
+ //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
+void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
+{
+ //cycle all equipped items
+ for (int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
+ {
+ //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
+ if(slot == exceptslot)
+ continue;
+
+ Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
+
+ if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
+ continue;
+
+ //cycle all (gem)enchants
+ for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
+ {
+ uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
+ if(!enchant_id) //if no enchant go to next enchant(slot)
+ continue;
+
+ SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
+ if(!enchantEntry)
+ continue;
+
+ //only metagems to be (de)activated, so only enchants with condition
+ uint32 condition = enchantEntry->EnchantmentCondition;
+ if(condition)
+ ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
+ }
+ }
+}
+
+void Player::SetBattleGroundEntryPoint()
+{
+ // Taxi path store
+ if (!m_taxi.empty())
+ {
+ m_bgData.mountSpell = 0;
+ m_bgData.taxiPath[0] = m_taxi.GetTaxiSource();
+ m_bgData.taxiPath[1] = m_taxi.GetTaxiDestination();
+
+ // On taxi we don't need check for dungeon
+ m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
+ return;
+ }
+ else
+ {
+ m_bgData.ClearTaxiPath();
+
+ // Mount spell id storing
+ if (IsMounted())
+ {
+ AuraEffectList const& auras = GetAuraEffectsByType(SPELL_AURA_MOUNTED);
+ if (!auras.empty())
+ m_bgData.mountSpell = (*auras.begin())->GetId();
+ }
+ else
+ m_bgData.mountSpell = 0;
+
+ // If map is dungeon find linked graveyard
+ if(GetMap()->IsDungeon())
+ {
+ if (const WorldSafeLocsEntry* entry = objmgr.GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
+ {
+ m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f);
+ return;
+ }
+ else
+ sLog.outError("SetBattleGroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId());
+ }
+ // If new entry point is not BG or arena set it
+ else if (!GetMap()->IsBattleGroundOrArena())
+ {
+ m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
+ return;
+ }
+ }
+
+ // In error cases use homebind position
+ m_bgData.joinPos = WorldLocation(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, 0.0f);
+}
+
+void Player::LeaveBattleground(bool teleportToEntryPoint)
+{
+ if(BattleGround *bg = GetBattleGround())
+ {
+ bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
+
+ // call after remove to be sure that player resurrected for correct cast
+ if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) )
+ {
+ if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
+ {
+ //lets check if player was teleported from BG and schedule delayed Deserter spell cast
+ if(IsBeingTeleportedFar())
+ {
+ ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER);
+ return;
+ }
+
+ CastSpell(this, 26013, true); // Deserter
+ }
+ }
+ }
+}
+
+bool Player::CanJoinToBattleground() const
+{
+ // check Deserter debuff
+ if (HasAura(26013))
+ return false;
+
+ return true;
+}
+
+bool Player::CanReportAfkDueToLimit()
+{
+ // a player can complain about 15 people per 5 minutes
+ if(m_bgData.bgAfkReportedCount++ >= 15)
+ return false;
+
+ return true;
+}
+
+///This player has been blamed to be inactive in a battleground
+void Player::ReportedAfkBy(Player* reporter)
+{
+ BattleGround *bg = GetBattleGround();
+ if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
+ return;
+
+ // check if player has 'Idle' or 'Inactive' debuff
+ if(m_bgData.bgAfkReporter.find(reporter->GetGUIDLow())==m_bgData.bgAfkReporter.end() && !HasAura(43680) && !HasAura(43681) && reporter->CanReportAfkDueToLimit())
+ {
+ m_bgData.bgAfkReporter.insert(reporter->GetGUIDLow());
+ // 3 players have to complain to apply debuff
+ if(m_bgData.bgAfkReporter.size() >= 3)
+ {
+ // cast 'Idle' spell
+ CastSpell(this, 43680, true);
+ m_bgData.bgAfkReporter.clear();
+ }
+ }
+}
+
+WorldLocation Player::GetStartPosition() const
+{
+ PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
+ uint32 mapId = info->mapId;
+ if (getClass() == CLASS_DEATH_KNIGHT && HasSpell(50977))
+ mapId = 0;
+ return WorldLocation(mapId, info->positionX, info->positionY, info->positionZ, 0);
+}
+
+bool Player::canSeeOrDetect(Unit const* u, bool detect, bool inVisibleList, bool is3dDistance) const
+{
+ // Always can see self
+ if (m_mover == u || this == u)
+ return true;
+
+ // phased visibility (both must phased in same way)
+ if(!InSamePhase(u))
+ return false;
+
+ // player visible for other player if not logout and at same transport
+ // including case when player is out of world
+ bool at_same_transport =
+ GetTransport() && u->GetTypeId() == TYPEID_PLAYER
+ && !GetSession()->PlayerLogout() && !((Player*)u)->GetSession()->PlayerLogout()
+ && !GetSession()->PlayerLoading() && !((Player*)u)->GetSession()->PlayerLoading()
+ && GetTransport() == ((Player*)u)->GetTransport();
+
+ // not in world
+ if(!at_same_transport && (!IsInWorld() || !u->IsInWorld()))
+ return false;
+
+ // forbidden to seen (at GM respawn command)
+ //if(u->GetVisibility() == VISIBILITY_RESPAWN)
+ // return false;
+
+ Map& _map = *u->GetMap();
+ // Grid dead/alive checks
+ // non visible at grid for any stealth state
+ if(!u->IsVisibleInGridForPlayer(this))
+ return false;
+
+ // always seen by owner
+ if(uint64 guid = u->GetCharmerOrOwnerGUID())
+ if(GetGUID() == guid)
+ return true;
+
+ if(uint64 guid = GetUInt64Value(PLAYER_FARSIGHT))
+ if(u->GetGUID() == guid)
+ return true;
+
+ // different visible distance checks
+ if(isInFlight()) // what see player in flight
+ {
+ if (!m_seer->IsWithinDistInMap(u, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
+ return false;
+ }
+ else if(!u->isAlive()) // distance for show body
+ {
+ if (!m_seer->IsWithinDistInMap(u, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
+ return false;
+ }
+ else if(u->GetTypeId() == TYPEID_PLAYER) // distance for show player
+ {
+ // Players far than max visible distance for player or not in our map are not visible too
+ if (!at_same_transport && !m_seer->IsWithinDistInMap(u, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
+ return false;
+ }
+ else if(u->GetCharmerOrOwnerGUID()) // distance for show pet/charmed
+ {
+ // Pet/charmed far than max visible distance for player or not in our map are not visible too
+ if (!m_seer->IsWithinDistInMap(u, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
+ return false;
+ }
+ else // distance for show creature
+ {
+ // Units farther than max visible distance for creature or not in our map are not visible too
+ if (!m_seer->IsWithinDistInMap(u
+ , u->isActiveObject() ? (MAX_VISIBILITY_DISTANCE - (inVisibleList ? 0.0f : World::GetVisibleUnitGreyDistance()))
+ : (_map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f))
+ , is3dDistance))
+ return false;
+ }
+
+ if(u->GetVisibility() == VISIBILITY_OFF)
+ {
+ // GMs see any players, not higher GMs and all units
+ if(isGameMaster())
+ {
+ if(u->GetTypeId() == TYPEID_PLAYER)
+ return ((Player *)u)->GetSession()->GetSecurity() <= GetSession()->GetSecurity();
+ else
+ return true;
+ }
+ return false;
+ }
+
+ // GM's can see everyone with invisibilitymask with less or equal security level
+ if(m_mover->m_invisibilityMask || u->m_invisibilityMask)
+ {
+ if(isGameMaster())
+ {
+ if(u->GetTypeId() == TYPEID_PLAYER)
+ return ((Player*)u)->GetSession()->GetSecurity() <= GetSession()->GetSecurity();
+ else
+ return true;
+ }
+
+ // player see other player with stealth/invisibility only if he in same group or raid or same team (raid/team case dependent from conf setting)
+ if(!m_mover->canDetectInvisibilityOf(u))
+ if(!(u->GetTypeId() == TYPEID_PLAYER && !IsHostileTo(u) && IsGroupVisibleFor(((Player*)u))))
+ return false;
+ }
+
+ // GM invisibility checks early, invisibility if any detectable, so if not stealth then visible
+ if(u->GetVisibility() == VISIBILITY_GROUP_STEALTH && !isGameMaster())
+ {
+ // if player is dead then he can't detect anyone in any cases
+ //do not know what is the use of this detect
+ // stealth and detected and visible for some seconds
+ if(!isAlive())
+ detect = false;
+ if(m_DetectInvTimer < 300 || !HaveAtClient(u))
+ if(!(u->GetTypeId() == TYPEID_PLAYER && !IsHostileTo(u) && IsGroupVisibleFor(((Player*)u))))
+ if(!detect || !m_mover->canDetectStealthOf(u, GetDistance(u)))
+ return false;
+ }
+
+ // If use this server will be too laggy
+ // Now check is target visible with LoS
+ //return u->IsWithinLOS(GetPositionX(),GetPositionY(),GetPositionZ());
+ return true;
+}
+
+bool Player::IsVisibleInGridForPlayer( Player const * pl ) const
+{
+ // gamemaster in GM mode see all, including ghosts
+ if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
+ return true;
+
+ // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
+ if (InBattleGround())
+ {
+ if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
+ return false;
+ return true;
+ }
+
+ // Live player see live player or dead player with not realized corpse
+ if(pl->isAlive() || pl->m_deathTimer > 0)
+ {
+ return isAlive() || m_deathTimer > 0;
+ }
+
+ // Ghost see other friendly ghosts, that's for sure
+ if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
+ return true;
+
+ // Dead player see live players near own corpse
+ if(isAlive())
+ {
+ Corpse *corpse = pl->GetCorpse();
+ if(corpse)
+ {
+ // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
+ if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
+ return true;
+ }
+ }
+
+ // and not see any other
+ return false;
+}
+
+bool Player::IsVisibleGloballyFor( Player* u ) const
+{
+ if(!u)
+ return false;
+
+ // Always can see self
+ if (u==this)
+ return true;
+
+ // Visible units, always are visible for all players
+ if (GetVisibility() == VISIBILITY_ON)
+ return true;
+
+ // GMs are visible for higher gms (or players are visible for gms)
+ if (u->GetSession()->GetSecurity() > SEC_PLAYER)
+ return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
+
+ // non faction visibility non-breakable for non-GMs
+ if (GetVisibility() == VISIBILITY_OFF)
+ return false;
+
+ // non-gm stealth/invisibility not hide from global player lists
+ return true;
+}
+
+template<class T>
+inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target, std::set<Unit*>& v)
+{
+ s64.insert(target->GetGUID());
+}
+
+template<>
+inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target, std::set<Unit*>& v)
+{
+ if(!target->IsTransport())
+ s64.insert(target->GetGUID());
+}
+
+template<>
+inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, Creature* target, std::set<Unit*>& v)
+{
+ s64.insert(target->GetGUID());
+ v.insert(target);
+}
+
+template<>
+inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, Player* target, std::set<Unit*>& v)
+{
+ s64.insert(target->GetGUID());
+ v.insert(target);
+}
+
+template<class T>
+inline void BeforeVisibilityDestroy(T* /*t*/, Player* /*p*/)
+{
+}
+
+template<>
+inline void BeforeVisibilityDestroy<Creature>(Creature* t, Player* p)
+{
+ if (p->GetPetGUID()==t->GetGUID() && ((Creature*)t)->isPet())
+ ((Pet*)t)->Remove(PET_SAVE_NOT_IN_SLOT, true);
+}
+
+void Player::UpdateVisibilityOf(WorldObject* target)
+{
+ if(HaveAtClient(target))
+ {
+ if(!target->isVisibleForInState(this, true))
+ {
+ if (target->GetTypeId()==TYPEID_UNIT)
+ BeforeVisibilityDestroy<Creature>((Creature*)target,this);
+
+ target->DestroyForPlayer(this);
+ m_clientGUIDs.erase(target->GetGUID());
+
+ #ifdef TRINITY_DEBUG
+ if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
+ sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
+ #endif
+ }
+ }
+ else
+ {
+ if(target->isVisibleForInState(this,false))
+ {
+ //if(target->isType(TYPEMASK_UNIT) && ((Unit*)target)->m_Vehicle)
+ // UpdateVisibilityOf(((Unit*)target)->m_Vehicle);
+
+ target->SendUpdateToPlayer(this);
+ m_clientGUIDs.insert(target->GetGUID());
+
+ #ifdef TRINITY_DEBUG
+ if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
+ sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
+ #endif
+
+ // target aura duration for caster show only if target exist at caster client
+ // send data at target visibility change (adding to client)
+ if(target->isType(TYPEMASK_UNIT))
+ SendInitialVisiblePackets((Unit*)target);
+ }
+ }
+}
+
+void Player::SendInitialVisiblePackets(Unit* target)
+{
+ SendAurasForTarget(target);
+ if(target->isAlive())
+ {
+ if(target->GetMotionMaster()->GetCurrentMovementGeneratorType() != IDLE_MOTION_TYPE)
+ target->SendMonsterMoveWithSpeedToCurrentDestination(this);
+ if(target->hasUnitState(UNIT_STAT_MELEE_ATTACKING) && target->getVictim())
+ target->SendMeleeAttackStart(target->getVictim());
+ }
+}
+
+template<class T>
+void Player::UpdateVisibilityOf(T* target, UpdateData& data, std::set<Unit*>& visibleNow)
+{
+ if(HaveAtClient(target))
+ {
+ if(!target->isVisibleForInState(this,true))
+ {
+ BeforeVisibilityDestroy<T>(target,this);
+
+ target->BuildOutOfRangeUpdateBlock(&data);
+ m_clientGUIDs.erase(target->GetGUID());
+
+ #ifdef TRINITY_DEBUG
+ if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
+ 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));
+ #endif
+ }
+ }
+ else //if(visibleNow.size() < 30 || target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->IsVehicle())
+ {
+ if(target->isVisibleForInState(this,false))
+ {
+ //if(target->isType(TYPEMASK_UNIT) && ((Unit*)target)->m_Vehicle)
+ // UpdateVisibilityOf(((Unit*)target)->m_Vehicle, data, visibleNow);
+
+ target->BuildCreateUpdateBlockForPlayer(&data, this);
+ UpdateVisibilityOf_helper(m_clientGUIDs,target,visibleNow);
+
+ #ifdef TRINITY_DEBUG
+ if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
+ 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));
+ #endif
+ }
+ }
+}
+
+template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, std::set<Unit*>& visibleNow);
+template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, std::set<Unit*>& visibleNow);
+template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, std::set<Unit*>& visibleNow);
+template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, std::set<Unit*>& visibleNow);
+template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, std::set<Unit*>& visibleNow);
+
+void Player::InitPrimaryProfessions()
+{
+ SetFreePrimaryProfessions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
+}
+
+Unit * Player::GetSelectedUnit() const
+{
+ if(m_curSelection)
+ return ObjectAccessor::GetUnit(*this, m_curSelection);
+ return NULL;
+}
+
+Player * Player::GetSelectedPlayer() const
+{
+ if(m_curSelection)
+ return ObjectAccessor::GetPlayer(*this, m_curSelection);
+ return NULL;
+}
+
+void Player::SendComboPoints()
+{
+ Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
+ if (combotarget)
+ {
+ WorldPacket data;
+ if(m_mover != this)
+ {
+ data.Initialize(SMSG_PET_UPDATE_COMBO_POINTS, m_mover->GetPackGUID().size()+combotarget->GetPackGUID().size()+1);
+ data.append(m_mover->GetPackGUID());
+ }
+ else
+ data.Initialize(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
+ data.append(combotarget->GetPackGUID());
+ data << uint8(m_comboPoints);
+ GetSession()->SendPacket(&data);
+ }
+}
+
+void Player::AddComboPoints(Unit* target, int8 count, Spell * spell)
+{
+ if(!count)
+ return;
+
+ int8 * comboPoints = spell ? &spell->m_comboPointGain : &m_comboPoints;
+
+ // without combo points lost (duration checked in aura)
+ RemoveAurasByType(SPELL_AURA_RETAIN_COMBO_POINTS);
+
+ if (target->GetGUID() == m_comboTarget)
+ *comboPoints += count;
+ else
+ {
+ if (m_comboTarget)
+ if (Unit* target2 = ObjectAccessor::GetUnit(*this, m_comboTarget))
+ target2->RemoveComboPointHolder(GetGUIDLow());
+
+ // Spells will always add value to m_comboPoints eventualy, so it must be cleared first
+ if (spell)
+ m_comboPoints = 0;
+
+ m_comboTarget = target->GetGUID();
+ *comboPoints = count;
+
+ target->AddComboPointHolder(GetGUIDLow());
+ }
+
+ if (*comboPoints > 5)
+ *comboPoints = 5;
+ else if (*comboPoints < 0)
+ *comboPoints = 0;
+
+ if (!spell)
+ SendComboPoints();
+}
+
+void Player::GainSpellComboPoints(int8 count)
+{
+ if(!count)
+ return;
+
+ m_comboPoints += count;
+ if (m_comboPoints > 5) m_comboPoints = 5;
+ else if (m_comboPoints < 0) m_comboPoints = 0;
+
+ SendComboPoints();
+}
+
+void Player::ClearComboPoints()
+{
+ if(!m_comboTarget)
+ return;
+
+ // without combopoints lost (duration checked in aura)
+ RemoveAurasByType(SPELL_AURA_RETAIN_COMBO_POINTS);
+
+ m_comboPoints = 0;
+
+ SendComboPoints();
+
+ if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
+ target->RemoveComboPointHolder(GetGUIDLow());
+
+ m_comboTarget = 0;
+}
+
+void Player::SetGroup(Group *group, int8 subgroup)
+{
+ if(group == NULL)
+ m_group.unlink();
+ else
+ {
+ // never use SetGroup without a subgroup unless you specify NULL for group
+ assert(subgroup >= 0);
+ m_group.link(group, this);
+ m_group.setSubGroup((uint8)subgroup);
+ }
+}
+
+void Player::SendInitialPacketsBeforeAddToMap()
+{
+ GetSocial()->SendSocialList();
+
+ // guild bank list wtf?
+
+ // Homebind
+ WorldPacket data(SMSG_BINDPOINTUPDATE, 5*4);
+ data << m_homebindX << m_homebindY << m_homebindZ;
+ data << (uint32) m_homebindMapId;
+ data << (uint32) m_homebindZoneId;
+ GetSession()->SendPacket(&data);
+
+ // SMSG_SET_PROFICIENCY
+ // SMSG_SET_PCT_SPELL_MODIFIER
+ // SMSG_SET_FLAT_SPELL_MODIFIER
+ // SMSG_UPDATE_AURA_DURATION
+
+ SendTalentsInfoData(false);
+
+ // SMSG_INSTANCE_DIFFICULTY
+
+ SendInitialSpells();
+
+ data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
+ data << uint32(0); // count, for(count) uint32;
+ GetSession()->SendPacket(&data);
+
+ SendInitialActionButtons();
+ m_reputationMgr.SendInitialReputations();
+ m_achievementMgr.SendAllAchievementData();
+
+ SendEquipmentSetList();
+
+ data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4);
+ data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
+ data << (float)0.01666667f; // game speed
+ data << uint32(0); // added in 3.1.2
+ GetSession()->SendPacket( &data );
+
+ GetReputationMgr().SendForceReactions(); // SMSG_SET_FORCED_REACTIONS
+
+ // SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...)
+ // SMSG_PET_GUIDS
+ // SMSG_UPDATE_WORLD_STATE
+ // SMSG_POWER_UPDATE
+
+}
+
+void Player::SendInitialPacketsAfterAddToMap()
+{
+ // update zone
+ uint32 newzone, newarea;
+ GetZoneAndAreaId(newzone,newarea);
+ UpdateZone(newzone,newarea); // also call SendInitWorldStates();
+
+ ResetTimeSync();
+ SendTimeSync();
+
+ CastSpell(this, 836, true); // LOGINEFFECT
+
+ // set some aura effects that send packet to player client after add player to map
+ // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
+ // same auras state lost at far teleport, send it one more time in this case also
+ static const AuraType auratypes[] =
+ {
+ SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
+ SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
+ SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED, SPELL_AURA_NONE
+ };
+ for (AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
+ {
+ Unit::AuraEffectList const& auraList = GetAuraEffectsByType(*itr);
+ if(!auraList.empty())
+ auraList.front()->HandleEffect(this, AURA_EFFECT_HANDLE_SEND_FOR_CLIENT, true);
+ }
+
+ if(HasAuraType(SPELL_AURA_MOD_STUN))
+ SetMovement(MOVE_ROOT);
+
+ // manual send package (have code in HandleEffect(this, AURA_EFFECT_HANDLE_SEND_FOR_CLIENT, true); that don't must be re-applied.
+ if(HasAuraType(SPELL_AURA_MOD_ROOT))
+ {
+ WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
+ data2.append(GetPackGUID());
+ data2 << (uint32)2;
+ SendMessageToSet(&data2,true);
+ }
+
+ SendAurasForTarget(this);
+ SendEnchantmentDurations(); // must be after add to map
+ SendItemDurations(); // must be after add to map
+}
+
+void Player::SendUpdateToOutOfRangeGroupMembers()
+{
+ if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
+ return;
+ if(Group* group = GetGroup())
+ group->UpdatePlayerOutOfRange(this);
+
+ m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
+ m_auraRaidUpdateMask = 0;
+ if(Pet *pet = GetPet())
+ pet->ResetAuraUpdateMaskForRaid();
+}
+
+void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
+{
+ WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
+ data << uint32(mapid);
+ data << uint8(reason); // transfer abort reason
+ switch(reason)
+ {
+ case TRANSFER_ABORT_INSUF_EXPAN_LVL:
+ case TRANSFER_ABORT_DIFFICULTY:
+ case TRANSFER_ABORT_UNIQUE_MESSAGE:
+ case TRANSFER_ABORT_ZONE_IN_COMBAT:
+ case TRANSFER_ABORT_MAX_PLAYERS:
+ data << uint8(arg);
+ break;
+ }
+ GetSession()->SendPacket(&data);
+}
+
+void Player::SendInstanceResetWarning( uint32 mapid, Difficulty difficulty, uint32 time )
+{
+ // type of warning, based on the time remaining until reset
+ uint32 type;
+ if(time > 3600)
+ type = RAID_INSTANCE_WELCOME;
+ else if(time > 900 && time <= 3600)
+ type = RAID_INSTANCE_WARNING_HOURS;
+ else if(time > 300 && time <= 900)
+ type = RAID_INSTANCE_WARNING_MIN;
+ else
+ type = RAID_INSTANCE_WARNING_MIN_SOON;
+
+ WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4);
+ data << uint32(type);
+ data << uint32(mapid);
+ data << uint32(difficulty); // difficulty
+ data << uint32(time);
+ if(type == RAID_INSTANCE_WELCOME)
+ {
+ data << uint8(0); // is your (1)
+ data << uint8(0); // is extended (1), ignored if prev field is 0
+ }
+ GetSession()->SendPacket(&data);
+}
+
+void Player::ApplyEquipCooldown( Item * pItem )
+{
+ for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
+ {
+ _Spell const& spellData = pItem->GetProto()->Spells[i];
+
+ // no spell
+ if( !spellData.SpellId )
+ continue;
+
+ // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
+ if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
+ continue;
+
+ AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
+
+ WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
+ data << pItem->GetGUID();
+ data << uint32(spellData.SpellId);
+ GetSession()->SendPacket(&data);
+ }
+}
+
+void Player::resetSpells(bool myClassOnly)
+{
+ // not need after this call
+ if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
+ RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS,true);
+
+ // make full copy of map (spells removed and marked as deleted at another spell remove
+ // and we can't use original map for safe iterative with visit each spell at loop end
+ PlayerSpellMap smap = GetSpellMap();
+
+ uint32 family;
+
+ if(myClassOnly)
+ {
+ ChrClassesEntry const* clsEntry = sChrClassesStore.LookupEntry(getClass());
+ if(!clsEntry)
+ return;
+ family = clsEntry->spellfamily;
+ }
+
+ for (PlayerSpellMap::const_iterator iter = smap.begin(); iter != smap.end(); ++iter)
+ {
+ if(myClassOnly)
+ {
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(iter->first);
+ if(!spellInfo)
+ continue;
+
+ // skip server-side/triggered spells
+ if(spellInfo->spellLevel == 0)
+ continue;
+
+ // skip wrong class/race skills
+ if(!IsSpellFitByClassAndRace(spellInfo->Id))
+ continue;
+
+ // skip other spell families
+ if(spellInfo->SpellFamilyName != family)
+ continue;
+
+ // skip spells with first rank learned as talent (and all talents then also)
+ uint32 first_rank = spellmgr.GetFirstSpellInChain(spellInfo->Id);
+ if(GetTalentSpellCost(first_rank) > 0)
+ continue;
+
+ // skip broken spells
+ if(!SpellMgr::IsSpellValid(spellInfo,this,false))
+ continue;
+ }
+ removeSpell(iter->first,false,false); // only iter->first can be accessed, object by iter->second can be deleted already
+ }
+
+ learnDefaultSpells();
+ learnQuestRewardedSpells();
+}
+
+void Player::learnDefaultSpells()
+{
+ // learn default race/class spells
+ PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
+ for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
+ {
+ uint32 tspell = *itr;
+ sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
+ if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
+ addSpell(tspell,true,true,true,false);
+ else // but send in normal spell in game learn case
+ learnSpell(tspell,true);
+ }
+}
+
+void Player::learnQuestRewardedSpells(Quest const* quest)
+{
+ int32 spell_id = quest->GetRewSpellCast();
+ uint32 src_spell_id = quest->GetSrcSpell();
+
+ // skip quests without rewarded spell
+ if( !spell_id )
+ return;
+
+ // if RewSpellCast = -1 we remove aura do to SrcSpell from player.
+ if (spell_id == -1 && src_spell_id)
+ {
+ this->RemoveAurasDueToSpell(src_spell_id);
+ return;
+ }
+
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
+ if(!spellInfo)
+ return;
+
+ // check learned spells state
+ bool found = false;
+ for (uint8 i = 0; i < 3; ++i)
+ {
+ if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
+ {
+ found = true;
+ break;
+ }
+ }
+
+ // skip quests with not teaching spell or already known spell
+ if(!found)
+ return;
+
+ // prevent learn non first rank unknown profession and second specialization for same profession)
+ uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
+ if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
+ {
+ // not have first rank learned (unlearned prof?)
+ uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
+ if( !HasSpell(first_spell) )
+ return;
+
+ SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
+ if(!learnedInfo)
+ return;
+
+ SpellsRequiringSpellMapBounds spellsRequired = spellmgr.GetSpellsRequiredForSpellBounds(learned_0);
+ for (SpellsRequiringSpellMap::const_iterator itr2 = spellsRequired.first; itr2 != spellsRequired.second; ++itr2)
+ {
+ uint32 profSpell = itr2->second;
+
+ // specialization
+ if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0 && profSpell)
+ {
+ // search other specialization for same prof
+ for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
+ {
+ if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
+ continue;
+
+ SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
+ if(!itrInfo)
+ return;
+
+ // compare only specializations
+ if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
+ continue;
+
+ // compare same chain spells
+ if (spellmgr.IsSpellRequiringSpell(itr->first, profSpell))
+ return;
+ }
+ }
+ }
+ }
+
+ CastSpell( this, spell_id, true);
+}
+
+void Player::learnQuestRewardedSpells()
+{
+ // learn spells received from quest completing
+ for (QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
+ {
+ // skip no rewarded quests
+ if(!itr->second.m_rewarded)
+ continue;
+
+ Quest const* quest = objmgr.GetQuestTemplate(itr->first);
+ if( !quest )
+ continue;
+
+ learnQuestRewardedSpells(quest);
+ }
+}
+
+void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
+{
+ uint32 raceMask = getRaceMask();
+ uint32 classMask = getClassMask();
+ for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
+ {
+ SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
+ if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
+ continue;
+ // Check race if set
+ if (pAbility->racemask && !(pAbility->racemask & raceMask))
+ continue;
+ // Check class if set
+ if (pAbility->classmask && !(pAbility->classmask & classMask))
+ continue;
+
+ if (sSpellStore.LookupEntry(pAbility->spellId))
+ {
+ // need unlearn spell
+ if (skill_value < pAbility->req_skill_value)
+ removeSpell(pAbility->spellId);
+ // need learn
+ else if (!IsInWorld())
+ addSpell(pAbility->spellId,true,true,true,false);
+ else
+ learnSpell(pAbility->spellId,true);
+ }
+ }
+}
+
+void Player::SendAurasForTarget(Unit *target)
+{
+ if(!target || target->GetVisibleAuras()->empty()) // speedup things
+ return;
+
+ WorldPacket data(SMSG_AURA_UPDATE_ALL);
+ data.append(target->GetPackGUID());
+
+ Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
+ for (Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
+ {
+ AuraApplication * auraApp = itr->second;
+ Aura * aura = auraApp->GetBase();
+ data << uint8(auraApp->GetSlot());
+ data << uint32(aura->GetId());
+
+ // flags
+ uint32 flags = auraApp->GetFlags();
+ if (aura->GetMaxDuration() > 0)
+ flags |= AFLAG_DURATION;
+ data << uint8(flags);
+ // level
+ data << uint8(aura->GetCasterLevel());
+ // charges
+ data << uint8(aura->GetStackAmount() > 1 ? aura->GetStackAmount() : (aura->GetCharges()) ? aura->GetCharges() : 1);
+
+ if(!(flags & AFLAG_CASTER))
+ data.appendPackGUID(aura->GetCasterGUID());
+
+ if(flags & AFLAG_DURATION) // include aura duration
+ {
+ data << uint32(aura->GetMaxDuration());
+ data << uint32(aura->GetDuration());
+ }
+ }
+
+ GetSession()->SendPacket(&data);
+}
+
+void Player::SetDailyQuestStatus( uint32 quest_id )
+{
+ for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
+ {
+ if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
+ {
+ SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
+ m_lastDailyQuestTime = time(NULL); // last daily quest time
+ m_DailyQuestChanged = true;
+ break;
+ }
+ }
+}
+
+void Player::ResetDailyQuestStatus()
+{
+ for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
+ SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
+
+ // DB data deleted in caller
+ m_DailyQuestChanged = false;
+ m_lastDailyQuestTime = 0;
+}
+
+BattleGround* Player::GetBattleGround() const
+{
+ if(GetBattleGroundId()==0)
+ return NULL;
+
+ return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgData.bgTypeID);
+}
+
+bool Player::InArena() const
+{
+ BattleGround *bg = GetBattleGround();
+ if(!bg || !bg->isArena())
+ return false;
+
+ return true;
+}
+
+bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
+{
+ // get a template bg instead of running one
+ BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
+ if(!bg)
+ return false;
+
+ // limit check leel to dbc compatible level range
+ uint32 level = getLevel();
+ if (level > DEFAULT_MAX_LEVEL)
+ level = DEFAULT_MAX_LEVEL;
+
+ if(level < bg->GetMinLevel() || level > bg->GetMaxLevel())
+ return false;
+
+ return true;
+}
+
+float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
+{
+ FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
+ if (!vendor_faction || !vendor_faction->faction)
+ return 1.0f;
+
+ ReputationRank rank = GetReputationRank(vendor_faction->faction);
+ if (rank <= REP_NEUTRAL)
+ return 1.0f;
+
+ return 1.0f - 0.05f* (rank - REP_NEUTRAL);
+}
+
+bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
+{
+ uint32 racemask = getRaceMask();
+ uint32 classmask = getClassMask();
+
+ SkillLineAbilityMapBounds bounds = spellmgr.GetSkillLineAbilityMapBounds(spell_id);
+ if (bounds.first==bounds.second)
+ return true;
+
+ for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
+ {
+ // skip wrong race skills
+ if (_spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
+ continue;
+
+ // skip wrong class skills
+ if (_spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
+ continue;
+
+ return true;
+ }
+
+ return false;
+}
+
+bool Player::HasQuestForGO(int32 GOId) const
+{
+ for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
+ {
+ uint32 questid = GetQuestSlotQuestId(i);
+ if (questid == 0)
+ continue;
+
+ QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
+ if (qs_itr == mQuestStatus.end())
+ continue;
+
+ QuestStatusData const& qs = qs_itr->second;
+
+ if (qs.m_status == QUEST_STATUS_INCOMPLETE)
+ {
+ Quest const* qinfo = objmgr.GetQuestTemplate(questid);
+ if (!qinfo)
+ continue;
+
+ if (GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
+ continue;
+
+ for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
+ {
+ if (qinfo->ReqCreatureOrGOId[j] >= 0) //skip non GO case
+ continue;
+
+ if ((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+void Player::UpdateForQuestWorldObjects()
+{
+ if (m_clientGUIDs.empty())
+ return;
+
+ UpdateData udata;
+ WorldPacket packet;
+ for (ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
+ {
+ if (IS_GAMEOBJECT_GUID(*itr))
+ {
+ if (GameObject *obj = HashMapHolder<GameObject>::Find(*itr))
+ obj->BuildValuesUpdateBlockForPlayer(&udata,this);
+ }
+ else if (IS_CRE_OR_VEH_GUID(*itr))
+ {
+ Creature *obj = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr);
+ if (!obj)
+ continue;
+
+ // check if this unit requires quest specific flags
+ if(!obj->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
+ continue;
+
+ SpellClickInfoMapBounds clickPair = objmgr.GetSpellClickInfoMapBounds(obj->GetEntry());
+ for (SpellClickInfoMap::const_iterator _itr = clickPair.first; _itr != clickPair.second; ++_itr)
+ if(_itr->second.questStart || _itr->second.questEnd)
+ {
+ obj->BuildCreateUpdateBlockForPlayer(&udata,this);
+ break;
+ }
+ }
+ }
+ udata.BuildPacket(&packet);
+ GetSession()->SendPacket(&packet);
+}
+
+void Player::SummonIfPossible(bool agree)
+{
+ if (!agree)
+ {
+ m_summon_expire = 0;
+ return;
+ }
+
+ // expire and auto declined
+ if (m_summon_expire < time(NULL))
+ return;
+
+ // stop taxi flight at summon
+ if (isInFlight())
+ {
+ GetMotionMaster()->MovementExpired();
+ CleanupAfterTaxiFlight();
+ }
+
+ // drop flag at summon
+ // 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
+ if (BattleGround *bg = GetBattleGround())
+ bg->EventPlayerDroppedFlag(this);
+
+ m_summon_expire = 0;
+
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
+
+ TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
+}
+
+void Player::RemoveItemDurations(Item *item)
+{
+ for (ItemDurationList::iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
+ {
+ if(*itr == item)
+ {
+ m_itemDuration.erase(itr);
+ break;
+ }
+ }
+}
+
+void Player::AddItemDurations(Item *item)
+{
+ if (item->GetUInt32Value(ITEM_FIELD_DURATION))
+ {
+ m_itemDuration.push_back(item);
+ item->SendTimeUpdate(this);
+ }
+}
+
+void Player::AutoUnequipOffhandIfNeed(bool force /*= false*/)
+{
+ Item *offItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
+ if (!offItem)
+ return;
+
+ // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
+ if (!force && (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed())))
+ return;
+
+ ItemPosCountVec off_dest;
+ uint8 off_msg = CanStoreItem(NULL_BAG, NULL_SLOT, off_dest, offItem, false);
+ if (off_msg == EQUIP_ERR_OK)
+ {
+ RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
+ StoreItem(off_dest, offItem, true);
+ }
+ else
+ {
+ MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
+ CharacterDatabase.BeginTransaction();
+ offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
+ offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
+ CharacterDatabase.CommitTransaction();
+
+ std::string subject = GetSession()->GetTrinityString(LANG_NOT_EQUIPPED_ITEM);
+ MailDraft(subject).AddItem(offItem).SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM));
+ }
+}
+
+OutdoorPvP * Player::GetOutdoorPvP() const
+{
+ return sOutdoorPvPMgr.GetOutdoorPvPToZoneId(GetZoneId());
+}
+
+bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
+{
+ if (spellInfo->EquippedItemClass < 0)
+ return true;
+
+ // scan other equipped items for same requirements (mostly 2 daggers/etc)
+ // for optimize check 2 used cases only
+ switch (spellInfo->EquippedItemClass)
+ {
+ case ITEM_CLASS_WEAPON:
+ {
+ for (uint8 i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
+ if(Item *item = GetUseableItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ if(item != ignoreItem && item->IsFitToSpellRequirements(spellInfo))
+ return true;
+ break;
+ }
+ case ITEM_CLASS_ARMOR:
+ {
+ // tabard not have dependent spells
+ for (uint8 i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
+ if(Item *item = GetUseableItemByPos( INVENTORY_SLOT_BAG_0, i ))
+ if(item != ignoreItem && item->IsFitToSpellRequirements(spellInfo))
+ return true;
+
+ // shields can be equipped to offhand slot
+ if(Item *item = GetUseableItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
+ if(item != ignoreItem && item->IsFitToSpellRequirements(spellInfo))
+ return true;
+
+ // ranged slot can have some armor subclasses
+ if(Item *item = GetUseableItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
+ if(item != ignoreItem && item->IsFitToSpellRequirements(spellInfo))
+ return true;
+
+ break;
+ }
+ default:
+ sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
+ break;
+ }
+
+ return false;
+}
+
+bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
+{
+ // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
+ if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
+ HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
+ return true;
+
+ // Check no reagent use mask
+ flag96 noReagentMask;
+ noReagentMask[0] = GetUInt32Value(PLAYER_NO_REAGENT_COST_1);
+ noReagentMask[1] = GetUInt32Value(PLAYER_NO_REAGENT_COST_1+1);
+ noReagentMask[2] = GetUInt32Value(PLAYER_NO_REAGENT_COST_1+2);
+ if (spellInfo->SpellFamilyFlags & noReagentMask)
+ return true;
+
+ return false;
+}
+
+void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
+{
+ for (AuraMap::iterator itr = m_ownedAuras.begin(); itr != m_ownedAuras.end();)
+ {
+ Aura * aura = itr->second;
+
+ // skip passive (passive item dependent spells work in another way) and not self applied auras
+ SpellEntry const* spellInfo = aura->GetSpellProto();
+ if(aura->IsPassive() || aura->GetCasterGUID() != GetGUID())
+ {
+ ++itr;
+ continue;
+ }
+
+ // skip if not item dependent or have alternative item
+ if(HasItemFitToSpellReqirements(spellInfo,pItem))
+ {
+ ++itr;
+ continue;
+ }
+
+ // no alt item, remove aura, restart check
+ RemoveOwnedAura(itr);
+ }
+
+ // currently casted spells can be dependent from item
+ for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
+ if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i)))
+ if (spell->getState()!=SPELL_STATE_DELAYED && !HasItemFitToSpellReqirements(spell->m_spellInfo,pItem) )
+ InterruptSpell(CurrentSpellTypes(i));
+}
+
+uint32 Player::GetResurrectionSpellId()
+{
+ // search priceless resurrection possibilities
+ uint32 prio = 0;
+ uint32 spell_id = 0;
+ AuraEffectList const& dummyAuras = GetAuraEffectsByType(SPELL_AURA_DUMMY);
+ for (AuraEffectList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
+ {
+ // Soulstone Resurrection // prio: 3 (max, non death persistent)
+ if (prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
+ {
+ switch ((*itr)->GetId())
+ {
+ case 20707: spell_id = 3026; break; // rank 1
+ case 20762: spell_id = 20758; break; // rank 2
+ case 20763: spell_id = 20759; break; // rank 3
+ case 20764: spell_id = 20760; break; // rank 4
+ case 20765: spell_id = 20761; break; // rank 5
+ case 27239: spell_id = 27240; break; // rank 6
+ case 47883: spell_id = 47882; break; // rank 7
+ default:
+ sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
+ continue;
+ }
+
+ prio = 3;
+ }
+ // Twisting Nether // prio: 2 (max)
+ else if ((*itr)->GetId()==23701 && roll_chance_i(10))
+ {
+ prio = 2;
+ spell_id = 23700;
+ }
+ }
+
+ // Reincarnation (passive spell) // prio: 1 // Glyph of Renewed Life
+ if (prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && (HasAura(58059) || HasItemCount(17030,1)))
+ spell_id = 21169;
+
+ return spell_id;
+}
+
+// Used in triggers for check "Only to targets that grant experience or honor" req
+bool Player::isHonorOrXPTarget(Unit* pVictim)
+{
+ uint8 v_level = pVictim->getLevel();
+ uint8 k_grey = Trinity::XP::GetGrayLevel(getLevel());
+
+ // Victim level less gray level
+ if(v_level <= k_grey)
+ return false;
+
+ if(pVictim->GetTypeId() == TYPEID_UNIT)
+ {
+ if (((Creature*)pVictim)->isTotem() ||
+ ((Creature*)pVictim)->isPet() ||
+ ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
+ return false;
+ }
+ return true;
+}
+
+bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
+{
+ bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
+
+ // prepare data for near group iteration (PvP and !PvP cases)
+ uint32 xp = 0;
+ bool honored_kill = false;
+
+ if(Group *pGroup = GetGroup())
+ {
+ uint32 count = 0;
+ uint32 sum_level = 0;
+ Player* member_with_max_level = NULL;
+ Player* not_gray_member_with_max_level = NULL;
+
+ pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
+
+ if(member_with_max_level)
+ {
+ // PvP kills doesn't yield experience
+ // also no XP gained if there is no member below gray level
+ xp = (PvP || !not_gray_member_with_max_level || GetVehicle()) ? 0 : Trinity::XP::Gain(not_gray_member_with_max_level, pVictim);
+
+ /// skip in check PvP case (for speed, not used)
+ bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
+ bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
+ float group_rate = Trinity::XP::xp_in_group_rate(count,is_raid);
+
+ for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
+ {
+ Player* pGroupGuy = itr->getSource();
+ if(!pGroupGuy)
+ continue;
+
+ if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
+ continue; // member (alive or dead) or his corpse at req. distance
+
+ // honor can be in PvP and !PvP (racial leader) cases (for alive)
+ if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count, -1, true) && pGroupGuy==this)
+ honored_kill = true;
+
+ // xp and reputation only in !PvP case
+ if(!PvP)
+ {
+ float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
+
+ // if is in dungeon then all receive full reputation at kill
+ // rewarded any alive/dead/near_corpse group member
+ pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
+
+ // XP updated only for alive group member
+ if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
+ pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
+ {
+ uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
+
+ // handle SPELL_AURA_MOD_XP_PCT auras
+ Unit::AuraEffectList const& ModXPPctAuras = GetAuraEffectsByType(SPELL_AURA_MOD_XP_PCT);
+ for (Unit::AuraEffectList::const_iterator i = ModXPPctAuras.begin(); i != ModXPPctAuras.end(); ++i)
+ itr_xp = uint32(itr_xp*(1.0f + (*i)->GetAmount() / 100.0f));
+
+ pGroupGuy->GiveXP(itr_xp, pVictim);
+ if(Pet* pet = pGroupGuy->GetPet())
+ pet->GivePetXP(itr_xp/2);
+ }
+
+ // quest objectives updated only for alive group member or dead but with not released body
+ if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
+ {
+ // normal creature (not pet/etc) can be only in !PvP case
+ if(pVictim->GetTypeId() == TYPEID_UNIT)
+ pGroupGuy->KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
+ }
+ }
+ }
+ }
+ }
+ else // if (!pGroup)
+ {
+ xp = (PvP || GetVehicle()) ? 0 : Trinity::XP::Gain(this, pVictim);
+
+ // honor can be in PvP and !PvP (racial leader) cases
+ if(RewardHonor(pVictim,1, -1, true))
+ honored_kill = true;
+
+ // xp and reputation only in !PvP case
+ if(!PvP)
+ {
+ RewardReputation(pVictim,1);
+
+ // handle SPELL_AURA_MOD_XP_PCT auras
+ Unit::AuraEffectList const& ModXPPctAuras = GetAuraEffectsByType(SPELL_AURA_MOD_XP_PCT);
+ for (Unit::AuraEffectList::const_iterator i = ModXPPctAuras.begin(); i != ModXPPctAuras.end(); ++i)
+ xp = uint32(xp*(1.0f + (*i)->GetAmount() / 100.0f));
+
+ GiveXP(xp, pVictim);
+
+ if(Pet* pet = GetPet())
+ pet->GivePetXP(xp);
+
+ // normal creature (not pet/etc) can be only in !PvP case
+ if(pVictim->GetTypeId() == TYPEID_UNIT)
+ KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
+ }
+ }
+ return xp || honored_kill;
+}
+
+void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
+{
+ if (!pRewardSource)
+ return;
+ uint64 creature_guid = (pRewardSource->GetTypeId() == TYPEID_UNIT) ? pRewardSource->GetGUID() : uint64(0);
+
+ // prepare data for near group iteration
+ if(Group *pGroup = GetGroup())
+ {
+ for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
+ {
+ Player* pGroupGuy = itr->getSource();
+ if(!pGroupGuy)
+ continue;
+
+ if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
+ continue; // member (alive or dead) or his corpse at req. distance
+
+ // quest objectives updated only for alive group member or dead but with not released body
+ if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
+ pGroupGuy->KilledMonsterCredit(creature_id, creature_guid);
+ }
+ }
+ else // if (!pGroup)
+ KilledMonsterCredit(creature_id, creature_guid);
+}
+
+bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
+{
+ if (!pRewardSource)
+ return false;
+ const WorldObject* player = GetCorpse();
+ if(!player || isAlive())
+ player = this;
+
+ if(player->GetMapId() != pRewardSource->GetMapId() || player->GetInstanceId() != pRewardSource->GetInstanceId())
+ return false;
+
+ return pRewardSource->GetDistance(player) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE);
+}
+
+uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
+{
+ Item* item = GetWeaponForAttack(attType,true);
+
+ // unarmed only with base attack
+ if(attType != BASE_ATTACK && !item)
+ return 0;
+
+ // weapon skill or (unarmed for base attack and for fist weapons)
+ uint32 skill = (item && item->GetSkill() != SKILL_FIST_WEAPONS) ? item->GetSkill() : uint32(SKILL_UNARMED);
+ return GetBaseSkillValue(skill);
+}
+
+void Player::ResurectUsingRequestData()
+{
+ /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
+ if(IS_PLAYER_GUID(m_resurrectGUID))
+ TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
+
+ //we cannot resurrect player when we triggered far teleport
+ //player will be resurrected upon teleportation
+ if(IsBeingTeleportedFar())
+ {
+ ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER);
+ return;
+ }
+
+ ResurrectPlayer(0.0f,false);
+
+ if(GetMaxHealth() > m_resurrectHealth)
+ SetHealth( m_resurrectHealth );
+ else
+ SetHealth( GetMaxHealth() );
+
+ if(GetMaxPower(POWER_MANA) > m_resurrectMana)
+ SetPower(POWER_MANA, m_resurrectMana );
+ else
+ SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
+
+ SetPower(POWER_RAGE, 0 );
+
+ SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
+
+ SpawnCorpseBones();
+}
+
+void Player::SetClientControl(Unit* target, uint8 allowMove)
+{
+ WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
+ data.append(target->GetPackGUID());
+ data << uint8(allowMove);
+ GetSession()->SendPacket(&data);
+ if(target == this)
+ SetMover(this);
+}
+
+void Player::UpdateZoneDependentAuras( uint32 newZone )
+{
+ // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
+ SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newZone);
+ for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
+ if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
+ if( !HasAura(itr->second->spellId) )
+ CastSpell(this,itr->second->spellId,true);
+}
+
+void Player::UpdateAreaDependentAuras( uint32 newArea )
+{
+ // remove auras from spells with area limitations
+ for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();)
+ {
+ // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
+ if(spellmgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
+ RemoveOwnedAura(iter);
+ else
+ ++iter;
+ }
+
+ // some auras applied at subzone enter
+ SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newArea);
+ for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
+ if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
+ if( !HasAura(itr->second->spellId) )
+ CastSpell(this,itr->second->spellId,true);
+
+ if(newArea == 4273 && GetVehicle() && GetPositionX() > 400) // Ulduar
+ {
+ switch(GetVehicleBase()->GetEntry())
+ {
+ case 33062:
+ case 33109:
+ case 33060:
+ GetVehicle()->Dismiss();
+ break;
+ }
+ }
+}
+
+uint32 Player::GetCorpseReclaimDelay(bool pvp) const
+{
+ if(pvp)
+ {
+ if(!sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP))
+ return copseReclaimDelay[0];
+ }
+ else if(!sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
+ return 0;
+
+ time_t now = time(NULL);
+ // 0..2 full period
+ // should be ceil(x)-1 but not floor(x)
+ uint32 count = (now < m_deathExpireTime - 1) ? (m_deathExpireTime - 1 - now)/DEATH_EXPIRE_STEP : 0;
+ return copseReclaimDelay[count];
+}
+
+void Player::UpdateCorpseReclaimDelay()
+{
+ bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
+
+ if ((pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
+ (!pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
+ return;
+
+ time_t now = time(NULL);
+ if(now < m_deathExpireTime)
+ {
+ // full and partly periods 1..3
+ uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
+ if(count < MAX_DEATH_COUNT)
+ m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
+ else
+ m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
+ }
+ else
+ m_deathExpireTime = now+DEATH_EXPIRE_STEP;
+}
+
+void Player::SendCorpseReclaimDelay(bool load)
+{
+ Corpse* corpse = GetCorpse();
+ if(load && !corpse)
+ return;
+
+ bool pvp;
+ if(corpse)
+ pvp = (corpse->GetType() == CORPSE_RESURRECTABLE_PVP);
+ else
+ pvp = (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH);
+
+ uint32 delay;
+ if(load)
+ {
+ if(corpse->GetGhostTime() > m_deathExpireTime)
+ return;
+
+ uint32 count;
+ if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
+ !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
+ {
+ count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
+ if(count>=MAX_DEATH_COUNT)
+ count = MAX_DEATH_COUNT-1;
+ }
+ else
+ count=0;
+
+ time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
+
+ time_t now = time(NULL);
+ if(now >= expected_time)
+ return;
+
+ delay = expected_time-now;
+ }
+ else
+ delay = GetCorpseReclaimDelay(pvp);
+
+ if(!delay) return;
+
+ //! corpse reclaim delay 30 * 1000ms or longer at often deaths
+ WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
+ data << uint32(delay*IN_MILISECONDS);
+ GetSession()->SendPacket( &data );
+}
+
+Player* Player::GetNextRandomRaidMember(float radius)
+{
+ Group *pGroup = GetGroup();
+ if(!pGroup)
+ return NULL;
+
+ std::vector<Player*> nearMembers;
+ nearMembers.reserve(pGroup->GetMembersCount());
+
+ for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
+ {
+ Player* Target = itr->getSource();
+
+ // IsHostileTo check duel and controlled by enemy
+ if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
+ !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
+ nearMembers.push_back(Target);
+ }
+
+ if (nearMembers.empty())
+ return NULL;
+
+ uint32 randTarget = urand(0,nearMembers.size()-1);
+ return nearMembers[randTarget];
+}
+
+PartyResult Player::CanUninviteFromGroup() const
+{
+ const Group* grp = GetGroup();
+ if(!grp)
+ return PARTY_RESULT_YOU_NOT_IN_GROUP;
+
+ if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
+ return PARTY_RESULT_YOU_NOT_LEADER;
+
+ if(InBattleGround())
+ return PARTY_RESULT_INVITE_RESTRICTED;
+
+ return PARTY_RESULT_OK;
+}
+
+void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
+{
+ //we must move references from m_group to m_originalGroup
+ SetOriginalGroup(GetGroup(), GetSubGroup());
+
+ m_group.unlink();
+ m_group.link(group, this);
+ m_group.setSubGroup((uint8)subgroup);
+}
+
+void Player::RemoveFromBattleGroundRaid()
+{
+ //remove existing reference
+ m_group.unlink();
+ if( Group* group = GetOriginalGroup() )
+ {
+ m_group.link(group, this);
+ m_group.setSubGroup(GetOriginalSubGroup());
+ }
+ SetOriginalGroup(NULL);
+}
+
+void Player::SetOriginalGroup(Group *group, int8 subgroup)
+{
+ if( group == NULL )
+ m_originalGroup.unlink();
+ else
+ {
+ // never use SetOriginalGroup without a subgroup unless you specify NULL for group
+ assert(subgroup >= 0);
+ m_originalGroup.link(group, this);
+ m_originalGroup.setSubGroup((uint8)subgroup);
+ }
+}
+
+void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
+{
+ LiquidData liquid_status;
+ ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
+ if (!res)
+ {
+ m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
+ // Small hack for enable breath in WMO
+ if (IsInWater())
+ m_MirrorTimerFlags|=UNDERWATER_INWATER;
+ return;
+ }
+
+ // All liquids type - check under water position
+ if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
+ {
+ if ( res & LIQUID_MAP_UNDER_WATER)
+ m_MirrorTimerFlags |= UNDERWATER_INWATER;
+ else
+ m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
+ }
+
+ // Allow travel in dark water on taxi or transport
+ if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
+ m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
+ else
+ m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
+
+ // in lava check, anywhere in lava level
+ if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
+ {
+ if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
+ m_MirrorTimerFlags |= UNDERWATER_INLAVA;
+ else
+ m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
+ }
+ // in slime check, anywhere in slime level
+ if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
+ {
+ if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
+ m_MirrorTimerFlags |= UNDERWATER_INSLIME;
+ else
+ m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
+ }
+}
+
+void Player::SetCanParry( bool value )
+{
+ if(m_canParry==value)
+ return;
+
+ m_canParry = value;
+ UpdateParryPercentage();
+}
+
+void Player::SetCanBlock( bool value )
+{
+ if(m_canBlock==value)
+ return;
+
+ m_canBlock = value;
+ UpdateBlockPercentage();
+}
+
+bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
+{
+ for (ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end(); ++itr)
+ if(itr->pos == pos)
+ return true;
+ return false;
+}
+
+//***********************************
+//-------------TRINITY---------------
+//***********************************
+
+void Player::StopCastingBindSight()
+{
+ if(WorldObject* target = GetViewpoint())
+ {
+ if(target->isType(TYPEMASK_UNIT))
+ {
+ ((Unit*)target)->RemoveAura(SPELL_AURA_BIND_SIGHT, GetGUID());
+ ((Unit*)target)->RemoveAura(SPELL_AURA_MOD_POSSESS, GetGUID());
+ ((Unit*)target)->RemoveAura(SPELL_AURA_MOD_POSSESS_PET, GetGUID());
+ }
+ }
+}
+
+void Player::SetViewpoint(WorldObject* target, bool apply)
+{
+ if(apply)
+ {
+ sLog.outDebug("Player::CreateViewpoint: Player %s create seer %u (TypeId: %u).", GetName(), target->GetEntry(), target->GetTypeId());
+
+ if(!AddUInt64Value(PLAYER_FARSIGHT, target->GetGUID()))
+ {
+ sLog.outCrash("Player::CreateViewpoint: Player %s cannot add new viewpoint!", GetName());
+ return;
+ }
+
+ // farsight dynobj or puppet may be very far away
+ UpdateVisibilityOf(target);
+
+ if(target->isType(TYPEMASK_UNIT) && !GetVehicle())
+ ((Unit*)target)->AddPlayerToVision(this);
+ }
+ else
+ {
+ sLog.outDebug("Player::CreateViewpoint: Player %s remove seer", GetName());
+
+ if(!RemoveUInt64Value(PLAYER_FARSIGHT, target->GetGUID()))
+ {
+ sLog.outCrash("Player::CreateViewpoint: Player %s cannot remove current viewpoint!", GetName());
+ return;
+ }
+
+ if(target->isType(TYPEMASK_UNIT) && !GetVehicle())
+ ((Unit*)target)->RemovePlayerFromVision(this);
+
+ //must immediately set seer back otherwise may crash
+ m_seer = this;
+
+ //WorldPacket data(SMSG_CLEAR_FAR_SIGHT_IMMEDIATE, 0);
+ //GetSession()->SendPacket(&data);
+ }
+}
+
+WorldObject* Player::GetViewpoint() const
+{
+ if(uint64 guid = GetUInt64Value(PLAYER_FARSIGHT))
+ return (WorldObject*)ObjectAccessor::GetObjectByTypeMask(*this, guid, TYPEMASK_SEER);
+ return NULL;
+}
+
+bool Player::CanUseBattleGroundObject()
+{
+ // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
+ // maybe gameobject code should handle that ForceReaction usage
+ // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
+ return ( //InBattleGround() && // in battleground - not need, check in other cases
+ //!IsMounted() && - not correct, player is dismounted when he clicks on flag
+ //player cannot use object when he is invulnerable (immune)
+ !isTotalImmune() && // not totally immune
+ //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
+ !HasStealthAura() && // not stealthed
+ !HasInvisibilityAura() && // not invisible
+ !HasAura(SPELL_RECENTLY_DROPPED_FLAG) && // can't pickup
+ isAlive() // live player
+ );
+}
+
+bool Player::CanCaptureTowerPoint()
+{
+ return ( !HasStealthAura() && // not stealthed
+ !HasInvisibilityAura() && // not invisible
+ isAlive() // live player
+ );
+}
+
+uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair, BarberShopStyleEntry const* newSkin )
+
+{
+ uint8 level = getLevel();
+
+ if(level > GT_MAX_LEVEL)
+ level = GT_MAX_LEVEL; // max level in this dbc
+
+ uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
+ uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
+ uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
+ uint8 skincolor = GetByteValue(PLAYER_BYTES, 0);
+
+ if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair) && (!newSkin || (newSkin->hair_id == skincolor)))
+ return 0;
+
+ GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
+
+ if(!bsc) // shouldn't happen
+ return 0xFFFFFFFF;
+
+ float cost = 0;
+
+ if(hairstyle != newhairstyle)
+ cost += bsc->cost; // full price
+
+ if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
+ cost += bsc->cost * 0.5f; // +1/2 of price
+
+ if(facialhair != newfacialhair)
+ cost += bsc->cost * 0.75f; // +3/4 of price
+
+ if(newSkin && skincolor != newSkin->hair_id)
+ cost += bsc->cost * 0.75f; // +5/6 of price
+
+ return uint32(cost);
+}
+
+void Player::InitGlyphsForLevel()
+{
+ for (uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
+ if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
+ if(gs->Order)
+ SetGlyphSlot(gs->Order - 1, gs->Id);
+
+ uint8 level = getLevel();
+ uint32 value = 0;
+
+ // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
+ if(level >= 15)
+ value |= (0x01 | 0x02);
+ if(level >= 30)
+ value |= 0x08;
+ if(level >= 50)
+ value |= 0x04;
+ if(level >= 70)
+ value |= 0x10;
+ if(level >= 80)
+ value |= 0x20;
+
+ SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
+}
+
+bool Player::isTotalImmune()
+{
+ AuraEffectList const& immune = GetAuraEffectsByType(SPELL_AURA_SCHOOL_IMMUNITY);
+
+ uint32 immuneMask = 0;
+ for (AuraEffectList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
+ {
+ immuneMask |= (*itr)->GetMiscValue();
+ if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
+ return true;
+ }
+ return false;
+}
+
+bool Player::HasTitle(uint32 bitIndex)
+{
+ if (bitIndex > MAX_TITLE_INDEX)
+ return false;
+
+ uint32 fieldIndexOffset = bitIndex / 32;
+ uint32 flag = 1 << (bitIndex % 32);
+ return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
+}
+
+void Player::SetTitle(CharTitlesEntry const* title, bool lost)
+{
+ uint32 fieldIndexOffset = title->bit_index / 32;
+ uint32 flag = 1 << (title->bit_index % 32);
+
+ if(lost)
+ {
+ if(!HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
+ return;
+
+ RemoveFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
+ }
+ else
+ {
+ if(HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
+ return;
+
+ SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
+ }
+
+ WorldPacket data(SMSG_TITLE_EARNED, 4 + 4);
+ data << uint32(title->bit_index);
+ data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost
+ GetSession()->SendPacket(&data);
+}
+
+/*-----------------------TRINITY--------------------------*/
+bool Player::isTotalImmunity()
+{
+ AuraEffectList const& immune = GetAuraEffectsByType(SPELL_AURA_SCHOOL_IMMUNITY);
+
+ for (AuraEffectList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
+ {
+ if (((*itr)->GetMiscValue() & SPELL_SCHOOL_MASK_ALL) !=0) // total immunity
+ {
+ return true;
+ }
+ if (((*itr)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL) !=0) // physical damage immunity
+ {
+ for (AuraEffectList::const_iterator i = immune.begin(); i != immune.end(); ++i)
+ {
+ if (((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_MAGIC) !=0) // magic immunity
+ {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+}
+
+void Player::UpdateCharmedAI()
+{
+ //This should only called in Player::Update
+ Creature *charmer = (Creature*)GetCharmer();
+
+ //kill self if charm aura has infinite duration
+ if(charmer->IsInEvadeMode())
+ {
+ AuraEffectList const& auras = GetAuraEffectsByType(SPELL_AURA_MOD_CHARM);
+ for (AuraEffectList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
+ if((*iter)->GetCasterGUID() == charmer->GetGUID() && (*iter)->GetBase()->IsPermanent())
+ {
+ charmer->DealDamage(this, GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
+ return;
+ }
+ }
+
+ if(!charmer->isInCombat())
+ GetMotionMaster()->MoveFollow(charmer, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE);
+
+ Unit *target = getVictim();
+ if(!target || !charmer->canAttack(target))
+ {
+ target = charmer->SelectNearestTarget();
+ if(!target)
+ return;
+
+ GetMotionMaster()->MoveChase(target);
+ Attack(target, true);
+ }
+}
+
+uint32 Player::GetRuneBaseCooldown(uint8 index)
+{
+ uint8 rune = GetBaseRune(index);
+ uint32 cooldown = RUNE_COOLDOWN;
+
+ AuraEffectList const& regenAura = GetAuraEffectsByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
+ for(AuraEffectList::const_iterator i = regenAura.begin();i != regenAura.end(); ++i)
+ {
+ if((*i)->GetMiscValue() == POWER_RUNE && (*i)->GetMiscValueB() == rune)
+ cooldown = cooldown*(100-(*i)->GetAmount())/100;
+ }
+
+ return cooldown;
+}
+
+void Player::RemoveRunesByAuraEffect(AuraEffect const * aura)
+{
+ for(uint8 i = 0; i < MAX_RUNES; ++i)
+ {
+ if (m_runes->runes[i].ConvertAura == aura)
+ {
+ ConvertRune(i, GetBaseRune(i));
+ SetRuneConvertAura(i, NULL);
+ }
+ }
+}
+
+void Player::RestoreBaseRune(uint8 index)
+{
+ AuraEffect const * aura = m_runes->runes[index].ConvertAura;
+ ConvertRune(index, GetBaseRune(index));
+ SetRuneConvertAura(index, NULL);
+ // Don't drop passive talents providing rune convertion
+ if (!aura || aura->GetAuraType() != SPELL_AURA_CONVERT_RUNE)
+ return;
+ for(uint8 i = 0; i < MAX_RUNES; ++i)
+ {
+ if (aura == m_runes->runes[i].ConvertAura)
+ return;
+ }
+ aura->GetBase()->Remove();
+}
+
+void Player::ConvertRune(uint8 index, RuneType newType)
+{
+ SetCurrentRune(index, newType);
+
+ WorldPacket data(SMSG_CONVERT_RUNE, 2);
+ data << uint8(index);
+ data << uint8(newType);
+ GetSession()->SendPacket(&data);
+}
+
+void Player::ResyncRunes(uint8 count)
+{
+ WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
+ for (uint32 i = 0; i < count; ++i)
+ {
+ data << uint8(GetCurrentRune(i)); // rune type
+ data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
+ }
+ GetSession()->SendPacket(&data);
+}
+
+void Player::AddRunePower(uint8 index)
+{
+ WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
+ data << uint32(1 << index); // mask (0x00-0x3F probably)
+ GetSession()->SendPacket(&data);
+}
+
+static RuneType runeSlotTypes[MAX_RUNES] = {
+ /*0*/ RUNE_BLOOD,
+ /*1*/ RUNE_BLOOD,
+ /*2*/ RUNE_UNHOLY,
+ /*3*/ RUNE_UNHOLY,
+ /*4*/ RUNE_FROST,
+ /*5*/ RUNE_FROST
+};
+
+void Player::InitRunes()
+{
+ if(getClass() != CLASS_DEATH_KNIGHT)
+ return;
+
+ m_runes = new Runes;
+
+ m_runes->runeState = 0;
+ m_runes->lastUsedRune = RUNE_BLOOD;
+
+ for (uint32 i = 0; i < MAX_RUNES; ++i)
+ {
+ SetBaseRune(i, runeSlotTypes[i]); // init base types
+ SetCurrentRune(i, runeSlotTypes[i]); // init current types
+ SetRuneCooldown(i, 0); // reset cooldowns
+ SetRuneConvertAura(i, NULL);
+ m_runes->SetRuneState(i);
+ }
+
+ for (uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
+ SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
+}
+
+bool Player::IsBaseRuneSlotsOnCooldown(RuneType runeType) const
+{
+ for (uint32 i = 0; i < MAX_RUNES; ++i)
+ if (GetBaseRune(i) == runeType && GetRuneCooldown(i) == 0)
+ return false;
+
+ return true;
+}
+
+void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
+{
+ Loot loot;
+ loot.FillLoot (loot_id,store,this,true);
+
+ uint32 max_slot = loot.GetMaxSlotInLootFor(this);
+ for (uint32 i = 0; i < max_slot; ++i)
+ {
+ LootItem* lootItem = loot.LootItemInSlot(i,this);
+
+ ItemPosCountVec dest;
+ uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
+ if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
+ msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
+ if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
+ msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
+ if(msg != EQUIP_ERR_OK)
+ {
+ SendEquipError( msg, NULL, NULL );
+ continue;
+ }
+
+ Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
+ SendNewItem(pItem, lootItem->count, false, false, broadcast);
+ }
+}
+
+uint32 Player::CalculateTalentsPoints() const
+{
+ uint32 base_talent = getLevel() < 10 ? 0 : getLevel()-9;
+
+ if(getClass() != CLASS_DEATH_KNIGHT || GetMapId() != 609)
+ return uint32(base_talent * sWorld.getRate(RATE_TALENT));
+
+ uint32 talentPointsForLevel = getLevel() < 56 ? 0 : getLevel() - 55;
+ talentPointsForLevel += m_questRewardTalentCount;
+
+ if(talentPointsForLevel > base_talent)
+ talentPointsForLevel = base_talent;
+
+ return uint32(talentPointsForLevel * sWorld.getRate(RATE_TALENT));
+}
+
+bool Player::IsKnowHowFlyIn(uint32 mapid, uint32 zone) const
+{
+ // continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update
+ uint32 v_map = GetVirtualMapForMapAndZone(mapid, zone);
+ return v_map != 571 || HasSpell(54197); // Cold Weather Flying
+}
+
+void Player::learnSpellHighRank(uint32 spellid)
+{
+ learnSpell(spellid,false);
+
+ if(uint32 next = spellmgr.GetNextSpellInChain(spellid))
+ learnSpellHighRank(next);
+}
+
+void Player::_LoadSkills(QueryResult_AutoPtr result)
+{
+ // 0 1 2
+ // SetPQuery(PLAYER_LOGIN_QUERY_LOADSKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = '%u'", GUID_LOPART(m_guid));
+
+ uint32 count = 0;
+ if (result)
+ {
+ do
+ {
+ Field *fields = result->Fetch();
+
+ uint16 skill = fields[0].GetUInt16();
+ uint16 value = fields[1].GetUInt16();
+ uint16 max = fields[2].GetUInt16();
+
+ SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(skill);
+ if(!pSkill)
+ {
+ sLog.outError("Character %u has skill %u that does not exist.", GetGUIDLow(), skill);
+ continue;
+ }
+
+ // set fixed skill ranges
+ switch(GetSkillRangeType(pSkill,false))
+ {
+ case SKILL_RANGE_LANGUAGE: // 300..300
+ value = max = 300;
+ break;
+ case SKILL_RANGE_MONO: // 1..1, grey monolite bar
+ value = max = 1;
+ break;
+ default:
+ break;
+ }
+ if(value == 0)
+ {
+ sLog.outError("Character %u has skill %u with value 0. Will be deleted.", GetGUIDLow(), skill);
+ CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), skill );
+ continue;
+ }
+
+ // enable unlearn button for primary professions only
+ if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
+ SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,1));
+ else
+ SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,0));
+
+ SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),MAKE_SKILL_VALUE(value, max));
+ SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
+
+ mSkillStatus.insert(SkillStatusMap::value_type(skill, SkillStatusData(count, SKILL_UNCHANGED)));
+
+ learnSkillRewardedSpells(skill, value);
+
+ ++count;
+
+ if(count >= PLAYER_MAX_SKILLS) // client limit
+ {
+ sLog.outError("Character %u has more than %u skills.", PLAYER_MAX_SKILLS);
+ break;
+ }
+ } while (result->NextRow());
+ }
+
+ for (; count < PLAYER_MAX_SKILLS; ++count)
+ {
+ SetUInt32Value(PLAYER_SKILL_INDEX(count), 0);
+ SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),0);
+ SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
+ }
+
+ // special settings
+ if (getClass() == CLASS_DEATH_KNIGHT)
+ {
+ uint8 base_level = std::min(getLevel(),uint8(sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL)));
+ if (base_level < 1)
+ base_level = 1;
+ uint16 base_skill = (base_level-1)*5; // 270 at starting level 55
+ if (base_skill < 1)
+ base_skill = 1; // skill mast be known and then > 0 in any case
+
+ if (GetPureSkillValue(SKILL_FIRST_AID) < base_skill)
+ SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
+ if (GetPureSkillValue(SKILL_AXES) < base_skill)
+ SetSkill(SKILL_AXES, base_skill,base_skill);
+ if (GetPureSkillValue(SKILL_DEFENSE) < base_skill)
+ SetSkill(SKILL_DEFENSE, base_skill,base_skill);
+ if (GetPureSkillValue(SKILL_POLEARMS) < base_skill)
+ SetSkill(SKILL_POLEARMS, base_skill,base_skill);
+ if (GetPureSkillValue(SKILL_SWORDS) < base_skill)
+ SetSkill(SKILL_SWORDS, base_skill,base_skill);
+ if (GetPureSkillValue(SKILL_2H_AXES) < base_skill)
+ SetSkill(SKILL_2H_AXES, base_skill,base_skill);
+ if (GetPureSkillValue(SKILL_2H_SWORDS) < base_skill)
+ SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
+ if (GetPureSkillValue(SKILL_UNARMED) < base_skill)
+ SetSkill(SKILL_UNARMED, base_skill,base_skill);
+ }
+}
+
+uint32 Player::GetPhaseMaskForSpawn() const
+{
+ uint32 phase = PHASEMASK_NORMAL;
+ if (!isGameMaster())
+ phase = GetPhaseMask();
+ else
+ {
+ AuraEffectList const& phases = GetAuraEffectsByType(SPELL_AURA_PHASE);
+ if (!phases.empty())
+ phase = phases.front()->GetMiscValue();
+ }
+
+ // some aura phases include 1 normal map in addition to phase itself
+ if (uint32 n_phase = phase & ~PHASEMASK_NORMAL)
+ return n_phase;
+
+ return PHASEMASK_NORMAL;
+}
+
+uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
+{
+ ItemPrototype const* pProto = pItem->GetProto();
+
+ // proto based limitations
+ if (uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
+ return res;
+
+ // check unique-equipped on gems
+ for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
+ {
+ uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
+ if (!enchant_id)
+ continue;
+ SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
+ if (!enchantEntry)
+ continue;
+
+ ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
+ if (!pGem)
+ continue;
+
+ // include for check equip another gems with same limit category for not equipped item (and then not counted)
+ uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
+ ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
+
+ if (uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
+ return res;
+ }
+
+ return EQUIP_ERR_OK;
+}
+
+uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
+{
+ // check unique-equipped on item
+ if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
+ {
+ // there is an equip limit on this item
+ if (HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
+ return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
+ }
+
+ // check unique-equipped limit
+ if (itemProto->ItemLimitCategory)
+ {
+ ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
+ if (!limitEntry)
+ return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
+
+ if (limit_count > limitEntry->maxCount)
+ return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
+
+ // there is an equip limit on this item
+ if (HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
+ return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
+ }
+
+ return EQUIP_ERR_OK;
+}
+
+void Player::HandleFall(MovementInfo const& movementInfo)
+{
+ // calculate total z distance of the fall
+ float z_diff = m_lastFallZ - movementInfo.z;
+ //sLog.outDebug("zDiff = %f", z_diff);
+
+ //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
+ // 14.57 can be calculated by resolving damageperc formula below to 0
+ if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
+ !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
+ !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
+ {
+ //Safe fall, fall height reduction
+ int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
+
+ float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
+
+ if (damageperc > 0)
+ {
+ uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
+
+ float height = movementInfo.z;
+ UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
+
+ if (damage > 0)
+ {
+ //Prevent fall damage from being more than the player maximum health
+ if (damage > GetMaxHealth())
+ damage = GetMaxHealth();
+
+ // Gust of Wind
+ if (HasAura(43621))
+ damage = GetMaxHealth()/2;
+
+ uint32 original_health = GetHealth();
+ uint32 final_damage = EnvironmentalDamage(DAMAGE_FALL, damage);
+
+ // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
+ if (isAlive() && final_damage < original_health)
+ GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
+ }
+
+ //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
+ 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);
+ }
+ }
+ RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_LANDING); // No fly zone - Parachute
+}
+
+void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
+{
+ GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1, miscvalue2, unit, time);
+}
+
+void Player::CompletedAchievement(AchievementEntry const* entry)
+{
+ GetAchievementMgr().CompletedAchievement(entry);
+}
+
+void Player::LearnTalent(uint32 talentId, uint32 talentRank)
+{
+ uint32 CurTalentPoints = GetFreeTalentPoints();
+
+ if(CurTalentPoints == 0)
+ return;
+
+ if (talentRank >= MAX_TALENT_RANK)
+ return;
+
+ TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
+
+ if(!talentInfo)
+ return;
+
+ TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
+
+ if(!talentTabInfo)
+ return;
+
+ // prevent learn talent for different class (cheating)
+ if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
+ return;
+
+ // find current max talent rank (0~5)
+ uint8 curtalent_maxrank = 0; // 0 = not learned any rank
+ for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
+ {
+ if(talentInfo->RankID[rank] && HasSpell(talentInfo->RankID[rank]))
+ {
+ curtalent_maxrank = (rank + 1);
+ break;
+ }
+ }
+
+ // we already have same or higher talent rank learned
+ if(curtalent_maxrank >= (talentRank + 1))
+ return;
+
+ // check if we have enough talent points
+ if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
+ return;
+
+ // Check if it requires another talent
+ if (talentInfo->DependsOn > 0)
+ {
+ if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
+ {
+ bool hasEnoughRank = false;
+ for (uint8 rank = talentInfo->DependsOnRank; rank < MAX_TALENT_RANK; rank++)
+ {
+ if (depTalentInfo->RankID[rank] != 0)
+ if (HasSpell(depTalentInfo->RankID[rank]))
+ hasEnoughRank = true;
+ }
+ if (!hasEnoughRank)
+ return;
+ }
+ }
+
+ // Find out how many points we have in this field
+ uint32 spentPoints = 0;
+
+ uint32 tTab = talentInfo->TalentTab;
+ if (talentInfo->Row > 0)
+ {
+ uint32 numRows = sTalentStore.GetNumRows();
+ for (uint32 i = 0; i < numRows; i++) // Loop through all talents.
+ {
+ // Someday, someone needs to revamp
+ const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
+ if (tmpTalent) // the way talents are tracked
+ {
+ if (tmpTalent->TalentTab == tTab)
+ {
+ for (uint8 rank = 0; rank < MAX_TALENT_RANK; rank++)
+ {
+ if (tmpTalent->RankID[rank] != 0)
+ {
+ if (HasSpell(tmpTalent->RankID[rank]))
+ {
+ spentPoints += (rank + 1);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // not have required min points spent in talent tree
+ if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
+ return;
+
+ // spell not set in talent.dbc
+ uint32 spellid = talentInfo->RankID[talentRank];
+ if( spellid == 0 )
+ {
+ sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
+ return;
+ }
+
+ // already known
+ if(HasSpell(spellid))
+ return;
+
+ // learn! (other talent ranks will unlearned at learning)
+ learnSpell(spellid, false);
+ AddTalent(spellid, m_activeSpec, true);
+
+ sLog.outDetail("TalentID: %u Rank: %u Spell: %u Spec: %u\n", talentId, talentRank, spellid, m_activeSpec);
+
+ // update free talent points
+ SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
+}
+
+void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
+{
+ Pet *pet = GetPet();
+
+ if(!pet)
+ return;
+
+ if(petGuid != pet->GetGUID())
+ return;
+
+ uint32 CurTalentPoints = pet->GetFreeTalentPoints();
+
+ if(CurTalentPoints == 0)
+ return;
+
+ if (talentRank >= MAX_PET_TALENT_RANK)
+ return;
+
+ TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
+
+ if(!talentInfo)
+ return;
+
+ TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
+
+ if(!talentTabInfo)
+ return;
+
+ CreatureInfo const *ci = pet->GetCreatureInfo();
+
+ if(!ci)
+ return;
+
+ CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
+
+ if(!pet_family)
+ return;
+
+ if(pet_family->petTalentType < 0) // not hunter pet
+ return;
+
+ // prevent learn talent for different family (cheating)
+ if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
+ return;
+
+ // find current max talent rank (0~5)
+ uint8 curtalent_maxrank = 0; // 0 = not learned any rank
+ for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
+ {
+ if(talentInfo->RankID[rank] && pet->HasSpell(talentInfo->RankID[rank]))
+ {
+ curtalent_maxrank = (rank + 1);
+ break;
+ }
+ }
+
+ // we already have same or higher talent rank learned
+ if(curtalent_maxrank >= (talentRank + 1))
+ return;
+
+ // check if we have enough talent points
+ if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
+ return;
+
+ // Check if it requires another talent
+ if (talentInfo->DependsOn > 0)
+ {
+ if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
+ {
+ bool hasEnoughRank = false;
+ for (uint8 rank = talentInfo->DependsOnRank; rank < MAX_TALENT_RANK; rank++)
+ {
+ if (depTalentInfo->RankID[rank] != 0)
+ if (pet->HasSpell(depTalentInfo->RankID[rank]))
+ hasEnoughRank = true;
+ }
+ if (!hasEnoughRank)
+ return;
+ }
+ }
+
+ // Find out how many points we have in this field
+ uint32 spentPoints = 0;
+
+ uint32 tTab = talentInfo->TalentTab;
+ if (talentInfo->Row > 0)
+ {
+ uint32 numRows = sTalentStore.GetNumRows();
+ for (uint32 i = 0; i < numRows; ++i) // Loop through all talents.
+ {
+ // Someday, someone needs to revamp
+ const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
+ if (tmpTalent) // the way talents are tracked
+ {
+ if (tmpTalent->TalentTab == tTab)
+ {
+ for (uint8 rank = 0; rank < MAX_TALENT_RANK; rank++)
+ {
+ if (tmpTalent->RankID[rank] != 0)
+ {
+ if (pet->HasSpell(tmpTalent->RankID[rank]))
+ {
+ spentPoints += (rank + 1);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // not have required min points spent in talent tree
+ if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
+ return;
+
+ // spell not set in talent.dbc
+ uint32 spellid = talentInfo->RankID[talentRank];
+ if( spellid == 0 )
+ {
+ sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
+ return;
+ }
+
+ // already known
+ if(pet->HasSpell(spellid))
+ return;
+
+ // learn! (other talent ranks will unlearned at learning)
+ pet->learnSpell(spellid);
+ sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
+
+ // update free talent points
+ pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
+}
+
+void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
+{
+ if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
+ {
+ if(apply)
+ SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(1LL << (ctEntry->BitIndex-1)));
+ else
+ RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(1LL << (ctEntry->BitIndex-1)));
+ }
+}
+
+void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
+{
+ if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <=minfo.z || opcode == MSG_MOVE_FALL_LAND)
+ SetFallInformation(minfo.fallTime, minfo.z);
+}
+
+void Player::UnsummonPetTemporaryIfAny()
+{
+ Pet* pet = GetPet();
+ if(!pet)
+ return;
+
+ if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
+ {
+ m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
+ m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
+ }
+
+ RemovePet(pet, PET_SAVE_AS_CURRENT);
+}
+
+void Player::ResummonPetTemporaryUnSummonedIfAny()
+{
+ if(!m_temporaryUnsummonedPetNumber)
+ return;
+
+ // not resummon in not appropriate state
+ if(IsPetNeedBeTemporaryUnsummoned())
+ return;
+
+ if(GetPetGUID())
+ return;
+
+ Pet* NewPet = new Pet(this);
+ if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
+ delete NewPet;
+
+ m_temporaryUnsummonedPetNumber = 0;
+}
+
+bool Player::canSeeSpellClickOn(Creature const *c) const
+{
+ if(!c->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
+ return false;
+
+ SpellClickInfoMapBounds clickPair = objmgr.GetSpellClickInfoMapBounds(c->GetEntry());
+ if(clickPair.first == clickPair.second)
+ return true;
+
+ for (SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
+ if(itr->second.IsFitToRequirements(this, c))
+ return true;
+
+ return false;
+}
+
+void Player::BuildPlayerTalentsInfoData(WorldPacket *data)
+{
+ *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
+ *data << uint8(m_specsCount); // talent group count (0, 1 or 2)
+ *data << uint8(m_activeSpec); // talent group index (0 or 1)
+
+ if(m_specsCount)
+ {
+ // loop through all specs (only 1 for now)
+ for (uint32 specIdx = 0; specIdx < m_specsCount; ++specIdx)
+ {
+ uint8 talentIdCount = 0;
+ size_t pos = data->wpos();
+ *data << uint8(talentIdCount); // [PH], talentIdCount
+
+ // find class talent tabs (all players have 3 talent tabs)
+ uint32 const* talentTabIds = GetTalentTabPages(getClass());
+
+ for (uint8 i = 0; i < 3; ++i)
+ {
+ uint32 talentTabId = talentTabIds[i];
+
+ for (uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
+ {
+ TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
+ if(!talentInfo)
+ continue;
+
+ // skip another tab talents
+ if(talentInfo->TalentTab != talentTabId)
+ continue;
+
+ // find max talent rank (0~4)
+ int8 curtalent_maxrank = -1;
+ for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
+ {
+ if(talentInfo->RankID[rank] && HasTalent(talentInfo->RankID[rank], specIdx))
+ {
+ curtalent_maxrank = rank;
+ break;
+ }
+ }
+
+ // not learned talent
+ if(curtalent_maxrank < 0)
+ continue;
+
+ *data << uint32(talentInfo->TalentID); // Talent.dbc
+ *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
+
+ ++talentIdCount;
+ }
+ }
+
+ data->put<uint8>(pos, talentIdCount); // put real count
+
+ *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
+
+ for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
+ *data << uint16(m_Glyphs[specIdx][i]); // GlyphProperties.dbc
+ }
+ }
+}
+
+void Player::BuildPetTalentsInfoData(WorldPacket *data)
+{
+ uint32 unspentTalentPoints = 0;
+ size_t pointsPos = data->wpos();
+ *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
+
+ uint8 talentIdCount = 0;
+ size_t countPos = data->wpos();
+ *data << uint8(talentIdCount); // [PH], talentIdCount
+
+ Pet *pet = GetPet();
+ if(!pet)
+ return;
+
+ unspentTalentPoints = pet->GetFreeTalentPoints();
+
+ data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
+
+ CreatureInfo const *ci = pet->GetCreatureInfo();
+ if(!ci)
+ return;
+
+ CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
+ if(!pet_family || pet_family->petTalentType < 0)
+ return;
+
+ for (uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
+ {
+ TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
+ if(!talentTabInfo)
+ continue;
+
+ if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
+ continue;
+
+ for (uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
+ {
+ TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
+ if(!talentInfo)
+ continue;
+
+ // skip another tab talents
+ if(talentInfo->TalentTab != talentTabId)
+ continue;
+
+ // find max talent rank (0~4)
+ int8 curtalent_maxrank = -1;
+ for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
+ {
+ if(talentInfo->RankID[rank] && pet->HasSpell(talentInfo->RankID[rank]))
+ {
+ curtalent_maxrank = rank;
+ break;
+ }
+ }
+
+ // not learned talent
+ if(curtalent_maxrank < 0)
+ continue;
+
+ *data << uint32(talentInfo->TalentID); // Talent.dbc
+ *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
+
+ ++talentIdCount;
+ }
+
+ data->put<uint8>(countPos, talentIdCount); // put real count
+
+ break;
+ }
+}
+
+void Player::SendTalentsInfoData(bool pet)
+{
+ WorldPacket data(SMSG_TALENTS_INFO, 50);
+ data << uint8(pet ? 1 : 0);
+ if(pet)
+ BuildPetTalentsInfoData(&data);
+ else
+ BuildPlayerTalentsInfoData(&data);
+ GetSession()->SendPacket(&data);
+}
+
+void Player::BuildEnchantmentsInfoData(WorldPacket *data)
+{
+ uint32 slotUsedMask = 0;
+ size_t slotUsedMaskPos = data->wpos();
+ *data << uint32(slotUsedMask); // slotUsedMask < 0x80000
+
+ for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
+ {
+ Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
+
+ if(!item)
+ continue;
+
+ slotUsedMask |= (1 << i);
+
+ *data << uint32(item->GetEntry()); // item entry
+
+ uint16 enchantmentMask = 0;
+ size_t enchantmentMaskPos = data->wpos();
+ *data << uint16(enchantmentMask); // enchantmentMask < 0x1000
+
+ for (uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
+ {
+ uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
+
+ if(!enchId)
+ continue;
+
+ enchantmentMask |= (1 << j);
+
+ *data << uint16(enchId); // enchantmentId?
+ }
+
+ data->put<uint16>(enchantmentMaskPos, enchantmentMask);
+
+ *data << uint16(0); // unknown
+ data->appendPackGUID(item->GetUInt64Value(ITEM_FIELD_CREATOR)); // item creator
+ *data << uint32(0); // seed?
+ }
+
+ data->put<uint32>(slotUsedMaskPos, slotUsedMask);
+}
+
+void Player::SendEquipmentSetList()
+{
+ uint32 count = 0;
+ WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4);
+ size_t count_pos = data.wpos();
+ data << uint32(count); // count placeholder
+ for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
+ {
+ if(itr->second.state==EQUIPMENT_SET_DELETED)
+ continue;
+ data.appendPackGUID(itr->second.Guid);
+ data << uint32(itr->first);
+ data << itr->second.Name;
+ data << itr->second.IconName;
+ for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
+ data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM));
+
+ ++count; // client have limit but it checked at loading and set
+ }
+ data.put<uint32>(count_pos, count);
+ GetSession()->SendPacket(&data);
+}
+
+void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
+{
+ if(eqset.Guid != 0)
+ {
+ bool found = false;
+
+ for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
+ {
+ if((itr->second.Guid == eqset.Guid) && (itr->first == index))
+ {
+ found = true;
+ break;
+ }
+ }
+
+ if(!found) // something wrong...
+ {
+ sLog.outError("Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
+ return;
+ }
+ }
+
+ EquipmentSet& eqslot = m_EquipmentSets[index];
+
+ EquipmentSetUpdateState old_state = eqslot.state;
+
+ eqslot = eqset;
+
+ if(eqset.Guid == 0)
+ {
+ eqslot.Guid = objmgr.GenerateEquipmentSetGuid();
+
+ WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1);
+ data << uint32(index);
+ data.appendPackGUID(eqslot.Guid);
+ GetSession()->SendPacket(&data);
+ }
+
+ eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
+}
+
+void Player::_SaveEquipmentSets()
+{
+ for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
+ {
+ uint32 index = itr->first;
+ EquipmentSet& eqset = itr->second;
+ switch(eqset.state)
+ {
+ case EQUIPMENT_SET_UNCHANGED:
+ ++itr;
+ break; // nothing do
+ case EQUIPMENT_SET_CHANGED:
+ 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'",
+ 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],
+ 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);
+ eqset.state = EQUIPMENT_SET_UNCHANGED;
+ ++itr;
+ break;
+ case EQUIPMENT_SET_NEW:
+ 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')",
+ 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],
+ 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]);
+ eqset.state = EQUIPMENT_SET_UNCHANGED;
+ ++itr;
+ break;
+ case EQUIPMENT_SET_DELETED:
+ CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE setguid="UI64FMTD, eqset.Guid);
+ m_EquipmentSets.erase(itr++);
+ break;
+ }
+ }
+}
+
+void Player::_SaveBGData()
+{
+ CharacterDatabase.PExecute("DELETE FROM character_battleground_data WHERE guid='%u'", GetGUIDLow());
+ if (m_bgData.bgInstanceID)
+ {
+ /* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
+ CharacterDatabase.PExecute("INSERT INTO character_battleground_data VALUES ('%u', '%u', '%u', '%f', '%f', '%f', '%f', '%u', '%u', '%u', '%u')",
+ GetGUIDLow(), m_bgData.bgInstanceID, m_bgData.bgTeam, m_bgData.joinPos.GetPositionX(), m_bgData.joinPos.GetPositionY(), m_bgData.joinPos.GetPositionZ(),
+ m_bgData.joinPos.GetOrientation(), m_bgData.joinPos.GetMapId(), m_bgData.taxiPath[0], m_bgData.taxiPath[1], m_bgData.mountSpell);
+ }
+}
+
+void Player::DeleteEquipmentSet(uint64 setGuid)
+{
+ for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
+ {
+ if(itr->second.Guid == setGuid)
+ {
+ if(itr->second.state == EQUIPMENT_SET_NEW)
+ m_EquipmentSets.erase(itr);
+ else
+ itr->second.state = EQUIPMENT_SET_DELETED;
+ break;
+ }
+ }
+}
+
+void Player::RemoveAtLoginFlag( AtLoginFlags f, bool in_db_also /*= false*/ )
+{
+ m_atLoginFlags &= ~f;
+
+ if(in_db_also)
+ CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f), GetGUIDLow());
+}
+
+void Player::SendClearCooldown( uint32 spell_id, Unit* target )
+{
+ WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
+ data << uint32(spell_id);
+ data << uint64(target->GetGUID());
+ SendDirectMessage(&data);
+}
+
+void Player::ResetMap()
+{
+ // this may be called during Map::Update
+ // after decrement+unlink, ++m_mapRefIter will continue correctly
+ // when the first element of the list is being removed
+ // nocheck_prev will return the padding element of the RefManager
+ // instead of NULL in the case of prev
+ GetMap()->UpdateIteratorBack(this);
+ Unit::ResetMap();
+ GetMapRef().unlink();
+}
+
+void Player::SetMap(Map * map)
+{
+ Unit::SetMap(map);
+ m_mapRef.link(map, this);
+}
+
+void Player::_LoadGlyphs(QueryResult_AutoPtr result)
+{
+ // SetPQuery(PLAYER_LOGIN_QUERY_LOADGLYPHS, "SELECT spec, glyph1, glyph2, glyph3, glyph4, glyph5, glyph6 from character_glyphs WHERE guid = '%u'", GUID_LOPART(m_guid));
+ if (!result)
+ return;
+
+ do
+ {
+ Field *fields = result->Fetch();
+
+ uint8 spec = fields[0].GetUInt8();
+ if (spec >= m_specsCount)
+ continue;
+
+ m_Glyphs[spec][0] = fields[1].GetUInt32();
+ m_Glyphs[spec][1] = fields[2].GetUInt32();
+ m_Glyphs[spec][2] = fields[3].GetUInt32();
+ m_Glyphs[spec][3] = fields[4].GetUInt32();
+ m_Glyphs[spec][4] = fields[5].GetUInt32();
+ m_Glyphs[spec][5] = fields[6].GetUInt32();
+
+ } while (result->NextRow());
+}
+
+void Player::_SaveGlyphs()
+{
+ CharacterDatabase.PExecute("DELETE FROM character_glyphs WHERE guid='%u'",GetGUIDLow());
+ for (uint8 spec = 0; spec < m_specsCount; ++spec)
+ {
+ CharacterDatabase.PExecute("INSERT INTO character_glyphs VALUES('%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
+ GetGUIDLow(), spec, m_Glyphs[spec][0], m_Glyphs[spec][1], m_Glyphs[spec][2], m_Glyphs[spec][3], m_Glyphs[spec][4], m_Glyphs[spec][5]);
+ }
+}
+
+void Player::_LoadTalents(QueryResult_AutoPtr result)
+{
+ // SetPQuery(PLAYER_LOGIN_QUERY_LOADTALENTS, "SELECT spell, spec FROM character_talent WHERE guid = '%u'", GUID_LOPART(m_guid));
+ if (result)
+ {
+ do
+ {
+ Field *fields = result->Fetch();
+
+ AddTalent(fields[0].GetUInt32(), fields[1].GetUInt32(), false);
+ }
+ while( result->NextRow() );
+ }
+}
+
+void Player::_SaveTalents()
+{
+ for (uint8 i = 0; i < MAX_TALENT_SPECS; ++i)
+ {
+ for (PlayerTalentMap::iterator itr = m_talents[i]->begin(); itr != m_talents[i]->end();)
+ {
+ if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
+ CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u' and spell = '%u' and spec = '%u'", GetGUIDLow(), itr->first, itr->second->spec);
+
+ if (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED)
+ CharacterDatabase.PExecute("INSERT INTO character_talent (guid,spell,spec) VALUES ('%u', '%u', '%u')", GetGUIDLow(), itr->first, itr->second->spec);
+
+ if (itr->second->state == PLAYERSPELL_REMOVED)
+ {
+ delete itr->second;
+ m_talents[i]->erase(itr++);
+ }
+ else
+ {
+ itr->second->state = PLAYERSPELL_UNCHANGED;
+ ++itr;
+ }
+ }
+ }
+}
+
+void Player::UpdateSpecCount(uint8 count)
+{
+ if (GetSpecsCount() == count)
+ return;
+
+ if (count == MIN_TALENT_SPECS)
+ {
+ _SaveActions(); // make sure the button list is cleaned up
+ // active spec becomes only spec?
+ CharacterDatabase.PExecute("DELETE FROM character_action WHERE spec<>'%u' AND guid='%u'",m_activeSpec, GetGUIDLow());
+ m_activeSpec = 0;
+ }
+ else if (count == MAX_TALENT_SPECS)
+ {
+ _SaveActions(); // make sure the button list is cleaned up
+ for (ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); ++itr)
+ CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,spec) VALUES ('%u', '%u', '%u', '%u', '%u')",
+ GetGUIDLow(), uint32(itr->first), uint32(itr->second.GetAction()), uint32(itr->second.GetType()), 1);
+ }
+ else
+ return;
+
+ SetSpecsCount(count);
+
+ SendTalentsInfoData(false);
+}
+
+void Player::ActivateSpec(uint8 spec)
+{
+ if (GetActiveSpec() == spec)
+ return;
+
+ if (GetSpecsCount() != MAX_TALENT_SPECS)
+ return;
+
+ if (GetMap()->IsBattleGround() && !HasAura(44521)) // In BattleGround with no Preparation buff
+ return;
+
+ _SaveActions();
+
+ if (IsNonMeleeSpellCasted(false))
+ InterruptNonMeleeSpells(false);
+
+ // "Hunter pets should have their talents refunded when a hunter switches talent specs, even if they are dismissed at the time."
+ if (getClass() == CLASS_HUNTER)
+ Pet::resetTalentsForAllPetsOf(this, GetPet());
+
+ UnsummonPetTemporaryIfAny();
+ ClearComboPointHolders();
+ ClearAllReactives();
+ UnsummonAllTotems();
+ RemoveAllControlled();
+ /*RemoveAllAurasOnDeath();
+ if (GetPet())
+ GetPet()->RemoveAllAurasOnDeath();*/
+
+ //RemoveAllAuras(this->GetGUID(), NULL, false, true); // removes too many auras
+ //ExitVehicle(); // should be impossible to switch specs from inside a vehicle..
+
+ for (uint32 i = 0; i < sTalentStore.GetNumRows(); ++i)
+ {
+ TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
+
+ if (!talentInfo)
+ continue;
+
+ TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
+
+ if (!talentTabInfo)
+ continue;
+
+ // unlearn only talents for character class
+ // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
+ // to prevent unexpected lost normal learned spell skip another class talents
+ if ((getClassMask() & talentTabInfo->ClassMask) == 0)
+ continue;
+
+ for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
+ {
+ // skip non-existant talent ranks
+ if (talentInfo->RankID[rank] == 0)
+ continue;
+ removeSpell(talentInfo->RankID[rank], true); // removes the talent, and all dependant, learned, and chained spells..
+ if (const SpellEntry *_spellEntry = sSpellStore.LookupEntry(talentInfo->RankID[rank]))
+ for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) // search through the SpellEntry for valid trigger spells
+ if (_spellEntry->EffectTriggerSpell[i] > 0 && _spellEntry->Effect[i] == SPELL_EFFECT_LEARN_SPELL)
+ removeSpell(_spellEntry->EffectTriggerSpell[i], true); // and remove any spells that the talent teaches
+ // if this talent rank can be found in the PlayerTalentMap, mark the talent as removed so it gets deleted
+ //PlayerTalentMap::iterator plrTalent = m_talents[m_activeSpec]->find(talentInfo->RankID[rank]);
+ //if (plrTalent != m_talents[m_activeSpec]->end())
+ // plrTalent->second->state = PLAYERSPELL_REMOVED;
+ }
+ }
+
+ // set glyphs
+ for (uint8 slot = 0; slot < MAX_GLYPH_SLOT_INDEX; ++slot)
+ // remove secondary glyph
+ if (uint32 oldglyph = m_Glyphs[m_activeSpec][slot])
+ if (GlyphPropertiesEntry const *old_gp = sGlyphPropertiesStore.LookupEntry(oldglyph))
+ RemoveAurasDueToSpell(old_gp->SpellId);
+
+ SetActiveSpec(spec);
+ uint32 spentTalents = 0;
+
+ for (uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
+ {
+ TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
+
+ if (!talentInfo)
+ continue;
+
+ TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
+
+ if (!talentTabInfo)
+ continue;
+
+ // learn only talents for character class
+ if ((getClassMask() & talentTabInfo->ClassMask) == 0)
+ continue;
+
+ // learn highest talent rank that exists in newly activated spec
+ for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank)
+ {
+ // skip non-existant talent ranks
+ if (talentInfo->RankID[rank] == 0)
+ continue;
+ // if the talent can be found in the newly activated PlayerTalentMap
+ if (HasTalent(talentInfo->RankID[rank], m_activeSpec))
+ {
+ learnSpell(talentInfo->RankID[rank], false); // add the talent to the PlayerSpellMap
+ spentTalents += (rank + 1); // increment the spentTalents count
+ }
+ }
+ }
+
+ // set glyphs
+ for (uint8 slot = 0; slot < MAX_GLYPH_SLOT_INDEX; ++slot)
+ {
+ uint32 glyph = m_Glyphs[m_activeSpec][slot];
+
+ // apply primary glyph
+ if (glyph)
+ if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
+ CastSpell(this, gp->SpellId, true);
+
+ SetGlyph(slot, glyph);
+ }
+
+ m_usedTalentCount = spentTalents;
+ InitTalentForLevel();
+
+ // Let client clear his current Actions
+ SendActionButtons(2);
+ m_actionButtons.clear();
+ if (QueryResult_AutoPtr result = CharacterDatabase.PQuery("SELECT button,action,type FROM character_action WHERE guid = '%u' AND spec = '%u' ORDER BY button", GetGUIDLow(), m_activeSpec))
+ _LoadActions(result, false);
+
+ ResummonPetTemporaryUnSummonedIfAny();
+ SendActionButtons(1);
+
+ Powers pw = getPowerType();
+ if (pw != POWER_MANA)
+ SetPower(POWER_MANA, 0); // Mana must be 0 even if it isn't the active power type.
+
+ SetPower(pw, 0);
+}
+
+void Player::ResetTimeSync()
+{
+ m_timeSyncCount = 0;
+ m_timeSyncTimer = 0;
+}
+
+void Player::SendTimeSync()
+{
+ WorldPacket data(SMSG_TIME_SYNC_REQ, 4);
+ data << uint32(m_timeSyncCount++);
+ GetSession()->SendPacket(&data);
+
+ // Send another opcode in 10s again
+ m_timeSyncTimer = 10000;
+}
+
+void Player::SetReputation(uint32 factionentry, uint32 value)
+{
+ GetReputationMgr().SetReputation(sFactionStore.LookupEntry(factionentry),value);
+}
+uint32 Player::GetReputation(uint32 factionentry)
+{
+ return GetReputationMgr().GetReputation(sFactionStore.LookupEntry(factionentry));
+}
+std::string Player::GetGuildName()
+{
+ return objmgr.GetGuildById(GetGuildId())->GetName();
+}
+
+void Player::SendDuelCountdown(uint32 counter)
+{
+ WorldPacket data(SMSG_DUEL_COUNTDOWN, 4);
+ data << uint32(counter); // seconds
+ GetSession()->SendPacket(&data);
+}
diff --git a/src/game/Player.h b/src/game/Player.h
index 0c4404617d0..f1ccfc60331 100644
--- a/src/game/Player.h
+++ b/src/game/Player.h
@@ -1,2637 +1,2637 @@
-/*
- * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
- *
- * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-#ifndef _PLAYER_H
-#define _PLAYER_H
-
-#include "Common.h"
-#include "ItemPrototype.h"
-#include "Unit.h"
-#include "Item.h"
-
-#include "Database/DatabaseEnv.h"
-#include "NPCHandler.h"
-#include "QuestDef.h"
-#include "Group.h"
-#include "Bag.h"
-#include "WorldSession.h"
-#include "Pet.h"
-#include "MapReference.h"
-#include "Util.h" // for Tokens typedef
-#include "AchievementMgr.h"
-#include "ReputationMgr.h"
-#include "BattleGround.h"
-#include "DBCEnums.h"
-
-#include<string>
-#include<vector>
-
-struct Mail;
-class Channel;
-class DynamicObject;
-class Creature;
-class Pet;
-class PlayerMenu;
-class UpdateMask;
-class SpellCastTargets;
-class PlayerSocial;
-class OutdoorPvP;
-
-typedef std::deque<Mail*> PlayerMails;
-
-#define PLAYER_MAX_SKILLS 127
-#define PLAYER_MAX_DAILY_QUESTS 25
-
-// Note: SPELLMOD_* values is aura types in fact
-enum SpellModType
-{
- SPELLMOD_FLAT = 107, // SPELL_AURA_ADD_FLAT_MODIFIER
- SPELLMOD_PCT = 108 // SPELL_AURA_ADD_PCT_MODIFIER
-};
-
-// 2^n values, Player::m_isunderwater is a bitmask. These are Trinity internal values, they are never send to any client
-enum PlayerUnderwaterState
-{
- UNDERWATER_NONE = 0x00,
- UNDERWATER_INWATER = 0x01, // terrain type is water and player is afflicted by it
- UNDERWATER_INLAVA = 0x02, // terrain type is lava and player is afflicted by it
- UNDERWATER_INSLIME = 0x04, // terrain type is lava and player is afflicted by it
- UNDERWARER_INDARKWATER = 0x08, // terrain type is dark water and player is afflicted by it
-
- UNDERWATER_EXIST_TIMERS = 0x10
-};
-
-enum PlayerSpellState
-{
- PLAYERSPELL_UNCHANGED = 0,
- PLAYERSPELL_CHANGED = 1,
- PLAYERSPELL_NEW = 2,
- PLAYERSPELL_REMOVED = 3,
- PLAYERSPELL_TEMPORARY = 4
-};
-
-struct PlayerSpell
-{
- PlayerSpellState state : 8;
- bool active : 1; // show in spellbook
- bool dependent : 1; // learned as result another spell learn, skill grow, quest reward, etc
- bool disabled : 1; // first rank has been learned in result talent learn but currently talent unlearned, save max learned ranks
-};
-
-struct PlayerTalent
-{
- PlayerSpellState state : 8;
- uint8 spec : 8;
-};
-
-// Spell modifier (used for modify other spells)
-struct SpellModifier
-{
- SpellModifier(Aura * _ownerAura = NULL) : charges(0), ownerAura(_ownerAura) {}
- SpellModOp op : 8;
- SpellModType type : 8;
- int16 charges : 16;
- int32 value;
- flag96 mask;
- uint32 spellId;
- Aura * const ownerAura;
-};
-
-typedef UNORDERED_MAP<uint32, PlayerTalent*> PlayerTalentMap;
-typedef UNORDERED_MAP<uint32, PlayerSpell*> PlayerSpellMap;
-typedef std::list<SpellModifier*> SpellModList;
-
-struct SpellCooldown
-{
- time_t end;
- uint16 itemid;
-};
-
-typedef std::map<uint32, SpellCooldown> SpellCooldowns;
-
-enum TrainerSpellState
-{
- TRAINER_SPELL_GREEN = 0,
- TRAINER_SPELL_RED = 1,
- TRAINER_SPELL_GRAY = 2,
- TRAINER_SPELL_GREEN_DISABLED = 10 // custom value, not send to client: formally green but learn not allowed
-};
-
-enum ActionButtonUpdateState
-{
- ACTIONBUTTON_UNCHANGED = 0,
- ACTIONBUTTON_CHANGED = 1,
- ACTIONBUTTON_NEW = 2,
- ACTIONBUTTON_DELETED = 3
-};
-
-enum ActionButtonType
-{
- ACTION_BUTTON_SPELL = 0x00,
- ACTION_BUTTON_C = 0x01, // click?
- ACTION_BUTTON_EQSET = 0x20,
- ACTION_BUTTON_MACRO = 0x40,
- ACTION_BUTTON_CMACRO = ACTION_BUTTON_C | ACTION_BUTTON_MACRO,
- ACTION_BUTTON_ITEM = 0x80
-};
-
-#define ACTION_BUTTON_ACTION(X) (uint32(X) & 0x00FFFFFF)
-#define ACTION_BUTTON_TYPE(X) ((uint32(X) & 0xFF000000) >> 24)
-#define MAX_ACTION_BUTTON_ACTION_VALUE (0x00FFFFFF+1)
-
-struct ActionButton
-{
- ActionButton() : packedData(0), uState( ACTIONBUTTON_NEW ), canRemoveByClient(true){}
-
- uint32 packedData;
- ActionButtonUpdateState uState;
- bool canRemoveByClient;
-
- // helpers
- ActionButtonType GetType() const { return ActionButtonType(ACTION_BUTTON_TYPE(packedData)); }
- uint32 GetAction() const { return ACTION_BUTTON_ACTION(packedData); }
- void SetActionAndType(uint32 action, ActionButtonType type)
- {
- uint32 newData = action | (uint32(type) << 24);
- if (newData != packedData || uState == ACTIONBUTTON_DELETED)
- {
- packedData = newData;
- if (uState != ACTIONBUTTON_NEW)
- uState = ACTIONBUTTON_CHANGED;
- }
- }
-};
-
-#define MAX_ACTION_BUTTONS 144 //checked in 3.2.0
-
-typedef std::map<uint8,ActionButton> ActionButtonList;
-
-struct PlayerCreateInfoItem
-{
- PlayerCreateInfoItem(uint32 id, uint32 amount) : item_id(id), item_amount(amount) {}
-
- uint32 item_id;
- uint32 item_amount;
-};
-
-typedef std::list<PlayerCreateInfoItem> PlayerCreateInfoItems;
-
-struct PlayerClassLevelInfo
-{
- PlayerClassLevelInfo() : basehealth(0), basemana(0) {}
- uint16 basehealth;
- uint16 basemana;
-};
-
-struct PlayerClassInfo
-{
- PlayerClassInfo() : levelInfo(NULL) { }
-
- PlayerClassLevelInfo* levelInfo; //[level-1] 0..MaxPlayerLevel-1
-};
-
-struct PlayerLevelInfo
-{
- PlayerLevelInfo() { for (uint8 i=0; i < MAX_STATS; ++i ) stats[i] = 0; }
-
- uint8 stats[MAX_STATS];
-};
-
-typedef std::list<uint32> PlayerCreateInfoSpells;
-
-struct PlayerCreateInfoAction
-{
- PlayerCreateInfoAction() : button(0), type(0), action(0) {}
- PlayerCreateInfoAction(uint8 _button, uint32 _action, uint8 _type) : button(_button), type(_type), action(_action) {}
-
- uint8 button;
- uint8 type;
- uint32 action;
-};
-
-typedef std::list<PlayerCreateInfoAction> PlayerCreateInfoActions;
-
-struct PlayerInfo
-{
- // existence checked by displayId != 0 // existence checked by displayId != 0
- PlayerInfo() : displayId_m(0),displayId_f(0),levelInfo(NULL)
- {
- }
-
- uint32 mapId;
- uint32 zoneId;
- float positionX;
- float positionY;
- float positionZ;
- uint16 displayId_m;
- uint16 displayId_f;
- PlayerCreateInfoItems item;
- PlayerCreateInfoSpells spell;
- PlayerCreateInfoActions action;
-
- PlayerLevelInfo* levelInfo; //[level-1] 0..MaxPlayerLevel-1
-};
-
-struct PvPInfo
-{
- PvPInfo() : inHostileArea(false), inNoPvPArea(false), inFFAPvPArea(false), endTimer(0) {}
-
- bool inHostileArea;
- bool inNoPvPArea;
- bool inFFAPvPArea;
- time_t endTimer;
-};
-
-struct DuelInfo
-{
- DuelInfo() : initiator(NULL), opponent(NULL), startTimer(0), startTime(0), outOfBound(0) {}
-
- Player *initiator;
- Player *opponent;
- time_t startTimer;
- time_t startTime;
- time_t outOfBound;
-};
-
-struct Areas
-{
- uint32 areaID;
- uint32 areaFlag;
- float x1;
- float x2;
- float y1;
- float y2;
-};
-
-#define MAX_RUNES 6
-#define RUNE_COOLDOWN 10000
-
-enum RuneType
-{
- RUNE_BLOOD = 0,
- RUNE_UNHOLY = 1,
- RUNE_FROST = 2,
- RUNE_DEATH = 3,
- NUM_RUNE_TYPES = 4
-};
-
-struct RuneInfo
-{
- uint8 BaseRune;
- uint8 CurrentRune;
- uint32 Cooldown;
- AuraEffect const * ConvertAura;
-};
-
-struct Runes
-{
- RuneInfo runes[MAX_RUNES];
- uint8 runeState; // mask of available runes
- RuneType lastUsedRune;
-
- void SetRuneState(uint8 index, bool set = true)
- {
- if(set)
- runeState |= (1 << index); // usable
- else
- runeState &= ~(1 << index); // on cooldown
- }
-};
-
-struct EnchantDuration
-{
- EnchantDuration() : item(NULL), slot(MAX_ENCHANTMENT_SLOT), leftduration(0) {};
- EnchantDuration(Item * _item, EnchantmentSlot _slot, uint32 _leftduration) : item(_item), slot(_slot),
- leftduration(_leftduration){ assert(item); };
-
- Item * item;
- EnchantmentSlot slot;
- uint32 leftduration;
-};
-
-typedef std::list<EnchantDuration> EnchantDurationList;
-typedef std::list<Item*> ItemDurationList;
-
-enum LfgType
-{
- LFG_TYPE_NONE = 0,
- LFG_TYPE_DUNGEON = 1,
- LFG_TYPE_RAID = 2,
- LFG_TYPE_QUEST = 3,
- LFG_TYPE_ZONE = 4,
- LFG_TYPE_HEROIC_DUNGEON = 5,
- LFG_TYPE_RANDOM_DUNGEON = 6
-};
-
-enum LfgRoles
-{
- LEADER = 0x01,
- TANK = 0x02,
- HEALER = 0x04,
- DAMAGE = 0x08
-};
-
-struct LookingForGroupSlot
-{
- LookingForGroupSlot() : entry(0), type(0) {}
- bool Empty() const { return !entry && !type; }
- void Clear() { entry = 0; type = 0; }
- void Set(uint32 _entry, uint32 _type ) { entry = _entry; type = _type; }
- bool Is(uint32 _entry, uint32 _type) const { return entry == _entry && type == _type; }
- bool canAutoJoin() const { return entry && (type == LFG_TYPE_DUNGEON || type == LFG_TYPE_HEROIC_DUNGEON); }
-
- uint32 entry;
- uint32 type;
-};
-
-#define MAX_LOOKING_FOR_GROUP_SLOT 3
-
-struct LookingForGroup
-{
- LookingForGroup() {}
- bool HaveInSlot(LookingForGroupSlot const& slot) const { return HaveInSlot(slot.entry, slot.type); }
- bool HaveInSlot(uint32 _entry, uint32 _type) const
- {
- for (uint8 i = 0; i < MAX_LOOKING_FOR_GROUP_SLOT; ++i)
- if(slots[i].Is(_entry, _type))
- return true;
- return false;
- }
-
- bool canAutoJoin() const
- {
- for (uint8 i = 0; i < MAX_LOOKING_FOR_GROUP_SLOT; ++i)
- if(slots[i].canAutoJoin())
- return true;
- return false;
- }
-
- bool Empty() const
- {
- for (uint8 i = 0; i < MAX_LOOKING_FOR_GROUP_SLOT; ++i)
- if(!slots[i].Empty())
- return false;
- return more.Empty();
- }
-
- LookingForGroupSlot slots[MAX_LOOKING_FOR_GROUP_SLOT];
- LookingForGroupSlot more;
- std::string comment;
- uint8 roles;
-};
-
-enum PlayerMovementType
-{
- MOVE_ROOT = 1,
- MOVE_UNROOT = 2,
- MOVE_WATER_WALK = 3,
- MOVE_LAND_WALK = 4
-};
-
-enum DrunkenState
-{
- DRUNKEN_SOBER = 0,
- DRUNKEN_TIPSY = 1,
- DRUNKEN_DRUNK = 2,
- DRUNKEN_SMASHED = 3
-};
-
-#define MAX_DRUNKEN 4
-
-enum PlayerFlags
-{
- PLAYER_FLAGS_GROUP_LEADER = 0x00000001,
- PLAYER_FLAGS_AFK = 0x00000002,
- PLAYER_FLAGS_DND = 0x00000004,
- PLAYER_FLAGS_GM = 0x00000008,
- PLAYER_FLAGS_GHOST = 0x00000010,
- PLAYER_FLAGS_RESTING = 0x00000020,
- PLAYER_FLAGS_UNK7 = 0x00000040,
- PLAYER_FLAGS_UNK8 = 0x00000080, // pre-3.0.3 PLAYER_FLAGS_FFA_PVP flag for FFA PVP state
- PLAYER_FLAGS_CONTESTED_PVP = 0x00000100, // Player has been involved in a PvP combat and will be attacked by contested guards
- PLAYER_FLAGS_IN_PVP = 0x00000200,
- PLAYER_FLAGS_HIDE_HELM = 0x00000400,
- PLAYER_FLAGS_HIDE_CLOAK = 0x00000800,
- PLAYER_FLAGS_UNK13 = 0x00001000, // played long time
- PLAYER_FLAGS_UNK14 = 0x00002000, // played too long time
- PLAYER_FLAGS_UNK15 = 0x00004000,
- PLAYER_FLAGS_DEVELOPER = 0x00008000, // <Dev> prefix for something?
- PLAYER_FLAGS_UNK17 = 0x00010000, // pre-3.0.3 PLAYER_FLAGS_SANCTUARY flag for player entered sanctuary
- PLAYER_FLAGS_UNK18 = 0x00020000, // taxi benchmark mode (on/off) (2.0.1)
- PLAYER_FLAGS_PVP_TIMER = 0x00040000, // 3.0.2, pvp timer active (after you disable pvp manually)
- PLAYER_FLAGS_UNK20 = 0x00080000,
- PLAYER_FLAGS_UNK21 = 0x00100000,
- PLAYER_FLAGS_UNK22 = 0x00200000,
- PLAYER_FLAGS_UNK23 = 0x00400000,
- PLAYER_ALLOW_ONLY_ABILITY = 0x00800000, // used by bladestorm and killing spree
- PLAYER_FLAGS_UNK25 = 0x01000000, // disabled all melee ability on tab include autoattack
-
- PLAYER_FLAGS_NO_XP_GAIN = 0x02000000
-};
-
-// used for PLAYER__FIELD_KNOWN_TITLES field (uint64), (1<<bit_index) without (-1)
-// can't use enum for uint64 values
-#define PLAYER_TITLE_DISABLED UI64LIT(0x0000000000000000)
-#define PLAYER_TITLE_NONE UI64LIT(0x0000000000000001)
-#define PLAYER_TITLE_PRIVATE UI64LIT(0x0000000000000002) // 1
-#define PLAYER_TITLE_CORPORAL UI64LIT(0x0000000000000004) // 2
-#define PLAYER_TITLE_SERGEANT_A UI64LIT(0x0000000000000008) // 3
-#define PLAYER_TITLE_MASTER_SERGEANT UI64LIT(0x0000000000000010) // 4
-#define PLAYER_TITLE_SERGEANT_MAJOR UI64LIT(0x0000000000000020) // 5
-#define PLAYER_TITLE_KNIGHT UI64LIT(0x0000000000000040) // 6
-#define PLAYER_TITLE_KNIGHT_LIEUTENANT UI64LIT(0x0000000000000080) // 7
-#define PLAYER_TITLE_KNIGHT_CAPTAIN UI64LIT(0x0000000000000100) // 8
-#define PLAYER_TITLE_KNIGHT_CHAMPION UI64LIT(0x0000000000000200) // 9
-#define PLAYER_TITLE_LIEUTENANT_COMMANDER UI64LIT(0x0000000000000400) // 10
-#define PLAYER_TITLE_COMMANDER UI64LIT(0x0000000000000800) // 11
-#define PLAYER_TITLE_MARSHAL UI64LIT(0x0000000000001000) // 12
-#define PLAYER_TITLE_FIELD_MARSHAL UI64LIT(0x0000000000002000) // 13
-#define PLAYER_TITLE_GRAND_MARSHAL UI64LIT(0x0000000000004000) // 14
-#define PLAYER_TITLE_SCOUT UI64LIT(0x0000000000008000) // 15
-#define PLAYER_TITLE_GRUNT UI64LIT(0x0000000000010000) // 16
-#define PLAYER_TITLE_SERGEANT_H UI64LIT(0x0000000000020000) // 17
-#define PLAYER_TITLE_SENIOR_SERGEANT UI64LIT(0x0000000000040000) // 18
-#define PLAYER_TITLE_FIRST_SERGEANT UI64LIT(0x0000000000080000) // 19
-#define PLAYER_TITLE_STONE_GUARD UI64LIT(0x0000000000100000) // 20
-#define PLAYER_TITLE_BLOOD_GUARD UI64LIT(0x0000000000200000) // 21
-#define PLAYER_TITLE_LEGIONNAIRE UI64LIT(0x0000000000400000) // 22
-#define PLAYER_TITLE_CENTURION UI64LIT(0x0000000000800000) // 23
-#define PLAYER_TITLE_CHAMPION UI64LIT(0x0000000001000000) // 24
-#define PLAYER_TITLE_LIEUTENANT_GENERAL UI64LIT(0x0000000002000000) // 25
-#define PLAYER_TITLE_GENERAL UI64LIT(0x0000000004000000) // 26
-#define PLAYER_TITLE_WARLORD UI64LIT(0x0000000008000000) // 27
-#define PLAYER_TITLE_HIGH_WARLORD UI64LIT(0x0000000010000000) // 28
-#define PLAYER_TITLE_GLADIATOR UI64LIT(0x0000000020000000) // 29
-#define PLAYER_TITLE_DUELIST UI64LIT(0x0000000040000000) // 30
-#define PLAYER_TITLE_RIVAL UI64LIT(0x0000000080000000) // 31
-#define PLAYER_TITLE_CHALLENGER UI64LIT(0x0000000100000000) // 32
-#define PLAYER_TITLE_SCARAB_LORD UI64LIT(0x0000000200000000) // 33
-#define PLAYER_TITLE_CONQUEROR UI64LIT(0x0000000400000000) // 34
-#define PLAYER_TITLE_JUSTICAR UI64LIT(0x0000000800000000) // 35
-#define PLAYER_TITLE_CHAMPION_OF_THE_NAARU UI64LIT(0x0000001000000000) // 36
-#define PLAYER_TITLE_MERCILESS_GLADIATOR UI64LIT(0x0000002000000000) // 37
-#define PLAYER_TITLE_OF_THE_SHATTERED_SUN UI64LIT(0x0000004000000000) // 38
-#define PLAYER_TITLE_HAND_OF_ADAL UI64LIT(0x0000008000000000) // 39
-#define PLAYER_TITLE_VENGEFUL_GLADIATOR UI64LIT(0x0000010000000000) // 40
-
-#define MAX_TITLE_INDEX (3*64) // 3 uint64 fields
-
-// used in PLAYER_FIELD_BYTES values
-enum PlayerFieldByteFlags
-{
- PLAYER_FIELD_BYTE_TRACK_STEALTHED = 0x00000002,
- PLAYER_FIELD_BYTE_RELEASE_TIMER = 0x00000008, // Display time till auto release spirit
- PLAYER_FIELD_BYTE_NO_RELEASE_WINDOW = 0x00000010 // Display no "release spirit" window at all
-};
-
-// used in PLAYER_FIELD_BYTES2 values
-enum PlayerFieldByte2Flags
-{
- PLAYER_FIELD_BYTE2_NONE = 0x0000,
- PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW = 0x4000
-};
-
-enum ActivateTaxiReplies
-{
- ERR_TAXIOK = 0,
- ERR_TAXIUNSPECIFIEDSERVERERROR = 1,
- ERR_TAXINOSUCHPATH = 2,
- ERR_TAXINOTENOUGHMONEY = 3,
- ERR_TAXITOOFARAWAY = 4,
- ERR_TAXINOVENDORNEARBY = 5,
- ERR_TAXINOTVISITED = 6,
- ERR_TAXIPLAYERBUSY = 7,
- ERR_TAXIPLAYERALREADYMOUNTED = 8,
- ERR_TAXIPLAYERSHAPESHIFTED = 9,
- ERR_TAXIPLAYERMOVING = 10,
- ERR_TAXISAMENODE = 11,
- ERR_TAXINOTSTANDING = 12
-};
-
-enum MirrorTimerType
-{
- FATIGUE_TIMER = 0,
- BREATH_TIMER = 1,
- FIRE_TIMER = 2
-};
-#define MAX_TIMERS 3
-#define DISABLED_MIRROR_TIMER -1
-
-// 2^n values
-enum PlayerExtraFlags
-{
- // gm abilities
- PLAYER_EXTRA_GM_ON = 0x0001,
- PLAYER_EXTRA_ACCEPT_WHISPERS = 0x0004,
- PLAYER_EXTRA_TAXICHEAT = 0x0008,
- PLAYER_EXTRA_GM_INVISIBLE = 0x0010,
- PLAYER_EXTRA_GM_CHAT = 0x0020, // Show GM badge in chat messages
-
- // other states
- PLAYER_EXTRA_PVP_DEATH = 0x0100 // store PvP death status until corpse creating.
-};
-
-// 2^n values
-enum AtLoginFlags
-{
- AT_LOGIN_NONE = 0x00,
- AT_LOGIN_RENAME = 0x01,
- AT_LOGIN_RESET_SPELLS = 0x02,
- AT_LOGIN_RESET_TALENTS = 0x04,
- AT_LOGIN_CUSTOMIZE = 0x08,
- AT_LOGIN_RESET_PET_TALENTS = 0x10,
- AT_LOGIN_FIRST = 0x20,
-};
-
-typedef std::map<uint32, QuestStatusData> QuestStatusMap;
-
-enum QuestSlotOffsets
-{
- QUEST_ID_OFFSET = 0,
- QUEST_STATE_OFFSET = 1,
- QUEST_COUNTS_OFFSET = 2,
- QUEST_TIME_OFFSET = 3
-};
-
-#define MAX_QUEST_OFFSET 5
-
-enum QuestSlotStateMask
-{
- QUEST_STATE_NONE = 0x0000,
- QUEST_STATE_COMPLETE = 0x0001,
- QUEST_STATE_FAIL = 0x0002
-};
-
-enum SkillUpdateState
-{
- SKILL_UNCHANGED = 0,
- SKILL_CHANGED = 1,
- SKILL_NEW = 2,
- SKILL_DELETED = 3
-};
-
-struct SkillStatusData
-{
- SkillStatusData(uint8 _pos, SkillUpdateState _uState) : pos(_pos), uState(_uState)
- {
- }
- uint8 pos;
- SkillUpdateState uState;
-};
-
-typedef UNORDERED_MAP<uint32, SkillStatusData> SkillStatusMap;
-
-class Quest;
-class Spell;
-class Item;
-class WorldSession;
-
-enum PlayerSlots
-{
- // first slot for item stored (in any way in player m_items data)
- PLAYER_SLOT_START = 0,
- // last+1 slot for item stored (in any way in player m_items data)
- PLAYER_SLOT_END = 150,
- PLAYER_SLOTS_COUNT = (PLAYER_SLOT_END - PLAYER_SLOT_START)
-};
-
-#define INVENTORY_SLOT_BAG_0 255
-
-enum EquipmentSlots // 19 slots
-{
- EQUIPMENT_SLOT_START = 0,
- EQUIPMENT_SLOT_HEAD = 0,
- EQUIPMENT_SLOT_NECK = 1,
- EQUIPMENT_SLOT_SHOULDERS = 2,
- EQUIPMENT_SLOT_BODY = 3,
- EQUIPMENT_SLOT_CHEST = 4,
- EQUIPMENT_SLOT_WAIST = 5,
- EQUIPMENT_SLOT_LEGS = 6,
- EQUIPMENT_SLOT_FEET = 7,
- EQUIPMENT_SLOT_WRISTS = 8,
- EQUIPMENT_SLOT_HANDS = 9,
- EQUIPMENT_SLOT_FINGER1 = 10,
- EQUIPMENT_SLOT_FINGER2 = 11,
- EQUIPMENT_SLOT_TRINKET1 = 12,
- EQUIPMENT_SLOT_TRINKET2 = 13,
- EQUIPMENT_SLOT_BACK = 14,
- EQUIPMENT_SLOT_MAINHAND = 15,
- EQUIPMENT_SLOT_OFFHAND = 16,
- EQUIPMENT_SLOT_RANGED = 17,
- EQUIPMENT_SLOT_TABARD = 18,
- EQUIPMENT_SLOT_END = 19
-};
-
-enum InventorySlots // 4 slots
-{
- INVENTORY_SLOT_BAG_START = 19,
- INVENTORY_SLOT_BAG_END = 23
-};
-
-enum InventoryPackSlots // 16 slots
-{
- INVENTORY_SLOT_ITEM_START = 23,
- INVENTORY_SLOT_ITEM_END = 39
-};
-
-enum BankItemSlots // 28 slots
-{
- BANK_SLOT_ITEM_START = 39,
- BANK_SLOT_ITEM_END = 67
-};
-
-enum BankBagSlots // 7 slots
-{
- BANK_SLOT_BAG_START = 67,
- BANK_SLOT_BAG_END = 74
-};
-
-enum BuyBackSlots // 12 slots
-{
- // stored in m_buybackitems
- BUYBACK_SLOT_START = 74,
- BUYBACK_SLOT_END = 86
-};
-
-enum KeyRingSlots // 32 slots
-{
- KEYRING_SLOT_START = 86,
- KEYRING_SLOT_END = 118
-};
-
-enum CurrencyTokenSlots // 32 slots
-{
- CURRENCYTOKEN_SLOT_START = 118,
- CURRENCYTOKEN_SLOT_END = 150
-};
-
-enum EquipmentSetUpdateState
-{
- EQUIPMENT_SET_UNCHANGED = 0,
- EQUIPMENT_SET_CHANGED = 1,
- EQUIPMENT_SET_NEW = 2,
- EQUIPMENT_SET_DELETED = 3
-};
-
-struct EquipmentSet
-{
- EquipmentSet() : Guid(0), state(EQUIPMENT_SET_NEW)
- {
- for (uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i)
- Items[i] = 0;
- }
-
- uint64 Guid;
- std::string Name;
- std::string IconName;
- uint32 Items[EQUIPMENT_SLOT_END];
- EquipmentSetUpdateState state;
-};
-
-#define MAX_EQUIPMENT_SET_INDEX 10 // client limit
-
-typedef std::map<uint32, EquipmentSet> EquipmentSets;
-
-struct ItemPosCount
-{
- ItemPosCount(uint16 _pos, uint32 _count) : pos(_pos), count(_count) {}
- bool isContainedIn(std::vector<ItemPosCount> const& vec) const;
- uint16 pos;
- uint32 count;
-};
-typedef std::vector<ItemPosCount> ItemPosCountVec;
-
-enum TradeSlots
-{
- TRADE_SLOT_COUNT = 7,
- TRADE_SLOT_TRADED_COUNT = 6,
- TRADE_SLOT_NONTRADED = 6
-};
-
-enum TransferAbortReason
-{
- TRANSFER_ABORT_NONE = 0x00,
- TRANSFER_ABORT_ERROR = 0x01,
- TRANSFER_ABORT_MAX_PLAYERS = 0x02, // Transfer Aborted: instance is full
- TRANSFER_ABORT_NOT_FOUND = 0x03, // Transfer Aborted: instance not found
- TRANSFER_ABORT_TOO_MANY_INSTANCES = 0x04, // You have entered too many instances recently.
- TRANSFER_ABORT_ZONE_IN_COMBAT = 0x06, // Unable to zone in while an encounter is in progress.
- TRANSFER_ABORT_INSUF_EXPAN_LVL = 0x07, // You must have <TBC,WotLK> expansion installed to access this area.
- TRANSFER_ABORT_DIFFICULTY = 0x08, // <Normal,Heroic,Epic> difficulty mode is not available for %s.
- TRANSFER_ABORT_UNIQUE_MESSAGE = 0x09, // Until you've escaped TLK's grasp, you cannot leave this place!
- TRANSFER_ABORT_TOO_MANY_REALM_INSTANCES = 0x0A, // Additional instances cannot be launched, please try again later.
- TRANSFER_ABORT_NEED_GROUP = 0x0B, // 3.1
- TRANSFER_ABORT_NOT_FOUND2 = 0x0C, // 3.1
- TRANSFER_ABORT_NOT_FOUND3 = 0x0D, // 3.1
- TRANSFER_ABORT_NOT_FOUND4 = 0x0E, // 3.2
- TRANSFER_ABORT_REALM_ONLY = 0x0F, // All players on party must be from the same realm.
- TRANSFER_ABORT_MAP_NOT_ALLOWED = 0x10, // Map can't be entered at this time.
-};
-
-enum InstanceResetWarningType
-{
- RAID_INSTANCE_WARNING_HOURS = 1, // WARNING! %s is scheduled to reset in %d hour(s).
- RAID_INSTANCE_WARNING_MIN = 2, // WARNING! %s is scheduled to reset in %d minute(s)!
- RAID_INSTANCE_WARNING_MIN_SOON = 3, // WARNING! %s is scheduled to reset in %d minute(s). Please exit the zone or you will be returned to your bind location!
- RAID_INSTANCE_WELCOME = 4, // Welcome to %s. This raid instance is scheduled to reset in %s.
- RAID_INSTANCE_EXPIRED = 5
-};
-
-// PLAYER_FIELD_ARENA_TEAM_INFO_1_1 offsets
-enum ArenaTeamInfoType
-{
- ARENA_TEAM_ID = 0,
- ARENA_TEAM_TYPE = 1, // new in 3.2 - team type?
- ARENA_TEAM_MEMBER = 2, // 0 - captain, 1 - member
- ARENA_TEAM_GAMES_WEEK = 3,
- ARENA_TEAM_GAMES_SEASON = 4,
- ARENA_TEAM_WINS_SEASON = 5,
- ARENA_TEAM_PERSONAL_RATING = 6,
- ARENA_TEAM_END = 7
-};
-
-class InstanceSave;
-
-enum RestType
-{
- REST_TYPE_NO = 0,
- REST_TYPE_IN_TAVERN = 1,
- REST_TYPE_IN_CITY = 2
-};
-
-enum DuelCompleteType
-{
- DUEL_INTERUPTED = 0,
- DUEL_WON = 1,
- DUEL_FLED = 2
-};
-
-enum TeleportToOptions
-{
- TELE_TO_GM_MODE = 0x01,
- TELE_TO_NOT_LEAVE_TRANSPORT = 0x02,
- TELE_TO_NOT_LEAVE_COMBAT = 0x04,
- TELE_TO_NOT_UNSUMMON_PET = 0x08,
- TELE_TO_SPELL = 0x10,
-};
-
-/// Type of environmental damages
-enum EnviromentalDamage
-{
- DAMAGE_EXHAUSTED = 0,
- DAMAGE_DROWNING = 1,
- DAMAGE_FALL = 2,
- DAMAGE_LAVA = 3,
- DAMAGE_SLIME = 4,
- DAMAGE_FIRE = 5,
- DAMAGE_FALL_TO_VOID = 6 // custom case for fall without durability loss
-};
-
-enum PlayedTimeIndex
-{
- PLAYED_TIME_TOTAL = 0,
- PLAYED_TIME_LEVEL = 1
-};
-
-#define MAX_PLAYED_TIME_INDEX 2
-
-// used at player loading query list preparing, and later result selection
-enum PlayerLoginQueryIndex
-{
- PLAYER_LOGIN_QUERY_LOADFROM = 0,
- PLAYER_LOGIN_QUERY_LOADGROUP = 1,
- PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES = 2,
- PLAYER_LOGIN_QUERY_LOADAURAS = 3,
- PLAYER_LOGIN_QUERY_LOADSPELLS = 4,
- PLAYER_LOGIN_QUERY_LOADQUESTSTATUS = 5,
- PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS = 6,
- PLAYER_LOGIN_QUERY_LOADREPUTATION = 7,
- PLAYER_LOGIN_QUERY_LOADINVENTORY = 8,
- PLAYER_LOGIN_QUERY_LOADACTIONS = 9,
- PLAYER_LOGIN_QUERY_LOADMAILCOUNT = 10,
- PLAYER_LOGIN_QUERY_LOADMAILDATE = 11,
- PLAYER_LOGIN_QUERY_LOADSOCIALLIST = 12,
- PLAYER_LOGIN_QUERY_LOADHOMEBIND = 13,
- PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS = 14,
- PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES = 15,
- PLAYER_LOGIN_QUERY_LOADGUILD = 16,
- PLAYER_LOGIN_QUERY_LOADARENAINFO = 17,
- PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS = 18,
- PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS = 19,
- PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS = 20,
- PLAYER_LOGIN_QUERY_LOADBGDATA = 21,
- PLAYER_LOGIN_QUERY_LOADGLYPHS = 22,
- PLAYER_LOGIN_QUERY_LOADTALENTS = 23,
- PLAYER_LOGIN_QUERY_LOADACCOUNTDATA = 24,
- PLAYER_LOGIN_QUERY_LOADSKILLS = 25,
- MAX_PLAYER_LOGIN_QUERY = 26
-};
-
-enum PlayerDelayedOperations
-{
- DELAYED_SAVE_PLAYER = 0x01,
- DELAYED_RESURRECT_PLAYER = 0x02,
- DELAYED_SPELL_CAST_DESERTER = 0x04,
- DELAYED_BG_MOUNT_RESTORE = 0x08, ///< Flag to restore mount state after teleport from BG
- DELAYED_BG_TAXI_RESTORE = 0x10, ///< Flag to restore taxi state after teleport from BG
- DELAYED_END
-};
-
-// Player summoning auto-decline time (in secs)
-#define MAX_PLAYER_SUMMON_DELAY (2*MINUTE)
-#define MAX_MONEY_AMOUNT (0x7FFFFFFF-1)
-
-struct InstancePlayerBind
-{
- InstanceSave *save;
- bool perm;
- /* permanent PlayerInstanceBinds are created in Raid/Heroic instances for players
- that aren't already permanently bound when they are inside when a boss is killed
- or when they enter an instance that the group leader is permanently bound to. */
- InstancePlayerBind() : save(NULL), perm(false) {}
-};
-
-struct AccessRequirement
-{
- uint8 levelMin;
- uint8 levelMax;
- uint8 heroicLevelMin;
- uint32 item;
- uint32 item2;
- uint32 heroicKey;
- uint32 heroicKey2;
- uint32 quest;
- std::string questFailedText;
- uint32 heroicQuest;
- std::string heroicQuestFailedText;
-};
-
-class PlayerTaxi
-{
- public:
- PlayerTaxi();
- ~PlayerTaxi() {}
- // Nodes
- void InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint8 level);
- void LoadTaxiMask(const char* data);
-
- bool IsTaximaskNodeKnown(uint32 nodeidx) const
- {
- uint8 field = uint8((nodeidx - 1) / 32);
- uint32 submask = 1<<((nodeidx-1)%32);
- return (m_taximask[field] & submask) == submask;
- }
- bool SetTaximaskNode(uint32 nodeidx)
- {
- uint8 field = uint8((nodeidx - 1) / 32);
- uint32 submask = 1<<((nodeidx-1)%32);
- if ((m_taximask[field] & submask) != submask )
- {
- m_taximask[field] |= submask;
- return true;
- }
- else
- return false;
- }
- void AppendTaximaskTo(ByteBuffer& data,bool all);
-
- // Destinations
- bool LoadTaxiDestinationsFromString(const std::string& values, uint32 team);
- std::string SaveTaxiDestinationsToString();
-
- void ClearTaxiDestinations() { m_TaxiDestinations.clear(); }
- void AddTaxiDestination(uint32 dest) { m_TaxiDestinations.push_back(dest); }
- uint32 GetTaxiSource() const { return m_TaxiDestinations.empty() ? 0 : m_TaxiDestinations.front(); }
- uint32 GetTaxiDestination() const { return m_TaxiDestinations.size() < 2 ? 0 : m_TaxiDestinations[1]; }
- uint32 GetCurrentTaxiPath() const;
- uint32 NextTaxiDestination()
- {
- m_TaxiDestinations.pop_front();
- return GetTaxiDestination();
- }
- bool empty() const { return m_TaxiDestinations.empty(); }
-
- friend std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi);
- private:
- TaxiMask m_taximask;
- std::deque<uint32> m_TaxiDestinations;
-};
-
-std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi);
-
-class Player;
-
-/// Holder for BattleGround data
-struct BGData
-{
- BGData() : bgInstanceID(0), bgTypeID(BATTLEGROUND_TYPE_NONE), bgAfkReportedCount(0), bgAfkReportedTimer(0),
- bgTeam(0), mountSpell(0) { ClearTaxiPath(); }
-
- uint32 bgInstanceID; ///< This variable is set to bg->m_InstanceID,
- /// when player is teleported to BG - (it is battleground's GUID)
- BattleGroundTypeId bgTypeID;
-
- std::set<uint32> bgAfkReporter;
- uint8 bgAfkReportedCount;
- time_t bgAfkReportedTimer;
-
- uint32 bgTeam; ///< What side the player will be added to
-
- uint32 mountSpell;
- uint32 taxiPath[2];
-
- WorldLocation joinPos; ///< From where player entered BG
-
- void ClearTaxiPath() { taxiPath[0] = taxiPath[1] = 0; }
- bool HasTaxiPath() const { return taxiPath[0] && taxiPath[1]; }
-};
-
-class Player : public Unit, public GridObject<Player>
-{
- friend class WorldSession;
- friend void Item::AddToUpdateQueueOf(Player *player);
- friend void Item::RemoveFromUpdateQueueOf(Player *player);
- public:
- explicit Player (WorldSession *session);
- ~Player ( );
-
- void CleanupsBeforeDelete(bool finalCleanup = true);
-
- static UpdateMask updateVisualBits;
- static void InitVisibleBits();
-
- void AddToWorld();
- void RemoveFromWorld();
-
- bool TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options = 0);
- void TeleportOutOfMap(Map *oldMap);
-
- bool TeleportTo(WorldLocation const &loc, uint32 options = 0)
- {
- return TeleportTo(loc.GetMapId(), loc.GetPositionX(), loc.GetPositionY(), loc.GetPositionZ(), loc.GetOrientation(), options);
- }
-
- bool TeleportToBGEntryPoint();
-
- void SetSummonPoint(uint32 mapid, float x, float y, float z)
- {
- m_summon_expire = time(NULL) + MAX_PLAYER_SUMMON_DELAY;
- m_summon_mapid = mapid;
- m_summon_x = x;
- m_summon_y = y;
- m_summon_z = z;
- }
- void SummonIfPossible(bool agree);
-
- bool 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 );
-
- void Update( uint32 time );
-
- static bool BuildEnumData( QueryResult_AutoPtr result, WorldPacket * p_data );
-
- void SetInWater(bool apply);
-
- bool IsInWater() const { return m_isInWater; }
- bool IsUnderWater() const;
- bool IsFalling() { return GetPositionZ() < m_lastFallZ; }
-
- void SendInitialPacketsBeforeAddToMap();
- void SendInitialPacketsAfterAddToMap();
- void SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg = 0);
- void SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint32 time);
-
- Creature* GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask);
- bool CanInteractWithNPCs(bool alive = true) const;
- GameObject* GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const;
-
- bool ToggleAFK();
- bool ToggleDND();
- bool isAFK() const { return HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_AFK); }
- bool isDND() const { return HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_DND); }
- uint8 chatTag() const;
- std::string afkMsg;
- std::string dndMsg;
-
- uint32 GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair, BarberShopStyleEntry const* newSkin=NULL);
-
- PlayerSocial *GetSocial() { return m_social; }
-
- PlayerTaxi m_taxi;
- void InitTaxiNodesForLevel() { m_taxi.InitTaxiNodesForLevel(getRace(), getClass(), getLevel()); }
- bool ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc = NULL, uint32 spellid = 0);
- bool ActivateTaxiPathTo(uint32 taxi_path_id, uint32 spellid = 0);
- void CleanupAfterTaxiFlight();
- void ContinueTaxiFlight();
- // mount_id can be used in scripting calls
- bool isAcceptWhispers() const { return m_ExtraFlags & PLAYER_EXTRA_ACCEPT_WHISPERS; }
- void SetAcceptWhispers(bool on) { if(on) m_ExtraFlags |= PLAYER_EXTRA_ACCEPT_WHISPERS; else m_ExtraFlags &= ~PLAYER_EXTRA_ACCEPT_WHISPERS; }
- bool isGameMaster() const { return m_ExtraFlags & PLAYER_EXTRA_GM_ON; }
- void SetGameMaster(bool on);
- bool isGMChat() const { return GetSession()->GetSecurity() >= SEC_MODERATOR && (m_ExtraFlags & PLAYER_EXTRA_GM_CHAT); }
- void SetGMChat(bool on) { if(on) m_ExtraFlags |= PLAYER_EXTRA_GM_CHAT; else m_ExtraFlags &= ~PLAYER_EXTRA_GM_CHAT; }
- bool isTaxiCheater() const { return m_ExtraFlags & PLAYER_EXTRA_TAXICHEAT; }
- void SetTaxiCheater(bool on) { if(on) m_ExtraFlags |= PLAYER_EXTRA_TAXICHEAT; else m_ExtraFlags &= ~PLAYER_EXTRA_TAXICHEAT; }
- bool isGMVisible() const { return !(m_ExtraFlags & PLAYER_EXTRA_GM_INVISIBLE); }
- void SetGMVisible(bool on);
- void SetPvPDeath(bool on) { if(on) m_ExtraFlags |= PLAYER_EXTRA_PVP_DEATH; else m_ExtraFlags &= ~PLAYER_EXTRA_PVP_DEATH; }
-
- void GiveXP(uint32 xp, Unit* victim);
- void GiveLevel(uint8 level);
-
- void InitStatsForLevel(bool reapplyMods = false);
-
- // Played Time Stuff
- time_t m_logintime;
- time_t m_Last_tick;
- uint32 m_Played_time[MAX_PLAYED_TIME_INDEX];
- uint32 GetTotalPlayedTime() { return m_Played_time[PLAYED_TIME_TOTAL]; }
- uint32 GetLevelPlayedTime() { return m_Played_time[PLAYED_TIME_LEVEL]; }
-
- void setDeathState(DeathState s); // overwrite Unit::setDeathState
-
- void InnEnter (int time,uint32 mapid, float x,float y,float z)
- {
- inn_pos_mapid = mapid;
- inn_pos_x = x;
- inn_pos_y = y;
- inn_pos_z = z;
- time_inn_enter = time;
- }
-
- float GetRestBonus() const { return m_rest_bonus; }
- void SetRestBonus(float rest_bonus_new);
-
- RestType GetRestType() const { return rest_type; }
- void SetRestType(RestType n_r_type) { rest_type = n_r_type; }
-
- uint32 GetInnPosMapId() const { return inn_pos_mapid; }
- float GetInnPosX() const { return inn_pos_x; }
- float GetInnPosY() const { return inn_pos_y; }
- float GetInnPosZ() const { return inn_pos_z; }
-
- int GetTimeInnEnter() const { return time_inn_enter; }
- void UpdateInnerTime (int time) { time_inn_enter = time; }
-
- Pet* GetPet() const;
- Pet* SummonPet(uint32 entry, float x, float y, float z, float ang, PetType petType, uint32 despwtime);
- void RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent = false);
- uint32 GetPhaseMaskForSpawn() const; // used for proper set phase for DB at GM-mode creature/GO spawn
-
- void Say(const std::string& text, const uint32 language);
- void Yell(const std::string& text, const uint32 language);
- void TextEmote(const std::string& text);
- void Whisper(const std::string& text, const uint32 language,uint64 receiver);
- void BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const;
-
- /*********************************************************/
- /*** STORAGE SYSTEM ***/
- /*********************************************************/
-
- void SetVirtualItemSlot( uint8 i, Item* item);
- void SetSheath( SheathState sheathed ); // overwrite Unit version
- uint8 FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const;
- uint32 GetItemCount( uint32 item, bool inBankAlso = false, Item* skipItem = NULL ) const;
- Item* GetItemByGuid( uint64 guid ) const;
- Item* GetItemByEntry( uint32 entry ) const;
- Item* GetItemByPos( uint16 pos ) const;
- Item* GetItemByPos( uint8 bag, uint8 slot ) const;
- inline Item* GetUseableItemByPos( uint8 bag, uint8 slot ) const //Does additional check for disarmed weapons
- {
- if (!CanUseAttackType(GetAttackBySlot(slot)))
- return NULL;
- return GetItemByPos(bag, slot);
- }
- Item* GetWeaponForAttack(WeaponAttackType attackType, bool useable = false) const;
- Item* GetShield(bool useable = false) const;
- static uint8 GetAttackBySlot( uint8 slot ); // MAX_ATTACK if not weapon slot
- std::vector<Item *> &GetItemUpdateQueue() { return m_itemUpdateQueue; }
- static bool IsInventoryPos( uint16 pos ) { return IsInventoryPos(pos >> 8,pos & 255); }
- static bool IsInventoryPos( uint8 bag, uint8 slot );
- static bool IsEquipmentPos( uint16 pos ) { return IsEquipmentPos(pos >> 8,pos & 255); }
- static bool IsEquipmentPos( uint8 bag, uint8 slot );
- static bool IsBagPos( uint16 pos );
- static bool IsBankPos( uint16 pos ) { return IsBankPos(pos >> 8,pos & 255); }
- static bool IsBankPos( uint8 bag, uint8 slot );
- bool IsValidPos( uint16 pos ) { return IsBankPos(pos >> 8,pos & 255); }
- bool IsValidPos( uint8 bag, uint8 slot );
- uint8 GetBankBagSlotCount() const { return GetByteValue(PLAYER_BYTES_2, 2); }
- void SetBankBagSlotCount(uint8 count) { SetByteValue(PLAYER_BYTES_2, 2, count); }
- bool HasItemCount( uint32 item, uint32 count, bool inBankAlso = false ) const;
- bool HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem = NULL);
- bool CanNoReagentCast(SpellEntry const* spellInfo) const;
- bool HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot = NULL_SLOT) const;
- bool HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot = NULL_SLOT) const;
- uint8 CountItemWithLimitCategory(uint32 limitCategory, Item* skipItem = NULL) const;
- uint8 CanTakeMoreSimilarItems(Item* pItem) const { return _CanTakeMoreSimilarItems(pItem->GetEntry(),pItem->GetCount(),pItem); }
- uint8 CanTakeMoreSimilarItems(uint32 entry, uint32 count) const { return _CanTakeMoreSimilarItems(entry,count,NULL); }
- uint8 CanStoreNewItem( uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 item, uint32 count, uint32* no_space_count = NULL ) const
- {
- return _CanStoreItem(bag, slot, dest, item, count, NULL, false, no_space_count );
- }
- uint8 CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec& dest, Item *pItem, bool swap = false ) const
- {
- if(!pItem)
- return EQUIP_ERR_ITEM_NOT_FOUND;
- uint32 count = pItem->GetCount();
- return _CanStoreItem( bag, slot, dest, pItem->GetEntry(), count, pItem, swap, NULL );
-
- }
- uint8 CanStoreItems( Item **pItem,int count) const;
- uint8 CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const;
- uint8 CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading = true ) const;
-
- uint8 CanEquipUniqueItem( Item * pItem, uint8 except_slot = NULL_SLOT, uint32 limit_count = 1 ) const;
- uint8 CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot = NULL_SLOT, uint32 limit_count = 1 ) const;
- uint8 CanUnequipItems( uint32 item, uint32 count ) const;
- uint8 CanUnequipItem( uint16 src, bool swap ) const;
- uint8 CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec& dest, Item *pItem, bool swap, bool not_loading = true ) const;
- uint8 CanUseItem( Item *pItem, bool not_loading = true ) const;
- bool HasItemTotemCategory( uint32 TotemCategory ) const;
- bool CanUseItem( ItemPrototype const *pItem );
- uint8 CanUseAmmo( uint32 item ) const;
- Item* StoreNewItem( ItemPosCountVec const& pos, uint32 item, bool update,int32 randomPropertyId = 0 );
- Item* StoreItem( ItemPosCountVec const& pos, Item *pItem, bool update );
- Item* EquipNewItem( uint16 pos, uint32 item, bool update );
- Item* EquipItem( uint16 pos, Item *pItem, bool update );
- void AutoUnequipOffhandIfNeed(bool force = false);
- bool StoreNewItemInBestSlots(uint32 item_id, uint32 item_count);
- void AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast = false);
- void AutoStoreLoot(uint32 loot_id, LootStore const& store, bool broadcast = false) { AutoStoreLoot(NULL_BAG,NULL_SLOT,loot_id,store,broadcast); }
-
- uint8 _CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count = NULL) const;
- uint8 _CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 entry, uint32 count, Item *pItem = NULL, bool swap = false, uint32* no_space_count = NULL ) const;
-
- void ApplyEquipCooldown( Item * pItem );
- void SetAmmo( uint32 item );
- void RemoveAmmo();
- float GetAmmoDPS() const { return m_ammoDPS; }
- bool CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const;
- void QuickEquipItem( uint16 pos, Item *pItem);
- void VisualizeItem( uint8 slot, Item *pItem);
- void SetVisibleItemSlot(uint8 slot, Item *pItem);
- Item* BankItem( ItemPosCountVec const& dest, Item *pItem, bool update )
- {
- return StoreItem( dest, pItem, update);
- }
- Item* BankItem( uint16 pos, Item *pItem, bool update );
- void RemoveItem( uint8 bag, uint8 slot, bool update );
- void MoveItemFromInventory(uint8 bag, uint8 slot, bool update);
- // in trade, auction, guild bank, mail....
- void MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB = false);
- // in trade, guild bank, mail....
- void RemoveItemDependentAurasAndCasts( Item * pItem );
- void DestroyItem( uint8 bag, uint8 slot, bool update );
- void DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check = false);
- void DestroyItemCount( Item* item, uint32& count, bool update );
- void DestroyConjuredItems( bool update );
- void DestroyZoneLimitedItem( bool update, uint32 new_zone );
- void SplitItem( uint16 src, uint16 dst, uint32 count );
- void SwapItem( uint16 src, uint16 dst );
- void AddItemToBuyBackSlot( Item *pItem );
- Item* GetItemFromBuyBackSlot( uint32 slot );
- void RemoveItemFromBuyBackSlot( uint32 slot, bool del );
- uint32 GetMaxKeyringSize() const { return KEYRING_SLOT_END-KEYRING_SLOT_START; }
- void SendEquipError( uint8 msg, Item* pItem, Item *pItem2 );
- void SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param );
- void SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param );
- void AddWeaponProficiency(uint32 newflag) { m_WeaponProficiency |= newflag; }
- void AddArmorProficiency(uint32 newflag) { m_ArmorProficiency |= newflag; }
- uint32 GetWeaponProficiency() const { return m_WeaponProficiency; }
- uint32 GetArmorProficiency() const { return m_ArmorProficiency; }
- bool IsUseEquipedWeapon( bool mainhand ) const
- {
- // disarm applied only to mainhand weapon
- return !IsInFeralForm() && (!mainhand || !HasFlag(UNIT_FIELD_FLAGS,UNIT_FLAG_DISARMED) );
- }
- bool IsTwoHandUsed() const
- {
- Item* mainItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
- return mainItem && mainItem->GetProto()->InventoryType == INVTYPE_2HWEAPON && !CanTitanGrip();
- }
- void SendNewItem( Item *item, uint32 count, bool received, bool created, bool broadcast = false );
- bool BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint8 bag, uint8 slot);
-
- float GetReputationPriceDiscount( Creature const* pCreature ) const;
- Player* GetTrader() const { return pTrader; }
- void ClearTrade();
- void TradeCancel(bool sendback);
-
- void UpdateEnchantTime(uint32 time);
- void UpdateItemDuration(uint32 time, bool realtimeonly=false);
- void AddEnchantmentDurations(Item *item);
- void RemoveEnchantmentDurations(Item *item);
- void RemoveArenaEnchantments(EnchantmentSlot slot);
- void AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration);
- void ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur = true, bool ignore_condition = false);
- void ApplyEnchantment(Item *item,bool apply);
- void SendEnchantmentDurations();
- void BuildEnchantmentsInfoData(WorldPacket *data);
- void AddItemDurations(Item *item);
- void RemoveItemDurations(Item *item);
- void SendItemDurations();
- void LoadCorpse();
- void LoadPet();
-
- uint32 m_stableSlots;
-
- /*********************************************************/
- /*** GOSSIP SYSTEM ***/
- /*********************************************************/
-
- void PrepareGossipMenu(WorldObject *pSource, uint32 menuId = 0);
- void SendPreparedGossip(WorldObject *pSource);
- void OnGossipSelect(WorldObject *pSource, uint32 gossipListId, uint32 menuId);
-
- uint32 GetGossipTextId(uint32 menuId);
- uint32 GetGossipTextId(WorldObject *pSource);
- uint32 GetDefaultGossipMenuForSource(WorldObject *pSource);
-
- /*********************************************************/
- /*** QUEST SYSTEM ***/
- /*********************************************************/
-
- int32 GetQuestLevel( Quest const* pQuest ) const { return pQuest && (pQuest->GetQuestLevel() > 0) ? pQuest->GetQuestLevel() : getLevel(); }
-
- void PrepareQuestMenu( uint64 guid );
- void SendPreparedQuest( uint64 guid );
- bool IsActiveQuest( uint32 quest_id ) const;
- Quest const *GetNextQuest( uint64 guid, Quest const *pQuest );
- bool CanSeeStartQuest( Quest const *pQuest );
- bool CanTakeQuest( Quest const *pQuest, bool msg );
- bool CanAddQuest( Quest const *pQuest, bool msg );
- bool CanCompleteQuest( uint32 quest_id );
- bool CanCompleteRepeatableQuest(Quest const *pQuest);
- bool CanRewardQuest( Quest const *pQuest, bool msg );
- bool CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg );
- void AddQuest( Quest const *pQuest, Object *questGiver );
- void CompleteQuest( uint32 quest_id );
- void IncompleteQuest( uint32 quest_id );
- void RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce = true );
- void FailQuest( uint32 quest_id );
- bool SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg );
- bool SatisfyQuestLevel( Quest const* qInfo, bool msg );
- bool SatisfyQuestLog( bool msg );
- bool SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg );
- bool SatisfyQuestRace( Quest const* qInfo, bool msg );
- bool SatisfyQuestReputation( Quest const* qInfo, bool msg );
- bool SatisfyQuestStatus( Quest const* qInfo, bool msg );
- bool SatisfyQuestTimed( Quest const* qInfo, bool msg );
- bool SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg );
- bool SatisfyQuestNextChain( Quest const* qInfo, bool msg );
- bool SatisfyQuestPrevChain( Quest const* qInfo, bool msg );
- bool SatisfyQuestDay( Quest const* qInfo, bool msg );
- bool GiveQuestSourceItem( Quest const *pQuest );
- bool TakeQuestSourceItem( uint32 quest_id, bool msg );
- bool GetQuestRewardStatus( uint32 quest_id ) const;
- QuestStatus GetQuestStatus( uint32 quest_id ) const;
- void SetQuestStatus( uint32 quest_id, QuestStatus status );
-
- void SetDailyQuestStatus( uint32 quest_id );
- void ResetDailyQuestStatus();
-
- uint16 FindQuestSlot( uint32 quest_id ) const;
- uint32 GetQuestSlotQuestId(uint16 slot) const { return GetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_ID_OFFSET); }
- uint32 GetQuestSlotState(uint16 slot) const { return GetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET); }
- uint16 GetQuestSlotCounter(uint16 slot, uint8 counter) const { return (uint16)(GetUInt64Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET) >> (counter * 16)); }
- uint32 GetQuestSlotTime(uint16 slot) const { return GetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_TIME_OFFSET); }
- void SetQuestSlot(uint16 slot, uint32 quest_id, uint32 timer = 0)
- {
- SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_ID_OFFSET, quest_id);
- SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, 0);
- SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET, 0);
- SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET + 1, 0);
- SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_TIME_OFFSET, timer);
- }
- void SetQuestSlotCounter(uint16 slot, uint8 counter, uint16 count)
- {
- uint64 val = GetUInt64Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET);
- val &= ~((uint64)0xFFFF << (counter * 16));
- val |= ((uint64)count << (counter * 16));
- SetUInt64Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET, val);
- }
- void SetQuestSlotState(uint16 slot, uint32 state) { SetFlag(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, state); }
- void RemoveQuestSlotState(uint16 slot, uint32 state) { RemoveFlag(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, state); }
- void SetQuestSlotTimer(uint16 slot, uint32 timer) { SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_TIME_OFFSET, timer); }
- void SwapQuestSlot(uint16 slot1, uint16 slot2)
- {
- for (int i = 0; i < MAX_QUEST_OFFSET; ++i)
- {
- uint32 temp1 = GetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot1 + i);
- uint32 temp2 = GetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot2 + i);
-
- SetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot1 + i, temp2);
- SetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot2 + i, temp1);
- }
- }
- uint32 GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry);
- void AreaExploredOrEventHappens( uint32 questId );
- void GroupEventHappens( uint32 questId, WorldObject const* pEventObject );
- void ItemAddedQuestCheck( uint32 entry, uint32 count );
- void ItemRemovedQuestCheck( uint32 entry, uint32 count );
- void KilledMonster( CreatureInfo const* cInfo, uint64 guid );
- void KilledMonsterCredit( uint32 entry, uint64 guid );
- void CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id );
- void TalkedToCreature( uint32 entry, uint64 guid );
- void MoneyChanged( uint32 value );
- void ReputationChanged(FactionEntry const* factionEntry );
- void ReputationChanged2(FactionEntry const* factionEntry );
- bool HasQuestForItem( uint32 itemid ) const;
- bool HasQuestForGO(int32 GOId) const;
- void UpdateForQuestWorldObjects();
- bool CanShareQuest(uint32 quest_id) const;
-
- void SendQuestComplete( uint32 quest_id );
- void SendQuestReward( Quest const *pQuest, uint32 XP, Object* questGiver );
- void SendQuestFailed( uint32 quest_id );
- void SendQuestTimerFailed( uint32 quest_id );
- void SendCanTakeQuestResponse( uint32 msg );
- void SendQuestConfirmAccept(Quest const* pQuest, Player* pReceiver);
- void SendPushToPartyResponse( Player *pPlayer, uint32 msg );
- void SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count );
- void SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count );
-
- uint64 GetDivider() { return m_divider; }
- void SetDivider( uint64 guid ) { m_divider = guid; }
-
- uint32 GetInGameTime() { return m_ingametime; }
-
- void SetInGameTime( uint32 time ) { m_ingametime = time; }
-
- void AddTimedQuest( uint32 quest_id ) { m_timedquests.insert(quest_id); }
- void RemoveTimedQuest( uint32 quest_id ) { m_timedquests.erase(quest_id); }
-
- /*********************************************************/
- /*** LOAD SYSTEM ***/
- /*********************************************************/
-
- bool LoadFromDB(uint32 guid, SqlQueryHolder *holder);
- bool isBeingLoaded() const { return GetSession()->PlayerLoading();}
-
- bool MinimalLoadFromDB(QueryResult_AutoPtr result, uint32 guid);
- static bool LoadValuesArrayFromDB(Tokens& data,uint64 guid);
- static uint32 GetUInt32ValueFromArray(Tokens const& data, uint16 index);
- static float GetFloatValueFromArray(Tokens const& data, uint16 index);
- static uint32 GetUInt32ValueFromDB(uint16 index, uint64 guid);
- static float GetFloatValueFromDB(uint16 index, uint64 guid);
- static uint32 GetZoneIdFromDB(uint64 guid);
- static uint32 GetLevelFromDB(uint64 guid);
- static bool LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid);
-
- /*********************************************************/
- /*** SAVE SYSTEM ***/
- /*********************************************************/
-
- void SaveToDB();
- void SaveInventoryAndGoldToDB(); // fast save function for item/money cheating preventing
- void SaveGoldToDB();
- void SaveDataFieldToDB();
- static bool SaveValuesArrayInDB(Tokens const& data,uint64 guid);
- static void SetUInt32ValueInArray(Tokens& data,uint16 index, uint32 value);
- static void SetFloatValueInArray(Tokens& data,uint16 index, float value);
- static void SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid);
- static void SetFloatValueInDB(uint16 index, float value, uint64 guid);
- static void Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair);
- static void SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid);
-
- bool m_mailsLoaded;
- bool m_mailsUpdated;
-
- void SetBindPoint(uint64 guid);
- void SendTalentWipeConfirm(uint64 guid);
- void SendPetSkillWipeConfirm();
- void CalcRage( uint32 damage,bool attacker );
- void RegenerateAll();
- void Regenerate(Powers power);
- void RegenerateHealth();
- void setRegenTimerCount(uint32 time) {m_regenTimerCount = time;}
- void setWeaponChangeTimer(uint32 time) {m_weaponChangeTimer = time;}
-
- uint32 GetMoney() { return GetUInt32Value (PLAYER_FIELD_COINAGE); }
- void ModifyMoney( int32 d )
- {
- d = GetSession()->HandleOnGetMoney(d);
- if(d < 0)
- SetMoney (GetMoney() > uint32(-d) ? GetMoney() + d : 0);
- else
- SetMoney (GetMoney() < uint32(MAX_MONEY_AMOUNT - d) ? GetMoney() + d : MAX_MONEY_AMOUNT);
-
- // "At Gold Limit"
- if(GetMoney() >= MAX_MONEY_AMOUNT)
- SendEquipError(EQUIP_ERR_TOO_MUCH_GOLD,NULL,NULL);
- }
- void SetMoney( uint32 value )
- {
- SetUInt32Value (PLAYER_FIELD_COINAGE, value);
- MoneyChanged( value );
- UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED);
- }
-
- QuestStatusMap& getQuestStatusMap() { return mQuestStatus; };
-
- const uint64& GetSelection( ) const { return m_curSelection; }
- Unit *GetSelectedUnit() const;
- Player *GetSelectedPlayer() const;
- void SetSelection(const uint64 &guid) { m_curSelection = guid; SetUInt64Value(UNIT_FIELD_TARGET, guid); }
-
- uint8 GetComboPoints() { return m_comboPoints; }
- const uint64& GetComboTarget() const { return m_comboTarget; }
-
- void AddComboPoints(Unit* target, int8 count, Spell * spell = NULL);
- void GainSpellComboPoints(int8 count);
- void ClearComboPoints();
- void SendComboPoints();
-
- void SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError = 0, uint32 item_guid = 0, uint32 item_count = 0);
- void SendNewMail();
- void UpdateNextMailTimeAndUnreads();
- void AddNewMailDeliverTime(time_t deliver_time);
- bool IsMailsLoaded() const { return m_mailsLoaded; }
-
- void RemoveMail(uint32 id);
-
- void AddMail(Mail* mail) { m_mail.push_front(mail);}// for call from WorldSession::SendMailTo
- uint32 GetMailSize() { return m_mail.size();}
- Mail* GetMail(uint32 id);
-
- PlayerMails::iterator GetMailBegin() { return m_mail.begin();}
- PlayerMails::iterator GetMailEnd() { return m_mail.end();}
-
- /*********************************************************/
- /*** MAILED ITEMS SYSTEM ***/
- /*********************************************************/
-
- uint8 unReadMails;
- time_t m_nextMailDelivereTime;
-
- typedef UNORDERED_MAP<uint32, Item*> ItemMap;
-
- ItemMap mMitems; //template defined in objectmgr.cpp
-
- Item* GetMItem(uint32 id)
- {
- ItemMap::const_iterator itr = mMitems.find(id);
- return itr != mMitems.end() ? itr->second : NULL;
- }
-
- void AddMItem(Item* it)
- {
- ASSERT( it );
- //assert deleted, because items can be added before loading
- mMitems[it->GetGUIDLow()] = it;
- }
-
- bool RemoveMItem(uint32 id)
- {
- return mMitems.erase(id) ? true : false;
- }
-
- void PetSpellInitialize();
- void CharmSpellInitialize();
- void PossessSpellInitialize();
- void VehicleSpellInitialize();
- void SendRemoveControlBar();
- bool HasSpell(uint32 spell) const;
- bool HasActiveSpell(uint32 spell) const; // show in spellbook
- TrainerSpellState GetTrainerSpellState(TrainerSpell const* trainer_spell) const;
- bool IsSpellFitByClassAndRace( uint32 spell_id ) const;
- bool IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const;
-
- void SendProficiency(uint8 pr1, uint32 pr2);
- void SendInitialSpells();
- bool addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled);
- void learnSpell(uint32 spell_id, bool dependent);
- void removeSpell(uint32 spell_id, bool disabled = false, bool learn_low_rank = true);
- void resetSpells(bool myClassOnly = false);
- void learnDefaultSpells();
- void learnQuestRewardedSpells();
- void learnQuestRewardedSpells(Quest const* quest);
- void learnSpellHighRank(uint32 spellid);
- void AddTemporarySpell(uint32 spellId);
- void RemoveTemporarySpell(uint32 spellId);
- void SetReputation(uint32 factionentry, uint32 value);
- uint32 GetReputation(uint32 factionentry);
- std::string GetGuildName();
- uint32 GetFreeTalentPoints() const { return GetUInt32Value(PLAYER_CHARACTER_POINTS1); }
- void SetFreeTalentPoints(uint32 points) { SetUInt32Value(PLAYER_CHARACTER_POINTS1,points); }
- bool resetTalents(bool no_cost = false);
- uint32 resetTalentsCost() const;
- void InitTalentForLevel();
- void BuildPlayerTalentsInfoData(WorldPacket *data);
- void BuildPetTalentsInfoData(WorldPacket *data);
- void SendTalentsInfoData(bool pet);
- void LearnTalent(uint32 talentId, uint32 talentRank);
- void LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank);
-
- bool AddTalent(uint32 spell, uint8 spec, bool learning);
- bool HasTalent(uint32 spell_id, uint8 spec) const;
-
- uint32 CalculateTalentsPoints() const;
-
- // Dual Spec
- void UpdateSpecCount(uint8 count);
- uint32 GetActiveSpec() { return m_activeSpec; }
- void SetActiveSpec(uint8 spec){ m_activeSpec = spec; }
- uint8 GetSpecsCount() { return m_specsCount; }
- void SetSpecsCount(uint8 count) { m_specsCount = count; }
- void ActivateSpec(uint8 spec);
-
- void InitGlyphsForLevel();
- void SetGlyphSlot(uint8 slot, uint32 slottype) { SetUInt32Value(PLAYER_FIELD_GLYPH_SLOTS_1 + slot, slottype); }
- uint32 GetGlyphSlot(uint8 slot) { return GetUInt32Value(PLAYER_FIELD_GLYPH_SLOTS_1 + slot); }
- void SetGlyph(uint8 slot, uint32 glyph)
- {
- m_Glyphs[m_activeSpec][slot] = glyph;
- SetUInt32Value(PLAYER_FIELD_GLYPHS_1 + slot, glyph);
- }
- uint32 GetGlyph(uint8 slot) { return m_Glyphs[m_activeSpec][slot]; }
-
- uint32 GetFreePrimaryProfessionPoints() const { return GetUInt32Value(PLAYER_CHARACTER_POINTS2); }
- void SetFreePrimaryProfessions(uint16 profs) { SetUInt32Value(PLAYER_CHARACTER_POINTS2, profs); }
- void InitPrimaryProfessions();
-
- PlayerSpellMap const& GetSpellMap() const { return m_spells; }
- PlayerSpellMap & GetSpellMap() { return m_spells; }
-
- SpellCooldowns const& GetSpellCooldownMap() const { return m_spellCooldowns; }
-
- void AddSpellMod(SpellModifier* mod, bool apply);
- bool IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell * spell = NULL);
- template <class T> T ApplySpellMod(uint32 spellId, SpellModOp op, T &basevalue, Spell * spell = NULL);
- void RemoveSpellMods(Spell * spell);
- void RestoreSpellMods(Spell * spell);
- void DropModCharge(SpellModifier * mod, Spell * spell);
- void SetSpellModTakingSpell(Spell* spell, bool apply);
-
- static uint32 const infinityCooldownDelay = MONTH; // used for set "infinity cooldowns" for spells and check
- static uint32 const infinityCooldownDelayCheck = MONTH/2;
- bool HasSpellCooldown(uint32 spell_id) const
- {
- SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id);
- return itr != m_spellCooldowns.end() && itr->second.end > time(NULL);
- }
- uint32 GetSpellCooldownDelay(uint32 spell_id) const
- {
- SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id);
- time_t t = time(NULL);
- return itr != m_spellCooldowns.end() && itr->second.end > t ? itr->second.end - t : 0;
- }
- void AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell = NULL, bool infinityCooldown = false );
- void AddSpellCooldown(uint32 spell_id, uint32 itemid, time_t end_time);
- void SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId = 0, Spell* spell = NULL);
- void ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs );
- void RemoveSpellCooldown(uint32 spell_id, bool update = false);
- void RemoveSpellCategoryCooldown(uint32 cat, bool update = false);
- void SendClearCooldown( uint32 spell_id, Unit* target );
-
- void RemoveCategoryCooldown(uint32 cat);
- void RemoveArenaSpellCooldowns();
- void RemoveAllSpellCooldown();
- void _LoadSpellCooldowns(QueryResult_AutoPtr result);
- void _SaveSpellCooldowns();
- void SetLastPotionId(uint32 item_id) { m_lastPotionId = item_id; }
- void UpdatePotionCooldown(Spell* spell = NULL);
-
- void setResurrectRequestData(uint64 guid, uint32 mapId, float X, float Y, float Z, uint32 health, uint32 mana)
- {
- m_resurrectGUID = guid;
- m_resurrectMap = mapId;
- m_resurrectX = X;
- m_resurrectY = Y;
- m_resurrectZ = Z;
- m_resurrectHealth = health;
- m_resurrectMana = mana;
- }
- void clearResurrectRequestData() { setResurrectRequestData(0,0,0.0f,0.0f,0.0f,0,0); }
- bool isRessurectRequestedBy(uint64 guid) const { return m_resurrectGUID == guid; }
- bool isRessurectRequested() const { return m_resurrectGUID != 0; }
- void ResurectUsingRequestData();
-
- int getCinematic()
- {
- return m_cinematic;
- }
- void setCinematic(int cine)
- {
- m_cinematic = cine;
- }
-
- ActionButton* addActionButton(uint8 button, uint32 action, uint8 type);
- void removeActionButton(uint8 button);
- void SendInitialActionButtons() const { SendActionButtons(0); }
- void SendActionButtons(uint32 state) const;
-
- PvPInfo pvpInfo;
- void UpdatePvPState(bool onlyFFA = false);
- void SetPvP(bool state)
- {
- Unit::SetPvP(state);
- for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
- (*itr)->SetPvP(state);
- }
- void UpdatePvP(bool state, bool override=false);
- void UpdateZone(uint32 newZone,uint32 newArea);
- void UpdateArea(uint32 newArea);
-
- void UpdateZoneDependentAuras( uint32 zone_id ); // zones
- void UpdateAreaDependentAuras( uint32 area_id ); // subzones
-
- void UpdateAfkReport(time_t currTime);
- void UpdatePvPFlag(time_t currTime);
- void UpdateContestedPvP(uint32 currTime);
- void SetContestedPvPTimer(uint32 newTime) {m_contestedPvPTimer = newTime;}
- void ResetContestedPvP()
- {
- clearUnitState(UNIT_STAT_ATTACK_PLAYER);
- RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
- m_contestedPvPTimer = 0;
- }
-
- /** todo: -maybe move UpdateDuelFlag+DuelComplete to independent DuelHandler.. **/
- DuelInfo *duel;
- void UpdateDuelFlag(time_t currTime);
- void CheckDuelDistance(time_t currTime);
- void DuelComplete(DuelCompleteType type);
- void SendDuelCountdown(uint32 counter);
-
- bool IsGroupVisibleFor(Player* p) const;
- bool IsInSameGroupWith(Player const* p) const;
- bool IsInSameRaidWith(Player const* p) const { return p==this || (GetGroup() != NULL && GetGroup() == p->GetGroup()); }
- void UninviteFromGroup();
- static void RemoveFromGroup(Group* group, uint64 guid);
- void RemoveFromGroup() { RemoveFromGroup(GetGroup(),GetGUID()); }
- void SendUpdateToOutOfRangeGroupMembers();
-
- void SetInGuild(uint32 GuildId) { SetUInt32Value(PLAYER_GUILDID, GuildId); }
- void SetRank(uint32 rankId){ SetUInt32Value(PLAYER_GUILDRANK, rankId); }
- void SetGuildIdInvited(uint32 GuildId) { m_GuildIdInvited = GuildId; }
- uint32 GetGuildId() { return GetUInt32Value(PLAYER_GUILDID); }
- static uint32 GetGuildIdFromDB(uint64 guid);
- uint32 GetRank(){ return GetUInt32Value(PLAYER_GUILDRANK); }
- static uint32 GetRankFromDB(uint64 guid);
- int GetGuildIdInvited() { return m_GuildIdInvited; }
- static void RemovePetitionsAndSigns(uint64 guid, uint32 type);
-
- // Arena Team
- void SetInArenaTeam(uint32 ArenaTeamId, uint8 slot, uint8 type)
- {
- SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END) + ARENA_TEAM_ID, ArenaTeamId);
- SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END) + ARENA_TEAM_TYPE, type);
- }
- uint32 GetArenaTeamId(uint8 slot) { return GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END)); }
- static uint32 GetArenaTeamIdFromDB(uint64 guid, uint8 slot);
- void SetArenaTeamIdInvited(uint32 ArenaTeamId) { m_ArenaTeamIdInvited = ArenaTeamId; }
- uint32 GetArenaTeamIdInvited() { return m_ArenaTeamIdInvited; }
- static void LeaveAllArenaTeams(uint64 guid);
-
- Difficulty GetDifficulty(bool isRaid) const { return isRaid ? m_raidDifficulty : m_dungeonDifficulty; }
- Difficulty GetDungeonDifficulty() const { return m_dungeonDifficulty; }
- Difficulty GetRaidDifficulty() const { return m_raidDifficulty; }
- void SetDungeonDifficulty(Difficulty dungeon_difficulty) { m_dungeonDifficulty = dungeon_difficulty; }
- void SetRaidDifficulty(Difficulty raid_difficulty) { m_raidDifficulty = raid_difficulty; }
-
- bool UpdateSkill(uint32 skill_id, uint32 step);
- bool UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step);
-
- bool UpdateCraftSkill(uint32 spellid);
- bool UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator = 1);
- bool UpdateFishingSkill();
-
- uint32 GetBaseDefenseSkillValue() const { return GetBaseSkillValue(SKILL_DEFENSE); }
- uint32 GetBaseWeaponSkillValue(WeaponAttackType attType) const;
-
- uint32 GetSpellByProto(ItemPrototype *proto);
-
- float GetHealthBonusFromStamina();
- float GetManaBonusFromIntellect();
-
- bool UpdateStats(Stats stat);
- bool UpdateAllStats();
- void UpdateResistances(uint32 school);
- void UpdateArmor();
- void UpdateMaxHealth();
- void UpdateMaxPower(Powers power);
- void ApplyFeralAPBonus(int32 amount, bool apply);
- void UpdateAttackPowerAndDamage(bool ranged = false);
- void UpdateShieldBlockValue();
- void UpdateDamagePhysical(WeaponAttackType attType);
- void ApplySpellPowerBonus(int32 amount, bool apply);
- void UpdateSpellDamageAndHealingBonus();
- void ApplyRatingMod(CombatRating cr, int32 value, bool apply);
- void UpdateRating(CombatRating cr);
- void UpdateAllRatings();
-
- void CalculateMinMaxDamage(WeaponAttackType attType, bool normalized, bool addTotalPct, float& min_damage, float& max_damage);
-
- void UpdateDefenseBonusesMod();
- inline void RecalculateRating(CombatRating cr) { ApplyRatingMod(cr, 0, true);}
- float GetMeleeCritFromAgility();
- float GetDodgeFromAgility();
- float GetSpellCritFromIntellect();
- float OCTRegenHPPerSpirit();
- float OCTRegenMPPerSpirit();
- float GetRatingCoefficient(CombatRating cr) const;
- float GetRatingBonusValue(CombatRating cr) const;
- uint32 GetBaseSpellPowerBonus() { return m_baseSpellPower; }
-
- float GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const;
- void UpdateBlockPercentage();
- void UpdateCritPercentage(WeaponAttackType attType);
- void UpdateAllCritPercentages();
- void UpdateParryPercentage();
- void UpdateDodgePercentage();
- void UpdateMeleeHitChances();
- void UpdateRangedHitChances();
- void UpdateSpellHitChances();
-
- void UpdateAllSpellCritChances();
- void UpdateSpellCritChance(uint32 school);
- void UpdateArmorPenetration(int32 amount);
- void UpdateExpertise(WeaponAttackType attType);
- void ApplyManaRegenBonus(int32 amount, bool apply);
- void ApplyHealthRegenBonus(int32 amount, bool apply);
- void UpdateManaRegen();
-
- const uint64& GetLootGUID() const { return m_lootGuid; }
- void SetLootGUID(const uint64 &guid) { m_lootGuid = guid; }
-
- void RemovedInsignia(Player* looterPlr);
-
- WorldSession* GetSession() const { return m_session; }
- void SetSession(WorldSession *s) { m_session = s; }
-
- void BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const;
- void DestroyForPlayer( Player *target, bool anim = false ) const;
- void SendLogXPGain(uint32 GivenXP,Unit* victim,uint32 RestXP);
-
- // notifiers
- void SendAttackSwingCantAttack();
- void SendAttackSwingCancelAttack();
- void SendAttackSwingDeadTarget();
- void SendAttackSwingNotInRange();
- void SendAttackSwingBadFacingAttack();
- void SendAutoRepeatCancel(Unit *target);
- void SendExplorationExperience(uint32 Area, uint32 Experience);
-
- void SendDungeonDifficulty(bool IsInGroup);
- void SendRaidDifficulty(bool IsInGroup);
- void ResetInstances(uint8 method, bool isRaid);
- void SendResetInstanceSuccess(uint32 MapId);
- void SendResetInstanceFailed(uint32 reason, uint32 MapId);
- void SendResetFailedNotify(uint32 mapid);
-
- virtual bool SetPosition(float x, float y, float z, float orientation, bool teleport = false);
- bool SetPosition(const Position &pos, bool teleport = false) { return SetPosition(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), teleport); }
- void UpdateUnderwaterState( Map * m, float x, float y, float z );
-
- void SendMessageToSet(WorldPacket *data, bool self);// overwrite Object::SendMessageToSet
- void SendMessageToSetInRange(WorldPacket *data, float fist, bool self);// overwrite Object::SendMessageToSetInRange
- void SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only);
-
- void SendTeleportAckMsg();
-
- static void DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars = true);
-
- Corpse *GetCorpse() const;
- void SpawnCorpseBones();
- void CreateCorpse();
- bool FallGround(uint8 FallMode = 0);
- void KillPlayer();
- uint32 GetResurrectionSpellId();
- void ResurrectPlayer(float restore_percent, bool applySickness = false);
- void BuildPlayerRepop();
- void RepopAtGraveyard();
-
- void DurabilityLossAll(double percent, bool inventory);
- void DurabilityLoss(Item* item, double percent);
- void DurabilityPointsLossAll(int32 points, bool inventory);
- void DurabilityPointsLoss(Item* item, int32 points);
- void DurabilityPointLossForEquipSlot(EquipmentSlots slot);
- uint32 DurabilityRepairAll(bool cost, float discountMod, bool guildBank);
- uint32 DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank);
-
- void UpdateMirrorTimers();
- void StopMirrorTimers()
- {
- StopMirrorTimer(FATIGUE_TIMER);
- StopMirrorTimer(BREATH_TIMER);
- StopMirrorTimer(FIRE_TIMER);
- }
-
- void SetMovement(PlayerMovementType pType);
-
- void JoinedChannel(Channel *c);
- void LeftChannel(Channel *c);
- void CleanupChannels();
- void UpdateLocalChannels( uint32 newZone );
- void LeaveLFGChannel();
-
- void UpdateDefense();
- void UpdateWeaponSkill (WeaponAttackType attType);
- void UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence);
-
- void SetSkill(uint32 id, uint16 currVal, uint16 maxVal);
- uint16 GetMaxSkillValue(uint32 skill) const; // max + perm. bonus + temp bonus
- uint16 GetPureMaxSkillValue(uint32 skill) const; // max
- uint16 GetSkillValue(uint32 skill) const; // skill value + perm. bonus + temp bonus
- uint16 GetBaseSkillValue(uint32 skill) const; // skill value + perm. bonus
- uint16 GetPureSkillValue(uint32 skill) const; // skill value
- int16 GetSkillPermBonusValue(uint32 skill) const;
- int16 GetSkillTempBonusValue(uint32 skill) const;
- bool HasSkill(uint32 skill) const;
- void learnSkillRewardedSpells(uint32 id, uint32 value);
-
- WorldLocation& GetTeleportDest() { return m_teleport_dest; }
- bool IsBeingTeleported() const { return mSemaphoreTeleport_Near || mSemaphoreTeleport_Far; }
- bool IsBeingTeleportedNear() const { return mSemaphoreTeleport_Near; }
- bool IsBeingTeleportedFar() const { return mSemaphoreTeleport_Far; }
- void SetSemaphoreTeleportNear(bool semphsetting) { mSemaphoreTeleport_Near = semphsetting; }
- void SetSemaphoreTeleportFar(bool semphsetting) { mSemaphoreTeleport_Far = semphsetting; }
- void ProcessDelayedOperations();
-
- void CheckExploreSystem(void);
-
- static uint32 TeamForRace(uint8 race);
- uint32 GetTeam() const { return m_team; }
- TeamId GetTeamId() const { return m_team == ALLIANCE ? TEAM_ALLIANCE : TEAM_HORDE; }
- static uint32 getFactionForRace(uint8 race);
- void setFactionForRace(uint8 race);
-
- void InitDisplayIds();
-
- bool IsAtGroupRewardDistance(WorldObject const* pRewardSource) const;
- bool RewardPlayerAndGroupAtKill(Unit* pVictim);
- void RewardPlayerAndGroupAtEvent(uint32 creature_id,WorldObject* pRewardSource);
- bool isHonorOrXPTarget(Unit* pVictim);
-
- ReputationMgr& GetReputationMgr() { return m_reputationMgr; }
- ReputationMgr const& GetReputationMgr() const { return m_reputationMgr; }
- ReputationRank GetReputationRank(uint32 faction_id) const;
- void RewardReputation(Unit *pVictim, float rate);
- void RewardReputation(Quest const *pQuest);
-
- void UpdateSkillsForLevel();
- void UpdateSkillsToMaxSkillsForLevel(); // for .levelup
- void ModifySkillBonus(uint32 skillid,int32 val, bool talent);
-
- /*********************************************************/
- /*** PVP SYSTEM ***/
- /*********************************************************/
- void UpdateHonorFields();
- bool RewardHonor(Unit *pVictim, uint32 groupsize, float honor = -1, bool pvptoken = false);
- uint32 GetHonorPoints() { return GetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY); }
- uint32 GetArenaPoints() { return GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY); }
- void ModifyHonorPoints( int32 value );
- void ModifyArenaPoints( int32 value );
- uint32 GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot);
-
- //End of PvP System
-
- inline SpellCooldowns GetSpellCooldowns() const { return m_spellCooldowns; }
-
- void SetDrunkValue(uint16 newDrunkValue, uint32 itemid=0);
- uint16 GetDrunkValue() const { return m_drunk; }
- static DrunkenState GetDrunkenstateByValue(uint16 value);
-
- uint32 GetDeathTimer() const { return m_deathTimer; }
- uint32 GetCorpseReclaimDelay(bool pvp) const;
- void UpdateCorpseReclaimDelay();
- void SendCorpseReclaimDelay(bool load = false);
-
- uint32 GetShieldBlockValue() const; // overwrite Unit version (virtual)
- bool CanParry() const { return m_canParry; }
- void SetCanParry(bool value);
- bool CanBlock() const { return m_canBlock; }
- void SetCanBlock(bool value);
- bool CanTitanGrip() const { return m_canTitanGrip; }
- void SetCanTitanGrip(bool value) { m_canTitanGrip = value; }
- bool CanTameExoticPets() const { return isGameMaster() || HasAuraType(SPELL_AURA_ALLOW_TAME_PET_TYPE); }
-
- void SetRegularAttackTime();
- void SetBaseModValue(BaseModGroup modGroup, BaseModType modType, float value) { m_auraBaseMod[modGroup][modType] = value; }
- void HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply);
- float GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const;
- float GetTotalBaseModValue(BaseModGroup modGroup) const;
- float GetTotalPercentageModValue(BaseModGroup modGroup) const { return m_auraBaseMod[modGroup][FLAT_MOD] + m_auraBaseMod[modGroup][PCT_MOD]; }
- void _ApplyAllStatBonuses();
- void _RemoveAllStatBonuses();
-
- void _ApplyWeaponDependentAuraMods(Item *item, WeaponAttackType attackType, bool apply);
- void _ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, AuraEffect const * aura, bool apply);
- void _ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, AuraEffect const * aura, bool apply);
-
- void _ApplyItemMods(Item *item,uint8 slot,bool apply);
- void _RemoveAllItemMods();
- void _ApplyAllItemMods();
- void _ApplyAllLevelScaleItemMods(bool apply);
- void _ApplyItemBonuses(ItemPrototype const *proto,uint8 slot,bool apply, bool only_level_scale = false);
- void _ApplyAmmoBonuses();
- bool EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot);
- void ToggleMetaGemsActive(uint8 exceptslot, bool apply);
- void CorrectMetaGemEnchants(uint8 slot, bool apply);
- void InitDataForForm(bool reapplyMods = false);
-
- void ApplyItemEquipSpell(Item *item, bool apply, bool form_change = false);
- void ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change = false);
- void UpdateEquipSpellsAtFormChange();
- void CastItemCombatSpell(Unit *target, WeaponAttackType attType, uint32 procVictim, uint32 procEx);
- void CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex);
- void CastItemCombatSpell(Unit *target, WeaponAttackType attType, uint32 procVictim, uint32 procEx, Item *item, ItemPrototype const * proto);
-
- void SendEquipmentSetList();
- void SetEquipmentSet(uint32 index, EquipmentSet eqset);
- void DeleteEquipmentSet(uint64 setGuid);
-
- void SendInitWorldStates(uint32 zone, uint32 area);
- void SendUpdateWorldState(uint32 Field, uint32 Value);
- void SendDirectMessage(WorldPacket *data);
-
- void SendAurasForTarget(Unit *target);
-
- PlayerMenu* PlayerTalkClass;
- std::vector<ItemSetEffect *> ItemSetEff;
-
- void SendLoot(uint64 guid, LootType loot_type);
- void SendLootRelease( uint64 guid );
- void SendNotifyLootItemRemoved(uint8 lootSlot);
- void SendNotifyLootMoneyRemoved();
-
- /*********************************************************/
- /*** BATTLEGROUND SYSTEM ***/
- /*********************************************************/
-
- bool InBattleGround() const { return m_bgData.bgInstanceID != 0; }
- bool InArena() const;
- uint32 GetBattleGroundId() const { return m_bgData.bgInstanceID; }
- BattleGroundTypeId GetBattleGroundTypeId() const { return m_bgData.bgTypeID; }
- BattleGround* GetBattleGround() const;
-
- bool InBattleGroundQueue() const
- {
- for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
- if (m_bgBattleGroundQueueID[i].bgQueueTypeId != BATTLEGROUND_QUEUE_NONE)
- return true;
- return false;
- }
-
- BattleGroundQueueTypeId GetBattleGroundQueueTypeId(uint32 index) const { return m_bgBattleGroundQueueID[index].bgQueueTypeId; }
- uint32 GetBattleGroundQueueIndex(BattleGroundQueueTypeId bgQueueTypeId) const
- {
- for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
- if (m_bgBattleGroundQueueID[i].bgQueueTypeId == bgQueueTypeId)
- return i;
- return PLAYER_MAX_BATTLEGROUND_QUEUES;
- }
- bool IsInvitedForBattleGroundQueueType(BattleGroundQueueTypeId bgQueueTypeId) const
- {
- for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
- if (m_bgBattleGroundQueueID[i].bgQueueTypeId == bgQueueTypeId)
- return m_bgBattleGroundQueueID[i].invitedToInstance != 0;
- return false;
- }
- bool InBattleGroundQueueForBattleGroundQueueType(BattleGroundQueueTypeId bgQueueTypeId) const
- {
- return GetBattleGroundQueueIndex(bgQueueTypeId) < PLAYER_MAX_BATTLEGROUND_QUEUES;
- }
-
- void SetBattleGroundId(uint32 val, BattleGroundTypeId bgTypeId)
- {
- m_bgData.bgInstanceID = val;
- m_bgData.bgTypeID = bgTypeId;
- }
- uint32 AddBattleGroundQueueId(BattleGroundQueueTypeId val)
- {
- for (uint8 i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
- {
- if (m_bgBattleGroundQueueID[i].bgQueueTypeId == BATTLEGROUND_QUEUE_NONE || m_bgBattleGroundQueueID[i].bgQueueTypeId == val)
- {
- m_bgBattleGroundQueueID[i].bgQueueTypeId = val;
- m_bgBattleGroundQueueID[i].invitedToInstance = 0;
- return i;
- }
- }
- return PLAYER_MAX_BATTLEGROUND_QUEUES;
- }
- bool HasFreeBattleGroundQueueId()
- {
- for (uint8 i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
- if (m_bgBattleGroundQueueID[i].bgQueueTypeId == BATTLEGROUND_QUEUE_NONE)
- return true;
- return false;
- }
- void RemoveBattleGroundQueueId(BattleGroundQueueTypeId val)
- {
- for (uint8 i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
- {
- if (m_bgBattleGroundQueueID[i].bgQueueTypeId == val)
- {
- m_bgBattleGroundQueueID[i].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
- m_bgBattleGroundQueueID[i].invitedToInstance = 0;
- return;
- }
- }
- }
- void SetInviteForBattleGroundQueueType(BattleGroundQueueTypeId bgQueueTypeId, uint32 instanceId)
- {
- for (uint8 i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
- if (m_bgBattleGroundQueueID[i].bgQueueTypeId == bgQueueTypeId)
- m_bgBattleGroundQueueID[i].invitedToInstance = instanceId;
- }
- bool IsInvitedForBattleGroundInstance(uint32 instanceId) const
- {
- for (uint8 i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
- if (m_bgBattleGroundQueueID[i].invitedToInstance == instanceId)
- return true;
- return false;
- }
- WorldLocation const& GetBattleGroundEntryPoint() const { return m_bgData.joinPos; }
- void SetBattleGroundEntryPoint();
-
- void SetBGTeam(uint32 team) { m_bgData.bgTeam = team; }
- uint32 GetBGTeam() const { return m_bgData.bgTeam ? m_bgData.bgTeam : GetTeam(); }
-
- void LeaveBattleground(bool teleportToEntryPoint = true);
- bool CanJoinToBattleground() const;
- bool CanReportAfkDueToLimit();
- void ReportedAfkBy(Player* reporter);
- void ClearAfkReports() { m_bgData.bgAfkReporter.clear(); }
-
- bool GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const;
- bool isTotalImmunity();
- bool CanUseBattleGroundObject();
- bool isTotalImmune();
- bool CanCaptureTowerPoint();
-
- /*********************************************************/
- /*** OUTDOOR PVP SYSTEM ***/
- /*********************************************************/
-
- OutdoorPvP * GetOutdoorPvP() const;
- // returns true if the player is in active state for outdoor pvp objective capturing, false otherwise
- bool IsOutdoorPvPActive();
-
- /*********************************************************/
- /*** REST SYSTEM ***/
- /*********************************************************/
-
- bool isRested() const { return GetRestTime() >= 10*IN_MILISECONDS; }
- uint32 GetXPRestBonus(uint32 xp);
- uint32 GetRestTime() const { return m_restTime;}
- void SetRestTime(uint32 v) { m_restTime = v;}
-
- /*********************************************************/
- /*** ENVIROMENTAL SYSTEM ***/
- /*********************************************************/
-
- uint32 EnvironmentalDamage(EnviromentalDamage type, uint32 damage);
-
- /*********************************************************/
- /*** FLOOD FILTER SYSTEM ***/
- /*********************************************************/
-
- void UpdateSpeakTime();
- bool CanSpeak() const;
- void ChangeSpeakTime(int utime);
-
- /*********************************************************/
- /*** VARIOUS SYSTEMS ***/
- /*********************************************************/
- void UpdateFallInformationIfNeed(MovementInfo const& minfo,uint16 opcode);
- Unit *m_mover;
- WorldObject *m_seer;
- void SetFallInformation(uint32 time, float z)
- {
- m_lastFallTime = time;
- m_lastFallZ = z;
- }
- void HandleFall(MovementInfo const& movementInfo);
-
- bool IsKnowHowFlyIn(uint32 mapid, uint32 zone) const;
-
- void SetClientControl(Unit* target, uint8 allowMove);
-
- void SetMover(Unit* target)
- {
- m_mover->m_movedPlayer = NULL;
- m_mover = target;
- m_mover->m_movedPlayer = this;
- }
- void SetSeer(WorldObject *target) { m_seer = target; }
- void SetViewpoint(WorldObject *target, bool apply);
- WorldObject* GetViewpoint() const;
- void StopCastingCharm();
- void StopCastingBindSight();
-
- uint32 GetSaveTimer() const { return m_nextSave; }
- void SetSaveTimer(uint32 timer) { m_nextSave = timer; }
-
- // Recall position
- uint32 m_recallMap;
- float m_recallX;
- float m_recallY;
- float m_recallZ;
- float m_recallO;
- void SaveRecallPosition();
-
- // Homebind coordinates
- uint32 m_homebindMapId;
- uint16 m_homebindZoneId;
- float m_homebindX;
- float m_homebindY;
- float m_homebindZ;
-
- WorldLocation GetStartPosition() const;
-
- // currently visible objects at player client
- typedef std::set<uint64> ClientGUIDs;
- ClientGUIDs m_clientGUIDs;
-
- bool HaveAtClient(WorldObject const* u) const { return u==this || m_clientGUIDs.find(u->GetGUID())!=m_clientGUIDs.end(); }
-
- bool canSeeOrDetect(Unit const* u, bool detect, bool inVisibleList = false, bool is3dDistance = true) const;
- bool IsVisibleInGridForPlayer(Player const* pl) const;
- bool IsVisibleGloballyFor(Player* pl) const;
-
- void UpdateVisibilityOf(WorldObject* target);
- void SendInitialVisiblePackets(Unit* target);
-
- template<class T>
- void UpdateVisibilityOf(T* target, UpdateData& data, std::set<Unit*>& visibleNow);
-
- // Stealth detection system
- void HandleStealthedUnitsDetection();
-
- uint8 m_forced_speed_changes[MAX_MOVE_TYPE];
-
- bool HasAtLoginFlag(AtLoginFlags f) const { return m_atLoginFlags & f; }
- void SetAtLoginFlag(AtLoginFlags f) { m_atLoginFlags |= f; }
- void RemoveAtLoginFlag(AtLoginFlags f, bool in_db_also = false);
-
- LookingForGroup m_lookingForGroup;
-
- // Temporarily removed pet cache
- uint32 GetTemporaryUnsummonedPetNumber() const { return m_temporaryUnsummonedPetNumber; }
- void SetTemporaryUnsummonedPetNumber(uint32 petnumber) { m_temporaryUnsummonedPetNumber = petnumber; }
- void UnsummonPetTemporaryIfAny();
- void ResummonPetTemporaryUnSummonedIfAny();
- bool IsPetNeedBeTemporaryUnsummoned() const { return !IsInWorld() || !isAlive() || IsMounted() /*+in flight*/; }
-
- void SendCinematicStart(uint32 CinematicSequenceId);
- void SendMovieStart(uint32 MovieId);
-
- /*********************************************************/
- /*** INSTANCE SYSTEM ***/
- /*********************************************************/
-
- typedef UNORDERED_MAP< uint32 /*mapId*/, InstancePlayerBind > BoundInstancesMap;
-
- void UpdateHomebindTime(uint32 time);
-
- uint32 m_HomebindTimer;
- bool m_InstanceValid;
- // permanent binds and solo binds by difficulty
- BoundInstancesMap m_boundInstances[MAX_DIFFICULTY];
- InstancePlayerBind* GetBoundInstance(uint32 mapid, Difficulty difficulty);
- BoundInstancesMap& GetBoundInstances(Difficulty difficulty) { return m_boundInstances[difficulty]; }
- InstanceSave * GetInstanceSave(uint32 mapid, bool raid);
- void UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload = false);
- void UnbindInstance(BoundInstancesMap::iterator &itr, Difficulty difficulty, bool unload = false);
- InstancePlayerBind* BindToInstance(InstanceSave *save, bool permanent, bool load = false);
- void SendRaidInfo();
- void SendSavedInstances();
- static void ConvertInstancesToGroup(Player *player, Group *group = NULL, uint64 player_guid = 0);
- bool Satisfy(AccessRequirement const*, uint32 target_map, bool report = false);
-
- // last used pet number (for BG's)
- uint32 GetLastPetNumber() const { return m_lastpetnumber; }
- void SetLastPetNumber(uint32 petnumber) { m_lastpetnumber = petnumber; }
-
- /*********************************************************/
- /*** GROUP SYSTEM ***/
- /*********************************************************/
-
- Group * GetGroupInvite() { return m_groupInvite; }
- void SetGroupInvite(Group *group) { m_groupInvite = group; }
- Group * GetGroup() { return m_group.getTarget(); }
- const Group * GetGroup() const { return (const Group*)m_group.getTarget(); }
- GroupReference& GetGroupRef() { return m_group; }
- void SetGroup(Group *group, int8 subgroup = -1);
- uint8 GetSubGroup() const { return m_group.getSubGroup(); }
- uint32 GetGroupUpdateFlag() const { return m_groupUpdateMask; }
- void SetGroupUpdateFlag(uint32 flag) { m_groupUpdateMask |= flag; }
- const uint64& GetAuraUpdateMaskForRaid() const { return m_auraRaidUpdateMask; }
- void SetAuraUpdateMaskForRaid(uint8 slot) { m_auraRaidUpdateMask |= (uint64(1) << slot); }
- Player* GetNextRandomRaidMember(float radius);
- PartyResult CanUninviteFromGroup() const;
- // BattleGround Group System
- void SetBattleGroundRaid(Group *group, int8 subgroup = -1);
- void RemoveFromBattleGroundRaid();
- Group * GetOriginalGroup() { return m_originalGroup.getTarget(); }
- GroupReference& GetOriginalGroupRef() { return m_originalGroup; }
- uint8 GetOriginalSubGroup() const { return m_originalGroup.getSubGroup(); }
- void SetOriginalGroup(Group *group, int8 subgroup = -1);
-
- MapReference &GetMapRef() { return m_mapRef; }
-
- // Set map to player and add reference
- void SetMap(Map * map);
- void ResetMap();
-
- bool isAllowedToLoot(Creature* creature);
-
- DeclinedName const* GetDeclinedNames() const { return m_declinedname; }
- uint8 GetRunesState() const { return m_runes->runeState; }
- RuneType GetBaseRune(uint8 index) const { return RuneType(m_runes->runes[index].BaseRune); }
- RuneType GetCurrentRune(uint8 index) const { return RuneType(m_runes->runes[index].CurrentRune); }
- uint32 GetRuneCooldown(uint8 index) const { return m_runes->runes[index].Cooldown; }
- uint32 GetRuneBaseCooldown(uint8 index);
- bool IsBaseRuneSlotsOnCooldown(RuneType runeType) const;
- RuneType GetLastUsedRune() { return m_runes->lastUsedRune; }
- void SetLastUsedRune(RuneType type) { m_runes->lastUsedRune = type; }
- void SetBaseRune(uint8 index, RuneType baseRune) { m_runes->runes[index].BaseRune = baseRune; }
- void SetCurrentRune(uint8 index, RuneType currentRune) { m_runes->runes[index].CurrentRune = currentRune; }
- void SetRuneCooldown(uint8 index, uint32 cooldown) { m_runes->runes[index].Cooldown = cooldown; m_runes->SetRuneState(index, (cooldown == 0) ? true : false); }
- void SetRuneConvertAura(uint8 index, AuraEffect const * aura) { m_runes->runes[index].ConvertAura = aura; }
- void AddRuneByAuraEffect(uint8 index, RuneType newType, AuraEffect const * aura) { SetRuneConvertAura(index, aura); ConvertRune(index, newType); }
- void RemoveRunesByAuraEffect(AuraEffect const * aura);
- void RestoreBaseRune(uint8 index);
- void ConvertRune(uint8 index, RuneType newType);
- void ResyncRunes(uint8 count);
- void AddRunePower(uint8 index);
- void InitRunes();
-
- AchievementMgr& GetAchievementMgr() { return m_achievementMgr; }
- void UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscvalue1 = 0, uint32 miscvalue2 = 0, Unit *unit = NULL, uint32 time = 0);
- void CompletedAchievement(AchievementEntry const* entry);
-
- bool HasTitle(uint32 bitIndex);
- bool HasTitle(CharTitlesEntry const* title) { return HasTitle(title->bit_index); }
- void SetTitle(CharTitlesEntry const* title, bool lost = false);
-
- //bool isActiveObject() const { return true; }
- bool canSeeSpellClickOn(Creature const* creature) const;
- uint32 GetActionButtonSpell(uint8 button) const
- {
- ActionButtonList::const_iterator ab = m_actionButtons.find(button);
- return ab != m_actionButtons.end() && ab->second.uState != ACTIONBUTTON_DELETED && ab->second.GetType() == ACTION_BUTTON_SPELL ? ab->second.GetAction() : 0;
- }
-
- uint32 GetChampioningFaction() const { return m_ChampioningFaction; }
- void SetChampioningFaction(uint32 faction) { m_ChampioningFaction = faction; }
-Spell * m_spellModTakingSpell;
- protected:
- uint32 m_AreaID;
- uint32 m_regenTimerCount;
- float m_powerFraction[MAX_POWERS];
- uint32 m_contestedPvPTimer;
-
- /*********************************************************/
- /*** BATTLEGROUND SYSTEM ***/
- /*********************************************************/
-
- /*
- this is an array of BG queues (BgTypeIDs) in which is player
- */
- struct BgBattleGroundQueueID_Rec
- {
- BattleGroundQueueTypeId bgQueueTypeId;
- uint32 invitedToInstance;
- };
-
- BgBattleGroundQueueID_Rec m_bgBattleGroundQueueID[PLAYER_MAX_BATTLEGROUND_QUEUES];
- BGData m_bgData;
-
- /*********************************************************/
- /*** QUEST SYSTEM ***/
- /*********************************************************/
-
- //We allow only one timed quest active at the same time. Below can then be simple value instead of set.
- std::set<uint32> m_timedquests;
-
- uint64 m_divider;
- uint32 m_ingametime;
-
- /*********************************************************/
- /*** LOAD SYSTEM ***/
- /*********************************************************/
-
- void _LoadActions(QueryResult_AutoPtr result, bool startup);
- void _LoadAuras(QueryResult_AutoPtr result, uint32 timediff);
- void _LoadGlyphAuras();
- void _LoadBoundInstances(QueryResult_AutoPtr result);
- void _LoadInventory(QueryResult_AutoPtr result, uint32 timediff);
- void _LoadMailInit(QueryResult_AutoPtr resultUnread, QueryResult_AutoPtr resultDelivery);
- void _LoadMail();
- void _LoadMailedItems(Mail *mail);
- void _LoadQuestStatus(QueryResult_AutoPtr result);
- void _LoadDailyQuestStatus(QueryResult_AutoPtr result);
- void _LoadGroup(QueryResult_AutoPtr result);
- void _LoadSkills(QueryResult_AutoPtr result);
- void _LoadSpells(QueryResult_AutoPtr result);
- void _LoadFriendList(QueryResult_AutoPtr result);
- bool _LoadHomeBind(QueryResult_AutoPtr result);
- void _LoadDeclinedNames(QueryResult_AutoPtr result);
- void _LoadArenaTeamInfo(QueryResult_AutoPtr result);
- void _LoadEquipmentSets(QueryResult_AutoPtr result);
- void _LoadBGData(QueryResult_AutoPtr result);
- void _LoadGlyphs(QueryResult_AutoPtr result);
- void _LoadTalents(QueryResult_AutoPtr result);
-
- /*********************************************************/
- /*** SAVE SYSTEM ***/
- /*********************************************************/
-
- void _SaveActions();
- void _SaveAuras();
- void _SaveInventory();
- void _SaveMail();
- void _SaveQuestStatus();
- void _SaveDailyQuestStatus();
- void _SaveSkills();
- void _SaveSpells();
- void _SaveEquipmentSets();
- void _SaveBGData();
- void _SaveGlyphs();
- void _SaveTalents();
-
- void _SetCreateBits(UpdateMask *updateMask, Player *target) const;
- void _SetUpdateBits(UpdateMask *updateMask, Player *target) const;
-
- /*********************************************************/
- /*** ENVIRONMENTAL SYSTEM ***/
- /*********************************************************/
- void HandleSobering();
- void SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen);
- void StopMirrorTimer(MirrorTimerType Type);
- void HandleDrowning(uint32 time_diff);
- int32 getMaxTimer(MirrorTimerType timer);
-
- /*********************************************************/
- /*** HONOR SYSTEM ***/
- /*********************************************************/
- time_t m_lastHonorUpdateTime;
-
- void outDebugValues() const;
- uint64 m_lootGuid;
-
- uint32 m_team;
- uint32 m_nextSave;
- time_t m_speakTime;
- uint32 m_speakCount;
- Difficulty m_dungeonDifficulty;
- Difficulty m_raidDifficulty;
-
- uint32 m_atLoginFlags;
-
- Item* m_items[PLAYER_SLOTS_COUNT];
- uint32 m_currentBuybackSlot;
-
- std::vector<Item*> m_itemUpdateQueue;
- bool m_itemUpdateQueueBlocked;
-
- uint32 m_ExtraFlags;
- uint64 m_curSelection;
-
- uint64 m_comboTarget;
- int8 m_comboPoints;
-
- QuestStatusMap mQuestStatus;
-
- SkillStatusMap mSkillStatus;
-
- uint32 m_GuildIdInvited;
- uint32 m_ArenaTeamIdInvited;
-
- PlayerMails m_mail;
- PlayerSpellMap m_spells;
- PlayerTalentMap *m_talents[MAX_TALENT_SPECS];
- uint32 m_lastPotionId; // last used health/mana potion in combat, that block next potion use
-
- uint8 m_activeSpec;
- uint8 m_specsCount;
-
- uint32 m_Glyphs[MAX_TALENT_SPECS][MAX_GLYPH_SLOT_INDEX];
-
- ActionButtonList m_actionButtons;
-
- float m_auraBaseMod[BASEMOD_END][MOD_END];
- int16 m_baseRatingValue[MAX_COMBAT_RATING];
- uint16 m_baseSpellPower;
- uint16 m_baseFeralAP;
- uint16 m_baseManaRegen;
- uint16 m_baseHealthRegen;
-
- SpellModList m_spellMods[MAX_SPELLMOD];
- //uint32 m_pad;
-// Spell * m_spellModTakingSpell; // Spell for which charges are dropped in spell::finish
-
- EnchantDurationList m_enchantDuration;
- ItemDurationList m_itemDuration;
-
- void ResetTimeSync();
- void SendTimeSync();
-
- uint64 m_resurrectGUID;
- uint32 m_resurrectMap;
- float m_resurrectX, m_resurrectY, m_resurrectZ;
- uint32 m_resurrectHealth, m_resurrectMana;
-
- WorldSession *m_session;
-
- typedef std::list<Channel*> JoinedChannelsList;
- JoinedChannelsList m_channels;
-
- int m_cinematic;
-
- Player *pTrader;
- bool acceptTrade;
- uint64 tradeItems[TRADE_SLOT_COUNT];
- uint32 tradeGold;
-
- bool m_DailyQuestChanged;
- time_t m_lastDailyQuestTime;
-
- uint32 m_drunkTimer;
- uint16 m_drunk;
- uint32 m_weaponChangeTimer;
-
- uint32 m_zoneUpdateId;
- uint32 m_zoneUpdateTimer;
- uint32 m_areaUpdateId;
-
- uint32 m_deathTimer;
- time_t m_deathExpireTime;
-
- uint32 m_restTime;
-
- uint32 m_WeaponProficiency;
- uint32 m_ArmorProficiency;
- bool m_canParry;
- bool m_canBlock;
- bool m_canTitanGrip;
- uint8 m_swingErrorMsg;
- float m_ammoDPS;
-
- ////////////////////Rest System/////////////////////
- int time_inn_enter;
- uint32 inn_pos_mapid;
- float inn_pos_x;
- float inn_pos_y;
- float inn_pos_z;
- float m_rest_bonus;
- RestType rest_type;
- ////////////////////Rest System/////////////////////
- uint32 m_resetTalentsCost;
- time_t m_resetTalentsTime;
- uint32 m_usedTalentCount;
- uint32 m_questRewardTalentCount;
-
- // Social
- PlayerSocial *m_social;
-
- // Groups
- GroupReference m_group;
- GroupReference m_originalGroup;
- Group *m_groupInvite;
- uint32 m_groupUpdateMask;
- uint64 m_auraRaidUpdateMask;
-
- // last used pet number (for BG's)
- uint32 m_lastpetnumber;
-
- // Player summoning
- time_t m_summon_expire;
- uint32 m_summon_mapid;
- float m_summon_x;
- float m_summon_y;
- float m_summon_z;
-
- DeclinedName *m_declinedname;
- Runes *m_runes;
- EquipmentSets m_EquipmentSets;
- private:
- // internal common parts for CanStore/StoreItem functions
- uint8 _CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec& dest, ItemPrototype const *pProto, uint32& count, bool swap, Item *pSrcItem ) const;
- uint8 _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;
- uint8 _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;
- Item* _StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update );
-
- void UpdateKnownCurrencies(uint32 itemId, bool apply);
- int32 CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest);
- void AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData );
-
- bool IsCanDelayTeleport() const { return m_bCanDelayTeleport; }
- void SetCanDelayTeleport(bool setting) { m_bCanDelayTeleport = setting; }
- bool IsHasDelayedTeleport() const { return m_bHasDelayedTeleport; }
- void SetDelayedTeleportFlag(bool setting) { m_bHasDelayedTeleport = setting; }
-
- void ScheduleDelayedOperation(uint32 operation)
- {
- if(operation < DELAYED_END)
- m_DelayedOperations |= operation;
- }
-
- MapReference m_mapRef;
-
- void UpdateCharmedAI();
- UnitAI *i_AI;
-
- uint32 m_lastFallTime;
- float m_lastFallZ;
-
- int32 m_MirrorTimer[MAX_TIMERS];
- uint8 m_MirrorTimerFlags;
- uint8 m_MirrorTimerFlagsLast;
- bool m_isInWater;
-
- // Current teleport data
- WorldLocation m_teleport_dest;
- uint32 m_teleport_options;
- bool mSemaphoreTeleport_Near;
- bool mSemaphoreTeleport_Far;
-
- uint32 m_DelayedOperations;
- bool m_bCanDelayTeleport;
- bool m_bHasDelayedTeleport;
-
- uint32 m_DetectInvTimer;
-
- // Temporary removed pet cache
- uint32 m_temporaryUnsummonedPetNumber;
- uint32 m_oldpetspell;
-
- AchievementMgr m_achievementMgr;
- ReputationMgr m_reputationMgr;
-
- SpellCooldowns m_spellCooldowns;
-
- uint32 m_ChampioningFaction;
-
- uint32 m_timeSyncCount;
- uint32 m_timeSyncTimer;
-};
-
-void AddItemsSetItem(Player*player,Item *item);
-void RemoveItemsSetItem(Player*player,ItemPrototype const *proto);
-
-// "the bodies of template functions must be made available in a header file"
-template <class T> T Player::ApplySpellMod(uint32 spellId, SpellModOp op, T &basevalue, Spell * spell)
-{
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
- if (!spellInfo) return 0;
- float totalmul = 1.0f;
- int32 totalflat = 0;
-
- // Drop charges for triggering spells instead of triggered ones
- if (m_spellModTakingSpell)
- spell = m_spellModTakingSpell;
-
- for (SpellModList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
- {
- SpellModifier *mod = *itr;
-
- // Charges can be set only for mods with auras
- if (!mod->ownerAura)
- assert(mod->charges == 0);
-
- if(!IsAffectedBySpellmod(spellInfo,mod,spell))
- continue;
-
- if (mod->type == SPELLMOD_FLAT)
- totalflat += mod->value;
- else if (mod->type == SPELLMOD_PCT)
- {
- // skip percent mods for null basevalue (most important for spell mods with charges )
- if(basevalue == T(0))
- continue;
-
- // special case (skip >10sec spell casts for instant cast setting)
- if( mod->op==SPELLMOD_CASTING_TIME && basevalue >= T(10000) && mod->value <= -100)
- continue;
-
- totalmul *= 1.0f + (float)mod->value / 100.0f;
- }
-
- DropModCharge(mod, spell);
- }
- float diff = (float)basevalue * (totalmul - 1.0f) + (float)totalflat;
- basevalue = T((float)basevalue + diff);
- return T(diff);
-}
-#endif
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _PLAYER_H
+#define _PLAYER_H
+
+#include "Common.h"
+#include "ItemPrototype.h"
+#include "Unit.h"
+#include "Item.h"
+
+#include "Database/DatabaseEnv.h"
+#include "NPCHandler.h"
+#include "QuestDef.h"
+#include "Group.h"
+#include "Bag.h"
+#include "WorldSession.h"
+#include "Pet.h"
+#include "MapReference.h"
+#include "Util.h" // for Tokens typedef
+#include "AchievementMgr.h"
+#include "ReputationMgr.h"
+#include "BattleGround.h"
+#include "DBCEnums.h"
+
+#include<string>
+#include<vector>
+
+struct Mail;
+class Channel;
+class DynamicObject;
+class Creature;
+class Pet;
+class PlayerMenu;
+class UpdateMask;
+class SpellCastTargets;
+class PlayerSocial;
+class OutdoorPvP;
+
+typedef std::deque<Mail*> PlayerMails;
+
+#define PLAYER_MAX_SKILLS 127
+#define PLAYER_MAX_DAILY_QUESTS 25
+
+// Note: SPELLMOD_* values is aura types in fact
+enum SpellModType
+{
+ SPELLMOD_FLAT = 107, // SPELL_AURA_ADD_FLAT_MODIFIER
+ SPELLMOD_PCT = 108 // SPELL_AURA_ADD_PCT_MODIFIER
+};
+
+// 2^n values, Player::m_isunderwater is a bitmask. These are Trinity internal values, they are never send to any client
+enum PlayerUnderwaterState
+{
+ UNDERWATER_NONE = 0x00,
+ UNDERWATER_INWATER = 0x01, // terrain type is water and player is afflicted by it
+ UNDERWATER_INLAVA = 0x02, // terrain type is lava and player is afflicted by it
+ UNDERWATER_INSLIME = 0x04, // terrain type is lava and player is afflicted by it
+ UNDERWARER_INDARKWATER = 0x08, // terrain type is dark water and player is afflicted by it
+
+ UNDERWATER_EXIST_TIMERS = 0x10
+};
+
+enum PlayerSpellState
+{
+ PLAYERSPELL_UNCHANGED = 0,
+ PLAYERSPELL_CHANGED = 1,
+ PLAYERSPELL_NEW = 2,
+ PLAYERSPELL_REMOVED = 3,
+ PLAYERSPELL_TEMPORARY = 4
+};
+
+struct PlayerSpell
+{
+ PlayerSpellState state : 8;
+ bool active : 1; // show in spellbook
+ bool dependent : 1; // learned as result another spell learn, skill grow, quest reward, etc
+ bool disabled : 1; // first rank has been learned in result talent learn but currently talent unlearned, save max learned ranks
+};
+
+struct PlayerTalent
+{
+ PlayerSpellState state : 8;
+ uint8 spec : 8;
+};
+
+// Spell modifier (used for modify other spells)
+struct SpellModifier
+{
+ SpellModifier(Aura * _ownerAura = NULL) : charges(0), ownerAura(_ownerAura) {}
+ SpellModOp op : 8;
+ SpellModType type : 8;
+ int16 charges : 16;
+ int32 value;
+ flag96 mask;
+ uint32 spellId;
+ Aura * const ownerAura;
+};
+
+typedef UNORDERED_MAP<uint32, PlayerTalent*> PlayerTalentMap;
+typedef UNORDERED_MAP<uint32, PlayerSpell*> PlayerSpellMap;
+typedef std::list<SpellModifier*> SpellModList;
+
+struct SpellCooldown
+{
+ time_t end;
+ uint16 itemid;
+};
+
+typedef std::map<uint32, SpellCooldown> SpellCooldowns;
+
+enum TrainerSpellState
+{
+ TRAINER_SPELL_GREEN = 0,
+ TRAINER_SPELL_RED = 1,
+ TRAINER_SPELL_GRAY = 2,
+ TRAINER_SPELL_GREEN_DISABLED = 10 // custom value, not send to client: formally green but learn not allowed
+};
+
+enum ActionButtonUpdateState
+{
+ ACTIONBUTTON_UNCHANGED = 0,
+ ACTIONBUTTON_CHANGED = 1,
+ ACTIONBUTTON_NEW = 2,
+ ACTIONBUTTON_DELETED = 3
+};
+
+enum ActionButtonType
+{
+ ACTION_BUTTON_SPELL = 0x00,
+ ACTION_BUTTON_C = 0x01, // click?
+ ACTION_BUTTON_EQSET = 0x20,
+ ACTION_BUTTON_MACRO = 0x40,
+ ACTION_BUTTON_CMACRO = ACTION_BUTTON_C | ACTION_BUTTON_MACRO,
+ ACTION_BUTTON_ITEM = 0x80
+};
+
+#define ACTION_BUTTON_ACTION(X) (uint32(X) & 0x00FFFFFF)
+#define ACTION_BUTTON_TYPE(X) ((uint32(X) & 0xFF000000) >> 24)
+#define MAX_ACTION_BUTTON_ACTION_VALUE (0x00FFFFFF+1)
+
+struct ActionButton
+{
+ ActionButton() : packedData(0), uState( ACTIONBUTTON_NEW ), canRemoveByClient(true){}
+
+ uint32 packedData;
+ ActionButtonUpdateState uState;
+ bool canRemoveByClient;
+
+ // helpers
+ ActionButtonType GetType() const { return ActionButtonType(ACTION_BUTTON_TYPE(packedData)); }
+ uint32 GetAction() const { return ACTION_BUTTON_ACTION(packedData); }
+ void SetActionAndType(uint32 action, ActionButtonType type)
+ {
+ uint32 newData = action | (uint32(type) << 24);
+ if (newData != packedData || uState == ACTIONBUTTON_DELETED)
+ {
+ packedData = newData;
+ if (uState != ACTIONBUTTON_NEW)
+ uState = ACTIONBUTTON_CHANGED;
+ }
+ }
+};
+
+#define MAX_ACTION_BUTTONS 144 //checked in 3.2.0
+
+typedef std::map<uint8,ActionButton> ActionButtonList;
+
+struct PlayerCreateInfoItem
+{
+ PlayerCreateInfoItem(uint32 id, uint32 amount) : item_id(id), item_amount(amount) {}
+
+ uint32 item_id;
+ uint32 item_amount;
+};
+
+typedef std::list<PlayerCreateInfoItem> PlayerCreateInfoItems;
+
+struct PlayerClassLevelInfo
+{
+ PlayerClassLevelInfo() : basehealth(0), basemana(0) {}
+ uint16 basehealth;
+ uint16 basemana;
+};
+
+struct PlayerClassInfo
+{
+ PlayerClassInfo() : levelInfo(NULL) { }
+
+ PlayerClassLevelInfo* levelInfo; //[level-1] 0..MaxPlayerLevel-1
+};
+
+struct PlayerLevelInfo
+{
+ PlayerLevelInfo() { for (uint8 i=0; i < MAX_STATS; ++i ) stats[i] = 0; }
+
+ uint8 stats[MAX_STATS];
+};
+
+typedef std::list<uint32> PlayerCreateInfoSpells;
+
+struct PlayerCreateInfoAction
+{
+ PlayerCreateInfoAction() : button(0), type(0), action(0) {}
+ PlayerCreateInfoAction(uint8 _button, uint32 _action, uint8 _type) : button(_button), type(_type), action(_action) {}
+
+ uint8 button;
+ uint8 type;
+ uint32 action;
+};
+
+typedef std::list<PlayerCreateInfoAction> PlayerCreateInfoActions;
+
+struct PlayerInfo
+{
+ // existence checked by displayId != 0 // existence checked by displayId != 0
+ PlayerInfo() : displayId_m(0),displayId_f(0),levelInfo(NULL)
+ {
+ }
+
+ uint32 mapId;
+ uint32 zoneId;
+ float positionX;
+ float positionY;
+ float positionZ;
+ uint16 displayId_m;
+ uint16 displayId_f;
+ PlayerCreateInfoItems item;
+ PlayerCreateInfoSpells spell;
+ PlayerCreateInfoActions action;
+
+ PlayerLevelInfo* levelInfo; //[level-1] 0..MaxPlayerLevel-1
+};
+
+struct PvPInfo
+{
+ PvPInfo() : inHostileArea(false), inNoPvPArea(false), inFFAPvPArea(false), endTimer(0) {}
+
+ bool inHostileArea;
+ bool inNoPvPArea;
+ bool inFFAPvPArea;
+ time_t endTimer;
+};
+
+struct DuelInfo
+{
+ DuelInfo() : initiator(NULL), opponent(NULL), startTimer(0), startTime(0), outOfBound(0) {}
+
+ Player *initiator;
+ Player *opponent;
+ time_t startTimer;
+ time_t startTime;
+ time_t outOfBound;
+};
+
+struct Areas
+{
+ uint32 areaID;
+ uint32 areaFlag;
+ float x1;
+ float x2;
+ float y1;
+ float y2;
+};
+
+#define MAX_RUNES 6
+#define RUNE_COOLDOWN 10000
+
+enum RuneType
+{
+ RUNE_BLOOD = 0,
+ RUNE_UNHOLY = 1,
+ RUNE_FROST = 2,
+ RUNE_DEATH = 3,
+ NUM_RUNE_TYPES = 4
+};
+
+struct RuneInfo
+{
+ uint8 BaseRune;
+ uint8 CurrentRune;
+ uint32 Cooldown;
+ AuraEffect const * ConvertAura;
+};
+
+struct Runes
+{
+ RuneInfo runes[MAX_RUNES];
+ uint8 runeState; // mask of available runes
+ RuneType lastUsedRune;
+
+ void SetRuneState(uint8 index, bool set = true)
+ {
+ if(set)
+ runeState |= (1 << index); // usable
+ else
+ runeState &= ~(1 << index); // on cooldown
+ }
+};
+
+struct EnchantDuration
+{
+ EnchantDuration() : item(NULL), slot(MAX_ENCHANTMENT_SLOT), leftduration(0) {};
+ EnchantDuration(Item * _item, EnchantmentSlot _slot, uint32 _leftduration) : item(_item), slot(_slot),
+ leftduration(_leftduration){ assert(item); };
+
+ Item * item;
+ EnchantmentSlot slot;
+ uint32 leftduration;
+};
+
+typedef std::list<EnchantDuration> EnchantDurationList;
+typedef std::list<Item*> ItemDurationList;
+
+enum LfgType
+{
+ LFG_TYPE_NONE = 0,
+ LFG_TYPE_DUNGEON = 1,
+ LFG_TYPE_RAID = 2,
+ LFG_TYPE_QUEST = 3,
+ LFG_TYPE_ZONE = 4,
+ LFG_TYPE_HEROIC_DUNGEON = 5,
+ LFG_TYPE_RANDOM_DUNGEON = 6
+};
+
+enum LfgRoles
+{
+ LEADER = 0x01,
+ TANK = 0x02,
+ HEALER = 0x04,
+ DAMAGE = 0x08
+};
+
+struct LookingForGroupSlot
+{
+ LookingForGroupSlot() : entry(0), type(0) {}
+ bool Empty() const { return !entry && !type; }
+ void Clear() { entry = 0; type = 0; }
+ void Set(uint32 _entry, uint32 _type ) { entry = _entry; type = _type; }
+ bool Is(uint32 _entry, uint32 _type) const { return entry == _entry && type == _type; }
+ bool canAutoJoin() const { return entry && (type == LFG_TYPE_DUNGEON || type == LFG_TYPE_HEROIC_DUNGEON); }
+
+ uint32 entry;
+ uint32 type;
+};
+
+#define MAX_LOOKING_FOR_GROUP_SLOT 3
+
+struct LookingForGroup
+{
+ LookingForGroup() {}
+ bool HaveInSlot(LookingForGroupSlot const& slot) const { return HaveInSlot(slot.entry, slot.type); }
+ bool HaveInSlot(uint32 _entry, uint32 _type) const
+ {
+ for (uint8 i = 0; i < MAX_LOOKING_FOR_GROUP_SLOT; ++i)
+ if(slots[i].Is(_entry, _type))
+ return true;
+ return false;
+ }
+
+ bool canAutoJoin() const
+ {
+ for (uint8 i = 0; i < MAX_LOOKING_FOR_GROUP_SLOT; ++i)
+ if(slots[i].canAutoJoin())
+ return true;
+ return false;
+ }
+
+ bool Empty() const
+ {
+ for (uint8 i = 0; i < MAX_LOOKING_FOR_GROUP_SLOT; ++i)
+ if(!slots[i].Empty())
+ return false;
+ return more.Empty();
+ }
+
+ LookingForGroupSlot slots[MAX_LOOKING_FOR_GROUP_SLOT];
+ LookingForGroupSlot more;
+ std::string comment;
+ uint8 roles;
+};
+
+enum PlayerMovementType
+{
+ MOVE_ROOT = 1,
+ MOVE_UNROOT = 2,
+ MOVE_WATER_WALK = 3,
+ MOVE_LAND_WALK = 4
+};
+
+enum DrunkenState
+{
+ DRUNKEN_SOBER = 0,
+ DRUNKEN_TIPSY = 1,
+ DRUNKEN_DRUNK = 2,
+ DRUNKEN_SMASHED = 3
+};
+
+#define MAX_DRUNKEN 4
+
+enum PlayerFlags
+{
+ PLAYER_FLAGS_GROUP_LEADER = 0x00000001,
+ PLAYER_FLAGS_AFK = 0x00000002,
+ PLAYER_FLAGS_DND = 0x00000004,
+ PLAYER_FLAGS_GM = 0x00000008,
+ PLAYER_FLAGS_GHOST = 0x00000010,
+ PLAYER_FLAGS_RESTING = 0x00000020,
+ PLAYER_FLAGS_UNK7 = 0x00000040,
+ PLAYER_FLAGS_UNK8 = 0x00000080, // pre-3.0.3 PLAYER_FLAGS_FFA_PVP flag for FFA PVP state
+ PLAYER_FLAGS_CONTESTED_PVP = 0x00000100, // Player has been involved in a PvP combat and will be attacked by contested guards
+ PLAYER_FLAGS_IN_PVP = 0x00000200,
+ PLAYER_FLAGS_HIDE_HELM = 0x00000400,
+ PLAYER_FLAGS_HIDE_CLOAK = 0x00000800,
+ PLAYER_FLAGS_UNK13 = 0x00001000, // played long time
+ PLAYER_FLAGS_UNK14 = 0x00002000, // played too long time
+ PLAYER_FLAGS_UNK15 = 0x00004000,
+ PLAYER_FLAGS_DEVELOPER = 0x00008000, // <Dev> prefix for something?
+ PLAYER_FLAGS_UNK17 = 0x00010000, // pre-3.0.3 PLAYER_FLAGS_SANCTUARY flag for player entered sanctuary
+ PLAYER_FLAGS_UNK18 = 0x00020000, // taxi benchmark mode (on/off) (2.0.1)
+ PLAYER_FLAGS_PVP_TIMER = 0x00040000, // 3.0.2, pvp timer active (after you disable pvp manually)
+ PLAYER_FLAGS_UNK20 = 0x00080000,
+ PLAYER_FLAGS_UNK21 = 0x00100000,
+ PLAYER_FLAGS_UNK22 = 0x00200000,
+ PLAYER_FLAGS_UNK23 = 0x00400000,
+ PLAYER_ALLOW_ONLY_ABILITY = 0x00800000, // used by bladestorm and killing spree
+ PLAYER_FLAGS_UNK25 = 0x01000000, // disabled all melee ability on tab include autoattack
+
+ PLAYER_FLAGS_NO_XP_GAIN = 0x02000000
+};
+
+// used for PLAYER__FIELD_KNOWN_TITLES field (uint64), (1<<bit_index) without (-1)
+// can't use enum for uint64 values
+#define PLAYER_TITLE_DISABLED UI64LIT(0x0000000000000000)
+#define PLAYER_TITLE_NONE UI64LIT(0x0000000000000001)
+#define PLAYER_TITLE_PRIVATE UI64LIT(0x0000000000000002) // 1
+#define PLAYER_TITLE_CORPORAL UI64LIT(0x0000000000000004) // 2
+#define PLAYER_TITLE_SERGEANT_A UI64LIT(0x0000000000000008) // 3
+#define PLAYER_TITLE_MASTER_SERGEANT UI64LIT(0x0000000000000010) // 4
+#define PLAYER_TITLE_SERGEANT_MAJOR UI64LIT(0x0000000000000020) // 5
+#define PLAYER_TITLE_KNIGHT UI64LIT(0x0000000000000040) // 6
+#define PLAYER_TITLE_KNIGHT_LIEUTENANT UI64LIT(0x0000000000000080) // 7
+#define PLAYER_TITLE_KNIGHT_CAPTAIN UI64LIT(0x0000000000000100) // 8
+#define PLAYER_TITLE_KNIGHT_CHAMPION UI64LIT(0x0000000000000200) // 9
+#define PLAYER_TITLE_LIEUTENANT_COMMANDER UI64LIT(0x0000000000000400) // 10
+#define PLAYER_TITLE_COMMANDER UI64LIT(0x0000000000000800) // 11
+#define PLAYER_TITLE_MARSHAL UI64LIT(0x0000000000001000) // 12
+#define PLAYER_TITLE_FIELD_MARSHAL UI64LIT(0x0000000000002000) // 13
+#define PLAYER_TITLE_GRAND_MARSHAL UI64LIT(0x0000000000004000) // 14
+#define PLAYER_TITLE_SCOUT UI64LIT(0x0000000000008000) // 15
+#define PLAYER_TITLE_GRUNT UI64LIT(0x0000000000010000) // 16
+#define PLAYER_TITLE_SERGEANT_H UI64LIT(0x0000000000020000) // 17
+#define PLAYER_TITLE_SENIOR_SERGEANT UI64LIT(0x0000000000040000) // 18
+#define PLAYER_TITLE_FIRST_SERGEANT UI64LIT(0x0000000000080000) // 19
+#define PLAYER_TITLE_STONE_GUARD UI64LIT(0x0000000000100000) // 20
+#define PLAYER_TITLE_BLOOD_GUARD UI64LIT(0x0000000000200000) // 21
+#define PLAYER_TITLE_LEGIONNAIRE UI64LIT(0x0000000000400000) // 22
+#define PLAYER_TITLE_CENTURION UI64LIT(0x0000000000800000) // 23
+#define PLAYER_TITLE_CHAMPION UI64LIT(0x0000000001000000) // 24
+#define PLAYER_TITLE_LIEUTENANT_GENERAL UI64LIT(0x0000000002000000) // 25
+#define PLAYER_TITLE_GENERAL UI64LIT(0x0000000004000000) // 26
+#define PLAYER_TITLE_WARLORD UI64LIT(0x0000000008000000) // 27
+#define PLAYER_TITLE_HIGH_WARLORD UI64LIT(0x0000000010000000) // 28
+#define PLAYER_TITLE_GLADIATOR UI64LIT(0x0000000020000000) // 29
+#define PLAYER_TITLE_DUELIST UI64LIT(0x0000000040000000) // 30
+#define PLAYER_TITLE_RIVAL UI64LIT(0x0000000080000000) // 31
+#define PLAYER_TITLE_CHALLENGER UI64LIT(0x0000000100000000) // 32
+#define PLAYER_TITLE_SCARAB_LORD UI64LIT(0x0000000200000000) // 33
+#define PLAYER_TITLE_CONQUEROR UI64LIT(0x0000000400000000) // 34
+#define PLAYER_TITLE_JUSTICAR UI64LIT(0x0000000800000000) // 35
+#define PLAYER_TITLE_CHAMPION_OF_THE_NAARU UI64LIT(0x0000001000000000) // 36
+#define PLAYER_TITLE_MERCILESS_GLADIATOR UI64LIT(0x0000002000000000) // 37
+#define PLAYER_TITLE_OF_THE_SHATTERED_SUN UI64LIT(0x0000004000000000) // 38
+#define PLAYER_TITLE_HAND_OF_ADAL UI64LIT(0x0000008000000000) // 39
+#define PLAYER_TITLE_VENGEFUL_GLADIATOR UI64LIT(0x0000010000000000) // 40
+
+#define MAX_TITLE_INDEX (3*64) // 3 uint64 fields
+
+// used in PLAYER_FIELD_BYTES values
+enum PlayerFieldByteFlags
+{
+ PLAYER_FIELD_BYTE_TRACK_STEALTHED = 0x00000002,
+ PLAYER_FIELD_BYTE_RELEASE_TIMER = 0x00000008, // Display time till auto release spirit
+ PLAYER_FIELD_BYTE_NO_RELEASE_WINDOW = 0x00000010 // Display no "release spirit" window at all
+};
+
+// used in PLAYER_FIELD_BYTES2 values
+enum PlayerFieldByte2Flags
+{
+ PLAYER_FIELD_BYTE2_NONE = 0x0000,
+ PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW = 0x4000
+};
+
+enum ActivateTaxiReplies
+{
+ ERR_TAXIOK = 0,
+ ERR_TAXIUNSPECIFIEDSERVERERROR = 1,
+ ERR_TAXINOSUCHPATH = 2,
+ ERR_TAXINOTENOUGHMONEY = 3,
+ ERR_TAXITOOFARAWAY = 4,
+ ERR_TAXINOVENDORNEARBY = 5,
+ ERR_TAXINOTVISITED = 6,
+ ERR_TAXIPLAYERBUSY = 7,
+ ERR_TAXIPLAYERALREADYMOUNTED = 8,
+ ERR_TAXIPLAYERSHAPESHIFTED = 9,
+ ERR_TAXIPLAYERMOVING = 10,
+ ERR_TAXISAMENODE = 11,
+ ERR_TAXINOTSTANDING = 12
+};
+
+enum MirrorTimerType
+{
+ FATIGUE_TIMER = 0,
+ BREATH_TIMER = 1,
+ FIRE_TIMER = 2
+};
+#define MAX_TIMERS 3
+#define DISABLED_MIRROR_TIMER -1
+
+// 2^n values
+enum PlayerExtraFlags
+{
+ // gm abilities
+ PLAYER_EXTRA_GM_ON = 0x0001,
+ PLAYER_EXTRA_ACCEPT_WHISPERS = 0x0004,
+ PLAYER_EXTRA_TAXICHEAT = 0x0008,
+ PLAYER_EXTRA_GM_INVISIBLE = 0x0010,
+ PLAYER_EXTRA_GM_CHAT = 0x0020, // Show GM badge in chat messages
+
+ // other states
+ PLAYER_EXTRA_PVP_DEATH = 0x0100 // store PvP death status until corpse creating.
+};
+
+// 2^n values
+enum AtLoginFlags
+{
+ AT_LOGIN_NONE = 0x00,
+ AT_LOGIN_RENAME = 0x01,
+ AT_LOGIN_RESET_SPELLS = 0x02,
+ AT_LOGIN_RESET_TALENTS = 0x04,
+ AT_LOGIN_CUSTOMIZE = 0x08,
+ AT_LOGIN_RESET_PET_TALENTS = 0x10,
+ AT_LOGIN_FIRST = 0x20,
+};
+
+typedef std::map<uint32, QuestStatusData> QuestStatusMap;
+
+enum QuestSlotOffsets
+{
+ QUEST_ID_OFFSET = 0,
+ QUEST_STATE_OFFSET = 1,
+ QUEST_COUNTS_OFFSET = 2,
+ QUEST_TIME_OFFSET = 3
+};
+
+#define MAX_QUEST_OFFSET 5
+
+enum QuestSlotStateMask
+{
+ QUEST_STATE_NONE = 0x0000,
+ QUEST_STATE_COMPLETE = 0x0001,
+ QUEST_STATE_FAIL = 0x0002
+};
+
+enum SkillUpdateState
+{
+ SKILL_UNCHANGED = 0,
+ SKILL_CHANGED = 1,
+ SKILL_NEW = 2,
+ SKILL_DELETED = 3
+};
+
+struct SkillStatusData
+{
+ SkillStatusData(uint8 _pos, SkillUpdateState _uState) : pos(_pos), uState(_uState)
+ {
+ }
+ uint8 pos;
+ SkillUpdateState uState;
+};
+
+typedef UNORDERED_MAP<uint32, SkillStatusData> SkillStatusMap;
+
+class Quest;
+class Spell;
+class Item;
+class WorldSession;
+
+enum PlayerSlots
+{
+ // first slot for item stored (in any way in player m_items data)
+ PLAYER_SLOT_START = 0,
+ // last+1 slot for item stored (in any way in player m_items data)
+ PLAYER_SLOT_END = 150,
+ PLAYER_SLOTS_COUNT = (PLAYER_SLOT_END - PLAYER_SLOT_START)
+};
+
+#define INVENTORY_SLOT_BAG_0 255
+
+enum EquipmentSlots // 19 slots
+{
+ EQUIPMENT_SLOT_START = 0,
+ EQUIPMENT_SLOT_HEAD = 0,
+ EQUIPMENT_SLOT_NECK = 1,
+ EQUIPMENT_SLOT_SHOULDERS = 2,
+ EQUIPMENT_SLOT_BODY = 3,
+ EQUIPMENT_SLOT_CHEST = 4,
+ EQUIPMENT_SLOT_WAIST = 5,
+ EQUIPMENT_SLOT_LEGS = 6,
+ EQUIPMENT_SLOT_FEET = 7,
+ EQUIPMENT_SLOT_WRISTS = 8,
+ EQUIPMENT_SLOT_HANDS = 9,
+ EQUIPMENT_SLOT_FINGER1 = 10,
+ EQUIPMENT_SLOT_FINGER2 = 11,
+ EQUIPMENT_SLOT_TRINKET1 = 12,
+ EQUIPMENT_SLOT_TRINKET2 = 13,
+ EQUIPMENT_SLOT_BACK = 14,
+ EQUIPMENT_SLOT_MAINHAND = 15,
+ EQUIPMENT_SLOT_OFFHAND = 16,
+ EQUIPMENT_SLOT_RANGED = 17,
+ EQUIPMENT_SLOT_TABARD = 18,
+ EQUIPMENT_SLOT_END = 19
+};
+
+enum InventorySlots // 4 slots
+{
+ INVENTORY_SLOT_BAG_START = 19,
+ INVENTORY_SLOT_BAG_END = 23
+};
+
+enum InventoryPackSlots // 16 slots
+{
+ INVENTORY_SLOT_ITEM_START = 23,
+ INVENTORY_SLOT_ITEM_END = 39
+};
+
+enum BankItemSlots // 28 slots
+{
+ BANK_SLOT_ITEM_START = 39,
+ BANK_SLOT_ITEM_END = 67
+};
+
+enum BankBagSlots // 7 slots
+{
+ BANK_SLOT_BAG_START = 67,
+ BANK_SLOT_BAG_END = 74
+};
+
+enum BuyBackSlots // 12 slots
+{
+ // stored in m_buybackitems
+ BUYBACK_SLOT_START = 74,
+ BUYBACK_SLOT_END = 86
+};
+
+enum KeyRingSlots // 32 slots
+{
+ KEYRING_SLOT_START = 86,
+ KEYRING_SLOT_END = 118
+};
+
+enum CurrencyTokenSlots // 32 slots
+{
+ CURRENCYTOKEN_SLOT_START = 118,
+ CURRENCYTOKEN_SLOT_END = 150
+};
+
+enum EquipmentSetUpdateState
+{
+ EQUIPMENT_SET_UNCHANGED = 0,
+ EQUIPMENT_SET_CHANGED = 1,
+ EQUIPMENT_SET_NEW = 2,
+ EQUIPMENT_SET_DELETED = 3
+};
+
+struct EquipmentSet
+{
+ EquipmentSet() : Guid(0), state(EQUIPMENT_SET_NEW)
+ {
+ for (uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i)
+ Items[i] = 0;
+ }
+
+ uint64 Guid;
+ std::string Name;
+ std::string IconName;
+ uint32 Items[EQUIPMENT_SLOT_END];
+ EquipmentSetUpdateState state;
+};
+
+#define MAX_EQUIPMENT_SET_INDEX 10 // client limit
+
+typedef std::map<uint32, EquipmentSet> EquipmentSets;
+
+struct ItemPosCount
+{
+ ItemPosCount(uint16 _pos, uint32 _count) : pos(_pos), count(_count) {}
+ bool isContainedIn(std::vector<ItemPosCount> const& vec) const;
+ uint16 pos;
+ uint32 count;
+};
+typedef std::vector<ItemPosCount> ItemPosCountVec;
+
+enum TradeSlots
+{
+ TRADE_SLOT_COUNT = 7,
+ TRADE_SLOT_TRADED_COUNT = 6,
+ TRADE_SLOT_NONTRADED = 6
+};
+
+enum TransferAbortReason
+{
+ TRANSFER_ABORT_NONE = 0x00,
+ TRANSFER_ABORT_ERROR = 0x01,
+ TRANSFER_ABORT_MAX_PLAYERS = 0x02, // Transfer Aborted: instance is full
+ TRANSFER_ABORT_NOT_FOUND = 0x03, // Transfer Aborted: instance not found
+ TRANSFER_ABORT_TOO_MANY_INSTANCES = 0x04, // You have entered too many instances recently.
+ TRANSFER_ABORT_ZONE_IN_COMBAT = 0x06, // Unable to zone in while an encounter is in progress.
+ TRANSFER_ABORT_INSUF_EXPAN_LVL = 0x07, // You must have <TBC,WotLK> expansion installed to access this area.
+ TRANSFER_ABORT_DIFFICULTY = 0x08, // <Normal,Heroic,Epic> difficulty mode is not available for %s.
+ TRANSFER_ABORT_UNIQUE_MESSAGE = 0x09, // Until you've escaped TLK's grasp, you cannot leave this place!
+ TRANSFER_ABORT_TOO_MANY_REALM_INSTANCES = 0x0A, // Additional instances cannot be launched, please try again later.
+ TRANSFER_ABORT_NEED_GROUP = 0x0B, // 3.1
+ TRANSFER_ABORT_NOT_FOUND2 = 0x0C, // 3.1
+ TRANSFER_ABORT_NOT_FOUND3 = 0x0D, // 3.1
+ TRANSFER_ABORT_NOT_FOUND4 = 0x0E, // 3.2
+ TRANSFER_ABORT_REALM_ONLY = 0x0F, // All players on party must be from the same realm.
+ TRANSFER_ABORT_MAP_NOT_ALLOWED = 0x10, // Map can't be entered at this time.
+};
+
+enum InstanceResetWarningType
+{
+ RAID_INSTANCE_WARNING_HOURS = 1, // WARNING! %s is scheduled to reset in %d hour(s).
+ RAID_INSTANCE_WARNING_MIN = 2, // WARNING! %s is scheduled to reset in %d minute(s)!
+ RAID_INSTANCE_WARNING_MIN_SOON = 3, // WARNING! %s is scheduled to reset in %d minute(s). Please exit the zone or you will be returned to your bind location!
+ RAID_INSTANCE_WELCOME = 4, // Welcome to %s. This raid instance is scheduled to reset in %s.
+ RAID_INSTANCE_EXPIRED = 5
+};
+
+// PLAYER_FIELD_ARENA_TEAM_INFO_1_1 offsets
+enum ArenaTeamInfoType
+{
+ ARENA_TEAM_ID = 0,
+ ARENA_TEAM_TYPE = 1, // new in 3.2 - team type?
+ ARENA_TEAM_MEMBER = 2, // 0 - captain, 1 - member
+ ARENA_TEAM_GAMES_WEEK = 3,
+ ARENA_TEAM_GAMES_SEASON = 4,
+ ARENA_TEAM_WINS_SEASON = 5,
+ ARENA_TEAM_PERSONAL_RATING = 6,
+ ARENA_TEAM_END = 7
+};
+
+class InstanceSave;
+
+enum RestType
+{
+ REST_TYPE_NO = 0,
+ REST_TYPE_IN_TAVERN = 1,
+ REST_TYPE_IN_CITY = 2
+};
+
+enum DuelCompleteType
+{
+ DUEL_INTERUPTED = 0,
+ DUEL_WON = 1,
+ DUEL_FLED = 2
+};
+
+enum TeleportToOptions
+{
+ TELE_TO_GM_MODE = 0x01,
+ TELE_TO_NOT_LEAVE_TRANSPORT = 0x02,
+ TELE_TO_NOT_LEAVE_COMBAT = 0x04,
+ TELE_TO_NOT_UNSUMMON_PET = 0x08,
+ TELE_TO_SPELL = 0x10,
+};
+
+/// Type of environmental damages
+enum EnviromentalDamage
+{
+ DAMAGE_EXHAUSTED = 0,
+ DAMAGE_DROWNING = 1,
+ DAMAGE_FALL = 2,
+ DAMAGE_LAVA = 3,
+ DAMAGE_SLIME = 4,
+ DAMAGE_FIRE = 5,
+ DAMAGE_FALL_TO_VOID = 6 // custom case for fall without durability loss
+};
+
+enum PlayedTimeIndex
+{
+ PLAYED_TIME_TOTAL = 0,
+ PLAYED_TIME_LEVEL = 1
+};
+
+#define MAX_PLAYED_TIME_INDEX 2
+
+// used at player loading query list preparing, and later result selection
+enum PlayerLoginQueryIndex
+{
+ PLAYER_LOGIN_QUERY_LOADFROM = 0,
+ PLAYER_LOGIN_QUERY_LOADGROUP = 1,
+ PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES = 2,
+ PLAYER_LOGIN_QUERY_LOADAURAS = 3,
+ PLAYER_LOGIN_QUERY_LOADSPELLS = 4,
+ PLAYER_LOGIN_QUERY_LOADQUESTSTATUS = 5,
+ PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS = 6,
+ PLAYER_LOGIN_QUERY_LOADREPUTATION = 7,
+ PLAYER_LOGIN_QUERY_LOADINVENTORY = 8,
+ PLAYER_LOGIN_QUERY_LOADACTIONS = 9,
+ PLAYER_LOGIN_QUERY_LOADMAILCOUNT = 10,
+ PLAYER_LOGIN_QUERY_LOADMAILDATE = 11,
+ PLAYER_LOGIN_QUERY_LOADSOCIALLIST = 12,
+ PLAYER_LOGIN_QUERY_LOADHOMEBIND = 13,
+ PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS = 14,
+ PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES = 15,
+ PLAYER_LOGIN_QUERY_LOADGUILD = 16,
+ PLAYER_LOGIN_QUERY_LOADARENAINFO = 17,
+ PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS = 18,
+ PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS = 19,
+ PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS = 20,
+ PLAYER_LOGIN_QUERY_LOADBGDATA = 21,
+ PLAYER_LOGIN_QUERY_LOADGLYPHS = 22,
+ PLAYER_LOGIN_QUERY_LOADTALENTS = 23,
+ PLAYER_LOGIN_QUERY_LOADACCOUNTDATA = 24,
+ PLAYER_LOGIN_QUERY_LOADSKILLS = 25,
+ MAX_PLAYER_LOGIN_QUERY = 26
+};
+
+enum PlayerDelayedOperations
+{
+ DELAYED_SAVE_PLAYER = 0x01,
+ DELAYED_RESURRECT_PLAYER = 0x02,
+ DELAYED_SPELL_CAST_DESERTER = 0x04,
+ DELAYED_BG_MOUNT_RESTORE = 0x08, ///< Flag to restore mount state after teleport from BG
+ DELAYED_BG_TAXI_RESTORE = 0x10, ///< Flag to restore taxi state after teleport from BG
+ DELAYED_END
+};
+
+// Player summoning auto-decline time (in secs)
+#define MAX_PLAYER_SUMMON_DELAY (2*MINUTE)
+#define MAX_MONEY_AMOUNT (0x7FFFFFFF-1)
+
+struct InstancePlayerBind
+{
+ InstanceSave *save;
+ bool perm;
+ /* permanent PlayerInstanceBinds are created in Raid/Heroic instances for players
+ that aren't already permanently bound when they are inside when a boss is killed
+ or when they enter an instance that the group leader is permanently bound to. */
+ InstancePlayerBind() : save(NULL), perm(false) {}
+};
+
+struct AccessRequirement
+{
+ uint8 levelMin;
+ uint8 levelMax;
+ uint8 heroicLevelMin;
+ uint32 item;
+ uint32 item2;
+ uint32 heroicKey;
+ uint32 heroicKey2;
+ uint32 quest;
+ std::string questFailedText;
+ uint32 heroicQuest;
+ std::string heroicQuestFailedText;
+};
+
+class PlayerTaxi
+{
+ public:
+ PlayerTaxi();
+ ~PlayerTaxi() {}
+ // Nodes
+ void InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint8 level);
+ void LoadTaxiMask(const char* data);
+
+ bool IsTaximaskNodeKnown(uint32 nodeidx) const
+ {
+ uint8 field = uint8((nodeidx - 1) / 32);
+ uint32 submask = 1<<((nodeidx-1)%32);
+ return (m_taximask[field] & submask) == submask;
+ }
+ bool SetTaximaskNode(uint32 nodeidx)
+ {
+ uint8 field = uint8((nodeidx - 1) / 32);
+ uint32 submask = 1<<((nodeidx-1)%32);
+ if ((m_taximask[field] & submask) != submask )
+ {
+ m_taximask[field] |= submask;
+ return true;
+ }
+ else
+ return false;
+ }
+ void AppendTaximaskTo(ByteBuffer& data,bool all);
+
+ // Destinations
+ bool LoadTaxiDestinationsFromString(const std::string& values, uint32 team);
+ std::string SaveTaxiDestinationsToString();
+
+ void ClearTaxiDestinations() { m_TaxiDestinations.clear(); }
+ void AddTaxiDestination(uint32 dest) { m_TaxiDestinations.push_back(dest); }
+ uint32 GetTaxiSource() const { return m_TaxiDestinations.empty() ? 0 : m_TaxiDestinations.front(); }
+ uint32 GetTaxiDestination() const { return m_TaxiDestinations.size() < 2 ? 0 : m_TaxiDestinations[1]; }
+ uint32 GetCurrentTaxiPath() const;
+ uint32 NextTaxiDestination()
+ {
+ m_TaxiDestinations.pop_front();
+ return GetTaxiDestination();
+ }
+ bool empty() const { return m_TaxiDestinations.empty(); }
+
+ friend std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi);
+ private:
+ TaxiMask m_taximask;
+ std::deque<uint32> m_TaxiDestinations;
+};
+
+std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi);
+
+class Player;
+
+/// Holder for BattleGround data
+struct BGData
+{
+ BGData() : bgInstanceID(0), bgTypeID(BATTLEGROUND_TYPE_NONE), bgAfkReportedCount(0), bgAfkReportedTimer(0),
+ bgTeam(0), mountSpell(0) { ClearTaxiPath(); }
+
+ uint32 bgInstanceID; ///< This variable is set to bg->m_InstanceID,
+ /// when player is teleported to BG - (it is battleground's GUID)
+ BattleGroundTypeId bgTypeID;
+
+ std::set<uint32> bgAfkReporter;
+ uint8 bgAfkReportedCount;
+ time_t bgAfkReportedTimer;
+
+ uint32 bgTeam; ///< What side the player will be added to
+
+ uint32 mountSpell;
+ uint32 taxiPath[2];
+
+ WorldLocation joinPos; ///< From where player entered BG
+
+ void ClearTaxiPath() { taxiPath[0] = taxiPath[1] = 0; }
+ bool HasTaxiPath() const { return taxiPath[0] && taxiPath[1]; }
+};
+
+class Player : public Unit, public GridObject<Player>
+{
+ friend class WorldSession;
+ friend void Item::AddToUpdateQueueOf(Player *player);
+ friend void Item::RemoveFromUpdateQueueOf(Player *player);
+ public:
+ explicit Player (WorldSession *session);
+ ~Player ( );
+
+ void CleanupsBeforeDelete(bool finalCleanup = true);
+
+ static UpdateMask updateVisualBits;
+ static void InitVisibleBits();
+
+ void AddToWorld();
+ void RemoveFromWorld();
+
+ bool TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options = 0);
+ void TeleportOutOfMap(Map *oldMap);
+
+ bool TeleportTo(WorldLocation const &loc, uint32 options = 0)
+ {
+ return TeleportTo(loc.GetMapId(), loc.GetPositionX(), loc.GetPositionY(), loc.GetPositionZ(), loc.GetOrientation(), options);
+ }
+
+ bool TeleportToBGEntryPoint();
+
+ void SetSummonPoint(uint32 mapid, float x, float y, float z)
+ {
+ m_summon_expire = time(NULL) + MAX_PLAYER_SUMMON_DELAY;
+ m_summon_mapid = mapid;
+ m_summon_x = x;
+ m_summon_y = y;
+ m_summon_z = z;
+ }
+ void SummonIfPossible(bool agree);
+
+ bool 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 );
+
+ void Update( uint32 time );
+
+ static bool BuildEnumData( QueryResult_AutoPtr result, WorldPacket * p_data );
+
+ void SetInWater(bool apply);
+
+ bool IsInWater() const { return m_isInWater; }
+ bool IsUnderWater() const;
+ bool IsFalling() { return GetPositionZ() < m_lastFallZ; }
+
+ void SendInitialPacketsBeforeAddToMap();
+ void SendInitialPacketsAfterAddToMap();
+ void SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg = 0);
+ void SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint32 time);
+
+ Creature* GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask);
+ bool CanInteractWithNPCs(bool alive = true) const;
+ GameObject* GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const;
+
+ bool ToggleAFK();
+ bool ToggleDND();
+ bool isAFK() const { return HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_AFK); }
+ bool isDND() const { return HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_DND); }
+ uint8 chatTag() const;
+ std::string afkMsg;
+ std::string dndMsg;
+
+ uint32 GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair, BarberShopStyleEntry const* newSkin=NULL);
+
+ PlayerSocial *GetSocial() { return m_social; }
+
+ PlayerTaxi m_taxi;
+ void InitTaxiNodesForLevel() { m_taxi.InitTaxiNodesForLevel(getRace(), getClass(), getLevel()); }
+ bool ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc = NULL, uint32 spellid = 0);
+ bool ActivateTaxiPathTo(uint32 taxi_path_id, uint32 spellid = 0);
+ void CleanupAfterTaxiFlight();
+ void ContinueTaxiFlight();
+ // mount_id can be used in scripting calls
+ bool isAcceptWhispers() const { return m_ExtraFlags & PLAYER_EXTRA_ACCEPT_WHISPERS; }
+ void SetAcceptWhispers(bool on) { if(on) m_ExtraFlags |= PLAYER_EXTRA_ACCEPT_WHISPERS; else m_ExtraFlags &= ~PLAYER_EXTRA_ACCEPT_WHISPERS; }
+ bool isGameMaster() const { return m_ExtraFlags & PLAYER_EXTRA_GM_ON; }
+ void SetGameMaster(bool on);
+ bool isGMChat() const { return GetSession()->GetSecurity() >= SEC_MODERATOR && (m_ExtraFlags & PLAYER_EXTRA_GM_CHAT); }
+ void SetGMChat(bool on) { if(on) m_ExtraFlags |= PLAYER_EXTRA_GM_CHAT; else m_ExtraFlags &= ~PLAYER_EXTRA_GM_CHAT; }
+ bool isTaxiCheater() const { return m_ExtraFlags & PLAYER_EXTRA_TAXICHEAT; }
+ void SetTaxiCheater(bool on) { if(on) m_ExtraFlags |= PLAYER_EXTRA_TAXICHEAT; else m_ExtraFlags &= ~PLAYER_EXTRA_TAXICHEAT; }
+ bool isGMVisible() const { return !(m_ExtraFlags & PLAYER_EXTRA_GM_INVISIBLE); }
+ void SetGMVisible(bool on);
+ void SetPvPDeath(bool on) { if(on) m_ExtraFlags |= PLAYER_EXTRA_PVP_DEATH; else m_ExtraFlags &= ~PLAYER_EXTRA_PVP_DEATH; }
+
+ void GiveXP(uint32 xp, Unit* victim);
+ void GiveLevel(uint8 level);
+
+ void InitStatsForLevel(bool reapplyMods = false);
+
+ // Played Time Stuff
+ time_t m_logintime;
+ time_t m_Last_tick;
+ uint32 m_Played_time[MAX_PLAYED_TIME_INDEX];
+ uint32 GetTotalPlayedTime() { return m_Played_time[PLAYED_TIME_TOTAL]; }
+ uint32 GetLevelPlayedTime() { return m_Played_time[PLAYED_TIME_LEVEL]; }
+
+ void setDeathState(DeathState s); // overwrite Unit::setDeathState
+
+ void InnEnter (int time,uint32 mapid, float x,float y,float z)
+ {
+ inn_pos_mapid = mapid;
+ inn_pos_x = x;
+ inn_pos_y = y;
+ inn_pos_z = z;
+ time_inn_enter = time;
+ }
+
+ float GetRestBonus() const { return m_rest_bonus; }
+ void SetRestBonus(float rest_bonus_new);
+
+ RestType GetRestType() const { return rest_type; }
+ void SetRestType(RestType n_r_type) { rest_type = n_r_type; }
+
+ uint32 GetInnPosMapId() const { return inn_pos_mapid; }
+ float GetInnPosX() const { return inn_pos_x; }
+ float GetInnPosY() const { return inn_pos_y; }
+ float GetInnPosZ() const { return inn_pos_z; }
+
+ int GetTimeInnEnter() const { return time_inn_enter; }
+ void UpdateInnerTime (int time) { time_inn_enter = time; }
+
+ Pet* GetPet() const;
+ Pet* SummonPet(uint32 entry, float x, float y, float z, float ang, PetType petType, uint32 despwtime);
+ void RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent = false);
+ uint32 GetPhaseMaskForSpawn() const; // used for proper set phase for DB at GM-mode creature/GO spawn
+
+ void Say(const std::string& text, const uint32 language);
+ void Yell(const std::string& text, const uint32 language);
+ void TextEmote(const std::string& text);
+ void Whisper(const std::string& text, const uint32 language,uint64 receiver);
+ void BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const;
+
+ /*********************************************************/
+ /*** STORAGE SYSTEM ***/
+ /*********************************************************/
+
+ void SetVirtualItemSlot( uint8 i, Item* item);
+ void SetSheath( SheathState sheathed ); // overwrite Unit version
+ uint8 FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const;
+ uint32 GetItemCount( uint32 item, bool inBankAlso = false, Item* skipItem = NULL ) const;
+ Item* GetItemByGuid( uint64 guid ) const;
+ Item* GetItemByEntry( uint32 entry ) const;
+ Item* GetItemByPos( uint16 pos ) const;
+ Item* GetItemByPos( uint8 bag, uint8 slot ) const;
+ inline Item* GetUseableItemByPos( uint8 bag, uint8 slot ) const //Does additional check for disarmed weapons
+ {
+ if (!CanUseAttackType(GetAttackBySlot(slot)))
+ return NULL;
+ return GetItemByPos(bag, slot);
+ }
+ Item* GetWeaponForAttack(WeaponAttackType attackType, bool useable = false) const;
+ Item* GetShield(bool useable = false) const;
+ static uint8 GetAttackBySlot( uint8 slot ); // MAX_ATTACK if not weapon slot
+ std::vector<Item *> &GetItemUpdateQueue() { return m_itemUpdateQueue; }
+ static bool IsInventoryPos( uint16 pos ) { return IsInventoryPos(pos >> 8,pos & 255); }
+ static bool IsInventoryPos( uint8 bag, uint8 slot );
+ static bool IsEquipmentPos( uint16 pos ) { return IsEquipmentPos(pos >> 8,pos & 255); }
+ static bool IsEquipmentPos( uint8 bag, uint8 slot );
+ static bool IsBagPos( uint16 pos );
+ static bool IsBankPos( uint16 pos ) { return IsBankPos(pos >> 8,pos & 255); }
+ static bool IsBankPos( uint8 bag, uint8 slot );
+ bool IsValidPos( uint16 pos ) { return IsBankPos(pos >> 8,pos & 255); }
+ bool IsValidPos( uint8 bag, uint8 slot );
+ uint8 GetBankBagSlotCount() const { return GetByteValue(PLAYER_BYTES_2, 2); }
+ void SetBankBagSlotCount(uint8 count) { SetByteValue(PLAYER_BYTES_2, 2, count); }
+ bool HasItemCount( uint32 item, uint32 count, bool inBankAlso = false ) const;
+ bool HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem = NULL);
+ bool CanNoReagentCast(SpellEntry const* spellInfo) const;
+ bool HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot = NULL_SLOT) const;
+ bool HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot = NULL_SLOT) const;
+ uint8 CountItemWithLimitCategory(uint32 limitCategory, Item* skipItem = NULL) const;
+ uint8 CanTakeMoreSimilarItems(Item* pItem) const { return _CanTakeMoreSimilarItems(pItem->GetEntry(),pItem->GetCount(),pItem); }
+ uint8 CanTakeMoreSimilarItems(uint32 entry, uint32 count) const { return _CanTakeMoreSimilarItems(entry,count,NULL); }
+ uint8 CanStoreNewItem( uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 item, uint32 count, uint32* no_space_count = NULL ) const
+ {
+ return _CanStoreItem(bag, slot, dest, item, count, NULL, false, no_space_count );
+ }
+ uint8 CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec& dest, Item *pItem, bool swap = false ) const
+ {
+ if(!pItem)
+ return EQUIP_ERR_ITEM_NOT_FOUND;
+ uint32 count = pItem->GetCount();
+ return _CanStoreItem( bag, slot, dest, pItem->GetEntry(), count, pItem, swap, NULL );
+
+ }
+ uint8 CanStoreItems( Item **pItem,int count) const;
+ uint8 CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const;
+ uint8 CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading = true ) const;
+
+ uint8 CanEquipUniqueItem( Item * pItem, uint8 except_slot = NULL_SLOT, uint32 limit_count = 1 ) const;
+ uint8 CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot = NULL_SLOT, uint32 limit_count = 1 ) const;
+ uint8 CanUnequipItems( uint32 item, uint32 count ) const;
+ uint8 CanUnequipItem( uint16 src, bool swap ) const;
+ uint8 CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec& dest, Item *pItem, bool swap, bool not_loading = true ) const;
+ uint8 CanUseItem( Item *pItem, bool not_loading = true ) const;
+ bool HasItemTotemCategory( uint32 TotemCategory ) const;
+ bool CanUseItem( ItemPrototype const *pItem );
+ uint8 CanUseAmmo( uint32 item ) const;
+ Item* StoreNewItem( ItemPosCountVec const& pos, uint32 item, bool update,int32 randomPropertyId = 0 );
+ Item* StoreItem( ItemPosCountVec const& pos, Item *pItem, bool update );
+ Item* EquipNewItem( uint16 pos, uint32 item, bool update );
+ Item* EquipItem( uint16 pos, Item *pItem, bool update );
+ void AutoUnequipOffhandIfNeed(bool force = false);
+ bool StoreNewItemInBestSlots(uint32 item_id, uint32 item_count);
+ void AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast = false);
+ void AutoStoreLoot(uint32 loot_id, LootStore const& store, bool broadcast = false) { AutoStoreLoot(NULL_BAG,NULL_SLOT,loot_id,store,broadcast); }
+
+ uint8 _CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count = NULL) const;
+ uint8 _CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 entry, uint32 count, Item *pItem = NULL, bool swap = false, uint32* no_space_count = NULL ) const;
+
+ void ApplyEquipCooldown( Item * pItem );
+ void SetAmmo( uint32 item );
+ void RemoveAmmo();
+ float GetAmmoDPS() const { return m_ammoDPS; }
+ bool CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const;
+ void QuickEquipItem( uint16 pos, Item *pItem);
+ void VisualizeItem( uint8 slot, Item *pItem);
+ void SetVisibleItemSlot(uint8 slot, Item *pItem);
+ Item* BankItem( ItemPosCountVec const& dest, Item *pItem, bool update )
+ {
+ return StoreItem( dest, pItem, update);
+ }
+ Item* BankItem( uint16 pos, Item *pItem, bool update );
+ void RemoveItem( uint8 bag, uint8 slot, bool update );
+ void MoveItemFromInventory(uint8 bag, uint8 slot, bool update);
+ // in trade, auction, guild bank, mail....
+ void MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB = false);
+ // in trade, guild bank, mail....
+ void RemoveItemDependentAurasAndCasts( Item * pItem );
+ void DestroyItem( uint8 bag, uint8 slot, bool update );
+ void DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check = false);
+ void DestroyItemCount( Item* item, uint32& count, bool update );
+ void DestroyConjuredItems( bool update );
+ void DestroyZoneLimitedItem( bool update, uint32 new_zone );
+ void SplitItem( uint16 src, uint16 dst, uint32 count );
+ void SwapItem( uint16 src, uint16 dst );
+ void AddItemToBuyBackSlot( Item *pItem );
+ Item* GetItemFromBuyBackSlot( uint32 slot );
+ void RemoveItemFromBuyBackSlot( uint32 slot, bool del );
+ uint32 GetMaxKeyringSize() const { return KEYRING_SLOT_END-KEYRING_SLOT_START; }
+ void SendEquipError( uint8 msg, Item* pItem, Item *pItem2 );
+ void SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param );
+ void SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param );
+ void AddWeaponProficiency(uint32 newflag) { m_WeaponProficiency |= newflag; }
+ void AddArmorProficiency(uint32 newflag) { m_ArmorProficiency |= newflag; }
+ uint32 GetWeaponProficiency() const { return m_WeaponProficiency; }
+ uint32 GetArmorProficiency() const { return m_ArmorProficiency; }
+ bool IsUseEquipedWeapon( bool mainhand ) const
+ {
+ // disarm applied only to mainhand weapon
+ return !IsInFeralForm() && (!mainhand || !HasFlag(UNIT_FIELD_FLAGS,UNIT_FLAG_DISARMED) );
+ }
+ bool IsTwoHandUsed() const
+ {
+ Item* mainItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
+ return mainItem && mainItem->GetProto()->InventoryType == INVTYPE_2HWEAPON && !CanTitanGrip();
+ }
+ void SendNewItem( Item *item, uint32 count, bool received, bool created, bool broadcast = false );
+ bool BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint8 bag, uint8 slot);
+
+ float GetReputationPriceDiscount( Creature const* pCreature ) const;
+ Player* GetTrader() const { return pTrader; }
+ void ClearTrade();
+ void TradeCancel(bool sendback);
+
+ void UpdateEnchantTime(uint32 time);
+ void UpdateItemDuration(uint32 time, bool realtimeonly=false);
+ void AddEnchantmentDurations(Item *item);
+ void RemoveEnchantmentDurations(Item *item);
+ void RemoveArenaEnchantments(EnchantmentSlot slot);
+ void AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration);
+ void ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur = true, bool ignore_condition = false);
+ void ApplyEnchantment(Item *item,bool apply);
+ void SendEnchantmentDurations();
+ void BuildEnchantmentsInfoData(WorldPacket *data);
+ void AddItemDurations(Item *item);
+ void RemoveItemDurations(Item *item);
+ void SendItemDurations();
+ void LoadCorpse();
+ void LoadPet();
+
+ uint32 m_stableSlots;
+
+ /*********************************************************/
+ /*** GOSSIP SYSTEM ***/
+ /*********************************************************/
+
+ void PrepareGossipMenu(WorldObject *pSource, uint32 menuId = 0);
+ void SendPreparedGossip(WorldObject *pSource);
+ void OnGossipSelect(WorldObject *pSource, uint32 gossipListId, uint32 menuId);
+
+ uint32 GetGossipTextId(uint32 menuId);
+ uint32 GetGossipTextId(WorldObject *pSource);
+ uint32 GetDefaultGossipMenuForSource(WorldObject *pSource);
+
+ /*********************************************************/
+ /*** QUEST SYSTEM ***/
+ /*********************************************************/
+
+ int32 GetQuestLevel( Quest const* pQuest ) const { return pQuest && (pQuest->GetQuestLevel() > 0) ? pQuest->GetQuestLevel() : getLevel(); }
+
+ void PrepareQuestMenu( uint64 guid );
+ void SendPreparedQuest( uint64 guid );
+ bool IsActiveQuest( uint32 quest_id ) const;
+ Quest const *GetNextQuest( uint64 guid, Quest const *pQuest );
+ bool CanSeeStartQuest( Quest const *pQuest );
+ bool CanTakeQuest( Quest const *pQuest, bool msg );
+ bool CanAddQuest( Quest const *pQuest, bool msg );
+ bool CanCompleteQuest( uint32 quest_id );
+ bool CanCompleteRepeatableQuest(Quest const *pQuest);
+ bool CanRewardQuest( Quest const *pQuest, bool msg );
+ bool CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg );
+ void AddQuest( Quest const *pQuest, Object *questGiver );
+ void CompleteQuest( uint32 quest_id );
+ void IncompleteQuest( uint32 quest_id );
+ void RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce = true );
+ void FailQuest( uint32 quest_id );
+ bool SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg );
+ bool SatisfyQuestLevel( Quest const* qInfo, bool msg );
+ bool SatisfyQuestLog( bool msg );
+ bool SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg );
+ bool SatisfyQuestRace( Quest const* qInfo, bool msg );
+ bool SatisfyQuestReputation( Quest const* qInfo, bool msg );
+ bool SatisfyQuestStatus( Quest const* qInfo, bool msg );
+ bool SatisfyQuestTimed( Quest const* qInfo, bool msg );
+ bool SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg );
+ bool SatisfyQuestNextChain( Quest const* qInfo, bool msg );
+ bool SatisfyQuestPrevChain( Quest const* qInfo, bool msg );
+ bool SatisfyQuestDay( Quest const* qInfo, bool msg );
+ bool GiveQuestSourceItem( Quest const *pQuest );
+ bool TakeQuestSourceItem( uint32 quest_id, bool msg );
+ bool GetQuestRewardStatus( uint32 quest_id ) const;
+ QuestStatus GetQuestStatus( uint32 quest_id ) const;
+ void SetQuestStatus( uint32 quest_id, QuestStatus status );
+
+ void SetDailyQuestStatus( uint32 quest_id );
+ void ResetDailyQuestStatus();
+
+ uint16 FindQuestSlot( uint32 quest_id ) const;
+ uint32 GetQuestSlotQuestId(uint16 slot) const { return GetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_ID_OFFSET); }
+ uint32 GetQuestSlotState(uint16 slot) const { return GetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET); }
+ uint16 GetQuestSlotCounter(uint16 slot, uint8 counter) const { return (uint16)(GetUInt64Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET) >> (counter * 16)); }
+ uint32 GetQuestSlotTime(uint16 slot) const { return GetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_TIME_OFFSET); }
+ void SetQuestSlot(uint16 slot, uint32 quest_id, uint32 timer = 0)
+ {
+ SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_ID_OFFSET, quest_id);
+ SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, 0);
+ SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET, 0);
+ SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET + 1, 0);
+ SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_TIME_OFFSET, timer);
+ }
+ void SetQuestSlotCounter(uint16 slot, uint8 counter, uint16 count)
+ {
+ uint64 val = GetUInt64Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET);
+ val &= ~((uint64)0xFFFF << (counter * 16));
+ val |= ((uint64)count << (counter * 16));
+ SetUInt64Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET, val);
+ }
+ void SetQuestSlotState(uint16 slot, uint32 state) { SetFlag(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, state); }
+ void RemoveQuestSlotState(uint16 slot, uint32 state) { RemoveFlag(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, state); }
+ void SetQuestSlotTimer(uint16 slot, uint32 timer) { SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_TIME_OFFSET, timer); }
+ void SwapQuestSlot(uint16 slot1, uint16 slot2)
+ {
+ for (int i = 0; i < MAX_QUEST_OFFSET; ++i)
+ {
+ uint32 temp1 = GetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot1 + i);
+ uint32 temp2 = GetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot2 + i);
+
+ SetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot1 + i, temp2);
+ SetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot2 + i, temp1);
+ }
+ }
+ uint32 GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry);
+ void AreaExploredOrEventHappens( uint32 questId );
+ void GroupEventHappens( uint32 questId, WorldObject const* pEventObject );
+ void ItemAddedQuestCheck( uint32 entry, uint32 count );
+ void ItemRemovedQuestCheck( uint32 entry, uint32 count );
+ void KilledMonster( CreatureInfo const* cInfo, uint64 guid );
+ void KilledMonsterCredit( uint32 entry, uint64 guid );
+ void CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id );
+ void TalkedToCreature( uint32 entry, uint64 guid );
+ void MoneyChanged( uint32 value );
+ void ReputationChanged(FactionEntry const* factionEntry );
+ void ReputationChanged2(FactionEntry const* factionEntry );
+ bool HasQuestForItem( uint32 itemid ) const;
+ bool HasQuestForGO(int32 GOId) const;
+ void UpdateForQuestWorldObjects();
+ bool CanShareQuest(uint32 quest_id) const;
+
+ void SendQuestComplete( uint32 quest_id );
+ void SendQuestReward( Quest const *pQuest, uint32 XP, Object* questGiver );
+ void SendQuestFailed( uint32 quest_id );
+ void SendQuestTimerFailed( uint32 quest_id );
+ void SendCanTakeQuestResponse( uint32 msg );
+ void SendQuestConfirmAccept(Quest const* pQuest, Player* pReceiver);
+ void SendPushToPartyResponse( Player *pPlayer, uint32 msg );
+ void SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count );
+ void SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count );
+
+ uint64 GetDivider() { return m_divider; }
+ void SetDivider( uint64 guid ) { m_divider = guid; }
+
+ uint32 GetInGameTime() { return m_ingametime; }
+
+ void SetInGameTime( uint32 time ) { m_ingametime = time; }
+
+ void AddTimedQuest( uint32 quest_id ) { m_timedquests.insert(quest_id); }
+ void RemoveTimedQuest( uint32 quest_id ) { m_timedquests.erase(quest_id); }
+
+ /*********************************************************/
+ /*** LOAD SYSTEM ***/
+ /*********************************************************/
+
+ bool LoadFromDB(uint32 guid, SqlQueryHolder *holder);
+ bool isBeingLoaded() const { return GetSession()->PlayerLoading();}
+
+ bool MinimalLoadFromDB(QueryResult_AutoPtr result, uint32 guid);
+ static bool LoadValuesArrayFromDB(Tokens& data,uint64 guid);
+ static uint32 GetUInt32ValueFromArray(Tokens const& data, uint16 index);
+ static float GetFloatValueFromArray(Tokens const& data, uint16 index);
+ static uint32 GetUInt32ValueFromDB(uint16 index, uint64 guid);
+ static float GetFloatValueFromDB(uint16 index, uint64 guid);
+ static uint32 GetZoneIdFromDB(uint64 guid);
+ static uint32 GetLevelFromDB(uint64 guid);
+ static bool LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid);
+
+ /*********************************************************/
+ /*** SAVE SYSTEM ***/
+ /*********************************************************/
+
+ void SaveToDB();
+ void SaveInventoryAndGoldToDB(); // fast save function for item/money cheating preventing
+ void SaveGoldToDB();
+ void SaveDataFieldToDB();
+ static bool SaveValuesArrayInDB(Tokens const& data,uint64 guid);
+ static void SetUInt32ValueInArray(Tokens& data,uint16 index, uint32 value);
+ static void SetFloatValueInArray(Tokens& data,uint16 index, float value);
+ static void SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid);
+ static void SetFloatValueInDB(uint16 index, float value, uint64 guid);
+ static void Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair);
+ static void SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid);
+
+ bool m_mailsLoaded;
+ bool m_mailsUpdated;
+
+ void SetBindPoint(uint64 guid);
+ void SendTalentWipeConfirm(uint64 guid);
+ void SendPetSkillWipeConfirm();
+ void CalcRage( uint32 damage,bool attacker );
+ void RegenerateAll();
+ void Regenerate(Powers power);
+ void RegenerateHealth();
+ void setRegenTimerCount(uint32 time) {m_regenTimerCount = time;}
+ void setWeaponChangeTimer(uint32 time) {m_weaponChangeTimer = time;}
+
+ uint32 GetMoney() { return GetUInt32Value (PLAYER_FIELD_COINAGE); }
+ void ModifyMoney( int32 d )
+ {
+ d = GetSession()->HandleOnGetMoney(d);
+ if(d < 0)
+ SetMoney (GetMoney() > uint32(-d) ? GetMoney() + d : 0);
+ else
+ SetMoney (GetMoney() < uint32(MAX_MONEY_AMOUNT - d) ? GetMoney() + d : MAX_MONEY_AMOUNT);
+
+ // "At Gold Limit"
+ if(GetMoney() >= MAX_MONEY_AMOUNT)
+ SendEquipError(EQUIP_ERR_TOO_MUCH_GOLD,NULL,NULL);
+ }
+ void SetMoney( uint32 value )
+ {
+ SetUInt32Value (PLAYER_FIELD_COINAGE, value);
+ MoneyChanged( value );
+ UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED);
+ }
+
+ QuestStatusMap& getQuestStatusMap() { return mQuestStatus; };
+
+ const uint64& GetSelection( ) const { return m_curSelection; }
+ Unit *GetSelectedUnit() const;
+ Player *GetSelectedPlayer() const;
+ void SetSelection(const uint64 &guid) { m_curSelection = guid; SetUInt64Value(UNIT_FIELD_TARGET, guid); }
+
+ uint8 GetComboPoints() { return m_comboPoints; }
+ const uint64& GetComboTarget() const { return m_comboTarget; }
+
+ void AddComboPoints(Unit* target, int8 count, Spell * spell = NULL);
+ void GainSpellComboPoints(int8 count);
+ void ClearComboPoints();
+ void SendComboPoints();
+
+ void SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError = 0, uint32 item_guid = 0, uint32 item_count = 0);
+ void SendNewMail();
+ void UpdateNextMailTimeAndUnreads();
+ void AddNewMailDeliverTime(time_t deliver_time);
+ bool IsMailsLoaded() const { return m_mailsLoaded; }
+
+ void RemoveMail(uint32 id);
+
+ void AddMail(Mail* mail) { m_mail.push_front(mail);}// for call from WorldSession::SendMailTo
+ uint32 GetMailSize() { return m_mail.size();}
+ Mail* GetMail(uint32 id);
+
+ PlayerMails::iterator GetMailBegin() { return m_mail.begin();}
+ PlayerMails::iterator GetMailEnd() { return m_mail.end();}
+
+ /*********************************************************/
+ /*** MAILED ITEMS SYSTEM ***/
+ /*********************************************************/
+
+ uint8 unReadMails;
+ time_t m_nextMailDelivereTime;
+
+ typedef UNORDERED_MAP<uint32, Item*> ItemMap;
+
+ ItemMap mMitems; //template defined in objectmgr.cpp
+
+ Item* GetMItem(uint32 id)
+ {
+ ItemMap::const_iterator itr = mMitems.find(id);
+ return itr != mMitems.end() ? itr->second : NULL;
+ }
+
+ void AddMItem(Item* it)
+ {
+ ASSERT( it );
+ //assert deleted, because items can be added before loading
+ mMitems[it->GetGUIDLow()] = it;
+ }
+
+ bool RemoveMItem(uint32 id)
+ {
+ return mMitems.erase(id) ? true : false;
+ }
+
+ void PetSpellInitialize();
+ void CharmSpellInitialize();
+ void PossessSpellInitialize();
+ void VehicleSpellInitialize();
+ void SendRemoveControlBar();
+ bool HasSpell(uint32 spell) const;
+ bool HasActiveSpell(uint32 spell) const; // show in spellbook
+ TrainerSpellState GetTrainerSpellState(TrainerSpell const* trainer_spell) const;
+ bool IsSpellFitByClassAndRace( uint32 spell_id ) const;
+ bool IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const;
+
+ void SendProficiency(uint8 pr1, uint32 pr2);
+ void SendInitialSpells();
+ bool addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled);
+ void learnSpell(uint32 spell_id, bool dependent);
+ void removeSpell(uint32 spell_id, bool disabled = false, bool learn_low_rank = true);
+ void resetSpells(bool myClassOnly = false);
+ void learnDefaultSpells();
+ void learnQuestRewardedSpells();
+ void learnQuestRewardedSpells(Quest const* quest);
+ void learnSpellHighRank(uint32 spellid);
+ void AddTemporarySpell(uint32 spellId);
+ void RemoveTemporarySpell(uint32 spellId);
+ void SetReputation(uint32 factionentry, uint32 value);
+ uint32 GetReputation(uint32 factionentry);
+ std::string GetGuildName();
+ uint32 GetFreeTalentPoints() const { return GetUInt32Value(PLAYER_CHARACTER_POINTS1); }
+ void SetFreeTalentPoints(uint32 points) { SetUInt32Value(PLAYER_CHARACTER_POINTS1,points); }
+ bool resetTalents(bool no_cost = false);
+ uint32 resetTalentsCost() const;
+ void InitTalentForLevel();
+ void BuildPlayerTalentsInfoData(WorldPacket *data);
+ void BuildPetTalentsInfoData(WorldPacket *data);
+ void SendTalentsInfoData(bool pet);
+ void LearnTalent(uint32 talentId, uint32 talentRank);
+ void LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank);
+
+ bool AddTalent(uint32 spell, uint8 spec, bool learning);
+ bool HasTalent(uint32 spell_id, uint8 spec) const;
+
+ uint32 CalculateTalentsPoints() const;
+
+ // Dual Spec
+ void UpdateSpecCount(uint8 count);
+ uint32 GetActiveSpec() { return m_activeSpec; }
+ void SetActiveSpec(uint8 spec){ m_activeSpec = spec; }
+ uint8 GetSpecsCount() { return m_specsCount; }
+ void SetSpecsCount(uint8 count) { m_specsCount = count; }
+ void ActivateSpec(uint8 spec);
+
+ void InitGlyphsForLevel();
+ void SetGlyphSlot(uint8 slot, uint32 slottype) { SetUInt32Value(PLAYER_FIELD_GLYPH_SLOTS_1 + slot, slottype); }
+ uint32 GetGlyphSlot(uint8 slot) { return GetUInt32Value(PLAYER_FIELD_GLYPH_SLOTS_1 + slot); }
+ void SetGlyph(uint8 slot, uint32 glyph)
+ {
+ m_Glyphs[m_activeSpec][slot] = glyph;
+ SetUInt32Value(PLAYER_FIELD_GLYPHS_1 + slot, glyph);
+ }
+ uint32 GetGlyph(uint8 slot) { return m_Glyphs[m_activeSpec][slot]; }
+
+ uint32 GetFreePrimaryProfessionPoints() const { return GetUInt32Value(PLAYER_CHARACTER_POINTS2); }
+ void SetFreePrimaryProfessions(uint16 profs) { SetUInt32Value(PLAYER_CHARACTER_POINTS2, profs); }
+ void InitPrimaryProfessions();
+
+ PlayerSpellMap const& GetSpellMap() const { return m_spells; }
+ PlayerSpellMap & GetSpellMap() { return m_spells; }
+
+ SpellCooldowns const& GetSpellCooldownMap() const { return m_spellCooldowns; }
+
+ void AddSpellMod(SpellModifier* mod, bool apply);
+ bool IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell * spell = NULL);
+ template <class T> T ApplySpellMod(uint32 spellId, SpellModOp op, T &basevalue, Spell * spell = NULL);
+ void RemoveSpellMods(Spell * spell);
+ void RestoreSpellMods(Spell * spell);
+ void DropModCharge(SpellModifier * mod, Spell * spell);
+ void SetSpellModTakingSpell(Spell* spell, bool apply);
+
+ static uint32 const infinityCooldownDelay = MONTH; // used for set "infinity cooldowns" for spells and check
+ static uint32 const infinityCooldownDelayCheck = MONTH/2;
+ bool HasSpellCooldown(uint32 spell_id) const
+ {
+ SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id);
+ return itr != m_spellCooldowns.end() && itr->second.end > time(NULL);
+ }
+ uint32 GetSpellCooldownDelay(uint32 spell_id) const
+ {
+ SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id);
+ time_t t = time(NULL);
+ return itr != m_spellCooldowns.end() && itr->second.end > t ? itr->second.end - t : 0;
+ }
+ void AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell = NULL, bool infinityCooldown = false );
+ void AddSpellCooldown(uint32 spell_id, uint32 itemid, time_t end_time);
+ void SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId = 0, Spell* spell = NULL);
+ void ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs );
+ void RemoveSpellCooldown(uint32 spell_id, bool update = false);
+ void RemoveSpellCategoryCooldown(uint32 cat, bool update = false);
+ void SendClearCooldown( uint32 spell_id, Unit* target );
+
+ void RemoveCategoryCooldown(uint32 cat);
+ void RemoveArenaSpellCooldowns();
+ void RemoveAllSpellCooldown();
+ void _LoadSpellCooldowns(QueryResult_AutoPtr result);
+ void _SaveSpellCooldowns();
+ void SetLastPotionId(uint32 item_id) { m_lastPotionId = item_id; }
+ void UpdatePotionCooldown(Spell* spell = NULL);
+
+ void setResurrectRequestData(uint64 guid, uint32 mapId, float X, float Y, float Z, uint32 health, uint32 mana)
+ {
+ m_resurrectGUID = guid;
+ m_resurrectMap = mapId;
+ m_resurrectX = X;
+ m_resurrectY = Y;
+ m_resurrectZ = Z;
+ m_resurrectHealth = health;
+ m_resurrectMana = mana;
+ }
+ void clearResurrectRequestData() { setResurrectRequestData(0,0,0.0f,0.0f,0.0f,0,0); }
+ bool isRessurectRequestedBy(uint64 guid) const { return m_resurrectGUID == guid; }
+ bool isRessurectRequested() const { return m_resurrectGUID != 0; }
+ void ResurectUsingRequestData();
+
+ int getCinematic()
+ {
+ return m_cinematic;
+ }
+ void setCinematic(int cine)
+ {
+ m_cinematic = cine;
+ }
+
+ ActionButton* addActionButton(uint8 button, uint32 action, uint8 type);
+ void removeActionButton(uint8 button);
+ void SendInitialActionButtons() const { SendActionButtons(0); }
+ void SendActionButtons(uint32 state) const;
+
+ PvPInfo pvpInfo;
+ void UpdatePvPState(bool onlyFFA = false);
+ void SetPvP(bool state)
+ {
+ Unit::SetPvP(state);
+ for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
+ (*itr)->SetPvP(state);
+ }
+ void UpdatePvP(bool state, bool override=false);
+ void UpdateZone(uint32 newZone,uint32 newArea);
+ void UpdateArea(uint32 newArea);
+
+ void UpdateZoneDependentAuras( uint32 zone_id ); // zones
+ void UpdateAreaDependentAuras( uint32 area_id ); // subzones
+
+ void UpdateAfkReport(time_t currTime);
+ void UpdatePvPFlag(time_t currTime);
+ void UpdateContestedPvP(uint32 currTime);
+ void SetContestedPvPTimer(uint32 newTime) {m_contestedPvPTimer = newTime;}
+ void ResetContestedPvP()
+ {
+ clearUnitState(UNIT_STAT_ATTACK_PLAYER);
+ RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
+ m_contestedPvPTimer = 0;
+ }
+
+ /** todo: -maybe move UpdateDuelFlag+DuelComplete to independent DuelHandler.. **/
+ DuelInfo *duel;
+ void UpdateDuelFlag(time_t currTime);
+ void CheckDuelDistance(time_t currTime);
+ void DuelComplete(DuelCompleteType type);
+ void SendDuelCountdown(uint32 counter);
+
+ bool IsGroupVisibleFor(Player* p) const;
+ bool IsInSameGroupWith(Player const* p) const;
+ bool IsInSameRaidWith(Player const* p) const { return p==this || (GetGroup() != NULL && GetGroup() == p->GetGroup()); }
+ void UninviteFromGroup();
+ static void RemoveFromGroup(Group* group, uint64 guid);
+ void RemoveFromGroup() { RemoveFromGroup(GetGroup(),GetGUID()); }
+ void SendUpdateToOutOfRangeGroupMembers();
+
+ void SetInGuild(uint32 GuildId) { SetUInt32Value(PLAYER_GUILDID, GuildId); }
+ void SetRank(uint32 rankId){ SetUInt32Value(PLAYER_GUILDRANK, rankId); }
+ void SetGuildIdInvited(uint32 GuildId) { m_GuildIdInvited = GuildId; }
+ uint32 GetGuildId() { return GetUInt32Value(PLAYER_GUILDID); }
+ static uint32 GetGuildIdFromDB(uint64 guid);
+ uint32 GetRank(){ return GetUInt32Value(PLAYER_GUILDRANK); }
+ static uint32 GetRankFromDB(uint64 guid);
+ int GetGuildIdInvited() { return m_GuildIdInvited; }
+ static void RemovePetitionsAndSigns(uint64 guid, uint32 type);
+
+ // Arena Team
+ void SetInArenaTeam(uint32 ArenaTeamId, uint8 slot, uint8 type)
+ {
+ SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END) + ARENA_TEAM_ID, ArenaTeamId);
+ SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END) + ARENA_TEAM_TYPE, type);
+ }
+ uint32 GetArenaTeamId(uint8 slot) { return GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END)); }
+ static uint32 GetArenaTeamIdFromDB(uint64 guid, uint8 slot);
+ void SetArenaTeamIdInvited(uint32 ArenaTeamId) { m_ArenaTeamIdInvited = ArenaTeamId; }
+ uint32 GetArenaTeamIdInvited() { return m_ArenaTeamIdInvited; }
+ static void LeaveAllArenaTeams(uint64 guid);
+
+ Difficulty GetDifficulty(bool isRaid) const { return isRaid ? m_raidDifficulty : m_dungeonDifficulty; }
+ Difficulty GetDungeonDifficulty() const { return m_dungeonDifficulty; }
+ Difficulty GetRaidDifficulty() const { return m_raidDifficulty; }
+ void SetDungeonDifficulty(Difficulty dungeon_difficulty) { m_dungeonDifficulty = dungeon_difficulty; }
+ void SetRaidDifficulty(Difficulty raid_difficulty) { m_raidDifficulty = raid_difficulty; }
+
+ bool UpdateSkill(uint32 skill_id, uint32 step);
+ bool UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step);
+
+ bool UpdateCraftSkill(uint32 spellid);
+ bool UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator = 1);
+ bool UpdateFishingSkill();
+
+ uint32 GetBaseDefenseSkillValue() const { return GetBaseSkillValue(SKILL_DEFENSE); }
+ uint32 GetBaseWeaponSkillValue(WeaponAttackType attType) const;
+
+ uint32 GetSpellByProto(ItemPrototype *proto);
+
+ float GetHealthBonusFromStamina();
+ float GetManaBonusFromIntellect();
+
+ bool UpdateStats(Stats stat);
+ bool UpdateAllStats();
+ void UpdateResistances(uint32 school);
+ void UpdateArmor();
+ void UpdateMaxHealth();
+ void UpdateMaxPower(Powers power);
+ void ApplyFeralAPBonus(int32 amount, bool apply);
+ void UpdateAttackPowerAndDamage(bool ranged = false);
+ void UpdateShieldBlockValue();
+ void UpdateDamagePhysical(WeaponAttackType attType);
+ void ApplySpellPowerBonus(int32 amount, bool apply);
+ void UpdateSpellDamageAndHealingBonus();
+ void ApplyRatingMod(CombatRating cr, int32 value, bool apply);
+ void UpdateRating(CombatRating cr);
+ void UpdateAllRatings();
+
+ void CalculateMinMaxDamage(WeaponAttackType attType, bool normalized, bool addTotalPct, float& min_damage, float& max_damage);
+
+ void UpdateDefenseBonusesMod();
+ inline void RecalculateRating(CombatRating cr) { ApplyRatingMod(cr, 0, true);}
+ float GetMeleeCritFromAgility();
+ float GetDodgeFromAgility();
+ float GetSpellCritFromIntellect();
+ float OCTRegenHPPerSpirit();
+ float OCTRegenMPPerSpirit();
+ float GetRatingCoefficient(CombatRating cr) const;
+ float GetRatingBonusValue(CombatRating cr) const;
+ uint32 GetBaseSpellPowerBonus() { return m_baseSpellPower; }
+
+ float GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const;
+ void UpdateBlockPercentage();
+ void UpdateCritPercentage(WeaponAttackType attType);
+ void UpdateAllCritPercentages();
+ void UpdateParryPercentage();
+ void UpdateDodgePercentage();
+ void UpdateMeleeHitChances();
+ void UpdateRangedHitChances();
+ void UpdateSpellHitChances();
+
+ void UpdateAllSpellCritChances();
+ void UpdateSpellCritChance(uint32 school);
+ void UpdateArmorPenetration(int32 amount);
+ void UpdateExpertise(WeaponAttackType attType);
+ void ApplyManaRegenBonus(int32 amount, bool apply);
+ void ApplyHealthRegenBonus(int32 amount, bool apply);
+ void UpdateManaRegen();
+
+ const uint64& GetLootGUID() const { return m_lootGuid; }
+ void SetLootGUID(const uint64 &guid) { m_lootGuid = guid; }
+
+ void RemovedInsignia(Player* looterPlr);
+
+ WorldSession* GetSession() const { return m_session; }
+ void SetSession(WorldSession *s) { m_session = s; }
+
+ void BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const;
+ void DestroyForPlayer( Player *target, bool anim = false ) const;
+ void SendLogXPGain(uint32 GivenXP,Unit* victim,uint32 RestXP);
+
+ // notifiers
+ void SendAttackSwingCantAttack();
+ void SendAttackSwingCancelAttack();
+ void SendAttackSwingDeadTarget();
+ void SendAttackSwingNotInRange();
+ void SendAttackSwingBadFacingAttack();
+ void SendAutoRepeatCancel(Unit *target);
+ void SendExplorationExperience(uint32 Area, uint32 Experience);
+
+ void SendDungeonDifficulty(bool IsInGroup);
+ void SendRaidDifficulty(bool IsInGroup);
+ void ResetInstances(uint8 method, bool isRaid);
+ void SendResetInstanceSuccess(uint32 MapId);
+ void SendResetInstanceFailed(uint32 reason, uint32 MapId);
+ void SendResetFailedNotify(uint32 mapid);
+
+ virtual bool SetPosition(float x, float y, float z, float orientation, bool teleport = false);
+ bool SetPosition(const Position &pos, bool teleport = false) { return SetPosition(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), teleport); }
+ void UpdateUnderwaterState( Map * m, float x, float y, float z );
+
+ void SendMessageToSet(WorldPacket *data, bool self);// overwrite Object::SendMessageToSet
+ void SendMessageToSetInRange(WorldPacket *data, float fist, bool self);// overwrite Object::SendMessageToSetInRange
+ void SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only);
+
+ void SendTeleportAckMsg();
+
+ static void DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars = true);
+
+ Corpse *GetCorpse() const;
+ void SpawnCorpseBones();
+ void CreateCorpse();
+ bool FallGround(uint8 FallMode = 0);
+ void KillPlayer();
+ uint32 GetResurrectionSpellId();
+ void ResurrectPlayer(float restore_percent, bool applySickness = false);
+ void BuildPlayerRepop();
+ void RepopAtGraveyard();
+
+ void DurabilityLossAll(double percent, bool inventory);
+ void DurabilityLoss(Item* item, double percent);
+ void DurabilityPointsLossAll(int32 points, bool inventory);
+ void DurabilityPointsLoss(Item* item, int32 points);
+ void DurabilityPointLossForEquipSlot(EquipmentSlots slot);
+ uint32 DurabilityRepairAll(bool cost, float discountMod, bool guildBank);
+ uint32 DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank);
+
+ void UpdateMirrorTimers();
+ void StopMirrorTimers()
+ {
+ StopMirrorTimer(FATIGUE_TIMER);
+ StopMirrorTimer(BREATH_TIMER);
+ StopMirrorTimer(FIRE_TIMER);
+ }
+
+ void SetMovement(PlayerMovementType pType);
+
+ void JoinedChannel(Channel *c);
+ void LeftChannel(Channel *c);
+ void CleanupChannels();
+ void UpdateLocalChannels( uint32 newZone );
+ void LeaveLFGChannel();
+
+ void UpdateDefense();
+ void UpdateWeaponSkill (WeaponAttackType attType);
+ void UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence);
+
+ void SetSkill(uint32 id, uint16 currVal, uint16 maxVal);
+ uint16 GetMaxSkillValue(uint32 skill) const; // max + perm. bonus + temp bonus
+ uint16 GetPureMaxSkillValue(uint32 skill) const; // max
+ uint16 GetSkillValue(uint32 skill) const; // skill value + perm. bonus + temp bonus
+ uint16 GetBaseSkillValue(uint32 skill) const; // skill value + perm. bonus
+ uint16 GetPureSkillValue(uint32 skill) const; // skill value
+ int16 GetSkillPermBonusValue(uint32 skill) const;
+ int16 GetSkillTempBonusValue(uint32 skill) const;
+ bool HasSkill(uint32 skill) const;
+ void learnSkillRewardedSpells(uint32 id, uint32 value);
+
+ WorldLocation& GetTeleportDest() { return m_teleport_dest; }
+ bool IsBeingTeleported() const { return mSemaphoreTeleport_Near || mSemaphoreTeleport_Far; }
+ bool IsBeingTeleportedNear() const { return mSemaphoreTeleport_Near; }
+ bool IsBeingTeleportedFar() const { return mSemaphoreTeleport_Far; }
+ void SetSemaphoreTeleportNear(bool semphsetting) { mSemaphoreTeleport_Near = semphsetting; }
+ void SetSemaphoreTeleportFar(bool semphsetting) { mSemaphoreTeleport_Far = semphsetting; }
+ void ProcessDelayedOperations();
+
+ void CheckExploreSystem(void);
+
+ static uint32 TeamForRace(uint8 race);
+ uint32 GetTeam() const { return m_team; }
+ TeamId GetTeamId() const { return m_team == ALLIANCE ? TEAM_ALLIANCE : TEAM_HORDE; }
+ static uint32 getFactionForRace(uint8 race);
+ void setFactionForRace(uint8 race);
+
+ void InitDisplayIds();
+
+ bool IsAtGroupRewardDistance(WorldObject const* pRewardSource) const;
+ bool RewardPlayerAndGroupAtKill(Unit* pVictim);
+ void RewardPlayerAndGroupAtEvent(uint32 creature_id,WorldObject* pRewardSource);
+ bool isHonorOrXPTarget(Unit* pVictim);
+
+ ReputationMgr& GetReputationMgr() { return m_reputationMgr; }
+ ReputationMgr const& GetReputationMgr() const { return m_reputationMgr; }
+ ReputationRank GetReputationRank(uint32 faction_id) const;
+ void RewardReputation(Unit *pVictim, float rate);
+ void RewardReputation(Quest const *pQuest);
+
+ void UpdateSkillsForLevel();
+ void UpdateSkillsToMaxSkillsForLevel(); // for .levelup
+ void ModifySkillBonus(uint32 skillid,int32 val, bool talent);
+
+ /*********************************************************/
+ /*** PVP SYSTEM ***/
+ /*********************************************************/
+ void UpdateHonorFields();
+ bool RewardHonor(Unit *pVictim, uint32 groupsize, float honor = -1, bool pvptoken = false);
+ uint32 GetHonorPoints() { return GetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY); }
+ uint32 GetArenaPoints() { return GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY); }
+ void ModifyHonorPoints( int32 value );
+ void ModifyArenaPoints( int32 value );
+ uint32 GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot);
+
+ //End of PvP System
+
+ inline SpellCooldowns GetSpellCooldowns() const { return m_spellCooldowns; }
+
+ void SetDrunkValue(uint16 newDrunkValue, uint32 itemid=0);
+ uint16 GetDrunkValue() const { return m_drunk; }
+ static DrunkenState GetDrunkenstateByValue(uint16 value);
+
+ uint32 GetDeathTimer() const { return m_deathTimer; }
+ uint32 GetCorpseReclaimDelay(bool pvp) const;
+ void UpdateCorpseReclaimDelay();
+ void SendCorpseReclaimDelay(bool load = false);
+
+ uint32 GetShieldBlockValue() const; // overwrite Unit version (virtual)
+ bool CanParry() const { return m_canParry; }
+ void SetCanParry(bool value);
+ bool CanBlock() const { return m_canBlock; }
+ void SetCanBlock(bool value);
+ bool CanTitanGrip() const { return m_canTitanGrip; }
+ void SetCanTitanGrip(bool value) { m_canTitanGrip = value; }
+ bool CanTameExoticPets() const { return isGameMaster() || HasAuraType(SPELL_AURA_ALLOW_TAME_PET_TYPE); }
+
+ void SetRegularAttackTime();
+ void SetBaseModValue(BaseModGroup modGroup, BaseModType modType, float value) { m_auraBaseMod[modGroup][modType] = value; }
+ void HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply);
+ float GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const;
+ float GetTotalBaseModValue(BaseModGroup modGroup) const;
+ float GetTotalPercentageModValue(BaseModGroup modGroup) const { return m_auraBaseMod[modGroup][FLAT_MOD] + m_auraBaseMod[modGroup][PCT_MOD]; }
+ void _ApplyAllStatBonuses();
+ void _RemoveAllStatBonuses();
+
+ void _ApplyWeaponDependentAuraMods(Item *item, WeaponAttackType attackType, bool apply);
+ void _ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, AuraEffect const * aura, bool apply);
+ void _ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, AuraEffect const * aura, bool apply);
+
+ void _ApplyItemMods(Item *item,uint8 slot,bool apply);
+ void _RemoveAllItemMods();
+ void _ApplyAllItemMods();
+ void _ApplyAllLevelScaleItemMods(bool apply);
+ void _ApplyItemBonuses(ItemPrototype const *proto,uint8 slot,bool apply, bool only_level_scale = false);
+ void _ApplyAmmoBonuses();
+ bool EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot);
+ void ToggleMetaGemsActive(uint8 exceptslot, bool apply);
+ void CorrectMetaGemEnchants(uint8 slot, bool apply);
+ void InitDataForForm(bool reapplyMods = false);
+
+ void ApplyItemEquipSpell(Item *item, bool apply, bool form_change = false);
+ void ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change = false);
+ void UpdateEquipSpellsAtFormChange();
+ void CastItemCombatSpell(Unit *target, WeaponAttackType attType, uint32 procVictim, uint32 procEx);
+ void CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex);
+ void CastItemCombatSpell(Unit *target, WeaponAttackType attType, uint32 procVictim, uint32 procEx, Item *item, ItemPrototype const * proto);
+
+ void SendEquipmentSetList();
+ void SetEquipmentSet(uint32 index, EquipmentSet eqset);
+ void DeleteEquipmentSet(uint64 setGuid);
+
+ void SendInitWorldStates(uint32 zone, uint32 area);
+ void SendUpdateWorldState(uint32 Field, uint32 Value);
+ void SendDirectMessage(WorldPacket *data);
+
+ void SendAurasForTarget(Unit *target);
+
+ PlayerMenu* PlayerTalkClass;
+ std::vector<ItemSetEffect *> ItemSetEff;
+
+ void SendLoot(uint64 guid, LootType loot_type);
+ void SendLootRelease( uint64 guid );
+ void SendNotifyLootItemRemoved(uint8 lootSlot);
+ void SendNotifyLootMoneyRemoved();
+
+ /*********************************************************/
+ /*** BATTLEGROUND SYSTEM ***/
+ /*********************************************************/
+
+ bool InBattleGround() const { return m_bgData.bgInstanceID != 0; }
+ bool InArena() const;
+ uint32 GetBattleGroundId() const { return m_bgData.bgInstanceID; }
+ BattleGroundTypeId GetBattleGroundTypeId() const { return m_bgData.bgTypeID; }
+ BattleGround* GetBattleGround() const;
+
+ bool InBattleGroundQueue() const
+ {
+ for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
+ if (m_bgBattleGroundQueueID[i].bgQueueTypeId != BATTLEGROUND_QUEUE_NONE)
+ return true;
+ return false;
+ }
+
+ BattleGroundQueueTypeId GetBattleGroundQueueTypeId(uint32 index) const { return m_bgBattleGroundQueueID[index].bgQueueTypeId; }
+ uint32 GetBattleGroundQueueIndex(BattleGroundQueueTypeId bgQueueTypeId) const
+ {
+ for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
+ if (m_bgBattleGroundQueueID[i].bgQueueTypeId == bgQueueTypeId)
+ return i;
+ return PLAYER_MAX_BATTLEGROUND_QUEUES;
+ }
+ bool IsInvitedForBattleGroundQueueType(BattleGroundQueueTypeId bgQueueTypeId) const
+ {
+ for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
+ if (m_bgBattleGroundQueueID[i].bgQueueTypeId == bgQueueTypeId)
+ return m_bgBattleGroundQueueID[i].invitedToInstance != 0;
+ return false;
+ }
+ bool InBattleGroundQueueForBattleGroundQueueType(BattleGroundQueueTypeId bgQueueTypeId) const
+ {
+ return GetBattleGroundQueueIndex(bgQueueTypeId) < PLAYER_MAX_BATTLEGROUND_QUEUES;
+ }
+
+ void SetBattleGroundId(uint32 val, BattleGroundTypeId bgTypeId)
+ {
+ m_bgData.bgInstanceID = val;
+ m_bgData.bgTypeID = bgTypeId;
+ }
+ uint32 AddBattleGroundQueueId(BattleGroundQueueTypeId val)
+ {
+ for (uint8 i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
+ {
+ if (m_bgBattleGroundQueueID[i].bgQueueTypeId == BATTLEGROUND_QUEUE_NONE || m_bgBattleGroundQueueID[i].bgQueueTypeId == val)
+ {
+ m_bgBattleGroundQueueID[i].bgQueueTypeId = val;
+ m_bgBattleGroundQueueID[i].invitedToInstance = 0;
+ return i;
+ }
+ }
+ return PLAYER_MAX_BATTLEGROUND_QUEUES;
+ }
+ bool HasFreeBattleGroundQueueId()
+ {
+ for (uint8 i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
+ if (m_bgBattleGroundQueueID[i].bgQueueTypeId == BATTLEGROUND_QUEUE_NONE)
+ return true;
+ return false;
+ }
+ void RemoveBattleGroundQueueId(BattleGroundQueueTypeId val)
+ {
+ for (uint8 i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
+ {
+ if (m_bgBattleGroundQueueID[i].bgQueueTypeId == val)
+ {
+ m_bgBattleGroundQueueID[i].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
+ m_bgBattleGroundQueueID[i].invitedToInstance = 0;
+ return;
+ }
+ }
+ }
+ void SetInviteForBattleGroundQueueType(BattleGroundQueueTypeId bgQueueTypeId, uint32 instanceId)
+ {
+ for (uint8 i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
+ if (m_bgBattleGroundQueueID[i].bgQueueTypeId == bgQueueTypeId)
+ m_bgBattleGroundQueueID[i].invitedToInstance = instanceId;
+ }
+ bool IsInvitedForBattleGroundInstance(uint32 instanceId) const
+ {
+ for (uint8 i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
+ if (m_bgBattleGroundQueueID[i].invitedToInstance == instanceId)
+ return true;
+ return false;
+ }
+ WorldLocation const& GetBattleGroundEntryPoint() const { return m_bgData.joinPos; }
+ void SetBattleGroundEntryPoint();
+
+ void SetBGTeam(uint32 team) { m_bgData.bgTeam = team; }
+ uint32 GetBGTeam() const { return m_bgData.bgTeam ? m_bgData.bgTeam : GetTeam(); }
+
+ void LeaveBattleground(bool teleportToEntryPoint = true);
+ bool CanJoinToBattleground() const;
+ bool CanReportAfkDueToLimit();
+ void ReportedAfkBy(Player* reporter);
+ void ClearAfkReports() { m_bgData.bgAfkReporter.clear(); }
+
+ bool GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const;
+ bool isTotalImmunity();
+ bool CanUseBattleGroundObject();
+ bool isTotalImmune();
+ bool CanCaptureTowerPoint();
+
+ /*********************************************************/
+ /*** OUTDOOR PVP SYSTEM ***/
+ /*********************************************************/
+
+ OutdoorPvP * GetOutdoorPvP() const;
+ // returns true if the player is in active state for outdoor pvp objective capturing, false otherwise
+ bool IsOutdoorPvPActive();
+
+ /*********************************************************/
+ /*** REST SYSTEM ***/
+ /*********************************************************/
+
+ bool isRested() const { return GetRestTime() >= 10*IN_MILISECONDS; }
+ uint32 GetXPRestBonus(uint32 xp);
+ uint32 GetRestTime() const { return m_restTime;}
+ void SetRestTime(uint32 v) { m_restTime = v;}
+
+ /*********************************************************/
+ /*** ENVIROMENTAL SYSTEM ***/
+ /*********************************************************/
+
+ uint32 EnvironmentalDamage(EnviromentalDamage type, uint32 damage);
+
+ /*********************************************************/
+ /*** FLOOD FILTER SYSTEM ***/
+ /*********************************************************/
+
+ void UpdateSpeakTime();
+ bool CanSpeak() const;
+ void ChangeSpeakTime(int utime);
+
+ /*********************************************************/
+ /*** VARIOUS SYSTEMS ***/
+ /*********************************************************/
+ void UpdateFallInformationIfNeed(MovementInfo const& minfo,uint16 opcode);
+ Unit *m_mover;
+ WorldObject *m_seer;
+ void SetFallInformation(uint32 time, float z)
+ {
+ m_lastFallTime = time;
+ m_lastFallZ = z;
+ }
+ void HandleFall(MovementInfo const& movementInfo);
+
+ bool IsKnowHowFlyIn(uint32 mapid, uint32 zone) const;
+
+ void SetClientControl(Unit* target, uint8 allowMove);
+
+ void SetMover(Unit* target)
+ {
+ m_mover->m_movedPlayer = NULL;
+ m_mover = target;
+ m_mover->m_movedPlayer = this;
+ }
+ void SetSeer(WorldObject *target) { m_seer = target; }
+ void SetViewpoint(WorldObject *target, bool apply);
+ WorldObject* GetViewpoint() const;
+ void StopCastingCharm();
+ void StopCastingBindSight();
+
+ uint32 GetSaveTimer() const { return m_nextSave; }
+ void SetSaveTimer(uint32 timer) { m_nextSave = timer; }
+
+ // Recall position
+ uint32 m_recallMap;
+ float m_recallX;
+ float m_recallY;
+ float m_recallZ;
+ float m_recallO;
+ void SaveRecallPosition();
+
+ // Homebind coordinates
+ uint32 m_homebindMapId;
+ uint16 m_homebindZoneId;
+ float m_homebindX;
+ float m_homebindY;
+ float m_homebindZ;
+
+ WorldLocation GetStartPosition() const;
+
+ // currently visible objects at player client
+ typedef std::set<uint64> ClientGUIDs;
+ ClientGUIDs m_clientGUIDs;
+
+ bool HaveAtClient(WorldObject const* u) const { return u==this || m_clientGUIDs.find(u->GetGUID())!=m_clientGUIDs.end(); }
+
+ bool canSeeOrDetect(Unit const* u, bool detect, bool inVisibleList = false, bool is3dDistance = true) const;
+ bool IsVisibleInGridForPlayer(Player const* pl) const;
+ bool IsVisibleGloballyFor(Player* pl) const;
+
+ void UpdateVisibilityOf(WorldObject* target);
+ void SendInitialVisiblePackets(Unit* target);
+
+ template<class T>
+ void UpdateVisibilityOf(T* target, UpdateData& data, std::set<Unit*>& visibleNow);
+
+ // Stealth detection system
+ void HandleStealthedUnitsDetection();
+
+ uint8 m_forced_speed_changes[MAX_MOVE_TYPE];
+
+ bool HasAtLoginFlag(AtLoginFlags f) const { return m_atLoginFlags & f; }
+ void SetAtLoginFlag(AtLoginFlags f) { m_atLoginFlags |= f; }
+ void RemoveAtLoginFlag(AtLoginFlags f, bool in_db_also = false);
+
+ LookingForGroup m_lookingForGroup;
+
+ // Temporarily removed pet cache
+ uint32 GetTemporaryUnsummonedPetNumber() const { return m_temporaryUnsummonedPetNumber; }
+ void SetTemporaryUnsummonedPetNumber(uint32 petnumber) { m_temporaryUnsummonedPetNumber = petnumber; }
+ void UnsummonPetTemporaryIfAny();
+ void ResummonPetTemporaryUnSummonedIfAny();
+ bool IsPetNeedBeTemporaryUnsummoned() const { return !IsInWorld() || !isAlive() || IsMounted() /*+in flight*/; }
+
+ void SendCinematicStart(uint32 CinematicSequenceId);
+ void SendMovieStart(uint32 MovieId);
+
+ /*********************************************************/
+ /*** INSTANCE SYSTEM ***/
+ /*********************************************************/
+
+ typedef UNORDERED_MAP< uint32 /*mapId*/, InstancePlayerBind > BoundInstancesMap;
+
+ void UpdateHomebindTime(uint32 time);
+
+ uint32 m_HomebindTimer;
+ bool m_InstanceValid;
+ // permanent binds and solo binds by difficulty
+ BoundInstancesMap m_boundInstances[MAX_DIFFICULTY];
+ InstancePlayerBind* GetBoundInstance(uint32 mapid, Difficulty difficulty);
+ BoundInstancesMap& GetBoundInstances(Difficulty difficulty) { return m_boundInstances[difficulty]; }
+ InstanceSave * GetInstanceSave(uint32 mapid, bool raid);
+ void UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload = false);
+ void UnbindInstance(BoundInstancesMap::iterator &itr, Difficulty difficulty, bool unload = false);
+ InstancePlayerBind* BindToInstance(InstanceSave *save, bool permanent, bool load = false);
+ void SendRaidInfo();
+ void SendSavedInstances();
+ static void ConvertInstancesToGroup(Player *player, Group *group = NULL, uint64 player_guid = 0);
+ bool Satisfy(AccessRequirement const*, uint32 target_map, bool report = false);
+
+ // last used pet number (for BG's)
+ uint32 GetLastPetNumber() const { return m_lastpetnumber; }
+ void SetLastPetNumber(uint32 petnumber) { m_lastpetnumber = petnumber; }
+
+ /*********************************************************/
+ /*** GROUP SYSTEM ***/
+ /*********************************************************/
+
+ Group * GetGroupInvite() { return m_groupInvite; }
+ void SetGroupInvite(Group *group) { m_groupInvite = group; }
+ Group * GetGroup() { return m_group.getTarget(); }
+ const Group * GetGroup() const { return (const Group*)m_group.getTarget(); }
+ GroupReference& GetGroupRef() { return m_group; }
+ void SetGroup(Group *group, int8 subgroup = -1);
+ uint8 GetSubGroup() const { return m_group.getSubGroup(); }
+ uint32 GetGroupUpdateFlag() const { return m_groupUpdateMask; }
+ void SetGroupUpdateFlag(uint32 flag) { m_groupUpdateMask |= flag; }
+ const uint64& GetAuraUpdateMaskForRaid() const { return m_auraRaidUpdateMask; }
+ void SetAuraUpdateMaskForRaid(uint8 slot) { m_auraRaidUpdateMask |= (uint64(1) << slot); }
+ Player* GetNextRandomRaidMember(float radius);
+ PartyResult CanUninviteFromGroup() const;
+ // BattleGround Group System
+ void SetBattleGroundRaid(Group *group, int8 subgroup = -1);
+ void RemoveFromBattleGroundRaid();
+ Group * GetOriginalGroup() { return m_originalGroup.getTarget(); }
+ GroupReference& GetOriginalGroupRef() { return m_originalGroup; }
+ uint8 GetOriginalSubGroup() const { return m_originalGroup.getSubGroup(); }
+ void SetOriginalGroup(Group *group, int8 subgroup = -1);
+
+ MapReference &GetMapRef() { return m_mapRef; }
+
+ // Set map to player and add reference
+ void SetMap(Map * map);
+ void ResetMap();
+
+ bool isAllowedToLoot(Creature* creature);
+
+ DeclinedName const* GetDeclinedNames() const { return m_declinedname; }
+ uint8 GetRunesState() const { return m_runes->runeState; }
+ RuneType GetBaseRune(uint8 index) const { return RuneType(m_runes->runes[index].BaseRune); }
+ RuneType GetCurrentRune(uint8 index) const { return RuneType(m_runes->runes[index].CurrentRune); }
+ uint32 GetRuneCooldown(uint8 index) const { return m_runes->runes[index].Cooldown; }
+ uint32 GetRuneBaseCooldown(uint8 index);
+ bool IsBaseRuneSlotsOnCooldown(RuneType runeType) const;
+ RuneType GetLastUsedRune() { return m_runes->lastUsedRune; }
+ void SetLastUsedRune(RuneType type) { m_runes->lastUsedRune = type; }
+ void SetBaseRune(uint8 index, RuneType baseRune) { m_runes->runes[index].BaseRune = baseRune; }
+ void SetCurrentRune(uint8 index, RuneType currentRune) { m_runes->runes[index].CurrentRune = currentRune; }
+ void SetRuneCooldown(uint8 index, uint32 cooldown) { m_runes->runes[index].Cooldown = cooldown; m_runes->SetRuneState(index, (cooldown == 0) ? true : false); }
+ void SetRuneConvertAura(uint8 index, AuraEffect const * aura) { m_runes->runes[index].ConvertAura = aura; }
+ void AddRuneByAuraEffect(uint8 index, RuneType newType, AuraEffect const * aura) { SetRuneConvertAura(index, aura); ConvertRune(index, newType); }
+ void RemoveRunesByAuraEffect(AuraEffect const * aura);
+ void RestoreBaseRune(uint8 index);
+ void ConvertRune(uint8 index, RuneType newType);
+ void ResyncRunes(uint8 count);
+ void AddRunePower(uint8 index);
+ void InitRunes();
+
+ AchievementMgr& GetAchievementMgr() { return m_achievementMgr; }
+ void UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscvalue1 = 0, uint32 miscvalue2 = 0, Unit *unit = NULL, uint32 time = 0);
+ void CompletedAchievement(AchievementEntry const* entry);
+
+ bool HasTitle(uint32 bitIndex);
+ bool HasTitle(CharTitlesEntry const* title) { return HasTitle(title->bit_index); }
+ void SetTitle(CharTitlesEntry const* title, bool lost = false);
+
+ //bool isActiveObject() const { return true; }
+ bool canSeeSpellClickOn(Creature const* creature) const;
+ uint32 GetActionButtonSpell(uint8 button) const
+ {
+ ActionButtonList::const_iterator ab = m_actionButtons.find(button);
+ return ab != m_actionButtons.end() && ab->second.uState != ACTIONBUTTON_DELETED && ab->second.GetType() == ACTION_BUTTON_SPELL ? ab->second.GetAction() : 0;
+ }
+
+ uint32 GetChampioningFaction() const { return m_ChampioningFaction; }
+ void SetChampioningFaction(uint32 faction) { m_ChampioningFaction = faction; }
+Spell * m_spellModTakingSpell;
+ protected:
+ uint32 m_AreaID;
+ uint32 m_regenTimerCount;
+ float m_powerFraction[MAX_POWERS];
+ uint32 m_contestedPvPTimer;
+
+ /*********************************************************/
+ /*** BATTLEGROUND SYSTEM ***/
+ /*********************************************************/
+
+ /*
+ this is an array of BG queues (BgTypeIDs) in which is player
+ */
+ struct BgBattleGroundQueueID_Rec
+ {
+ BattleGroundQueueTypeId bgQueueTypeId;
+ uint32 invitedToInstance;
+ };
+
+ BgBattleGroundQueueID_Rec m_bgBattleGroundQueueID[PLAYER_MAX_BATTLEGROUND_QUEUES];
+ BGData m_bgData;
+
+ /*********************************************************/
+ /*** QUEST SYSTEM ***/
+ /*********************************************************/
+
+ //We allow only one timed quest active at the same time. Below can then be simple value instead of set.
+ std::set<uint32> m_timedquests;
+
+ uint64 m_divider;
+ uint32 m_ingametime;
+
+ /*********************************************************/
+ /*** LOAD SYSTEM ***/
+ /*********************************************************/
+
+ void _LoadActions(QueryResult_AutoPtr result, bool startup);
+ void _LoadAuras(QueryResult_AutoPtr result, uint32 timediff);
+ void _LoadGlyphAuras();
+ void _LoadBoundInstances(QueryResult_AutoPtr result);
+ void _LoadInventory(QueryResult_AutoPtr result, uint32 timediff);
+ void _LoadMailInit(QueryResult_AutoPtr resultUnread, QueryResult_AutoPtr resultDelivery);
+ void _LoadMail();
+ void _LoadMailedItems(Mail *mail);
+ void _LoadQuestStatus(QueryResult_AutoPtr result);
+ void _LoadDailyQuestStatus(QueryResult_AutoPtr result);
+ void _LoadGroup(QueryResult_AutoPtr result);
+ void _LoadSkills(QueryResult_AutoPtr result);
+ void _LoadSpells(QueryResult_AutoPtr result);
+ void _LoadFriendList(QueryResult_AutoPtr result);
+ bool _LoadHomeBind(QueryResult_AutoPtr result);
+ void _LoadDeclinedNames(QueryResult_AutoPtr result);
+ void _LoadArenaTeamInfo(QueryResult_AutoPtr result);
+ void _LoadEquipmentSets(QueryResult_AutoPtr result);
+ void _LoadBGData(QueryResult_AutoPtr result);
+ void _LoadGlyphs(QueryResult_AutoPtr result);
+ void _LoadTalents(QueryResult_AutoPtr result);
+
+ /*********************************************************/
+ /*** SAVE SYSTEM ***/
+ /*********************************************************/
+
+ void _SaveActions();
+ void _SaveAuras();
+ void _SaveInventory();
+ void _SaveMail();
+ void _SaveQuestStatus();
+ void _SaveDailyQuestStatus();
+ void _SaveSkills();
+ void _SaveSpells();
+ void _SaveEquipmentSets();
+ void _SaveBGData();
+ void _SaveGlyphs();
+ void _SaveTalents();
+
+ void _SetCreateBits(UpdateMask *updateMask, Player *target) const;
+ void _SetUpdateBits(UpdateMask *updateMask, Player *target) const;
+
+ /*********************************************************/
+ /*** ENVIRONMENTAL SYSTEM ***/
+ /*********************************************************/
+ void HandleSobering();
+ void SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen);
+ void StopMirrorTimer(MirrorTimerType Type);
+ void HandleDrowning(uint32 time_diff);
+ int32 getMaxTimer(MirrorTimerType timer);
+
+ /*********************************************************/
+ /*** HONOR SYSTEM ***/
+ /*********************************************************/
+ time_t m_lastHonorUpdateTime;
+
+ void outDebugValues() const;
+ uint64 m_lootGuid;
+
+ uint32 m_team;
+ uint32 m_nextSave;
+ time_t m_speakTime;
+ uint32 m_speakCount;
+ Difficulty m_dungeonDifficulty;
+ Difficulty m_raidDifficulty;
+
+ uint32 m_atLoginFlags;
+
+ Item* m_items[PLAYER_SLOTS_COUNT];
+ uint32 m_currentBuybackSlot;
+
+ std::vector<Item*> m_itemUpdateQueue;
+ bool m_itemUpdateQueueBlocked;
+
+ uint32 m_ExtraFlags;
+ uint64 m_curSelection;
+
+ uint64 m_comboTarget;
+ int8 m_comboPoints;
+
+ QuestStatusMap mQuestStatus;
+
+ SkillStatusMap mSkillStatus;
+
+ uint32 m_GuildIdInvited;
+ uint32 m_ArenaTeamIdInvited;
+
+ PlayerMails m_mail;
+ PlayerSpellMap m_spells;
+ PlayerTalentMap *m_talents[MAX_TALENT_SPECS];
+ uint32 m_lastPotionId; // last used health/mana potion in combat, that block next potion use
+
+ uint8 m_activeSpec;
+ uint8 m_specsCount;
+
+ uint32 m_Glyphs[MAX_TALENT_SPECS][MAX_GLYPH_SLOT_INDEX];
+
+ ActionButtonList m_actionButtons;
+
+ float m_auraBaseMod[BASEMOD_END][MOD_END];
+ int16 m_baseRatingValue[MAX_COMBAT_RATING];
+ uint16 m_baseSpellPower;
+ uint16 m_baseFeralAP;
+ uint16 m_baseManaRegen;
+ uint16 m_baseHealthRegen;
+
+ SpellModList m_spellMods[MAX_SPELLMOD];
+ //uint32 m_pad;
+// Spell * m_spellModTakingSpell; // Spell for which charges are dropped in spell::finish
+
+ EnchantDurationList m_enchantDuration;
+ ItemDurationList m_itemDuration;
+
+ void ResetTimeSync();
+ void SendTimeSync();
+
+ uint64 m_resurrectGUID;
+ uint32 m_resurrectMap;
+ float m_resurrectX, m_resurrectY, m_resurrectZ;
+ uint32 m_resurrectHealth, m_resurrectMana;
+
+ WorldSession *m_session;
+
+ typedef std::list<Channel*> JoinedChannelsList;
+ JoinedChannelsList m_channels;
+
+ int m_cinematic;
+
+ Player *pTrader;
+ bool acceptTrade;
+ uint64 tradeItems[TRADE_SLOT_COUNT];
+ uint32 tradeGold;
+
+ bool m_DailyQuestChanged;
+ time_t m_lastDailyQuestTime;
+
+ uint32 m_drunkTimer;
+ uint16 m_drunk;
+ uint32 m_weaponChangeTimer;
+
+ uint32 m_zoneUpdateId;
+ uint32 m_zoneUpdateTimer;
+ uint32 m_areaUpdateId;
+
+ uint32 m_deathTimer;
+ time_t m_deathExpireTime;
+
+ uint32 m_restTime;
+
+ uint32 m_WeaponProficiency;
+ uint32 m_ArmorProficiency;
+ bool m_canParry;
+ bool m_canBlock;
+ bool m_canTitanGrip;
+ uint8 m_swingErrorMsg;
+ float m_ammoDPS;
+
+ ////////////////////Rest System/////////////////////
+ int time_inn_enter;
+ uint32 inn_pos_mapid;
+ float inn_pos_x;
+ float inn_pos_y;
+ float inn_pos_z;
+ float m_rest_bonus;
+ RestType rest_type;
+ ////////////////////Rest System/////////////////////
+ uint32 m_resetTalentsCost;
+ time_t m_resetTalentsTime;
+ uint32 m_usedTalentCount;
+ uint32 m_questRewardTalentCount;
+
+ // Social
+ PlayerSocial *m_social;
+
+ // Groups
+ GroupReference m_group;
+ GroupReference m_originalGroup;
+ Group *m_groupInvite;
+ uint32 m_groupUpdateMask;
+ uint64 m_auraRaidUpdateMask;
+
+ // last used pet number (for BG's)
+ uint32 m_lastpetnumber;
+
+ // Player summoning
+ time_t m_summon_expire;
+ uint32 m_summon_mapid;
+ float m_summon_x;
+ float m_summon_y;
+ float m_summon_z;
+
+ DeclinedName *m_declinedname;
+ Runes *m_runes;
+ EquipmentSets m_EquipmentSets;
+ private:
+ // internal common parts for CanStore/StoreItem functions
+ uint8 _CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec& dest, ItemPrototype const *pProto, uint32& count, bool swap, Item *pSrcItem ) const;
+ uint8 _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;
+ uint8 _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;
+ Item* _StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update );
+
+ void UpdateKnownCurrencies(uint32 itemId, bool apply);
+ int32 CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest);
+ void AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData );
+
+ bool IsCanDelayTeleport() const { return m_bCanDelayTeleport; }
+ void SetCanDelayTeleport(bool setting) { m_bCanDelayTeleport = setting; }
+ bool IsHasDelayedTeleport() const { return m_bHasDelayedTeleport; }
+ void SetDelayedTeleportFlag(bool setting) { m_bHasDelayedTeleport = setting; }
+
+ void ScheduleDelayedOperation(uint32 operation)
+ {
+ if(operation < DELAYED_END)
+ m_DelayedOperations |= operation;
+ }
+
+ MapReference m_mapRef;
+
+ void UpdateCharmedAI();
+ UnitAI *i_AI;
+
+ uint32 m_lastFallTime;
+ float m_lastFallZ;
+
+ int32 m_MirrorTimer[MAX_TIMERS];
+ uint8 m_MirrorTimerFlags;
+ uint8 m_MirrorTimerFlagsLast;
+ bool m_isInWater;
+
+ // Current teleport data
+ WorldLocation m_teleport_dest;
+ uint32 m_teleport_options;
+ bool mSemaphoreTeleport_Near;
+ bool mSemaphoreTeleport_Far;
+
+ uint32 m_DelayedOperations;
+ bool m_bCanDelayTeleport;
+ bool m_bHasDelayedTeleport;
+
+ uint32 m_DetectInvTimer;
+
+ // Temporary removed pet cache
+ uint32 m_temporaryUnsummonedPetNumber;
+ uint32 m_oldpetspell;
+
+ AchievementMgr m_achievementMgr;
+ ReputationMgr m_reputationMgr;
+
+ SpellCooldowns m_spellCooldowns;
+
+ uint32 m_ChampioningFaction;
+
+ uint32 m_timeSyncCount;
+ uint32 m_timeSyncTimer;
+};
+
+void AddItemsSetItem(Player*player,Item *item);
+void RemoveItemsSetItem(Player*player,ItemPrototype const *proto);
+
+// "the bodies of template functions must be made available in a header file"
+template <class T> T Player::ApplySpellMod(uint32 spellId, SpellModOp op, T &basevalue, Spell * spell)
+{
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
+ if (!spellInfo) return 0;
+ float totalmul = 1.0f;
+ int32 totalflat = 0;
+
+ // Drop charges for triggering spells instead of triggered ones
+ if (m_spellModTakingSpell)
+ spell = m_spellModTakingSpell;
+
+ for (SpellModList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
+ {
+ SpellModifier *mod = *itr;
+
+ // Charges can be set only for mods with auras
+ if (!mod->ownerAura)
+ assert(mod->charges == 0);
+
+ if(!IsAffectedBySpellmod(spellInfo,mod,spell))
+ continue;
+
+ if (mod->type == SPELLMOD_FLAT)
+ totalflat += mod->value;
+ else if (mod->type == SPELLMOD_PCT)
+ {
+ // skip percent mods for null basevalue (most important for spell mods with charges )
+ if(basevalue == T(0))
+ continue;
+
+ // special case (skip >10sec spell casts for instant cast setting)
+ if( mod->op==SPELLMOD_CASTING_TIME && basevalue >= T(10000) && mod->value <= -100)
+ continue;
+
+ totalmul *= 1.0f + (float)mod->value / 100.0f;
+ }
+
+ DropModCharge(mod, spell);
+ }
+ float diff = (float)basevalue * (totalmul - 1.0f) + (float)totalflat;
+ basevalue = T((float)basevalue + diff);
+ return T(diff);
+}
+#endif
diff --git a/src/game/Spell.cpp b/src/game/Spell.cpp
index cd66e758353..ccc84acf098 100644
--- a/src/game/Spell.cpp
+++ b/src/game/Spell.cpp
@@ -1,6955 +1,6955 @@
-/*
- * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
- *
- * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-#include "Common.h"
-#include "Database/DatabaseEnv.h"
-#include "WorldPacket.h"
-#include "WorldSession.h"
-#include "GridNotifiers.h"
-#include "GridNotifiersImpl.h"
-#include "Opcodes.h"
-#include "Log.h"
-#include "UpdateMask.h"
-#include "World.h"
-#include "ObjectMgr.h"
-#include "SpellMgr.h"
-#include "Player.h"
-#include "Pet.h"
-#include "Unit.h"
-#include "Totem.h"
-#include "Spell.h"
-#include "DynamicObject.h"
-#include "Group.h"
-#include "UpdateData.h"
-#include "MapManager.h"
-#include "ObjectAccessor.h"
-#include "CellImpl.h"
-#include "Policies/SingletonImp.h"
-#include "SharedDefines.h"
-#include "LootMgr.h"
-#include "VMapFactory.h"
-#include "BattleGround.h"
-#include "Util.h"
-#include "TemporarySummon.h"
-#include "Vehicle.h"
-#include "SpellAuraEffects.h"
-#include "ScriptMgr.h"
-
-#define SPELL_CHANNEL_UPDATE_INTERVAL (1 * IN_MILISECONDS)
-
-extern pEffect SpellEffects[TOTAL_SPELL_EFFECTS];
-
-bool IsQuestTameSpell(uint32 spellId)
-{
- SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
- if (!spellproto) return false;
-
- return spellproto->Effect[0] == SPELL_EFFECT_THREAT
- && spellproto->Effect[1] == SPELL_EFFECT_APPLY_AURA && spellproto->EffectApplyAuraName[1] == SPELL_AURA_DUMMY;
-}
-
-class PrioritizeManaUnitWraper
-{
- public:
- explicit PrioritizeManaUnitWraper(Unit* unit) : i_unit(unit)
- {
- uint32 maxmana = unit->GetMaxPower(POWER_MANA);
- i_percent = maxmana ? unit->GetPower(POWER_MANA) * 100 / maxmana : 101;
- }
- Unit* getUnit() const { return i_unit; }
- uint32 getPercent() const { return i_percent; }
- private:
- Unit* i_unit;
- uint32 i_percent;
-};
-
-struct PrioritizeMana
-{
- int operator()( PrioritizeManaUnitWraper const& x, PrioritizeManaUnitWraper const& y ) const
- {
- return x.getPercent() > y.getPercent();
- }
-};
-
-typedef std::priority_queue<PrioritizeManaUnitWraper, std::vector<PrioritizeManaUnitWraper>, PrioritizeMana> PrioritizeManaUnitQueue;
-
-class PrioritizeHealthUnitWraper
-{
-public:
- explicit PrioritizeHealthUnitWraper(Unit* unit) : i_unit(unit)
- {
- i_percent = unit->GetHealth() * 100 / unit->GetMaxHealth();
- }
- Unit* getUnit() const { return i_unit; }
- uint32 getPercent() const { return i_percent; }
-private:
- Unit* i_unit;
- uint32 i_percent;
-};
-
-struct PrioritizeHealth
-{
- int operator()( PrioritizeHealthUnitWraper const& x, PrioritizeHealthUnitWraper const& y ) const
- {
- return x.getPercent() > y.getPercent();
- }
-};
-
-typedef std::priority_queue<PrioritizeHealthUnitWraper, std::vector<PrioritizeHealthUnitWraper>, PrioritizeHealth> PrioritizeHealthUnitQueue;
-
-SpellCastTargets::SpellCastTargets() : m_elevation(0), m_speed(0)
-{
- m_unitTarget = NULL;
- m_itemTarget = NULL;
- m_GOTarget = NULL;
-
- m_unitTargetGUID = 0;
- m_GOTargetGUID = 0;
- m_CorpseTargetGUID = 0;
- m_itemTargetGUID = 0;
- m_itemTargetEntry = 0;
-
- m_srcPos.Relocate(0,0,0,0);
- m_strTarget = "";
- m_targetMask = 0;
-}
-
-SpellCastTargets::~SpellCastTargets()
-{
-}
-
-void SpellCastTargets::setUnitTarget(Unit *target)
-{
- if (!target)
- return;
-
- m_unitTarget = target;
- m_unitTargetGUID = target->GetGUID();
- m_targetMask |= TARGET_FLAG_UNIT;
-}
-
-void SpellCastTargets::setSrc(float x, float y, float z)
-{
- m_srcPos.Relocate(x, y, z);
- m_targetMask |= TARGET_FLAG_SOURCE_LOCATION;
-}
-
-void SpellCastTargets::setSrc(Position *pos)
-{
- if(pos)
- {
- m_srcPos.Relocate(pos);
- m_targetMask |= TARGET_FLAG_SOURCE_LOCATION;
- }
-}
-
-void SpellCastTargets::setDst(float x, float y, float z, float orientation, uint32 mapId)
-{
- m_dstPos.Relocate(x, y, z, orientation);
- m_targetMask |= TARGET_FLAG_DEST_LOCATION;
- if(mapId != MAPID_INVALID)
- m_dstPos.m_mapId = mapId;
-}
-
-void SpellCastTargets::setDst(Position *pos)
-{
- if(pos)
- {
- m_dstPos.Relocate(pos);
- m_targetMask |= TARGET_FLAG_DEST_LOCATION;
- }
-}
-
-void SpellCastTargets::setGOTarget(GameObject *target)
-{
- m_GOTarget = target;
- m_GOTargetGUID = target->GetGUID();
- // m_targetMask |= TARGET_FLAG_OBJECT;
-}
-
-void SpellCastTargets::setItemTarget(Item* item)
-{
- if(!item)
- return;
-
- m_itemTarget = item;
- m_itemTargetGUID = item->GetGUID();
- m_itemTargetEntry = item->GetEntry();
- m_targetMask |= TARGET_FLAG_ITEM;
-}
-
-void SpellCastTargets::setCorpseTarget(Corpse* corpse)
-{
- m_CorpseTargetGUID = corpse->GetGUID();
-}
-
-void SpellCastTargets::Update(Unit* caster)
-{
- m_GOTarget = m_GOTargetGUID ? caster->GetMap()->GetGameObject(m_GOTargetGUID) : NULL;
- m_unitTarget = m_unitTargetGUID ?
- ( m_unitTargetGUID == caster->GetGUID() ? caster : ObjectAccessor::GetUnit(*caster, m_unitTargetGUID) ) :
- NULL;
-
- m_itemTarget = NULL;
- if(caster->GetTypeId() == TYPEID_PLAYER)
- {
- if(m_targetMask & TARGET_FLAG_ITEM)
- m_itemTarget = ((Player*)caster)->GetItemByGuid(m_itemTargetGUID);
- else if(m_targetMask & TARGET_FLAG_TRADE_ITEM)
- {
- // here it is not guid but slot
- Player* pTrader = ((Player*)caster)->GetTrader();
- if(pTrader && m_itemTargetGUID < TRADE_SLOT_COUNT)
- m_itemTarget = pTrader->GetItemByGuid(m_itemTargetGUID);
- }
- if(m_itemTarget)
- m_itemTargetEntry = m_itemTarget->GetEntry();
- }
-}
-
-bool SpellCastTargets::read ( WorldPacket * data, Unit *caster )
-{
- if(data->rpos() + 4 > data->size())
- return false;
-
- //data->hexlike();
-
- *data >> m_targetMask;
- //sLog.outDebug("Spell read, target mask = %u", m_targetMask);
-
- if(m_targetMask == TARGET_FLAG_SELF)
- return true;
-
- // TARGET_FLAG_UNK2 is used for non-combat pets, maybe other?
- if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_UNK2 ))
- if(!data->readPackGUID(m_unitTargetGUID))
- return false;
-
- if( m_targetMask & ( TARGET_FLAG_OBJECT ))
- if(!data->readPackGUID(m_GOTargetGUID))
- return false;
-
- if(( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM )) && caster->GetTypeId() == TYPEID_PLAYER)
- if(!data->readPackGUID(m_itemTargetGUID))
- return false;
-
- if( m_targetMask & (TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
- if(!data->readPackGUID(m_CorpseTargetGUID))
- return false;
-
- if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
- {
- if(data->rpos() + 1 + 4 + 4 + 4 > data->size())
- return false;
-
- if(!data->readPackGUID(m_unitTargetGUID))
- return false;
-
- *data >> m_srcPos.m_positionX >> m_srcPos.m_positionY >> m_srcPos.m_positionZ;
- if(!m_srcPos.IsPositionValid())
- return false;
- }
- else
- m_srcPos.Relocate(caster);
-
- if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
- {
- if(data->rpos() + 1 + 4 + 4 + 4 > data->size())
- return false;
-
- if(!data->readPackGUID(m_unitTargetGUID))
- return false;
-
- *data >> m_dstPos.m_positionX >> m_dstPos.m_positionY >> m_dstPos.m_positionZ;
- if(!m_dstPos.IsPositionValid())
- return false;
-
- if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
- {
- if(data->rpos() + 4 + 4 <= data->size())
- {
- *data >> m_elevation >> m_speed;
- // TODO: should also read
- m_srcPos.m_orientation = caster->GetOrientation();
- //*data >> uint16 >> uint8 >> uint32 >> uint32;
- //*data >> float >> float >> float >> float...
- }
- }
- }
- else
- m_dstPos.Relocate(caster);
-
- if( m_targetMask & TARGET_FLAG_STRING )
- {
- if(data->rpos() + 1 > data->size())
- return false;
-
- *data >> m_strTarget;
- }
-
- // find real units/GOs
- Update(caster);
- return true;
-}
-
-void SpellCastTargets::write ( WorldPacket * data )
-{
- *data << uint32(m_targetMask);
- //sLog.outDebug("Spell write, target mask = %u", m_targetMask);
-
- if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_PVP_CORPSE | TARGET_FLAG_OBJECT | TARGET_FLAG_CORPSE | TARGET_FLAG_UNK2 ) )
- {
- if(m_targetMask & TARGET_FLAG_UNIT)
- {
- if(m_unitTarget)
- data->append(m_unitTarget->GetPackGUID());
- else
- *data << uint8(0);
- }
- else if( m_targetMask & TARGET_FLAG_OBJECT )
- {
- if(m_GOTarget)
- data->append(m_GOTarget->GetPackGUID());
- else
- *data << uint8(0);
- }
- else if( m_targetMask & ( TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
- data->appendPackGUID(m_CorpseTargetGUID);
- else
- *data << uint8(0);
- }
-
- if( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM ) )
- {
- if(m_itemTarget)
- data->append(m_itemTarget->GetPackGUID());
- else
- *data << uint8(0);
- }
-
- if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
- {
- if(m_unitTarget)
- data->append(m_unitTarget->GetPackGUID());
- else
- *data << uint8(0);
-
- *data << m_srcPos.m_positionX << m_srcPos.m_positionY << m_srcPos.m_positionZ;
- }
-
- if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
- {
- if(m_unitTarget)
- data->append(m_unitTarget->GetPackGUID());
- else
- *data << uint8(0);
-
- *data << m_dstPos.m_positionX << m_dstPos.m_positionY << m_dstPos.m_positionZ;
- }
-
- if( m_targetMask & TARGET_FLAG_STRING )
- *data << m_strTarget;
-}
-
-Spell::Spell( Unit* Caster, SpellEntry const *info, bool triggered, uint64 originalCasterGUID, Spell** triggeringContainer, bool skipCheck )
-: m_spellInfo(info), m_spellValue(new SpellValue(m_spellInfo))
-, m_caster(Caster)
-{
- m_customAttr = spellmgr.GetSpellCustomAttr(m_spellInfo->Id);
- m_skipCheck = skipCheck;
- m_selfContainer = NULL;
- m_triggeringContainer = triggeringContainer;
- m_referencedFromCurrentSpell = false;
- m_executedCurrently = false;
- m_needComboPoints = NeedsComboPoints(m_spellInfo);
- m_comboPointGain = 0;
- m_delayStart = 0;
- m_delayAtDamageCount = 0;
-
- m_applyMultiplierMask = 0;
- m_effectMask = 0;
- m_auraScaleMask = 0;
-
- // Get data for type of attack
- switch (m_spellInfo->DmgClass)
- {
- case SPELL_DAMAGE_CLASS_MELEE:
- if (m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_OFFHAND)
- m_attackType = OFF_ATTACK;
- else
- m_attackType = BASE_ATTACK;
- break;
- case SPELL_DAMAGE_CLASS_RANGED:
- m_attackType = IsRangedWeaponSpell(m_spellInfo) ? RANGED_ATTACK : BASE_ATTACK;
- break;
- default:
- // Wands
- if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
- m_attackType = RANGED_ATTACK;
- else
- m_attackType = BASE_ATTACK;
- break;
- }
-
- m_spellSchoolMask = GetSpellSchoolMask(info); // Can be override for some spell (wand shoot for example)
-
- if(m_attackType == RANGED_ATTACK)
- {
- // wand case
- if((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId() == TYPEID_PLAYER)
- {
- if(Item* pItem = ((Player*)m_caster)->GetWeaponForAttack(RANGED_ATTACK))
- m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetProto()->Damage[0].DamageType);
- }
- }
- // Set health leech amount to zero
- m_healthLeech = 0;
-
- if(originalCasterGUID)
- m_originalCasterGUID = originalCasterGUID;
- else
- m_originalCasterGUID = m_caster->GetGUID();
-
- if(m_originalCasterGUID == m_caster->GetGUID())
- m_originalCaster = m_caster;
- else
- {
- m_originalCaster = ObjectAccessor::GetUnit(*m_caster, m_originalCasterGUID);
- if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
- }
-
- for (int i=0; i <3; ++i)
- m_currentBasePoints[i] = m_spellValue->EffectBasePoints[i];
-
- m_spellState = SPELL_STATE_NULL;
-
- m_TriggerSpells.clear();
- m_IsTriggeredSpell = triggered;
- //m_AreaAura = false;
- m_CastItem = NULL;
-
- unitTarget = NULL;
- itemTarget = NULL;
- gameObjTarget = NULL;
- focusObject = NULL;
- m_cast_count = 0;
- m_glyphIndex = 0;
- m_preCastSpell = 0;
- m_triggeredByAuraSpell = NULL;
- m_spellAura = NULL;
-
- //Auto Shot & Shoot (wand)
- m_autoRepeat = IsAutoRepeatRangedSpell(m_spellInfo);
-
- m_runesState = 0;
- m_powerCost = 0; // setup to correct value in Spell::prepare, don't must be used before.
- m_casttime = 0; // setup to correct value in Spell::prepare, don't must be used before.
- m_timer = 0; // will set to castime in prepare
-
- m_needAliveTargetMask = 0;
-
- // determine reflection
- m_canReflect = false;
-
- if(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && !IsAreaOfEffectSpell(m_spellInfo) && !(m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_CANT_REFLECTED))
- {
- for (int j = 0; j < 3; ++j)
- {
- if (m_spellInfo->Effect[j] == 0)
- continue;
-
- if(!IsPositiveTarget(m_spellInfo->EffectImplicitTargetA[j], m_spellInfo->EffectImplicitTargetB[j]))
- m_canReflect = true;
- else
- m_canReflect = (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NEGATIVE) ? true : false;
-
- if(m_canReflect)
- continue;
- else
- break;
- }
- }
-
- CleanupTargetList();
-}
-
-Spell::~Spell()
-{
- if(m_caster && m_caster->GetTypeId() == TYPEID_PLAYER)
- assert(((Player*)m_caster)->m_spellModTakingSpell != this);
- delete m_spellValue;
-}
-
-template<typename T>
-WorldObject* Spell::FindCorpseUsing()
-{
- // non-standard target selection
- float max_range = GetSpellMaxRange(m_spellInfo, false);
-
- CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
- Cell cell(p);
- cell.data.Part.reserved = ALL_DISTRICT;
- cell.SetNoCreate();
-
- WorldObject* result = NULL;
-
- T u_check(m_caster, max_range);
- Trinity::WorldObjectSearcher<T> searcher(m_caster, result, u_check);
-
- TypeContainerVisitor<Trinity::WorldObjectSearcher<T>, GridTypeMapContainer > grid_searcher(searcher);
- cell.Visit(p, grid_searcher, *m_caster->GetMap(), *m_caster, max_range);
-
- if (!result)
- {
- TypeContainerVisitor<Trinity::WorldObjectSearcher<T>, WorldTypeMapContainer > world_searcher(searcher);
- cell.Visit(p, world_searcher, *m_caster->GetMap(), *m_caster, max_range);
- }
-
- return result;
-}
-
-void Spell::SelectSpellTargets()
-{
- for (uint32 i = 0; i < 3; ++i)
- {
- // not call for empty effect.
- // Also some spells use not used effect targets for store targets for dummy effect in triggered spells
- if(!m_spellInfo->Effect[i])
- continue;
-
- uint32 effectTargetType = EffectTargetType[m_spellInfo->Effect[i]];
-
- // is it possible that areaaura is not applied to caster?
- if(effectTargetType == SPELL_REQUIRE_NONE)
- continue;
-
- uint32 targetA = m_spellInfo->EffectImplicitTargetA[i];
- uint32 targetB = m_spellInfo->EffectImplicitTargetB[i];
-
- if(targetA)
- SelectEffectTargets(i, targetA);
- if(targetB) // In very rare case !A && B
- SelectEffectTargets(i, targetB);
-
- if(effectTargetType != SPELL_REQUIRE_UNIT)
- {
- if(effectTargetType == SPELL_REQUIRE_CASTER)
- AddUnitTarget(m_caster, i);
- else if(effectTargetType == SPELL_REQUIRE_ITEM)
- {
- if(m_targets.getItemTarget())
- AddItemTarget(m_targets.getItemTarget(), i);
- }
- continue;
- }
-
- if(/*tmpUnitMap.empty() && */m_spellInfo->Targets & TARGET_FLAG_CASTER)
- {
- AddUnitTarget(m_caster, i);
- continue;
- }
-
- if(!targetA && !targetB)
- {
- if(!GetSpellMaxRangeForFriend(sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex)))
- {
- AddUnitTarget(m_caster, i);
- continue;
- }
-
- // add here custom effects that need default target.
- // FOR EVERY TARGET TYPE THERE IS A DIFFERENT FILL!!
- switch(m_spellInfo->Effect[i])
- {
- case SPELL_EFFECT_DUMMY:
- {
- switch(m_spellInfo->Id)
- {
- case 20577: // Cannibalize
- {
- WorldObject* result = FindCorpseUsing<Trinity::CannibalizeObjectCheck> ();
-
- if(result)
- {
- switch(result->GetTypeId())
- {
- case TYPEID_UNIT:
- case TYPEID_PLAYER:
- AddUnitTarget((Unit*)result, i);
- break;
- case TYPEID_CORPSE:
- m_targets.setCorpseTarget((Corpse*)result);
- if(Player* owner = ObjectAccessor::FindPlayer(((Corpse*)result)->GetOwnerGUID()))
- AddUnitTarget(owner, i);
- break;
- }
- }
- else
- {
- // clear cooldown at fail
- if(m_caster->GetTypeId() == TYPEID_PLAYER)
- ((Player*)m_caster)->RemoveSpellCooldown(m_spellInfo->Id, true);
- SendCastResult(SPELL_FAILED_NO_EDIBLE_CORPSES);
- finish(false);
- }
- break;
- }
- default:
- if(m_targets.getUnitTarget())
- AddUnitTarget(m_targets.getUnitTarget(), i);
- else
- AddUnitTarget(m_caster, i);
- break;
- }
- break;
- }
- case SPELL_EFFECT_RESURRECT:
- case SPELL_EFFECT_CREATE_ITEM:
- case SPELL_EFFECT_TRIGGER_SPELL:
- case SPELL_EFFECT_SKILL_STEP:
- case SPELL_EFFECT_PROFICIENCY:
- case SPELL_EFFECT_SUMMON_OBJECT_WILD:
- case SPELL_EFFECT_SELF_RESURRECT:
- case SPELL_EFFECT_REPUTATION:
- case SPELL_EFFECT_LEARN_SPELL:
- case SPELL_EFFECT_SEND_TAXI:
- if(m_targets.getUnitTarget())
- AddUnitTarget(m_targets.getUnitTarget(), i);
- // Triggered spells have additional spell targets - cast them even if no explicit unit target is given (required for spell 50516 for example)
- else if(m_spellInfo->Effect[i] == SPELL_EFFECT_TRIGGER_SPELL)
- AddUnitTarget(m_caster, i);
- break;
- case SPELL_EFFECT_SUMMON_PLAYER:
- if(m_caster->GetTypeId() == TYPEID_PLAYER && ((Player*)m_caster)->GetSelection())
- {
- Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
- if(target)
- AddUnitTarget(target, i);
- }
- break;
- case SPELL_EFFECT_RESURRECT_NEW:
- if(m_targets.getUnitTarget())
- AddUnitTarget(m_targets.getUnitTarget(), i);
- if(m_targets.getCorpseTargetGUID())
- {
- Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster, m_targets.getCorpseTargetGUID());
- if(corpse)
- {
- Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
- if(owner)
- AddUnitTarget(owner, i);
- }
- }
- break;
- case SPELL_EFFECT_SUMMON_CHANGE_ITEM:
- case SPELL_EFFECT_ADD_FARSIGHT:
- case SPELL_EFFECT_APPLY_GLYPH:
- case SPELL_EFFECT_STUCK:
- case SPELL_EFFECT_FEED_PET:
- case SPELL_EFFECT_DESTROY_ALL_TOTEMS:
- case SPELL_EFFECT_KILL_CREDIT2: // only one spell: 42793
- AddUnitTarget(m_caster, i);
- break;
- case SPELL_EFFECT_LEARN_PET_SPELL:
- if(Guardian* pet = m_caster->GetGuardianPet())
- AddUnitTarget(pet, i);
- break;
- /*case SPELL_EFFECT_ENCHANT_ITEM:
- case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
- case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC:
- case SPELL_EFFECT_DISENCHANT:
- case SPELL_EFFECT_PROSPECTING:
- case SPELL_EFFECT_MILLING:
- if(m_targets.getItemTarget())
- AddItemTarget(m_targets.getItemTarget(), i);
- break;*/
- case SPELL_EFFECT_APPLY_AURA:
- switch(m_spellInfo->EffectApplyAuraName[i])
- {
- case SPELL_AURA_ADD_FLAT_MODIFIER: // some spell mods auras have 0 target modes instead expected TARGET_UNIT_CASTER(1) (and present for other ranks for same spell for example)
- case SPELL_AURA_ADD_PCT_MODIFIER:
- AddUnitTarget(m_caster, i);
- break;
- default: // apply to target in other case
- break;
- }
- break;
- case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
- // AreaAura
- if(m_spellInfo->Attributes == 0x9050000 || m_spellInfo->Attributes == 0x10000)
- SelectEffectTargets(i, TARGET_UNIT_PARTY_TARGET);
- break;
- case SPELL_EFFECT_SKIN_PLAYER_CORPSE:
- if(m_targets.getUnitTarget())
- {
- AddUnitTarget(m_targets.getUnitTarget(), i);
- }
- else if (m_targets.getCorpseTargetGUID())
- {
- Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
- if(corpse)
- {
- Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
- if(owner)
- AddUnitTarget(owner, i);
- }
- }
- break;
- default:
- AddUnitTarget(m_caster, i);
- break;
- }
- }
- if(IsChanneledSpell(m_spellInfo))
- {
- uint8 mask = (1<<i);
- for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
- {
- if(ihit->effectMask & mask)
- {
- m_needAliveTargetMask |= mask;
- break;
- }
- }
- }
- else if (m_auraScaleMask)
- {
- bool checkLvl = !m_UniqueTargetInfo.empty();
- for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();)
- {
- // remove targets which did not pass min level check
- if(m_auraScaleMask && ihit->effectMask == m_auraScaleMask)
- {
- // Do not check for selfcast
- if (!ihit->scaleAura && ihit->targetGUID != m_caster->GetGUID())
- {
- m_UniqueTargetInfo.erase(ihit++);
- continue;
- }
- }
- ++ihit;
- }
- if (checkLvl && m_UniqueTargetInfo.empty())
- {
- SendCastResult(SPELL_FAILED_LOWLEVEL);
- finish(false);
- }
- }
- }
-
- if(m_targets.HasDst())
- {
- if(m_targets.HasTraj())
- {
- float speed = m_targets.GetSpeedXY();
- if(speed > 0.0f)
- m_delayMoment = (uint64)floor(m_targets.GetDist2d() / speed * 1000.0f);
- }
- else if(m_spellInfo->speed > 0.0f)
- {
- float dist = m_caster->GetDistance(m_targets.m_dstPos);
- m_delayMoment = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
- }
- }
-}
-
-void Spell::prepareDataForTriggerSystem(AuraEffect const * triggeredByAura)
-{
- //==========================================================================================
- // Now fill data for trigger system, need know:
- // can spell trigger another or not ( m_canTrigger )
- // Create base triggers flags for Attacker and Victim ( m_procAttacker, m_procVictim and m_procEx)
- //==========================================================================================
-
- m_procVictim = m_procAttacker = 0;
- // Get data for type of attack and fill base info for trigger
- switch (m_spellInfo->DmgClass)
- {
- case SPELL_DAMAGE_CLASS_MELEE:
- m_procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_SPELL_HIT;
- m_procVictim = PROC_FLAG_TAKEN_MELEE_SPELL_HIT;
- break;
- case SPELL_DAMAGE_CLASS_RANGED:
- // Auto attack
- if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
- {
- m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
- m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
- }
- else // Ranged spell attack
- {
- m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_SPELL_HIT;
- m_procVictim = PROC_FLAG_TAKEN_RANGED_SPELL_HIT;
- }
- break;
- default:
- if (m_spellInfo->EquippedItemClass == ITEM_CLASS_WEAPON &&
- m_spellInfo->EquippedItemSubClassMask & (1<<ITEM_SUBCLASS_WEAPON_WAND)
- && m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG) // Wands auto attack
- {
- m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
- m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
- }
- // For other spells trigger procflags are set in Spell::DoAllEffectOnTarget
- // Because spell positivity is dependant on target
- }
- m_procEx= PROC_EX_NONE;
-
- // Hunter trap spells - activation proc for Lock and Load, Entrapment and Misdirection
- if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER &&
- (m_spellInfo->SpellFamilyFlags[0] & 0x18 || // Freezing and Frost Trap, Freezing Arrow
- m_spellInfo->Id == 57879 || // Snake Trap - done this way to avoid double proc
- m_spellInfo->SpellFamilyFlags[2] & 0x00024000)) // Explosive and Immolation Trap
-
- m_procAttacker |= PROC_FLAG_ON_TRAP_ACTIVATION;
-
- /*
- Effects which are result of aura proc from triggered spell cannot proc
- to prevent chain proc of these spells
- */
-
- // Ranged autorepeat attack is set as triggered spell - ignore it
- if (!(m_procAttacker & PROC_FLAG_SUCCESSFUL_RANGED_HIT))
- {
- if (m_IsTriggeredSpell &&
- (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_TRIGGERED_CAN_TRIGGER ||
- m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_TRIGGERED_CAN_TRIGGER_2))
- m_procEx |= PROC_EX_INTERNAL_CANT_PROC;
- else if (m_IsTriggeredSpell)
- m_procEx |= PROC_EX_INTERNAL_TRIGGERED;
- }
- // Totem casts require spellfamilymask defined in spell_proc_event to proc
- if (m_originalCaster && m_caster != m_originalCaster && m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->isTotem() && m_caster->IsControlledByPlayer())
- {
- m_procEx |= PROC_EX_INTERNAL_REQ_FAMILY;
- }
-}
-
-void Spell::CleanupTargetList()
-{
- m_UniqueTargetInfo.clear();
- m_UniqueGOTargetInfo.clear();
- m_UniqueItemInfo.clear();
- m_delayMoment = 0;
-}
-
-void Spell::AddUnitTarget(Unit* pVictim, uint32 effIndex)
-{
- if (m_spellInfo->Effect[effIndex] == 0)
- return;
-
- if (!CheckTarget(pVictim, effIndex))
- return;
-
- // Check for effect immune skip if immuned
- bool immuned = pVictim->IsImmunedToSpellEffect(m_spellInfo, effIndex);
-
- uint64 targetGUID = pVictim->GetGUID();
-
- // Lookup target in already in list
- for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
- {
- if (targetGUID == ihit->targetGUID) // Found in list
- {
- if (!immuned)
- ihit->effectMask |= 1 << effIndex; // Add only effect mask if not immuned
- ihit->scaleAura = false;
- if (m_auraScaleMask && ihit->effectMask == m_auraScaleMask && m_caster != pVictim)
- {
- SpellEntry const * auraSpell = sSpellStore.LookupEntry(spellmgr.GetFirstSpellInChain(m_spellInfo->Id));
- if ((pVictim->getLevel() + 10) >= auraSpell->spellLevel)
- ihit->scaleAura = true;
- }
- return;
- }
- }
-
- // This is new target calculate data for him
-
- // Get spell hit result on target
- TargetInfo target;
- target.targetGUID = targetGUID; // Store target GUID
- target.effectMask = immuned ? 0 : 1 << effIndex; // Store index of effect if not immuned
- target.processed = false; // Effects not apply on target
- target.alive = pVictim->isAlive();
- target.damage = 0;
- target.crit = false;
- target.scaleAura = false;
- if (m_auraScaleMask && target.effectMask == m_auraScaleMask && m_caster != pVictim)
- {
- SpellEntry const * auraSpell = sSpellStore.LookupEntry(spellmgr.GetFirstSpellInChain(m_spellInfo->Id));
- if ((pVictim->getLevel() + 10) >= auraSpell->spellLevel)
- target.scaleAura = true;
- }
-
- // Calculate hit result
- if (m_originalCaster)
- {
- target.missCondition = m_originalCaster->SpellHitResult(pVictim, m_spellInfo, m_canReflect);
- if(m_skipCheck && target.missCondition != SPELL_MISS_IMMUNE)
- target.missCondition = SPELL_MISS_NONE;
- }
- else
- target.missCondition = SPELL_MISS_EVADE; //SPELL_MISS_NONE;
-
- // Spell have speed - need calculate incoming time
- // Incoming time is zero for self casts. At least I think so.
- if (m_spellInfo->speed > 0.0f && m_caster != pVictim)
- {
- // calculate spell incoming interval
- // TODO: this is a hack
- float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
-
- if (dist < 5.0f) dist = 5.0f;
- target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
-
- // Calculate minimum incoming time
- if (m_delayMoment == 0 || m_delayMoment>target.timeDelay)
- m_delayMoment = target.timeDelay;
- }
- else
- target.timeDelay = 0LL;
-
- // If target reflect spell back to caster
- if (target.missCondition == SPELL_MISS_REFLECT)
- {
- // Calculate reflected spell result on caster
- target.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect);
-
- if (target.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell
- target.reflectResult = SPELL_MISS_PARRY;
-
- // Increase time interval for reflected spells by 1.5
- target.timeDelay += target.timeDelay >> 1;
- }
- else
- target.reflectResult = SPELL_MISS_NONE;
-
- // Add target to list
- m_UniqueTargetInfo.push_back(target);
-}
-
-void Spell::AddUnitTarget(uint64 unitGUID, uint32 effIndex)
-{
- if (Unit* unit = m_caster->GetGUID() == unitGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, unitGUID))
- AddUnitTarget(unit, effIndex);
-}
-
-void Spell::AddGOTarget(GameObject* pVictim, uint32 effIndex)
-{
- if( m_spellInfo->Effect[effIndex] == 0 )
- return;
-
- uint64 targetGUID = pVictim->GetGUID();
-
- // Lookup target in already in list
- for (std::list<GOTargetInfo>::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit)
- {
- if (targetGUID == ihit->targetGUID) // Found in list
- {
- ihit->effectMask |= 1 << effIndex; // Add only effect mask
- return;
- }
- }
-
- // This is new target calculate data for him
-
- GOTargetInfo target;
- target.targetGUID = targetGUID;
- target.effectMask = 1 << effIndex;
- target.processed = false; // Effects not apply on target
-
- // Spell have speed - need calculate incoming time
- if (m_spellInfo->speed > 0.0f)
- {
- // calculate spell incoming interval
- float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
- if (dist < 5.0f) dist = 5.0f;
- target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
- if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
- m_delayMoment = target.timeDelay;
- }
- else
- target.timeDelay = 0LL;
-
- // Add target to list
- m_UniqueGOTargetInfo.push_back(target);
-}
-
-void Spell::AddGOTarget(uint64 goGUID, uint32 effIndex)
-{
- GameObject* go = m_caster->GetMap()->GetGameObject(goGUID);
- if (go)
- AddGOTarget(go, effIndex);
-}
-
-void Spell::AddItemTarget(Item* pitem, uint32 effIndex)
-{
- if( m_spellInfo->Effect[effIndex] == 0 )
- return;
-
- // Lookup target in already in list
- for (std::list<ItemTargetInfo>::iterator ihit = m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit)
- {
- if (pitem == ihit->item) // Found in list
- {
- ihit->effectMask |= 1<<effIndex; // Add only effect mask
- return;
- }
- }
-
- // This is new target add data
-
- ItemTargetInfo target;
- target.item = pitem;
- target.effectMask = 1 << effIndex;
- m_UniqueItemInfo.push_back(target);
-}
-
-void Spell::DoAllEffectOnTarget(TargetInfo *target)
-{
- if (!target || target == (TargetInfo*)0x10 || target->processed)
- return;
- target->processed = true; // Target checked in apply effects procedure
-
- // Get mask of effects for target
- uint32 mask = target->effectMask;
-
- Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
- if (!unit)
- return;
-
- if(unit->isAlive() != target->alive)
- return;
-
- // Get original caster (if exist) and calculate damage/healing from him data
- Unit *caster = m_originalCaster ? m_originalCaster : m_caster;
-
- // Skip if m_originalCaster not avaiable
- if (!caster)
- return;
-
- SpellMissInfo missInfo = target->missCondition;
-
- // Need init unitTarget by default unit (can changed in code on reflect)
- // Or on missInfo!=SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem)
- unitTarget = unit;
-
- // Reset damage/healing counter
- m_damage = target->damage;
- m_healing = -target->damage;
-
- // Fill base trigger info
- uint32 procAttacker = m_procAttacker;
- uint32 procVictim = m_procVictim;
- uint32 procEx = m_procEx;
-
- m_spellAura = NULL; // Set aura to null for every target-make sure that pointer is not used for unit without aura applied
-
- //Spells with this flag cannot trigger if effect is casted on self
- // Slice and Dice, relentless strikes, eviscerate
- bool canEffectTrigger = unitTarget->CanProc() && (m_spellInfo->AttributesEx4 & (SPELL_ATTR_EX4_CANT_PROC_FROM_SELFCAST) ? m_caster!=unitTarget : true);
- Unit * spellHitTarget = NULL;
-
- if (missInfo==SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
- spellHitTarget = unit;
- else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
- {
- if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
- {
- spellHitTarget = m_caster;
- if(m_caster->GetTypeId() == TYPEID_UNIT)
- ((Creature*)m_caster)->LowerPlayerDamageReq(target->damage);
- }
- }
-
- if(spellHitTarget)
- {
- SpellMissInfo missInfo = DoSpellHitOnUnit(spellHitTarget, mask, target->scaleAura);
- if(missInfo != SPELL_MISS_NONE)
- {
- if(missInfo != SPELL_MISS_MISS)
- m_caster->SendSpellMiss(unit, m_spellInfo->Id, missInfo);
- m_damage = 0;
- spellHitTarget = NULL;
- }
- }
-
- // Do not take combo points on dodge and miss
- if (m_needComboPoints && m_targets.getUnitTargetGUID() == target->targetGUID)
- if (missInfo != SPELL_MISS_NONE)
- m_needComboPoints = false;
-
- // Trigger info was not filled in spell::preparedatafortriggersystem - we do it now
- if (canEffectTrigger && !procAttacker && !procVictim)
- {
- bool positive = true;
- if (m_damage > 0)
- positive = false;
- else if (!m_healing)
- {
- for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i)
- // If at least one effect negative spell is negative hit
- if (mask & (1<<i) && !IsPositiveEffect(m_spellInfo->Id, i))
- {
- positive = false;
- break;
- }
- }
- switch(m_spellInfo->DmgClass)
- {
- case SPELL_DAMAGE_CLASS_MAGIC:
- if (positive)
- {
- procAttacker |= PROC_FLAG_SUCCESSFUL_POSITIVE_MAGIC_SPELL;
- procVictim |= PROC_FLAG_TAKEN_POSITIVE_MAGIC_SPELL;
- }
- else
- {
- procAttacker |= PROC_FLAG_SUCCESSFUL_NEGATIVE_MAGIC_SPELL;
- procVictim |= PROC_FLAG_TAKEN_NEGATIVE_MAGIC_SPELL;
- }
- break;
- case SPELL_DAMAGE_CLASS_NONE:
- if (positive)
- {
- procAttacker |= PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL_HIT;
- procVictim |= PROC_FLAG_TAKEN_POSITIVE_SPELL;
- }
- else
- {
- procAttacker |= PROC_FLAG_SUCCESSFUL_NEGATIVE_SPELL_HIT;
- procVictim |= PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT;
- }
- break;
- }
- }
- // All calculated do it!
- // Do healing and triggers
- if (m_healing > 0)
- {
- bool crit = caster->isSpellCrit(unitTarget, m_spellInfo, m_spellSchoolMask);
- uint32 addhealth = m_healing;
- if (crit)
- {
- procEx |= PROC_EX_CRITICAL_HIT;
- addhealth = caster->SpellCriticalHealingBonus(m_spellInfo, addhealth, NULL);
- }
- else
- procEx |= PROC_EX_NORMAL_HIT;
-
- // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
- if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT)
- caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, addhealth, m_attackType, m_spellInfo, m_triggeredByAuraSpell);
-
- int32 gain = caster->DealHeal(unitTarget, addhealth, m_spellInfo, crit);
- unitTarget->getHostilRefManager().threatAssist(caster, float(gain) * 0.5f, m_spellInfo);
- }
- // Do damage and triggers
- else if (m_damage > 0)
- {
- // Fill base damage struct (unitTarget - is real spell target)
- SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
-
- // Add bonuses and fill damageInfo struct
- caster->CalculateSpellDamageTaken(&damageInfo, m_damage, m_spellInfo, m_attackType, target->crit);
- caster->DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb);
-
- // Send log damage message to client
- caster->SendSpellNonMeleeDamageLog(&damageInfo);
-
- procEx |= createProcExtendMask(&damageInfo, missInfo);
- procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
-
- // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
- if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT)
- {
- caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo, m_triggeredByAuraSpell);
- if(caster->GetTypeId() == TYPEID_PLAYER && (m_spellInfo->Attributes & SPELL_ATTR_STOP_ATTACK_TARGET) == 0 &&
- (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_RANGED))
- ((Player *)caster)->CastItemCombatSpell(unitTarget, m_attackType, procVictim, procEx);
- }
-
- caster->DealSpellDamage(&damageInfo, true);
-
- // Haunt
- if(m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags[1] & 0x40000 && m_spellAura && m_spellAura->GetEffect(1))
- {
- AuraEffect * aurEff = m_spellAura->GetEffect(1);
- aurEff->SetAmount(aurEff->GetAmount() * damageInfo.damage / 100);
- }
- }
- // Passive spell hits/misses or active spells only misses (only triggers)
- else
- {
- // Fill base damage struct (unitTarget - is real spell target)
- SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
- procEx |= createProcExtendMask(&damageInfo, missInfo);
- // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
- if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT)
- caster->ProcDamageAndSpell(unit, procAttacker, procVictim, procEx, 0, m_attackType, m_spellInfo, m_triggeredByAuraSpell);
-
- // Failed Pickpocket, reveal rogue
- if (missInfo == SPELL_MISS_RESIST
- && m_customAttr & SPELL_ATTR_CU_PICKPOCKET
- && unitTarget->GetTypeId() == TYPEID_UNIT)
- {
- m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TALK);
- if (((Creature*)unitTarget)->IsAIEnabled)
- ((Creature*)unitTarget)->AI()->AttackStart(m_caster);
- }
- }
-
- if(m_caster && !m_caster->IsFriendlyTo(unit) && !IsPositiveSpell(m_spellInfo->Id))
- {
- m_caster->CombatStart(unit, !(m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_NO_INITIAL_AGGRO));
-
- if(m_customAttr & SPELL_ATTR_CU_AURA_CC)
- if(!unit->IsStandState())
- unit->SetStandState(UNIT_STAND_STATE_STAND);
- }
-
- if(spellHitTarget)
- {
- //AI functions
- if(spellHitTarget->GetTypeId() == TYPEID_UNIT)
- {
- if(((Creature*)spellHitTarget)->IsAIEnabled)
- ((Creature*)spellHitTarget)->AI()->SpellHit(m_caster, m_spellInfo);
-
- // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
- // ignore pets or autorepeat/melee casts for speed (not exist quest for spells (hm... )
- if(m_originalCaster && m_originalCaster->IsControlledByPlayer() && !((Creature*)spellHitTarget)->isPet() && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive())
- if(Player* p = m_originalCaster->GetCharmerOrOwnerPlayerOrPlayerItself())
- p->CastedCreatureOrGO(spellHitTarget->GetEntry(),spellHitTarget->GetGUID(),m_spellInfo->Id);
- }
-
- if(m_caster && m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->IsAIEnabled)
- ((Creature*)m_caster)->AI()->SpellHitTarget(spellHitTarget, m_spellInfo);
-
- // Needs to be called after dealing damage/healing to not remove breaking on damage auras
- DoTriggersOnSpellHit(spellHitTarget);
-
- // if target is fallged for pvp also flag caster if a player
- if(unit->IsPvP())
- {
- if (m_caster->GetTypeId() == TYPEID_PLAYER)
- ((Player*)m_caster)->UpdatePvP(true);
- }
-
- }
-}
-
-SpellMissInfo Spell::DoSpellHitOnUnit(Unit *unit, const uint32 effectMask, bool scaleAura)
-{
- if(!unit || !effectMask)
- return SPELL_MISS_EVADE;
-
- // Recheck immune (only for delayed spells)
- if(m_spellInfo->speed && (unit->IsImmunedToDamage(m_spellInfo) || unit->IsImmunedToSpell(m_spellInfo)))
- return SPELL_MISS_IMMUNE;
-
- if (unit->GetTypeId() == TYPEID_PLAYER)
- {
- ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id);
- ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id);
- }
-
- if(m_caster->GetTypeId() == TYPEID_PLAYER)
- {
- ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, unit);
- }
-
- if( m_caster != unit )
- {
- // Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells
- if (m_spellInfo->speed > 0.0f &&
- unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE) &&
- unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
- {
- return SPELL_MISS_EVADE;
- }
-
- if( !m_caster->IsFriendlyTo(unit) )
- {
- // reset damage to 0 if target has Invisibility and isn't visible for caster
- // I do not think this is a correct way to fix it. Sanctuary effect should make all delayed spells invalid
- // for delayed spells ignore not visible explicit target
- if(m_spellInfo->speed > 0.0f && unit == m_targets.getUnitTarget()
- && (unit->m_invisibilityMask || m_caster->m_invisibilityMask)
- && !m_caster->canSeeOrDetect(unit, true))
- {
- // that was causing CombatLog errors
- // return SPELL_MISS_EVADE;
- return SPELL_MISS_MISS; // miss = do not send anything here
- }
-
- unit->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_HITBYSPELL);
- //TODO: This is a hack. But we do not know what types of stealth should be interrupted by CC
- if((m_customAttr & SPELL_ATTR_CU_AURA_CC) && unit->IsControlledByPlayer())
- unit->RemoveAurasByType(SPELL_AURA_MOD_STEALTH);
- }
- else
- {
- // for delayed spells ignore negative spells (after duel end) for friendly targets
- // TODO: this cause soul transfer bugged
- if(m_spellInfo->speed > 0.0f && unit->GetTypeId() == TYPEID_PLAYER && !IsPositiveSpell(m_spellInfo->Id))
- {
- return SPELL_MISS_EVADE;
- }
-
- // assisting case, healing and resurrection
- if(unit->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
- {
- m_caster->SetContestedPvP();
- if(m_caster->GetTypeId() == TYPEID_PLAYER)
- ((Player*)m_caster)->UpdatePvP(true);
- }
- if( unit->isInCombat() && !(m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_NO_INITIAL_AGGRO) )
- {
- m_caster->SetInCombatState(unit->GetCombatTimer() > 0, unit);
- unit->getHostilRefManager().threatAssist(m_caster, 0.0f);
- }
- }
- }
-
- // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add
- if(m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo,m_triggeredByAuraSpell))
- {
- m_diminishLevel = unit->GetDiminishing(m_diminishGroup);
- DiminishingReturnsType type = GetDiminishingReturnsGroupType(m_diminishGroup);
- // Increase Diminishing on unit, current informations for actually casts will use values above
- if((type == DRTYPE_PLAYER && (unit->GetTypeId() == TYPEID_PLAYER || ((Creature*)unit)->isPet() || ((Creature*)unit)->isPossessedByPlayer())) || type == DRTYPE_ALL)
- unit->IncrDiminishing(m_diminishGroup);
- }
-
- uint8 aura_effmask = 0;
- for (uint8 i = 0; i < 3; ++i)
- if (effectMask & (1<<i) && IsUnitOwnedAuraEffect(m_spellInfo->Effect[i]))
- aura_effmask |= 1<<i;
-
- if (aura_effmask)
- {
- // Select rank for aura with level requirements only in specific cases
- // Unit has to be target only of aura effect, both caster and target have to be players, target has to be other than unit target
- SpellEntry const * aurSpellInfo = m_spellInfo;
- int32 basePoints[3];
- if (scaleAura)
- {
- aurSpellInfo = spellmgr.SelectAuraRankForPlayerLevel(m_spellInfo,unitTarget->getLevel());
- assert (aurSpellInfo);
- for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
- {
- basePoints[i] = aurSpellInfo->EffectBasePoints[i];
- if (m_spellInfo->Effect[i] != aurSpellInfo->Effect[i])
- {
- aurSpellInfo = m_spellInfo;
- break;
- }
- }
- }
-
- if(m_originalCaster)
- {
- if (m_spellAura = Aura::TryCreate(aurSpellInfo, effectMask, unit,
- m_originalCaster,(aurSpellInfo == m_spellInfo)? &m_currentBasePoints[0] : &basePoints[0], m_CastItem))
- {
- // Now Reduce spell duration using data received at spell hit
- int32 duration = m_spellAura->GetMaxDuration();
- int32 limitduration = GetDiminishingReturnsLimitDuration(m_diminishGroup,aurSpellInfo);
- unit->ApplyDiminishingToDuration(m_diminishGroup, duration, m_originalCaster, m_diminishLevel,limitduration);
- ((UnitAura*)m_spellAura)->SetDiminishGroup(m_diminishGroup);
-
- bool positive = IsPositiveSpell(m_spellAura->GetId());
- AuraApplication * aurApp = m_spellAura->GetApplicationOfTarget(m_originalCaster->GetGUID());
- if (aurApp)
- positive = aurApp->IsPositive();
-
- duration = m_originalCaster->ModSpellDuration(aurSpellInfo, unit, duration, positive);
-
- //mod duration of channeled aura by spell haste
- if (IsChanneledSpell(m_spellInfo))
- m_originalCaster->ModSpellCastTime(aurSpellInfo, duration, this);
-
- if(duration != m_spellAura->GetMaxDuration())
- {
- m_spellAura->SetMaxDuration(duration);
- m_spellAura->SetDuration(duration);
- }
-
- // Prayer of Mending (jump animation), we need formal caster instead original for correct animation
- if(aurSpellInfo->SpellFamilyName == SPELLFAMILY_PRIEST)
- {
- if(aurSpellInfo->SpellFamilyFlags[1] & 0x000020)
- m_caster->CastSpell(unit, 41637, true, NULL, NULL, m_originalCasterGUID);
- }
- m_spellAura->_RegisterForTargets();
- }
- }
- }
-
- for (uint32 effectNumber = 0; effectNumber < 3; ++effectNumber)
- {
- if (effectMask & (1<<effectNumber))
- HandleEffects(unit,NULL,NULL,effectNumber);
- }
-
- return SPELL_MISS_NONE;
-}
-
-void Spell::DoTriggersOnSpellHit(Unit *unit)
-{
- // Apply additional spell effects to target
- if (m_preCastSpell)
- {
- // Special spell id
- // TODO: Handle all of special spells in one place?
- if(m_preCastSpell==61988)
- {
- //Cast Forbearance
- m_caster->CastSpell(unit,25771, true, m_CastItem);
- // Cast Avenging Wrath Marker
- m_caster->CastSpell(unit,61987, true, m_CastItem);
- }
- else if (sSpellStore.LookupEntry(m_preCastSpell))
- m_caster->CastSpell(unit,m_preCastSpell, true, m_CastItem);
- }
-
- // spells with this flag can trigger only if not selfcast (eviscerate for example)
- if (m_ChanceTriggerSpells.size() && (!((m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_CANT_PROC_FROM_SELFCAST) && unit==m_caster)))
- {
- int _duration=0;
- for (ChanceTriggerSpells::const_iterator i = m_ChanceTriggerSpells.begin(); i != m_ChanceTriggerSpells.end(); ++i)
- {
- // SPELL_AURA_ADD_TARGET_TRIGGER auras shouldn't trigger auras without duration
- // set duration equal to triggering spell
- if(roll_chance_i(i->second))
- {
- m_caster->CastSpell(unit, i->first, true);
- sLog.outDebug("Spell %d triggered spell %d by SPELL_AURA_ADD_TARGET_TRIGGER aura", m_spellInfo->Id, i->first->Id);
- }
- if (GetSpellDuration(i->first)==-1)
- {
- if (Aura * triggeredAur = unit->GetAura(i->first->Id, m_caster->GetGUID()))
- {
- // get duration from aura-only once
- if (!_duration)
- {
- Aura * aur = unit->GetAura(m_spellInfo->Id, m_caster->GetGUID());
- _duration = aur ? aur->GetDuration() : -1;
- }
- triggeredAur->SetDuration(_duration);
- }
- }
- }
- }
-
- if(m_customAttr & SPELL_ATTR_CU_LINK_HIT)
- {
- if(const std::vector<int32> *spell_triggered = spellmgr.GetSpellLinked(m_spellInfo->Id + SPELL_LINK_HIT))
- for (std::vector<int32>::const_iterator i = spell_triggered->begin(); i != spell_triggered->end(); ++i)
- if(*i < 0)
- unit->RemoveAurasDueToSpell(-(*i));
- else
- unit->CastSpell(unit, *i, true, 0, 0, m_caster->GetGUID());
- }
-}
-
-void Spell::DoAllEffectOnTarget(GOTargetInfo *target)
-{
- if (target->processed) // Check target
- return;
- target->processed = true; // Target checked in apply effects procedure
-
- uint32 effectMask = target->effectMask;
- if(!effectMask)
- return;
-
- GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID);
- if(!go)
- return;
-
- for (uint32 effectNumber = 0; effectNumber < 3; ++effectNumber)
- if (effectMask & (1 << effectNumber))
- HandleEffects(NULL, NULL, go, effectNumber);
-
- // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
- // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
- if(m_originalCaster && m_originalCaster->IsControlledByPlayer() && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
- {
- if ( Player* p = m_originalCaster->GetCharmerOrOwnerPlayerOrPlayerItself() )
- p->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
- }
-}
-
-void Spell::DoAllEffectOnTarget(ItemTargetInfo *target)
-{
- uint32 effectMask = target->effectMask;
- if(!target->item || !effectMask)
- return;
-
- for (uint32 effectNumber = 0; effectNumber < 3; ++effectNumber)
- if (effectMask & (1 << effectNumber))
- HandleEffects(NULL, target->item, NULL, effectNumber);
-}
-
-bool Spell::UpdateChanneledTargetList()
-{
- // Not need check return true
- if (m_needAliveTargetMask == 0)
- return true;
-
- uint8 needAliveTargetMask = m_needAliveTargetMask;
- uint8 needAuraMask = 0;
- for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
- if (m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA)
- needAuraMask |= 1<<i;
-
- needAuraMask &= needAliveTargetMask;
-
- float range;
- if(needAuraMask)
- {
- range = GetSpellMaxRange(m_spellInfo, IsPositiveSpell(m_spellInfo->Id));
- if(Player * modOwner = m_caster->GetSpellModOwner())
- modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
- }
-
- for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
- {
- if( ihit->missCondition == SPELL_MISS_NONE && (needAliveTargetMask & ihit->effectMask) )
- {
- Unit *unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
-
- if (unit && unit->isAlive())
- {
- if (needAuraMask & ihit->effectMask)
- {
- if(AuraApplication * aurApp = unit->GetAuraApplication(m_spellInfo->Id, m_originalCasterGUID))
- {
- if (m_caster != unit && !m_caster->IsWithinDistInMap(unit,range))
- {
- ihit->effectMask &= ~aurApp->GetEffectMask();
- unit->RemoveAura(aurApp);
- continue;
- }
- }
- else // aura is dispelled
- continue;
- }
-
- needAliveTargetMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target
- }
- }
- }
-
- // is all effects from m_needAliveTargetMask have alive targets
- return needAliveTargetMask == 0;
-}
-
-// Helper for Chain Healing
-// Spell target first
-// Raidmates then descending by injury suffered (MaxHealth - Health)
-// Other players/mobs then descending by injury suffered (MaxHealth - Health)
-struct ChainHealingOrder : public std::binary_function<const Unit*, const Unit*, bool>
-{
- const Unit* MainTarget;
- ChainHealingOrder(Unit const* Target) : MainTarget(Target) {};
- // functor for operator ">"
- bool operator()(Unit const* _Left, Unit const* _Right) const
- {
- return (ChainHealingHash(_Left) < ChainHealingHash(_Right));
- }
-
- int32 ChainHealingHash(Unit const* Target) const
- {
- /*if (Target == MainTarget)
- return 0;
- else*/ if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER &&
- ((Player const*)Target)->IsInSameRaidWith((Player const*)MainTarget))
- {
- if (Target->GetHealth() == Target->GetMaxHealth())
- return 40000;
- else
- return 20000 - Target->GetMaxHealth() + Target->GetHealth();
- }
- else
- return 40000 - Target->GetMaxHealth() + Target->GetHealth();
- }
-};
-
-// Helper for targets nearest to the spell target
-// The spell target is always first unless there is a target at _completely_ the same position (unbelievable case)
-struct TargetDistanceOrder : public std::binary_function<const Unit, const Unit, bool>
-{
- const Unit* MainTarget;
- TargetDistanceOrder(const Unit* Target) : MainTarget(Target) {};
- // functor for operator ">"
- bool operator()(const Unit* _Left, const Unit* _Right) const
- {
- return MainTarget->GetDistanceOrder(_Left,_Right);
- }
-};
-
-void Spell::SearchChainTarget(std::list<Unit*> &TagUnitMap, float max_range, uint32 num, SpellTargets TargetType)
-{
- Unit *cur = m_targets.getUnitTarget();
- if(!cur)
- return;
-
- // Get spell max affected targets
- /*uint32 unMaxTargets = m_spellInfo->MaxAffectedTargets;
- Unit::AuraList const& mod = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS);
- for (Unit::AuraList::const_iterator m = mod.begin(); m != mod.end(); ++m)
- {
- if (!(*m)->IsAffectedOnSpell(m_spellInfo))
- continue;
- unMaxTargets+=(*m)->GetAmount();
- }*/
-
- //FIXME: This very like horrible hack and wrong for most spells
- if(m_spellInfo->DmgClass != SPELL_DAMAGE_CLASS_MELEE)
- max_range += num * CHAIN_SPELL_JUMP_RADIUS;
-
- std::list<Unit*> tempUnitMap;
- if(TargetType == SPELL_TARGETS_CHAINHEAL)
- {
- SearchAreaTarget(tempUnitMap, max_range, PUSH_CHAIN, SPELL_TARGETS_ALLY);
- tempUnitMap.sort(ChainHealingOrder(m_caster));
- //if(cur->GetHealth() == cur->GetMaxHealth() && tempUnitMap.size())
- // cur = tempUnitMap.front();
- }
- else
- SearchAreaTarget(tempUnitMap, max_range, PUSH_CHAIN, TargetType);
- tempUnitMap.remove(cur);
-
- while(num)
- {
- TagUnitMap.push_back(cur);
- --num;
-
- if(tempUnitMap.empty())
- break;
-
- std::list<Unit*>::iterator next;
-
- if(TargetType == SPELL_TARGETS_CHAINHEAL)
- {
- next = tempUnitMap.begin();
- while(cur->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS
- || !cur->IsWithinLOSInMap(*next))
- {
- ++next;
- if(next == tempUnitMap.end())
- return;
- }
- }
- else
- {
- tempUnitMap.sort(TargetDistanceOrder(cur));
- next = tempUnitMap.begin();
-
- if(cur->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
- break;
- while(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE
- && !m_caster->isInFrontInMap(*next, max_range)
- || !m_caster->canSeeOrDetect(*next, false)
- || !cur->IsWithinLOSInMap(*next))
- {
- ++next;
- if(next == tempUnitMap.end() || cur->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
- return;
- }
- }
-
- cur = *next;
- tempUnitMap.erase(next);
- }
-}
-
-void Spell::SearchAreaTarget(std::list<Unit*> &TagUnitMap, float radius, SpellNotifyPushType type, SpellTargets TargetType, uint32 entry)
-{
- Position *pos;
- switch(type)
- {
- case PUSH_DST_CENTER:
- CheckDst();
- pos = &m_targets.m_dstPos;
- break;
- case PUSH_SRC_CENTER:
- CheckSrc();
- pos = &m_targets.m_srcPos;
- break;
- case PUSH_CHAIN:
- {
- Unit *target = m_targets.getUnitTarget();
- if(!target)
- {
- sLog.outError( "SPELL: cannot find unit target for spell ID %u\n", m_spellInfo->Id );
- return;
- }
- pos = target;
- break;
- }
- default:
- pos = m_caster;
- break;
- }
-
- Trinity::SpellNotifierCreatureAndPlayer notifier(m_caster, TagUnitMap, radius, type, TargetType, pos, entry);
- if((m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_PLAYERS_ONLY)
- || TargetType == SPELL_TARGETS_ENTRY && !entry)
- m_caster->GetMap()->VisitWorld(pos->m_positionX, pos->m_positionY, radius, notifier);
- else
- m_caster->GetMap()->VisitAll(pos->m_positionX, pos->m_positionY, radius, notifier);
-
- if(m_customAttr & SPELL_ATTR_CU_EXCLUDE_SELF)
- TagUnitMap.remove(m_caster);
-}
-
-WorldObject* Spell::SearchNearbyTarget(float range, SpellTargets TargetType)
-{
- switch(TargetType)
- {
- case SPELL_TARGETS_ENTRY:
- {
- SpellScriptTargetBounds bounds = spellmgr.GetSpellScriptTargetBounds(m_spellInfo->Id);
- if(bounds.first==bounds.second)
- {
- sLog.outDebug("Spell (ID: %u) (caster Entry: %u) does not have record in `spell_script_target`", m_spellInfo->Id, m_caster->GetEntry());
- if(IsPositiveSpell(m_spellInfo->Id))
- return SearchNearbyTarget(range, SPELL_TARGETS_ALLY);
- else
- return SearchNearbyTarget(range, SPELL_TARGETS_ENEMY);
- }
-
- Creature* creatureScriptTarget = NULL;
- GameObject* goScriptTarget = NULL;
-
- for (SpellScriptTarget::const_iterator i_spellST = bounds.first; i_spellST != bounds.second; ++i_spellST)
- {
- switch(i_spellST->second.type)
- {
- case SPELL_TARGET_TYPE_CONTROLLED:
- for (Unit::ControlList::iterator itr = m_caster->m_Controlled.begin(); itr != m_caster->m_Controlled.end(); ++itr)
- if ((*itr)->GetEntry() == i_spellST->second.targetEntry && (*itr)->IsWithinDistInMap(m_caster, range))
- {
- goScriptTarget = NULL;
- creatureScriptTarget = ((Creature *)*itr);
- range = m_caster->GetDistance(creatureScriptTarget);
- }
- break;
- case SPELL_TARGET_TYPE_GAMEOBJECT:
- if(i_spellST->second.targetEntry)
- {
- if(GameObject *go = m_caster->FindNearestGameObject(i_spellST->second.targetEntry, range))
- {
- // remember found target and range, next attempt will find more near target with another entry
- goScriptTarget = go;
- creatureScriptTarget = NULL;
- range = m_caster->GetDistance(goScriptTarget);
- }
- }
- else if( focusObject ) //Focus Object
- {
- float frange = m_caster->GetDistance(focusObject);
- if(range >= frange)
- {
- creatureScriptTarget = NULL;
- goScriptTarget = focusObject;
- range = frange;
- }
- }
- break;
- case SPELL_TARGET_TYPE_CREATURE:
- if(m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetEntry() == i_spellST->second.targetEntry)
- return m_targets.getUnitTarget();
- case SPELL_TARGET_TYPE_DEAD:
- default:
- if(Creature *cre = m_caster->FindNearestCreature(i_spellST->second.targetEntry, range, i_spellST->second.type != SPELL_TARGET_TYPE_DEAD))
- {
- creatureScriptTarget = cre;
- goScriptTarget = NULL;
- range = m_caster->GetDistance(creatureScriptTarget);
- }
- break;
- }
- }
-
- if(creatureScriptTarget)
- return creatureScriptTarget;
- else
- return goScriptTarget;
- }
- default:
- case SPELL_TARGETS_ENEMY:
- {
- Unit *target = NULL;
- Trinity::AnyUnfriendlyUnitInObjectRangeCheck u_check(m_caster, m_caster, range);
- Trinity::UnitLastSearcher<Trinity::AnyUnfriendlyUnitInObjectRangeCheck> searcher(m_caster, target, u_check);
- m_caster->VisitNearbyObject(range, searcher);
- return target;
- }
- case SPELL_TARGETS_ALLY:
- {
- Unit *target = NULL;
- Trinity::AnyFriendlyUnitInObjectRangeCheck u_check(m_caster, m_caster, range);
- Trinity::UnitLastSearcher<Trinity::AnyFriendlyUnitInObjectRangeCheck> searcher(m_caster, target, u_check);
- m_caster->VisitNearbyObject(range, searcher);
- return target;
- }
- }
-}
-
-void Spell::SelectEffectTargets(uint32 i, uint32 cur)
-{
- SpellNotifyPushType pushType = PUSH_NONE;
- Player *modOwner = NULL;
- if(m_originalCaster)
- modOwner = m_originalCaster->GetSpellModOwner();
-
- switch(SpellTargetType[cur])
- {
- case TARGET_TYPE_UNIT_CASTER:
- {
- switch(cur)
- {
- case TARGET_UNIT_CASTER:
- AddUnitTarget(m_caster, i);
- break;
- case TARGET_UNIT_CASTER_FISHING:
- {
- //AddUnitTarget(m_caster, i);
- float min_dis = GetSpellMinRange(m_spellInfo, true);
- float max_dis = GetSpellMaxRange(m_spellInfo, true);
- float dis = rand_norm() * (max_dis - min_dis) + min_dis;
- float x, y, z;
- m_caster->GetClosePoint(x, y, z, DEFAULT_WORLD_OBJECT_SIZE, dis);
- m_targets.setDst(x, y, z, m_caster->GetOrientation());
- break;
- }
- case TARGET_UNIT_MASTER:
- if(Unit* owner = m_caster->GetCharmerOrOwner())
- AddUnitTarget(owner, i);
- break;
- case TARGET_UNIT_PET:
- if(Guardian* pet = m_caster->GetGuardianPet())
- AddUnitTarget(pet, i);
- break;
- case TARGET_UNIT_PARTY_CASTER:
- case TARGET_UNIT_RAID_CASTER:
- pushType = PUSH_CASTER_CENTER;
- break;
- case TARGET_UNIT_VEHICLE:
- if(Unit *vehicle = m_caster->GetVehicleBase())
- AddUnitTarget(vehicle, i);
- break;
- case TARGET_UNIT_PASSENGER_0:
- case TARGET_UNIT_PASSENGER_1:
- case TARGET_UNIT_PASSENGER_2:
- case TARGET_UNIT_PASSENGER_3:
- case TARGET_UNIT_PASSENGER_4:
- case TARGET_UNIT_PASSENGER_5:
- case TARGET_UNIT_PASSENGER_6:
- case TARGET_UNIT_PASSENGER_7:
- if(m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->IsVehicle())
- if(Unit *unit = m_caster->GetVehicleKit()->GetPassenger(cur - TARGET_UNIT_PASSENGER_0))
- AddUnitTarget(unit, i);
- break;
- }
- break;
- }
-
- case TARGET_TYPE_UNIT_TARGET:
- {
- Unit *target = m_targets.getUnitTarget();
- if(!target)
- {
- sLog.outError("SPELL: no unit target for spell ID %u", m_spellInfo->Id);
- break;
- }
-
- switch(cur)
- {
- case TARGET_UNIT_TARGET_ENEMY:
- if(Unit *magnet = m_caster->SelectMagnetTarget(target, m_spellInfo))
- if(magnet != target)
- m_targets.setUnitTarget(magnet);
- pushType = PUSH_CHAIN;
- break;
- case TARGET_UNIT_TARGET_ANY:
- if(!IsPositiveSpell(m_spellInfo->Id))
- if(Unit *magnet = m_caster->SelectMagnetTarget(target, m_spellInfo))
- if(magnet != target)
- m_targets.setUnitTarget(magnet);
- pushType = PUSH_CHAIN;
- break;
- case TARGET_UNIT_CHAINHEAL:
- pushType = PUSH_CHAIN;
- break;
- case TARGET_UNIT_TARGET_ALLY:
- case TARGET_UNIT_TARGET_RAID:
- case TARGET_UNIT_TARGET_PARTY:
- case TARGET_UNIT_MINIPET:
- case TARGET_UNIT_UNK_92:
- AddUnitTarget(target, i);
- break;
- case TARGET_UNIT_PARTY_TARGET:
- case TARGET_UNIT_CLASS_TARGET:
- pushType = PUSH_CASTER_CENTER; // not real
- break;
- }
- break;
- }
-
- case TARGET_TYPE_UNIT_NEARBY:
- {
- WorldObject *target = NULL;
- float range;
-
- switch(cur)
- {
- case TARGET_UNIT_NEARBY_ENEMY:
- range = GetSpellMaxRange(m_spellInfo, false);
- if(modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
- target = SearchNearbyTarget(range, SPELL_TARGETS_ENEMY);
- break;
- case TARGET_UNIT_NEARBY_ALLY:
- case TARGET_UNIT_NEARBY_ALLY_UNK:
- case TARGET_UNIT_NEARBY_RAID:
- range = GetSpellMaxRange(m_spellInfo, true);
- if(modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
- target = SearchNearbyTarget(range, SPELL_TARGETS_ALLY);
- break;
- case TARGET_UNIT_NEARBY_ENTRY:
- case TARGET_GAMEOBJECT_NEARBY_ENTRY:
- range = GetSpellMaxRange(m_spellInfo, IsPositiveSpell(m_spellInfo->Id));
- if(modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
- target = SearchNearbyTarget(range, SPELL_TARGETS_ENTRY);
- break;
- }
-
- if(!target)
- return;
- else if(target->GetTypeId() == TYPEID_GAMEOBJECT)
- AddGOTarget((GameObject*)target, i);
- else
- {
- pushType = PUSH_CHAIN;
-
- if(m_targets.getUnitTarget() != target)
- m_targets.setUnitTarget((Unit*)target);
- }
-
- break;
- }
-
- case TARGET_TYPE_AREA_SRC:
- pushType = PUSH_SRC_CENTER;
- break;
-
- case TARGET_TYPE_AREA_DST:
- pushType = PUSH_DST_CENTER;
- break;
-
- case TARGET_TYPE_AREA_CONE:
- if(m_customAttr & SPELL_ATTR_CU_CONE_BACK)
- pushType = PUSH_IN_BACK;
- else if(m_customAttr & SPELL_ATTR_CU_CONE_LINE)
- pushType = PUSH_IN_LINE;
- else
- pushType = PUSH_IN_FRONT;
- break;
-
- case TARGET_TYPE_DEST_CASTER: //4+8+2
- {
- if (cur == TARGET_SRC_CASTER)
- {
- m_targets.setSrc(m_caster);
- break;
- }
- else if (cur == TARGET_DST_CASTER)
- {
- m_targets.setDst(m_caster);
- break;
- }
-
- float angle, dist;
-
- float objSize = m_caster->GetObjectSize();
- dist = GetSpellRadiusForFriend(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
- if(dist < objSize)
- dist = objSize;
- else if(cur == TARGET_DEST_CASTER_RANDOM)
- dist = objSize + (dist - objSize) * rand_norm();
-
- switch(cur)
- {
- case TARGET_DEST_CASTER_FRONT_LEFT: angle = -M_PI/4; break;
- case TARGET_DEST_CASTER_BACK_LEFT: angle = -3*M_PI/4; break;
- case TARGET_DEST_CASTER_BACK_RIGHT: angle = 3*M_PI/4; break;
- case TARGET_DEST_CASTER_FRONT_RIGHT:angle = M_PI/4; break;
- case TARGET_MINION:
- case TARGET_DEST_CASTER_FRONT_LEAP:
- case TARGET_DEST_CASTER_FRONT: angle = 0.0f; break;
- case TARGET_DEST_CASTER_BACK: angle = M_PI; break;
- case TARGET_DEST_CASTER_RIGHT: angle = M_PI/2; break;
- case TARGET_DEST_CASTER_LEFT: angle = -M_PI/2; break;
- default: angle = rand_norm()*2*M_PI; break;
- }
-
- Position pos;
- m_caster->GetNearPosition(pos, dist, angle);
- m_targets.setDst(&pos); // also flag
- break;
- }
-
- case TARGET_TYPE_DEST_TARGET: //2+8+2
- {
- Unit *target = m_targets.getUnitTarget();
- if(!target)
- {
- sLog.outError("SPELL: no unit target for spell ID %u\n", m_spellInfo->Id);
- break;
- }
-
- if(cur == TARGET_DST_TARGET_ENEMY || cur == TARGET_DEST_TARGET_ANY)
- {
- m_targets.setDst(target);
- break;
- }
-
- float angle, dist;
-
- float objSize = target->GetObjectSize();
- dist = target->GetSpellRadiusForTarget(target, sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
- if(dist < objSize)
- dist = objSize;
- else if(cur == TARGET_DEST_CASTER_RANDOM)
- dist = objSize + (dist - objSize) * rand_norm();
-
- switch(cur)
- {
- case TARGET_DEST_TARGET_FRONT: angle = 0.0f; break;
- case TARGET_DEST_TARGET_BACK: angle = M_PI; break;
- case TARGET_DEST_TARGET_RIGHT: angle = M_PI/2; break;
- case TARGET_DEST_TARGET_LEFT: angle = -M_PI/2; break;
- case TARGET_DEST_TARGET_FRONT_LEFT: angle = -M_PI/4; break;
- case TARGET_DEST_TARGET_BACK_LEFT: angle = -3*M_PI/4; break;
- case TARGET_DEST_TARGET_BACK_RIGHT: angle = 3*M_PI/4; break;
- case TARGET_DEST_TARGET_FRONT_RIGHT:angle = M_PI/4; break;
- default: angle = rand_norm()*2*M_PI; break;
- }
-
- Position pos;
- target->GetNearPosition(pos, dist, angle);
- m_targets.setDst(&pos);
- break;
- }
-
- case TARGET_TYPE_DEST_DEST: //5+8+1
- {
- if(!m_targets.HasDst())
- {
- sLog.outError("SPELL: no destination for spell ID %u\n", m_spellInfo->Id);
- break;
- }
-
- float angle;
- switch(cur)
- {
- case TARGET_DEST_DYNOBJ_ENEMY:
- case TARGET_DEST_DYNOBJ_ALLY:
- case TARGET_DEST_DYNOBJ_NONE:
- case TARGET_DEST_DEST:
- return;
- case TARGET_DEST_TRAJ:
- SelectTrajTargets();
- return;
- case TARGET_DEST_DEST_FRONT: angle = 0.0f; break;
- case TARGET_DEST_DEST_BACK: angle = M_PI; break;
- case TARGET_DEST_DEST_RIGHT: angle = M_PI/2; break;
- case TARGET_DEST_DEST_LEFT: angle = -M_PI/2; break;
- case TARGET_DEST_DEST_FRONT_LEFT: angle = -M_PI/4; break;
- case TARGET_DEST_DEST_BACK_LEFT: angle = -3*M_PI/4; break;
- case TARGET_DEST_DEST_BACK_RIGHT: angle = 3*M_PI/4; break;
- case TARGET_DEST_DEST_FRONT_RIGHT:angle = M_PI/4; break;
- default: angle = rand_norm()*2*M_PI; break;
- }
-
- float dist;
- dist = GetSpellRadiusForFriend(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
- if (cur == TARGET_DEST_DEST_RANDOM || cur == TARGET_DEST_DEST_RANDOM_DIR_DIST)
- dist *= rand_norm();
-
- // must has dst, no need to set flag
- m_caster->MovePosition(m_targets.m_dstPos, dist, angle);
- break;
- }
-
- case TARGET_TYPE_DEST_SPECIAL:
- {
- switch(cur)
- {
- case TARGET_DST_DB:
- if(SpellTargetPosition const* st = spellmgr.GetSpellTargetPosition(m_spellInfo->Id))
- {
- //TODO: fix this check
- if(m_spellInfo->Effect[0] == SPELL_EFFECT_TELEPORT_UNITS
- || m_spellInfo->Effect[1] == SPELL_EFFECT_TELEPORT_UNITS
- || m_spellInfo->Effect[2] == SPELL_EFFECT_TELEPORT_UNITS)
- m_targets.setDst(st->target_X, st->target_Y, st->target_Z, st->target_Orientation, (int32)st->target_mapId);
- else if(st->target_mapId == m_caster->GetMapId())
- m_targets.setDst(st->target_X, st->target_Y, st->target_Z, st->target_Orientation);
- }
- else
- {
- sLog.outDebug( "SPELL: unknown target coordinates for spell ID %u", m_spellInfo->Id );
- Unit *target = NULL;
- if(uint64 guid = m_caster->GetUInt64Value(UNIT_FIELD_TARGET))
- target = ObjectAccessor::GetUnit(*m_caster, guid);
- m_targets.setDst(target ? target : m_caster);
- }
- break;
- case TARGET_DST_HOME:
- if(m_caster->GetTypeId() == TYPEID_PLAYER)
- m_targets.setDst(((Player*)m_caster)->m_homebindX,((Player*)m_caster)->m_homebindY,((Player*)m_caster)->m_homebindZ, ((Player*)m_caster)->GetOrientation(), ((Player*)m_caster)->m_homebindMapId);
- break;
- case TARGET_DST_NEARBY_ENTRY:
- {
- float range = GetSpellMaxRange(m_spellInfo, IsPositiveSpell(m_spellInfo->Id));
- if(modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
-
- if(WorldObject *target = SearchNearbyTarget(range, SPELL_TARGETS_ENTRY))
- m_targets.setDst(target);
- break;
- }
- }
- break;
- }
-
- case TARGET_TYPE_CHANNEL:
- {
- if (!m_originalCaster || !m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL))
- {
- sLog.outError( "SPELL: no current channeled spell for spell ID %u", m_spellInfo->Id );
- break;
- }
-
- switch (cur)
- {
- case TARGET_UNIT_CHANNEL:
- // in some cases unittarget is invalid and crash. do not know why it happens.
- if (Unit* target = Unit::GetUnit(*m_caster, m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_targets.getUnitTargetGUID()))
- AddUnitTarget(target, i);
- else
- sLog.outError( "SPELL: cannot find channel spell target for spell ID %u", m_spellInfo->Id );
- break;
- case TARGET_DEST_CHANNEL:
- if (m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_targets.HasDst())
- m_targets = m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_targets;
- else if (Unit* target = Unit::GetUnit(*m_caster, m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_targets.getUnitTargetGUID()))
- m_targets.setDst(target);
- else
- sLog.outError( "SPELL: cannot find channel spell destination for spell ID %u", m_spellInfo->Id );
- break;
- }
- break;
- }
-
- default:
- {
- switch (cur)
- {
- case TARGET_GAMEOBJECT:
- if(m_targets.getGOTarget())
- AddGOTarget(m_targets.getGOTarget(), i);
- break;
- case TARGET_GAMEOBJECT_ITEM:
- if (m_targets.getGOTargetGUID())
- AddGOTarget(m_targets.getGOTarget(), i);
- else if (m_targets.getItemTarget())
- AddItemTarget(m_targets.getItemTarget(), i);
- break;
- case TARGET_UNIT_DRIVER:
- if (Unit * driver = m_targets.getUnitTarget())
- if (driver->IsOnVehicle(driver))
- AddUnitTarget(driver, i);
- break;
- default:
- sLog.outError("Unhandled spell target %u", cur);
- break;
- }
- break;
- }
- }
-
- if (pushType == PUSH_CHAIN) // Chain
- {
- Unit *target = m_targets.getUnitTarget();
- if (!target)
- {
- sLog.outError("SPELL: no chain unit target for spell ID %u", m_spellInfo->Id);
- return;
- }
-
- //Chain: 2, 6, 22, 25, 45, 77
- uint32 maxTargets = m_spellInfo->EffectChainTarget[i];
- if (modOwner)
- modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, maxTargets, this);
-
- if (maxTargets > 1)
- {
- //otherwise, this multiplier is used for something else
- m_damageMultipliers[i] = 1.0f;
- m_applyMultiplierMask |= 1 << i;
-
- float range;
- std::list<Unit*> unitList;
-
- switch (cur)
- {
- case TARGET_UNIT_NEARBY_ENEMY:
- case TARGET_UNIT_TARGET_ENEMY:
- case TARGET_UNIT_NEARBY_ENTRY: // fix me
- range = GetSpellMaxRange(m_spellInfo, false);
- if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
- SearchChainTarget(unitList, range, maxTargets, SPELL_TARGETS_ENEMY);
- break;
- case TARGET_UNIT_CHAINHEAL:
- case TARGET_UNIT_NEARBY_ALLY: // fix me
- case TARGET_UNIT_NEARBY_ALLY_UNK:
- case TARGET_UNIT_NEARBY_RAID:
- range = GetSpellMaxRange(m_spellInfo, true);
- if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
- SearchChainTarget(unitList, range, maxTargets, SPELL_TARGETS_CHAINHEAL);
- break;
- }
-
- for (std::list<Unit*>::iterator itr = unitList.begin(); itr != unitList.end(); ++itr)
- AddUnitTarget(*itr, i);
- }
- else
- AddUnitTarget(target, i);
- }
- else if (pushType)
- {
- // Dummy, just for client
- if(EffectTargetType[m_spellInfo->Effect[i]] != SPELL_REQUIRE_UNIT)
- return;
-
- float radius;
- SpellTargets targetType;
- switch(cur)
- {
- case TARGET_UNIT_AREA_ENEMY_SRC:
- case TARGET_UNIT_AREA_ENEMY_DST:
- case TARGET_UNIT_CONE_ENEMY:
- case TARGET_UNIT_CONE_ENEMY_UNKNOWN:
- case TARGET_UNIT_AREA_PATH:
- radius = GetSpellRadius(m_spellInfo, i, false);
- targetType = SPELL_TARGETS_ENEMY;
- break;
- case TARGET_UNIT_AREA_ALLY_SRC:
- case TARGET_UNIT_AREA_ALLY_DST:
- case TARGET_UNIT_CONE_ALLY:
- radius = GetSpellRadius(m_spellInfo, i, true);
- targetType = SPELL_TARGETS_ALLY;
- break;
- case TARGET_UNIT_AREA_ENTRY_DST:
- case TARGET_UNIT_AREA_ENTRY_SRC:
- case TARGET_UNIT_CONE_ENTRY: // fix me
- radius = GetSpellRadius(m_spellInfo, i, IsPositiveSpell(m_spellInfo->Id));
- targetType = SPELL_TARGETS_ENTRY;
- break;
- default:
- radius = GetSpellRadius(m_spellInfo, i, true);
- targetType = SPELL_TARGETS_NONE;
- break;
- }
-
- if(modOwner)
- modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius, this);
- radius *= m_spellValue->RadiusMod;
-
- std::list<Unit*> unitList;
- if(targetType == SPELL_TARGETS_ENTRY)
- {
- SpellScriptTargetBounds bounds = spellmgr.GetSpellScriptTargetBounds(m_spellInfo->Id);
- if(bounds.first == bounds.second)
- {
- // Custom entries
- // TODO: move these to sql
- switch (m_spellInfo->Id)
- {
- case 46584: // Raise Dead
- {
- m_targets.m_targetMask &= ~TARGET_FLAG_DEST_LOCATION;
- if (WorldObject* result = FindCorpseUsing<Trinity::RaiseDeadObjectCheck> ())
- {
- switch(result->GetTypeId())
- {
- case TYPEID_UNIT:
- m_targets.setDst(result);
- }
- }
- break;
- }
- // Corpse Explosion
- case 49158:
- case 51325:
- case 51326:
- case 51327:
- case 51328:
- // Search for ghoul if our ghoul or dead body not valid unit target
- if (!(m_targets.getUnitTarget() && (m_targets.getUnitTarget()->GetEntry() == 26125 && m_targets.getUnitTarget()->GetOwnerGUID() == m_caster->GetGUID()
- || (m_targets.getUnitTarget()->getDeathState() == CORPSE
- && m_targets.getUnitTarget()->GetDisplayId() == m_targets.getUnitTarget()->GetNativeDisplayId()
- && m_targets.getUnitTarget()->GetTypeId() == TYPEID_UNIT
- && !((Creature*)m_targets.getUnitTarget())->isDeadByDefault()
- && !(m_targets.getUnitTarget()->GetCreatureTypeMask() & CREATURE_TYPEMASK_MECHANICAL_OR_ELEMENTAL))
- && m_targets.getUnitTarget()->GetDisplayId() == m_targets.getUnitTarget()->GetNativeDisplayId())))
- {
- CleanupTargetList();
-
- WorldObject* result = FindCorpseUsing <Trinity::ExplodeCorpseObjectCheck> ();
-
- if (result)
- {
- switch (result->GetTypeId())
- {
- case TYPEID_UNIT:
- case TYPEID_PLAYER:
- m_targets.setUnitTarget((Unit*)result);
- break;
- }
- }
- else
- {
- if (m_caster->GetTypeId() == TYPEID_PLAYER)
- ((Player*)m_caster)->RemoveSpellCooldown(m_spellInfo->Id,true);
- SendCastResult(SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW);
- finish(false);
- }
- }
- break;
-
- default:
- sLog.outDebug("Spell (ID: %u) (caster Entry: %u) does not have record in `spell_script_target`", m_spellInfo->Id, m_caster->GetEntry());
-
- if(m_spellInfo->Effect[i] == SPELL_EFFECT_TELEPORT_UNITS)
- SearchAreaTarget(unitList, radius, pushType, SPELL_TARGETS_ENTRY, 0);
- else if(IsPositiveEffect(m_spellInfo->Id, i))
- SearchAreaTarget(unitList, radius, pushType, SPELL_TARGETS_ALLY);
- else
- SearchAreaTarget(unitList, radius, pushType, SPELL_TARGETS_ENEMY);
- }
- }
- // let it be done in one check?
- else
- {
- for (SpellScriptTarget::const_iterator i_spellST = bounds.first; i_spellST != bounds.second; ++i_spellST)
- {
- if(i_spellST->second.type == SPELL_TARGET_TYPE_CREATURE)
- SearchAreaTarget(unitList, radius, pushType, SPELL_TARGETS_ENTRY, i_spellST->second.targetEntry);
- else if (i_spellST->second.type == SPELL_TARGET_TYPE_CONTROLLED)
- {
- for (Unit::ControlList::iterator itr = m_caster->m_Controlled.begin(); itr != m_caster->m_Controlled.end(); ++itr)
- if ((*itr)->GetEntry() == i_spellST->second.targetEntry &&
- /*(*itr)->IsWithinDistInMap(m_caster, radius)*/ (*itr)->IsInMap(m_caster)) // For 60243 and 52173 need skip radius check or use range (no radius entry for effect)
- unitList.push_back(*itr);
- }
- }
- }
- }
- else if (targetType)
- SearchAreaTarget(unitList, radius, pushType, targetType);
- else
- {
- switch (cur)
- {
- case TARGET_UNIT_AREA_PARTY_SRC:
- case TARGET_UNIT_AREA_PARTY_DST:
- m_caster->GetPartyMemberInDist(unitList, radius); //fix me
- break;
- case TARGET_OBJECT_AREA_SRC: // fix me
- case TARGET_OBJECT_AREA_DST:
- {
- float x, y, z;
- if(cur == TARGET_OBJECT_AREA_SRC)
- {
- if(m_targets.HasSrc())
- m_targets.m_srcPos.GetPosition(x, y, z);
- else
- break;
- }
- else
- {
- if(m_targets.HasDst())
- m_targets.m_dstPos.GetPosition(x, y, z);
- else
- break;
- }
-
- Trinity::GameObjectInRangeCheck check(x, y, z, radius + 50);
- std::list<GameObject*> goList;
- Trinity::GameObjectListSearcher<Trinity::GameObjectInRangeCheck> searcher(m_caster, goList, check);
- m_caster->GetMap()->VisitGrid(x, y, radius, searcher);
- for (std::list<GameObject*>::iterator itr = goList.begin(); itr != goList.end(); ++itr)
- AddGOTarget(*itr, i);
- break;
- }
- case TARGET_UNIT_PARTY_TARGET:
- m_targets.getUnitTarget()->GetPartyMemberInDist(unitList, radius);
- break;
- case TARGET_UNIT_PARTY_CASTER:
- m_caster->GetPartyMemberInDist(unitList, radius);
- break;
- case TARGET_UNIT_RAID_CASTER:
- m_caster->GetRaidMember(unitList, radius);
- break;
- case TARGET_UNIT_CLASS_TARGET:
- {
- Player* targetPlayer = m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER
- ? (Player*)m_targets.getUnitTarget() : NULL;
-
- Group* pGroup = targetPlayer ? targetPlayer->GetGroup() : NULL;
- if(pGroup)
- {
- for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
- {
- Player* Target = itr->getSource();
-
- // IsHostileTo check duel and controlled by enemy
- if( Target && targetPlayer->IsWithinDistInMap(Target, radius) &&
- targetPlayer->getClass() == Target->getClass() &&
- !m_caster->IsHostileTo(Target) )
- {
- AddUnitTarget(Target, i);
- }
- }
- }
- else if(m_targets.getUnitTarget())
- AddUnitTarget(m_targets.getUnitTarget(), i);
- break;
- }
- }
- }
-
- if(!unitList.empty())
- {
- if(uint32 maxTargets = m_spellValue->MaxAffectedTargets)
- {
- Unit::AuraEffectList const& Auras = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS);
- for (Unit::AuraEffectList::const_iterator j = Auras.begin(); j != Auras.end(); ++j)
- if((*j)->IsAffectedOnSpell(m_spellInfo))
- maxTargets += (*j)->GetAmount();
-
- if(m_spellInfo->Id == 5246) //Intimidating Shout
- unitList.remove(m_targets.getUnitTarget());
- Trinity::RandomResizeList(unitList, m_spellValue->MaxAffectedTargets);
- }
- else
- {
- switch (m_spellInfo->Id)
- {
- case 27285: // Seed of Corruption proc spell
- unitList.remove(m_targets.getUnitTarget());
- break;
- case 55789: // Improved Icy Talons
- case 59725: // Improved Spell Reflection - aoe aura
- unitList.remove(m_caster);
- break;
- case 57669: //Replenishment (special target selection) 10 targets with lowest mana
- {
- typedef std::priority_queue<PrioritizeManaUnitWraper, std::vector<PrioritizeManaUnitWraper>, PrioritizeMana> TopMana;
- TopMana manaUsers;
- for (std::list<Unit*>::iterator itr = unitList.begin() ; itr != unitList.end(); ++itr)
- {
- if ((*itr)->getPowerType() == POWER_MANA)
- {
- PrioritizeManaUnitWraper WTarget(*itr);
- manaUsers.push(WTarget);
- }
- }
-
- unitList.clear();
- while(!manaUsers.empty() && unitList.size()<10)
- {
- unitList.push_back(manaUsers.top().getUnit());
- manaUsers.pop();
- }
- break;
- }
- case 52759: // Ancestral Awakening
- {
- typedef std::priority_queue<PrioritizeHealthUnitWraper, std::vector<PrioritizeHealthUnitWraper>, PrioritizeHealth> TopHealth;
- TopHealth healedMembers;
- for (std::list<Unit*>::iterator itr = unitList.begin() ; itr != unitList.end(); ++itr)
- {
- PrioritizeHealthUnitWraper WTarget(*itr);
- healedMembers.push(WTarget);
- }
-
- unitList.clear();
- while(!healedMembers.empty() && unitList.size()<1)
- {
- unitList.push_back(healedMembers.top().getUnit());
- healedMembers.pop();
- }
- break;
- }
- }
- if (m_spellInfo->EffectImplicitTargetA[i] == TARGET_DEST_TARGET_ANY
- && m_spellInfo->EffectImplicitTargetB[i] == TARGET_UNIT_AREA_ALLY_DST)// Wild Growth, Circle of Healing, Glyph of holy light target special selection
- {
- typedef std::priority_queue<PrioritizeHealthUnitWraper, std::vector<PrioritizeHealthUnitWraper>, PrioritizeHealth> TopHealth;
- TopHealth healedMembers;
- for (std::list<Unit*>::iterator itr = unitList.begin() ; itr != unitList.end(); ++itr)
- {
- if ((*itr)->IsInRaidWith(m_targets.getUnitTarget()))
- {
- PrioritizeHealthUnitWraper WTarget(*itr);
- healedMembers.push(WTarget);
- }
- }
-
- unitList.clear();
- uint32 maxsize = 5;
-
- if (m_spellInfo->SpellFamilyName == SPELLFAMILY_DRUID && m_spellInfo->SpellFamilyFlags[1] & 0x04000000) // Wild Growth
- maxsize += m_caster->HasAura(62970) ? 1 : 0; // Glyph of Wild Growth
-
- if (m_spellInfo->SpellFamilyName == SPELLFAMILY_PRIEST && m_spellInfo->SpellFamilyFlags[0] & 0x10000000 && m_spellInfo->SpellIconID == 2214) // Circle of Healing
- maxsize += m_caster->HasAura(55675) ? 1 : 0; // Glyph of Circle of Healing
-
- while(!healedMembers.empty() && unitList.size()<maxsize)
- {
- unitList.push_back(healedMembers.top().getUnit());
- healedMembers.pop();
- }
- }
- // Death Pact
- if (m_spellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && m_spellInfo->SpellFamilyFlags[0] & 0x00080000)
- {
- Unit * unit_to_add = NULL;
- for (std::list<Unit*>::iterator itr = unitList.begin() ; itr != unitList.end(); ++itr)
- {
- if ((*itr)->GetTypeId() == TYPEID_UNIT
- && (*itr)->GetOwnerGUID() == m_caster->GetGUID()
- && ((Creature*)(*itr))->GetCreatureInfo()->type == CREATURE_TYPE_UNDEAD)
- {
- unit_to_add = (*itr);
- break;
- }
- }
- if (unit_to_add)
- {
- unitList.clear();
- unitList.push_back(unit_to_add);
- }
- // Pet not found - remove cooldown
- else
- {
- if (modOwner->GetTypeId() == TYPEID_PLAYER)
- modOwner->RemoveSpellCooldown(m_spellInfo->Id,true);
- SendCastResult(SPELL_FAILED_NO_PET);
- finish(false);
- }
- }
- }
- for (std::list<Unit*>::iterator itr = unitList.begin(); itr != unitList.end(); ++itr)
- AddUnitTarget(*itr, i);
- }
- }
-}
-
-void Spell::prepare(SpellCastTargets const* targets, AuraEffect const * triggeredByAura)
-{
- if (m_CastItem)
- m_castItemGUID = m_CastItem->GetGUID();
- else
- m_castItemGUID = 0;
-
- m_targets = *targets;
-
- if (!m_targets.getUnitTargetGUID() && m_spellInfo->Targets & TARGET_FLAG_UNIT)
- {
- Unit *target = NULL;
- if(m_caster->GetTypeId() == TYPEID_UNIT)
- target = m_caster->getVictim();
- else
- target = ObjectAccessor::GetUnit(*m_caster, ((Player*)m_caster)->GetSelection());
-
- if (target && IsValidSingleTargetSpell(target))
- m_targets.setUnitTarget(target);
- else
- {
- SendCastResult(SPELL_FAILED_BAD_TARGETS);
- finish(false);
- return;
- }
- }
-
- // Fill aura scaling information
- if (m_caster->IsControlledByPlayer() && !IsPassiveSpell(m_spellInfo->Id) && m_spellInfo->spellLevel && !IsChanneledSpell(m_spellInfo) && !m_IsTriggeredSpell)
- {
- for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
- {
- if (m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA)
- {
- // Change aura with ranks only if basepoints are taken from spellInfo and aura is positive
- if (IsPositiveEffect(m_spellInfo->Id, i))
- {
- m_auraScaleMask |= (1<<i);
- if (m_currentBasePoints[i] != m_spellInfo->EffectBasePoints[i])
- {
- m_auraScaleMask = 0;
- break;
- }
- }
- }
- }
- }
-
- m_spellState = SPELL_STATE_PREPARING;
-
- if(triggeredByAura)
- m_triggeredByAuraSpell = triggeredByAura->GetSpellProto();
-
- // create and add update event for this spell
- SpellEvent* Event = new SpellEvent(this);
- m_caster->m_Events.AddEvent(Event, m_caster->m_Events.CalculateTime(1));
-
- //Prevent casting at cast another spell (ServerSide check)
- if(m_caster->IsNonMeleeSpellCasted(false, true, true) && m_cast_count)
- {
- SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS);
- finish(false);
- return;
- }
-
- if(m_caster->GetTypeId() == TYPEID_PLAYER)
- {
- if(objmgr.IsPlayerSpellDisabled(m_spellInfo->Id))
- {
- SendCastResult(SPELL_FAILED_SPELL_UNAVAILABLE);
- finish(false);
- return;
- }
- }
- else if (m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->isPet())
- {
- if(objmgr.IsPetSpellDisabled(m_spellInfo->Id))
- {
- SendCastResult(SPELL_FAILED_SPELL_UNAVAILABLE);
- finish(false);
- return;
- }
- }
- else
- {
- if(objmgr.IsCreatureSpellDisabled(m_spellInfo->Id))
- {
- finish(false);
- return;
- }
- }
-
- if (m_caster->GetTypeId() == TYPEID_PLAYER)
- ((Player*)m_caster)->SetSpellModTakingSpell(this, true);
- // Fill cost data (not use power for item casts
- m_powerCost = m_CastItem ? 0 : CalculatePowerCost(m_spellInfo, m_caster, m_spellSchoolMask);
- if (m_caster->GetTypeId() == TYPEID_PLAYER)
- ((Player*)m_caster)->SetSpellModTakingSpell(this, false);
-
- SpellCastResult result = CheckCast(true);
- if(result != SPELL_CAST_OK && !IsAutoRepeat()) //always cast autorepeat dummy for triggering
- {
- if(triggeredByAura)
- {
- SendChannelUpdate(0);
- triggeredByAura->GetBase()->SetDuration(0);
- }
- SendCastResult(result);
-
- finish(false);
- return;
- }
-
- // Prepare data for triggers
- prepareDataForTriggerSystem(triggeredByAura);
-
- // Set combo point requirement
- if (m_IsTriggeredSpell || m_CastItem || !m_caster->m_movedPlayer)
- m_needComboPoints = false;
-
- // calculate cast time (calculated after first CheckCast check to prevent charge counting for first CheckCast fail)
- m_casttime = GetSpellCastTime(m_spellInfo, this);
- //m_caster->ModSpellCastTime(m_spellInfo, m_casttime, this);
-
- // set timer base at cast time
- ReSetTimer();
-
- sLog.outDebug("Spell::prepare: spell id %u source %u caster %d triggered %u mask %u", m_spellInfo->Id, m_caster->GetEntry(), m_originalCaster ? m_originalCaster->GetEntry() : -1, m_IsTriggeredSpell ? 1 : 0, m_targets.m_targetMask);
- //if(m_targets.getUnitTarget())
- // sLog.outError("Spell::prepare: unit target %u", m_targets.getUnitTarget()->GetEntry());
- //if(m_targets.HasDst())
- // sLog.outError("Spell::prepare: pos target %f %f %f", m_targets.m_dstPos.m_positionX, m_targets.m_dstPos.m_positionY, m_targets.m_dstPos.m_positionZ);
-
- //Containers for channeled spells have to be set
- //TODO:Apply this to all casted spells if needed
- // Why check duration? 29350: channelled triggers channelled
- if(m_IsTriggeredSpell && (!IsChanneledSpell(m_spellInfo) || !GetSpellMaxDuration(m_spellInfo)))
- cast(true);
- else
- {
- // stealth must be removed at cast starting (at show channel bar)
- // skip triggered spell (item equip spell casting and other not explicit character casts/item uses)
- if(!m_IsTriggeredSpell && isSpellBreakStealth(m_spellInfo) )
- {
- m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CAST);
- for (uint32 i = 0; i < 3; ++i)
- {
- if(EffectTargetType[m_spellInfo->Effect[i]] == SPELL_REQUIRE_UNIT)
- {
- m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_SPELL_ATTACK);
- break;
- }
- }
- }
-
- m_caster->SetCurrentCastedSpell( this );
- SendSpellStart();
-
- if(!m_casttime && !m_spellInfo->StartRecoveryTime
- && !m_castItemGUID //item: first cast may destroy item and second cast causes crash
- && GetCurrentContainer() == CURRENT_GENERIC_SPELL)
- cast(true);
- }
-}
-
-void Spell::cancel()
-{
- if(m_spellState == SPELL_STATE_FINISHED)
- return;
-
- SetReferencedFromCurrent(false);
- if(m_selfContainer && *m_selfContainer == this)
- *m_selfContainer = NULL;
-
- uint32 oldState = m_spellState;
- m_spellState = SPELL_STATE_FINISHED;
-
- m_autoRepeat = false;
- switch (oldState)
- {
- case SPELL_STATE_PREPARING:
- case SPELL_STATE_DELAYED:
- {
- SendInterrupted(0);
- SendCastResult(SPELL_FAILED_INTERRUPTED);
- } break;
-
- case SPELL_STATE_CASTING:
- {
- for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
- if ((*ihit).missCondition == SPELL_MISS_NONE)
- if (Unit* unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID))
- unit->RemoveOwnedAura(m_spellInfo->Id, m_originalCasterGUID, 0, AURA_REMOVE_BY_CANCEL);
-
- SendChannelUpdate(0);
- SendInterrupted(0);
- SendCastResult(SPELL_FAILED_INTERRUPTED);
-
- // spell is canceled-take mods and clear list
- if (m_caster->GetTypeId() == TYPEID_PLAYER)
- ((Player*)m_caster)->RemoveSpellMods(this);
-
- m_appliedMods.clear();
- } break;
-
- default:
- {
- } break;
- }
-
- m_caster->RemoveDynObject(m_spellInfo->Id);
- m_caster->RemoveGameObject(m_spellInfo->Id,true);
-
- //set state back so finish will be processed
- m_spellState = oldState;
-
- finish(false);
-}
-
-void Spell::cast(bool skipCheck)
-{
- // update pointers base at GUIDs to prevent access to non-existed already object
- UpdatePointers();
-
- if(Unit *target = m_targets.getUnitTarget())
- {
- // three check: prepare, cast (m_casttime > 0), hit (delayed)
- if(m_casttime && target->isAlive()
- && (target->m_invisibilityMask || m_caster->m_invisibilityMask
- || target->GetVisibility() == VISIBILITY_GROUP_STEALTH)
- && !target->IsFriendlyTo(m_caster) && !m_caster->canSeeOrDetect(target, true))
- {
- SendCastResult(SPELL_FAILED_BAD_TARGETS);
- SendInterrupted(0);
- finish(false);
- return;
- }
- }
- else
- {
- // cancel at lost main target unit
- if(m_targets.getUnitTargetGUID() && m_targets.getUnitTargetGUID() != m_caster->GetGUID())
- {
- cancel();
- return;
- }
- }
-
- SetExecutedCurrently(true);
-
- if(m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster)
- m_caster->SetInFront(m_targets.getUnitTarget());
-
- // Should this be done for original caster?
- if (m_caster->GetTypeId() == TYPEID_PLAYER)
- {
- // Set spell which will drop charges for triggered cast spells
- // if not successfully casted, will be remove in finish(false)
- ((Player*)m_caster)->SetSpellModTakingSpell(this, true);
- }
-
- // triggered cast called from Spell::prepare where it was already checked
- if(!m_IsTriggeredSpell || !skipCheck)
- {
- SpellCastResult castResult = CheckCast(false);
- if(castResult != SPELL_CAST_OK)
- {
- SendCastResult(castResult);
- SendInterrupted(0);
- //restore spell mods
- if (m_caster->GetTypeId() == TYPEID_PLAYER)
- {
- ((Player*)m_caster)->RestoreSpellMods(this);
- // cleanup after mod system
- // triggered spell pointer can be not removed in some cases
- ((Player*)m_caster)->SetSpellModTakingSpell(this, false);
- }
- finish(false);
- SetExecutedCurrently(false);
- return;
- }
- }
-
- SelectSpellTargets();
-
- // Spell may be finished after target map check
- if(m_spellState == SPELL_STATE_FINISHED)
- {
- SendInterrupted(0);
- //restore spell mods
- if (m_caster->GetTypeId() == TYPEID_PLAYER)
- {
- ((Player*)m_caster)->RestoreSpellMods(this);
- // cleanup after mod system
- // triggered spell pointer can be not removed in some cases
- ((Player*)m_caster)->SetSpellModTakingSpell(this, false);
- }
- finish(false);
- SetExecutedCurrently(false);
- return;
- }
-
- if(m_spellInfo->SpellFamilyName)
- {
- if (m_spellInfo->excludeCasterAuraSpell && !IsPositiveSpell(m_spellInfo->excludeCasterAuraSpell))
- m_preCastSpell = m_spellInfo->excludeCasterAuraSpell;
- else if (m_spellInfo->excludeTargetAuraSpell && !IsPositiveSpell(m_spellInfo->excludeTargetAuraSpell))
- m_preCastSpell = m_spellInfo->excludeTargetAuraSpell;
- }
- switch (m_spellInfo->SpellFamilyName)
- {
- case SPELLFAMILY_GENERIC:
- {
- if (m_spellInfo->Mechanic == MECHANIC_BANDAGE) // Bandages
- m_preCastSpell = 11196; // Recently Bandaged
- break;
- }
- case SPELLFAMILY_MAGE:
- {
- // Permafrost
- if (m_spellInfo->SpellFamilyFlags[1] & 0x00001000 || m_spellInfo->SpellFamilyFlags[0] & 0x00100220)
- m_preCastSpell = 68391;
- break;
- }
- }
- // traded items have trade slot instead of guid in m_itemTargetGUID
- // set to real guid to be sent later to the client
- m_targets.updateTradeSlotItem();
-
- if (m_caster->GetTypeId() == TYPEID_PLAYER)
- {
- if (!m_IsTriggeredSpell && m_CastItem)
- ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM, m_CastItem->GetEntry());
-
- ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id);
- }
-
- if(!m_IsTriggeredSpell)
- {
- // Powers have to be taken before SendSpellGo
- TakePower();
- TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot
- }
-
- // are there any spells need to be triggered after hit?
- // handle SPELL_AURA_ADD_TARGET_TRIGGER auras
- Unit::AuraEffectList const& targetTriggers = m_caster->GetAuraEffectsByType(SPELL_AURA_ADD_TARGET_TRIGGER);
- for (Unit::AuraEffectList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i)
- {
- if (!(*i)->IsAffectedOnSpell(m_spellInfo))
- continue;
- SpellEntry const *auraSpellInfo = (*i)->GetSpellProto();
- uint32 auraSpellIdx = (*i)->GetEffIndex();
- if(SpellEntry const *spellInfo = sSpellStore.LookupEntry(auraSpellInfo->EffectTriggerSpell[auraSpellIdx]))
- {
- // Calculate chance at that moment (can be depend for example from combo points)
- int32 chance = m_caster->CalculateSpellDamage(auraSpellInfo, auraSpellIdx, (*i)->GetBaseAmount(), NULL);
- m_ChanceTriggerSpells.push_back(std::make_pair(spellInfo, chance * (*i)->GetBase()->GetStackAmount()));
- }
- }
-
- if(m_customAttr & SPELL_ATTR_CU_DIRECT_DAMAGE)
- CalculateDamageDoneForAllTargets();
-
- // CAST SPELL
- SendSpellCooldown();
-
- for (uint32 i = 0; i < 3; ++i)
- {
- switch(m_spellInfo->Effect[i])
- {
- case SPELL_EFFECT_CHARGE:
- case SPELL_EFFECT_JUMP:
- case SPELL_EFFECT_JUMP2:
- case SPELL_EFFECT_LEAP_BACK:
- case SPELL_EFFECT_ACTIVATE_RUNE:
- HandleEffects(NULL,NULL,NULL,i);
- m_effectMask |= (1<<i);
- break;
- }
- }
-
- // we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()...
- SendSpellGo();
-
- // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells
- if (m_spellInfo->speed > 0.0f && !IsChanneledSpell(m_spellInfo) || m_spellInfo->Id == 14157)
- {
- // Remove used for cast item if need (it can be already NULL after TakeReagents call
- // in case delayed spell remove item at cast delay start
- TakeCastItem();
-
- // Okay, maps created, now prepare flags
- m_immediateHandled = false;
- m_spellState = SPELL_STATE_DELAYED;
- SetDelayStart(0);
-
- if(m_caster->hasUnitState(UNIT_STAT_CASTING) && !m_caster->IsNonMeleeSpellCasted(false, false, true))
- m_caster->clearUnitState(UNIT_STAT_CASTING);
- }
- else
- {
- // Immediate spell, no big deal
- handle_immediate();
- }
-
- if(m_customAttr & SPELL_ATTR_CU_LINK_CAST)
- {
- if(const std::vector<int32> *spell_triggered = spellmgr.GetSpellLinked(m_spellInfo->Id))
- for (std::vector<int32>::const_iterator i = spell_triggered->begin(); i != spell_triggered->end(); ++i)
- if(*i < 0)
- m_caster->RemoveAurasDueToSpell(-(*i));
- else
- m_caster->CastSpell(m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster, *i, true);
-
- }
- if (m_caster->GetTypeId() == TYPEID_PLAYER)
- ((Player*)m_caster)->SetSpellModTakingSpell(this, false);
-
- SetExecutedCurrently(false);
-}
-
-void Spell::handle_immediate()
-{
- // start channeling if applicable
- if(IsChanneledSpell(m_spellInfo))
- {
- int32 duration = GetSpellDuration(m_spellInfo);
- if (duration)
- {
- // Apply haste mods
- m_caster->ModSpellCastTime(m_spellInfo, duration, this);
- // Apply duration mod
- if(Player* modOwner = m_caster->GetSpellModOwner())
- modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration);
- m_spellState = SPELL_STATE_CASTING;
- m_caster->AddInterruptMask(m_spellInfo->ChannelInterruptFlags);
- SendChannelStart(duration);
- }
- }
-
- // process immediate effects (items, ground, etc.) also initialize some variables
- _handle_immediate_phase();
-
- for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
- DoAllEffectOnTarget(&(*ihit));
-
- for (std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit)
- DoAllEffectOnTarget(&(*ihit));
-
- // spell is finished, perform some last features of the spell here
- _handle_finish_phase();
-
- // Remove used for cast item if need (it can be already NULL after TakeReagents call
- TakeCastItem();
-
- if(m_spellState != SPELL_STATE_CASTING)
- finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell)
-}
-
-uint64 Spell::handle_delayed(uint64 t_offset)
-{
- UpdatePointers();
-
- if (m_caster->GetTypeId() == TYPEID_PLAYER)
- ((Player*)m_caster)->SetSpellModTakingSpell(this, true);
-
- uint64 next_time = 0;
-
- if (!m_immediateHandled)
- {
- _handle_immediate_phase();
- m_immediateHandled = true;
- }
-
- bool single_missile = (m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION);
-
- // now recheck units targeting correctness (need before any effects apply to prevent adding immunity at first effect not allow apply second spell effect and similar cases)
- for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
- {
- if (ihit->processed == false)
- {
- if ( single_missile || ihit->timeDelay <= t_offset )
- DoAllEffectOnTarget(&(*ihit));
- else if( next_time == 0 || ihit->timeDelay < next_time )
- next_time = ihit->timeDelay;
- }
- }
-
- // now recheck gameobject targeting correctness
- for (std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit)
- {
- if (ighit->processed == false)
- {
- if ( single_missile || ighit->timeDelay <= t_offset )
- DoAllEffectOnTarget(&(*ighit));
- else if( next_time == 0 || ighit->timeDelay < next_time )
- next_time = ighit->timeDelay;
- }
- }
-
- if (m_caster->GetTypeId() == TYPEID_PLAYER)
- ((Player*)m_caster)->SetSpellModTakingSpell(this, false);
-
- // All targets passed - need finish phase
- if (next_time == 0)
- {
- // spell is finished, perform some last features of the spell here
- _handle_finish_phase();
-
- finish(true); // successfully finish spell cast
-
- // return zero, spell is finished now
- return 0;
- }
- else
- {
- // spell is unfinished, return next execution time
- return next_time;
- }
-}
-
-void Spell::_handle_immediate_phase()
-{
- m_spellAura = NULL;
- // handle some immediate features of the spell here
- HandleThreatSpells(m_spellInfo->Id);
-
- m_needSpellLog = IsNeedSendToClient();
- for (uint32 j = 0; j < 3; ++j)
- {
- if(m_spellInfo->Effect[j] == 0)
- continue;
-
- // apply Send Event effect to ground in case empty target lists
- if( m_spellInfo->Effect[j] == SPELL_EFFECT_SEND_EVENT && !HaveTargetsForEffect(j) )
- {
- HandleEffects(NULL, NULL, NULL, j);
- continue;
- }
-
- // Don't do spell log, if is school damage spell
- if(m_spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE || m_spellInfo->Effect[j] == 0)
- m_needSpellLog = false;
- }
-
- // initialize Diminishing Returns Data
- m_diminishLevel = DIMINISHING_LEVEL_1;
- m_diminishGroup = DIMINISHING_NONE;
-
- // process items
- for (std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit)
- DoAllEffectOnTarget(&(*ihit));
-
- if(!m_originalCaster)
- return;
- uint8 oldEffMask = m_effectMask;
- // process ground
- for (uint32 j = 0; j < 3; ++j)
- {
- if(EffectTargetType[m_spellInfo->Effect[j]] == SPELL_REQUIRE_DEST)
- {
- if(!m_targets.HasDst()) // FIXME: this will ignore dest set in effect
- m_targets.setDst(m_caster);
- HandleEffects(m_originalCaster, NULL, NULL, j);
- m_effectMask |= (1<<j);
- }
- else if(EffectTargetType[m_spellInfo->Effect[j]] == SPELL_REQUIRE_NONE)
- {
- HandleEffects(m_originalCaster, NULL, NULL, j);
- m_effectMask |= (1<<j);
- }
- }
- if (oldEffMask != m_effectMask && m_UniqueTargetInfo.empty())
- {
- uint32 procAttacker = m_procAttacker;
- if (!procAttacker)
- {
- bool positive = true;
- for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i)
- // If at least one effect negative spell is negative hit
- if (m_effectMask & (1<<i) && !IsPositiveEffect(m_spellInfo->Id, i))
- {
- positive = false;
- break;
- }
- switch(m_spellInfo->DmgClass)
- {
- case SPELL_DAMAGE_CLASS_MAGIC:
- if (positive)
- procAttacker |= PROC_FLAG_SUCCESSFUL_POSITIVE_MAGIC_SPELL;
- else
- procAttacker |= PROC_FLAG_SUCCESSFUL_NEGATIVE_MAGIC_SPELL;
- break;
- case SPELL_DAMAGE_CLASS_NONE:
- if (positive)
- procAttacker |= PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL_HIT;
- else
- procAttacker |= PROC_FLAG_SUCCESSFUL_NEGATIVE_SPELL_HIT;
- break;
- }
- }
- // Proc damage for spells which have only dest targets (2484 should proc 51486 for example)
- m_originalCaster->ProcDamageAndSpell(0, procAttacker, 0, m_procEx | PROC_EX_NORMAL_HIT, 0, BASE_ATTACK, m_spellInfo, m_triggeredByAuraSpell);
- }
-}
-
-void Spell::_handle_finish_phase()
-{
- if(m_caster->m_movedPlayer)
- {
- // Take for real after all targets are processed
- if (m_needComboPoints)
- m_caster->m_movedPlayer->ClearComboPoints();
-
- // Real add combo points from effects
- if (m_comboPointGain)
- m_caster->m_movedPlayer->GainSpellComboPoints(m_comboPointGain);
- }
-
- // spell log
- if(m_needSpellLog)
- SendLogExecute();
-}
-
-void Spell::SendSpellCooldown()
-{
- if(m_caster->GetTypeId() != TYPEID_PLAYER)
- return;
-
- Player* _player = (Player*)m_caster;
-
- // mana/health/etc potions, disabled by client (until combat out as declarate)
- if (m_CastItem && m_CastItem->IsPotion())
- {
- // need in some way provided data for Spell::finish SendCooldownEvent
- _player->SetLastPotionId(m_CastItem->GetEntry());
- return;
- }
-
- // have infinity cooldown but set at aura apply // do not set cooldown for triggered spells (needed by reincarnation)
- if(m_spellInfo->Attributes & (SPELL_ATTR_DISABLED_WHILE_ACTIVE | SPELL_ATTR_PASSIVE ) || m_IsTriggeredSpell)
- return;
-
- _player->AddSpellAndCategoryCooldowns(m_spellInfo,m_CastItem ? m_CastItem->GetEntry() : 0, this);
-}
-
-void Spell::update(uint32 difftime)
-{
- // update pointers based at it's GUIDs
- UpdatePointers();
-
- if(m_targets.getUnitTargetGUID() && !m_targets.getUnitTarget())
- {
- sLog.outDebug("Spell %u is cancelled due to removal of target.", m_spellInfo->Id);
- cancel();
- return;
- }
-
- // check if the player caster has moved before the spell finished
- if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) &&
- m_caster->isMoving() && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT) &&
- (m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING)))
- {
- // don't cancel for melee, autorepeat, triggered and instant spells
- if(!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !m_IsTriggeredSpell)
- cancel();
- }
-
- switch(m_spellState)
- {
- case SPELL_STATE_PREPARING:
- {
- if(m_timer)
- {
- if(difftime >= m_timer)
- m_timer = 0;
- else
- m_timer -= difftime;
- }
-
- if(m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat())
- cast(m_spellInfo->CastingTimeIndex == 1);
- } break;
- case SPELL_STATE_CASTING:
- {
- if(m_timer > 0)
- {
- // check if there are alive targets left
- if (!UpdateChanneledTargetList())
- {
- sLog.outDebug("Channeled spell %d is removed due to lack of targets", m_spellInfo->Id);
- SendChannelUpdate(0);
- finish();
- }
-
- if(difftime >= m_timer)
- m_timer = 0;
- else
- m_timer -= difftime;
- }
-
- if(m_timer == 0)
- {
- SendChannelUpdate(0);
-
- // channeled spell processed independently for quest targeting
- // cast at creature (or GO) quest objectives update at successful cast channel finished
- // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
- if( !IsAutoRepeat() && !IsNextMeleeSwingSpell() )
- {
- if ( Player* p = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself() )
- {
- for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
- {
- TargetInfo* target = &*ihit;
- if(!IS_CRE_OR_VEH_GUID(target->targetGUID))
- continue;
-
- Unit* unit = m_caster->GetGUID() == target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target->targetGUID);
- if (unit == NULL)
- continue;
-
- p->CastedCreatureOrGO(unit->GetEntry(), unit->GetGUID(), m_spellInfo->Id);
- }
-
- for (std::list<GOTargetInfo>::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit)
- {
- GOTargetInfo* target = &*ihit;
-
- GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID);
- if(!go)
- continue;
-
- p->CastedCreatureOrGO(go->GetEntry(), go->GetGUID(), m_spellInfo->Id);
- }
- }
- }
-
- finish();
- }
- } break;
- default:
- {
- }break;
- }
-}
-
-void Spell::finish(bool ok)
-{
- if(!m_caster)
- return;
-
- if(m_spellState == SPELL_STATE_FINISHED)
- return;
- m_spellState = SPELL_STATE_FINISHED;
-
- if(IsChanneledSpell(m_spellInfo))
- m_caster->UpdateInterruptMask();
-
- if(m_caster->hasUnitState(UNIT_STAT_CASTING) && !m_caster->IsNonMeleeSpellCasted(false, false, true))
- m_caster->clearUnitState(UNIT_STAT_CASTING);
-
- // Unsummon summon as possessed creatures on spell cancel
- if(IsChanneledSpell(m_spellInfo) && m_caster->GetTypeId() == TYPEID_PLAYER)
- {
- if(Unit *charm = m_caster->GetCharm())
- if(charm->GetTypeId() == TYPEID_UNIT
- && ((Creature*)charm)->HasUnitTypeMask(UNIT_MASK_PUPPET)
- && charm->GetUInt32Value(UNIT_CREATED_BY_SPELL) == m_spellInfo->Id)
- ((Puppet*)charm)->UnSummon();
- }
-
- if(!ok)
- return;
-
- if (m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->isSummon())
- {
- // Unsummon statue
- uint32 spell = m_caster->GetUInt32Value(UNIT_CREATED_BY_SPELL);
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell );
- if (spellInfo && spellInfo->SpellIconID==2056)
- {
- sLog.outDebug("Statue %d is unsummoned in spell %d finish", m_caster->GetGUIDLow(), m_spellInfo->Id);
- m_caster->setDeathState(JUST_DIED);
- return;
- }
- }
-
- // Okay to remove extra attacks
- if(IsSpellHaveEffect(m_spellInfo, SPELL_EFFECT_ADD_EXTRA_ATTACKS))
- m_caster->m_extraAttacks = 0;
-
- // Heal caster for all health leech from all targets
- if (m_healthLeech)
- m_caster->DealHeal(m_caster, uint32(m_healthLeech), m_spellInfo);
-
- if (IsMeleeAttackResetSpell())
- {
- bool found = false;
- Unit::AuraEffectList const& vIgnoreReset = m_caster->GetAuraEffectsByType(SPELL_AURA_IGNORE_MELEE_RESET);
- for (Unit::AuraEffectList::const_iterator i = vIgnoreReset.begin(); i != vIgnoreReset.end(); ++i)
- {
- if ((*i)->IsAffectedOnSpell(m_spellInfo))
- {
- found = true;
- break;
- }
- }
- if (!found)
- {
- m_caster->resetAttackTimer(BASE_ATTACK);
- if(m_caster->haveOffhandWeapon())
- m_caster->resetAttackTimer(OFF_ATTACK);
- if(!(m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_NOT_RESET_AUTOSHOT))
- m_caster->resetAttackTimer(RANGED_ATTACK);
- }
- }
-
- // potions disabled by client, send event "not in combat" if need
- if (m_caster->GetTypeId() == TYPEID_PLAYER)
- {
- if (!m_triggeredByAuraSpell)
- ((Player*)m_caster)->UpdatePotionCooldown(this);
-
- // triggered spell pointer can be not set in some cases
- // this is needed for proper apply of triggered spell mods
- ((Player*)m_caster)->SetSpellModTakingSpell(this, true);
- }
-
- // call triggered spell only at successful cast (after clear combo points -> for add some if need)
- // I assume what he means is that some triggered spells may add combo points
- if(!m_TriggerSpells.empty())
- TriggerSpell();
-
- // Take mods after trigger spell (needed for 14177 to affect 48664)
- // mods are taken only on succesfull cast and independantly from targets of the spell
- if (m_caster->GetTypeId() == TYPEID_PLAYER)
- {
- ((Player*)m_caster)->RemoveSpellMods(this);
- ((Player*)m_caster)->SetSpellModTakingSpell(this, false);
- }
-
- // Stop Attack for some spells
- if( m_spellInfo->Attributes & SPELL_ATTR_STOP_ATTACK_TARGET )
- m_caster->AttackStop();
-}
-
-void Spell::SendCastResult(SpellCastResult result)
-{
- if(result == SPELL_CAST_OK)
- return;
-
- if (m_caster->GetTypeId() != TYPEID_PLAYER)
- return;
-
- if(((Player*)m_caster)->GetSession()->PlayerLoading()) // don't send cast results at loading time
- return;
-
- SendCastResult((Player*)m_caster,m_spellInfo,m_cast_count,result);
-}
-
-void Spell::SendCastResult(Player* caster, SpellEntry const* spellInfo, uint8 cast_count, SpellCastResult result)
-{
- if(result == SPELL_CAST_OK)
- return;
-
- WorldPacket data(SMSG_CAST_FAILED, (4+1+1));
- data << uint8(cast_count); // single cast or multi 2.3 (0/1)
- data << uint32(spellInfo->Id);
- data << uint8(result); // problem
- switch (result)
- {
- case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
- data << uint32(spellInfo->RequiresSpellFocus);
- break;
- case SPELL_FAILED_REQUIRES_AREA:
- // hardcode areas limitation case
- switch(spellInfo->Id)
- {
- case 41617: // Cenarion Mana Salve
- case 41619: // Cenarion Healing Salve
- data << uint32(3905);
- break;
- case 41618: // Bottled Nethergon Energy
- case 41620: // Bottled Nethergon Vapor
- data << uint32(3842);
- break;
- case 45373: // Bloodberry Elixir
- data << uint32(4075);
- break;
- default: // default case (don't must be)
- data << uint32(0);
- break;
- }
- break;
- case SPELL_FAILED_TOTEMS:
- if(spellInfo->Totem[0])
- data << uint32(spellInfo->Totem[0]);
- if(spellInfo->Totem[1])
- data << uint32(spellInfo->Totem[1]);
- break;
- case SPELL_FAILED_TOTEM_CATEGORY:
- if(spellInfo->TotemCategory[0])
- data << uint32(spellInfo->TotemCategory[0]);
- if(spellInfo->TotemCategory[1])
- data << uint32(spellInfo->TotemCategory[1]);
- break;
- case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
- data << uint32(spellInfo->EquippedItemClass);
- data << uint32(spellInfo->EquippedItemSubClassMask);
- //data << uint32(spellInfo->EquippedItemInventoryTypeMask);
- break;
- case SPELL_FAILED_TOO_MANY_OF_ITEM:
- {
- uint32 item;
- for(int8 x=0;x < 3;x++)
- if (spellInfo->EffectItemType[x])
- item = spellInfo->EffectItemType[x];
- ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
- if (pProto && pProto->ItemLimitCategory)
- data << uint32(pProto->ItemLimitCategory);
- break;
- }
- default:
- break;
- }
- caster->GetSession()->SendPacket(&data);
-}
-
-void Spell::SendSpellStart()
-{
- if(!IsNeedSendToClient())
- return;
-
- //sLog.outDebug("Sending SMSG_SPELL_START id=%u", m_spellInfo->Id);
-
- uint32 castFlags = CAST_FLAG_UNKNOWN_2;
- if(m_spellInfo->Attributes & SPELL_ATTR_REQ_AMMO)
- castFlags |= CAST_FLAG_AMMO;
- if ((m_caster->GetTypeId() == TYPEID_PLAYER ||
- (m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->isPet()))
- && m_spellInfo->powerType != POWER_HEALTH )
- castFlags |= CAST_FLAG_POWER_LEFT_SELF;
-
- if(m_spellInfo->runeCostID && m_spellInfo->powerType == POWER_RUNE)
- castFlags |= CAST_FLAG_UNKNOWN_19;
-
- WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2));
- if(m_CastItem)
- data.append(m_CastItem->GetPackGUID());
- else
- data.append(m_caster->GetPackGUID());
-
- data.append(m_caster->GetPackGUID());
- data << uint8(m_cast_count); // pending spell cast?
- data << uint32(m_spellInfo->Id); // spellId
- data << uint32(castFlags); // cast flags
- data << uint32(m_timer); // delay?
-
- m_targets.write(&data);
-
- if(castFlags & CAST_FLAG_POWER_LEFT_SELF)
- data << uint32(m_caster->GetPower((Powers)m_spellInfo->powerType));
-
- if ( castFlags & CAST_FLAG_AMMO )
- WriteAmmoToPacket(&data);
-
- if ( castFlags & CAST_FLAG_UNKNOWN_23 )
- {
- data << uint32(0);
- data << uint32(0);
- }
-
- m_caster->SendMessageToSet(&data, true);
-}
-
-void Spell::SendSpellGo()
-{
- // not send invisible spell casting
- if(!IsNeedSendToClient())
- return;
-
- //sLog.outDebug("Sending SMSG_SPELL_GO id=%u", m_spellInfo->Id);
-
- uint32 castFlags = CAST_FLAG_UNKNOWN_9;
-
- // triggered spells with spell visual != 0
- if((m_IsTriggeredSpell && !IsAutoRepeatRangedSpell(m_spellInfo)) || m_triggeredByAuraSpell)
- castFlags |= CAST_FLAG_PENDING;
-
- if(m_spellInfo->Attributes & SPELL_ATTR_REQ_AMMO)
- castFlags |= CAST_FLAG_AMMO; // arrows/bullets visual
- if ((m_caster->GetTypeId() == TYPEID_PLAYER ||
- (m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->isPet()))
- && m_spellInfo->powerType != POWER_HEALTH )
- castFlags |= CAST_FLAG_POWER_LEFT_SELF; // should only be sent to self, but the current messaging doesn't make that possible
-
- if((m_caster->GetTypeId() == TYPEID_PLAYER)
- && (m_caster->getClass() == CLASS_DEATH_KNIGHT)
- && m_spellInfo->runeCostID
- && m_spellInfo->powerType == POWER_RUNE)
- {
- castFlags |= CAST_FLAG_UNKNOWN_19; // same as in SMSG_SPELL_START
- castFlags |= CAST_FLAG_RUNE_LIST; // rune cooldowns list
- castFlags |= CAST_FLAG_UNKNOWN_9; // ??
- }
-
- if (IsSpellHaveEffect(m_spellInfo, SPELL_EFFECT_ACTIVATE_RUNE))
- {
- castFlags |= CAST_FLAG_RUNE_LIST; // rune cooldowns list
- castFlags |= CAST_FLAG_UNKNOWN_19; // same as in SMSG_SPELL_START
- }
-
- WorldPacket data(SMSG_SPELL_GO, 50); // guess size
-
- if(m_CastItem)
- data.append(m_CastItem->GetPackGUID());
- else
- data.append(m_caster->GetPackGUID());
-
- data.append(m_caster->GetPackGUID());
- data << uint8(m_cast_count); // pending spell cast?
- data << uint32(m_spellInfo->Id); // spellId
- data << uint32(castFlags); // cast flags
- data << uint32(getMSTime()); // timestamp
-
- WriteSpellGoTargets(&data);
-
- m_targets.write(&data);
-
- if(castFlags & CAST_FLAG_POWER_LEFT_SELF)
- data << uint32(m_caster->GetPower((Powers)m_spellInfo->powerType));
-
- if ( castFlags & CAST_FLAG_RUNE_LIST ) // rune cooldowns list
- {
- uint8 v1 = m_runesState;
- uint8 v2 = ((Player*)m_caster)->GetRunesState();
- data << uint8(v1); // runes state before
- data << uint8(v2); // runes state after
- for (uint8 i = 0; i < MAX_RUNES; ++i)
- {
- uint8 m = (1 << i);
- if(m & v1) // usable before...
- if(!(m & v2)) // ...but on cooldown now...
- data << uint8(0); // some unknown byte (time?)
- }
- }
-
- if ( castFlags & CAST_FLAG_UNKNOWN_18 ) // unknown wotlk
- {
- data << float(0);
- data << uint32(0);
- }
-
- if ( castFlags & CAST_FLAG_AMMO )
- WriteAmmoToPacket(&data);
-
- if ( castFlags & CAST_FLAG_UNKNOWN_20 ) // unknown wotlk
- {
- data << uint32(0);
- data << uint32(0);
- }
-
- if ( m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION )
- {
- data << uint8(0);
- }
-
- m_caster->SendMessageToSet(&data, true);
-}
-
-void Spell::WriteAmmoToPacket( WorldPacket * data )
-{
- uint32 ammoInventoryType = 0;
- uint32 ammoDisplayID = 0;
-
- if (m_caster->GetTypeId() == TYPEID_PLAYER)
- {
- Item *pItem = ((Player*)m_caster)->GetWeaponForAttack( RANGED_ATTACK );
- if(pItem)
- {
- ammoInventoryType = pItem->GetProto()->InventoryType;
- if( ammoInventoryType == INVTYPE_THROWN )
- ammoDisplayID = pItem->GetProto()->DisplayInfoID;
- else
- {
- uint32 ammoID = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
- if(ammoID)
- {
- ItemPrototype const *pProto = objmgr.GetItemPrototype( ammoID );
- if(pProto)
- {
- ammoDisplayID = pProto->DisplayInfoID;
- ammoInventoryType = pProto->InventoryType;
- }
- }
- else if(m_caster->HasAura(46699)) // Requires No Ammo
- {
- ammoDisplayID = 5996; // normal arrow
- ammoInventoryType = INVTYPE_AMMO;
- }
- }
- }
- }
- else
- {
- for (uint8 i = 0; i < 3; ++i)
- {
- if(uint32 item_id = m_caster->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i))
- {
- if(ItemEntry const * itemEntry = sItemStore.LookupEntry(item_id))
- {
- if(itemEntry->Class==ITEM_CLASS_WEAPON)
- {
- switch(itemEntry->SubClass)
- {
- case ITEM_SUBCLASS_WEAPON_THROWN:
- ammoDisplayID = itemEntry->DisplayId;
- ammoInventoryType = itemEntry->InventoryType;
- break;
- case ITEM_SUBCLASS_WEAPON_BOW:
- case ITEM_SUBCLASS_WEAPON_CROSSBOW:
- ammoDisplayID = 5996; // is this need fixing?
- ammoInventoryType = INVTYPE_AMMO;
- break;
- case ITEM_SUBCLASS_WEAPON_GUN:
- ammoDisplayID = 5998; // is this need fixing?
- ammoInventoryType = INVTYPE_AMMO;
- break;
- }
-
- if(ammoDisplayID)
- break;
- }
- }
- }
- }
- }
-
- *data << uint32(ammoDisplayID);
- *data << uint32(ammoInventoryType);
-}
-
-void Spell::WriteSpellGoTargets( WorldPacket * data )
-{
- // This function also fill data for channeled spells:
- // m_needAliveTargetMask req for stop channelig if one target die
- uint32 hit = m_UniqueGOTargetInfo.size(); // Always hits on GO
- uint32 miss = 0;
- for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
- {
- if ((*ihit).effectMask == 0) // No effect apply - all immuned add state
- {
- // possibly SPELL_MISS_IMMUNE2 for this??
- ihit->missCondition = SPELL_MISS_IMMUNE2;
- ++miss;
- }
- else if ((*ihit).missCondition == SPELL_MISS_NONE)
- ++hit;
- else
- ++miss;
- }
-
- *data << (uint8)hit;
- for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
- {
- if ((*ihit).missCondition == SPELL_MISS_NONE) // Add only hits
- {
- *data << uint64(ihit->targetGUID);
- m_needAliveTargetMask |=ihit->effectMask;
- }
- }
-
- for (std::list<GOTargetInfo>::const_iterator ighit = m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit)
- *data << uint64(ighit->targetGUID); // Always hits
-
- *data << (uint8)miss;
- for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
- {
- if( ihit->missCondition != SPELL_MISS_NONE ) // Add only miss
- {
- *data << uint64(ihit->targetGUID);
- *data << uint8(ihit->missCondition);
- if( ihit->missCondition == SPELL_MISS_REFLECT )
- *data << uint8(ihit->reflectResult);
- }
- }
- // Reset m_needAliveTargetMask for non channeled spell
- if(!IsChanneledSpell(m_spellInfo))
- m_needAliveTargetMask = 0;
-}
-
-void Spell::SendLogExecute()
-{
- Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
-
- WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8));
-
- if(m_caster->GetTypeId() == TYPEID_PLAYER)
- data.append(m_caster->GetPackGUID());
- else
- data.append(target->GetPackGUID());
-
- data << uint32(m_spellInfo->Id);
- uint32 count1 = 1;
- data << uint32(count1); // count1 (effect count?)
- for (uint32 i = 0; i < count1; ++i)
- {
- data << uint32(m_spellInfo->Effect[0]); // spell effect
- uint32 count2 = 1;
- data << uint32(count2); // count2 (target count?)
- for (uint32 j = 0; j < count2; ++j)
- {
- switch(m_spellInfo->Effect[0])
- {
- case SPELL_EFFECT_POWER_DRAIN:
- if(Unit *unit = m_targets.getUnitTarget())
- data.append(unit->GetPackGUID());
- else
- data << uint8(0);
- data << uint32(0);
- data << uint32(0);
- data << float(0);
- break;
- case SPELL_EFFECT_ADD_EXTRA_ATTACKS:
- if(Unit *unit = m_targets.getUnitTarget())
- data.append(unit->GetPackGUID());
- else
- data << uint8(0);
- data << uint32(m_caster->m_extraAttacks);
- break;
- case SPELL_EFFECT_INTERRUPT_CAST:
- if(Unit *unit = m_targets.getUnitTarget())
- data.append(unit->GetPackGUID());
- else
- data << uint8(0);
- data << uint32(0); // spellid
- break;
- case SPELL_EFFECT_DURABILITY_DAMAGE:
- if(Unit *unit = m_targets.getUnitTarget())
- data.append(unit->GetPackGUID());
- else
- data << uint8(0);
- data << uint32(0);
- data << uint32(0);
- break;
- case SPELL_EFFECT_OPEN_LOCK:
- if(Item *item = m_targets.getItemTarget())
- data.append(item->GetPackGUID());
- else
- data << uint8(0);
- break;
- case SPELL_EFFECT_CREATE_ITEM:
- case SPELL_EFFECT_CREATE_ITEM_2:
- data << uint32(m_spellInfo->EffectItemType[0]);
- break;
- case SPELL_EFFECT_SUMMON:
- case SPELL_EFFECT_TRANS_DOOR:
- case SPELL_EFFECT_SUMMON_PET:
- case SPELL_EFFECT_SUMMON_OBJECT_WILD:
- case SPELL_EFFECT_CREATE_HOUSE:
- case SPELL_EFFECT_DUEL:
- case SPELL_EFFECT_SUMMON_OBJECT_SLOT1:
- case SPELL_EFFECT_SUMMON_OBJECT_SLOT2:
- case SPELL_EFFECT_SUMMON_OBJECT_SLOT3:
- case SPELL_EFFECT_SUMMON_OBJECT_SLOT4:
- if(Unit *unit = m_targets.getUnitTarget())
- data.append(unit->GetPackGUID());
- else if(m_targets.getItemTargetGUID())
- data.appendPackGUID(m_targets.getItemTargetGUID());
- else if(GameObject *go = m_targets.getGOTarget())
- data.append(go->GetPackGUID());
- else
- data << uint8(0); // guid
- break;
- case SPELL_EFFECT_FEED_PET:
- data << uint32(m_targets.getItemTargetEntry());
- break;
- case SPELL_EFFECT_DISMISS_PET:
- if(Unit *unit = m_targets.getUnitTarget())
- data.append(unit->GetPackGUID());
- else
- data << uint8(0);
- break;
- case SPELL_EFFECT_RESURRECT:
- case SPELL_EFFECT_RESURRECT_NEW:
- if(Unit *unit = m_targets.getUnitTarget())
- data.append(unit->GetPackGUID());
- else
- data << uint8(0);
- break;
- default:
- return;
- }
- }
- }
-
- m_caster->SendMessageToSet(&data, true);
-}
-
-void Spell::SendInterrupted(uint8 result)
-{
- WorldPacket data(SMSG_SPELL_FAILURE, (8+4+1));
- data.append(m_caster->GetPackGUID());
- data << uint8(m_cast_count);
- data << uint32(m_spellInfo->Id);
- data << uint8(result);
- m_caster->SendMessageToSet(&data, true);
-
- data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+4));
- data.append(m_caster->GetPackGUID());
- data << uint8(m_cast_count);
- data << uint32(m_spellInfo->Id);
- data << uint8(result);
- m_caster->SendMessageToSet(&data, true);
-}
-
-void Spell::SendChannelUpdate(uint32 time)
-{
- if(time == 0)
- {
- m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
- m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, 0);
- }
-
- if (m_caster->GetTypeId() != TYPEID_PLAYER)
- return;
-
- WorldPacket data( MSG_CHANNEL_UPDATE, 8+4 );
- data.append(m_caster->GetPackGUID());
- data << uint32(time);
-
- m_caster->SendMessageToSet(&data, true);
-}
-
-void Spell::SendChannelStart(uint32 duration)
-{
- WorldObject* target = NULL;
-
- // select first not resisted target from target list for _0_ effect
- if(!m_UniqueTargetInfo.empty())
- {
- for (std::list<TargetInfo>::const_iterator itr = m_UniqueTargetInfo.begin(); itr != m_UniqueTargetInfo.end(); ++itr)
- {
- if( (itr->effectMask & (1 << 0)) && itr->reflectResult == SPELL_MISS_NONE && itr->targetGUID != m_caster->GetGUID())
- {
- target = ObjectAccessor::GetUnit(*m_caster, itr->targetGUID);
- break;
- }
- }
- }
- else if(!m_UniqueGOTargetInfo.empty())
- {
- for (std::list<GOTargetInfo>::const_iterator itr = m_UniqueGOTargetInfo.begin(); itr != m_UniqueGOTargetInfo.end(); ++itr)
- {
- if(itr->effectMask & (1 << 0) )
- {
- target = m_caster->GetMap()->GetGameObject(itr->targetGUID);
- break;
- }
- }
- }
-
- WorldPacket data( MSG_CHANNEL_START, (8+4+4) );
- data.append(m_caster->GetPackGUID());
- data << uint32(m_spellInfo->Id);
- data << uint32(duration);
-
- m_caster->SendMessageToSet(&data, true);
-
- m_timer = duration;
- if(target)
- m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, target->GetGUID());
- m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id);
-}
-
-void Spell::SendResurrectRequest(Player* target)
-{
- // Both players and NPCs can resurrect using spells - have a look at creature 28487 for example
- // However, the packet structure differs slightly
-
- const char* sentName = m_caster->GetTypeId() == TYPEID_PLAYER ? "" : m_caster->GetNameForLocaleIdx(target->GetSession()->GetSessionDbLocaleIndex());
-
- WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+strlen(sentName)+1+1+1));
- data << uint64(m_caster->GetGUID());
- data << uint32(strlen(sentName) + 1);
-
- data << sentName;
- data << uint8(0);
-
- data << uint8(m_caster->GetTypeId() == TYPEID_PLAYER ? 0 : 1);
- target->GetSession()->SendPacket(&data);
-}
-
-void Spell::SendPlaySpellVisual(uint32 SpellID)
-{
- if (m_caster->GetTypeId() != TYPEID_PLAYER)
- return;
-
- WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 8 + 4);
- data << uint64(m_caster->GetGUID());
- data << uint32(SpellID); // spell visual id?
- ((Player*)m_caster)->GetSession()->SendPacket(&data);
-}
-
-void Spell::TakeCastItem()
-{
- if(!m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER)
- return;
-
- // not remove cast item at triggered spell (equipping, weapon damage, etc)
- if(m_IsTriggeredSpell)
- return;
-
- ItemPrototype const *proto = m_CastItem->GetProto();
-
- if(!proto)
- {
- // This code is to avoid a crash
- // I'm not sure, if this is really an error, but I guess every item needs a prototype
- sLog.outError("Cast item has no item prototype highId=%d, lowId=%d",m_CastItem->GetGUIDHigh(), m_CastItem->GetGUIDLow());
- return;
- }
-
- bool expendable = false;
- bool withoutCharges = false;
-
- for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
- {
- if (proto->Spells[i].SpellId)
- {
- // item has limited charges
- if (proto->Spells[i].SpellCharges)
- {
- if (proto->Spells[i].SpellCharges < 0)
- expendable = true;
-
- int32 charges = m_CastItem->GetSpellCharges(i);
-
- // item has charges left
- if (charges)
- {
- (charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use
- if (proto->Stackable == 1)
- m_CastItem->SetSpellCharges(i, charges);
- m_CastItem->SetState(ITEM_CHANGED, (Player*)m_caster);
- }
-
- // all charges used
- withoutCharges = (charges == 0);
- }
- }
- }
-
- if (expendable && withoutCharges)
- {
- uint32 count = 1;
- ((Player*)m_caster)->DestroyItemCount(m_CastItem, count, true);
-
- // prevent crash at access to deleted m_targets.getItemTarget
- if(m_CastItem==m_targets.getItemTarget())
- m_targets.setItemTarget(NULL);
-
- m_CastItem = NULL;
- }
-}
-
-void Spell::TakePower()
-{
- if(m_CastItem || m_triggeredByAuraSpell)
- return;
-
- bool hit = true;
- if(m_caster->GetTypeId() == TYPEID_PLAYER)
- {
- if(m_spellInfo->powerType == POWER_RAGE || m_spellInfo->powerType == POWER_ENERGY)
- if(uint64 targetGUID = m_targets.getUnitTargetGUID())
- for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
- if(ihit->targetGUID == targetGUID)
- {
- if(ihit->missCondition != SPELL_MISS_NONE && ihit->missCondition != SPELL_MISS_MISS/* && ihit->targetGUID!=m_caster->GetGUID()*/)
- hit = false;
- if (ihit->missCondition != SPELL_MISS_NONE)
- {
- //lower spell cost on fail (by talent aura)
- if(Player *modOwner = ((Player*)m_caster)->GetSpellModOwner())
- modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_SPELL_COST_REFUND_ON_FAIL, m_powerCost);
- }
- break;
- }
- }
-
- Powers powerType = Powers(m_spellInfo->powerType);
-
- if(hit && powerType == POWER_RUNE)
- {
- TakeRunePower();
- return;
- }
-
- if (!m_powerCost)
- return;
-
- // health as power used
- if(m_spellInfo->powerType == POWER_HEALTH)
- {
- m_caster->ModifyHealth( -(int32)m_powerCost );
- return;
- }
-
- if(m_spellInfo->powerType >= MAX_POWERS)
- {
- sLog.outError("Spell::TakePower: Unknown power type '%d'", m_spellInfo->powerType);
- return;
- }
-
- if(hit)
- m_caster->ModifyPower(powerType, -m_powerCost);
- else
- m_caster->ModifyPower(powerType, -irand(0, m_powerCost/4));
-
- // Set the five second timer
- if (powerType == POWER_MANA && m_powerCost > 0)
- m_caster->SetLastManaUse(getMSTime());
-}
-
-void Spell::TakeAmmo()
-{
- if(m_attackType == RANGED_ATTACK && m_caster->GetTypeId() == TYPEID_PLAYER)
- {
- Item *pItem = ((Player*)m_caster)->GetWeaponForAttack( RANGED_ATTACK );
-
- // wands don't have ammo
- if(!pItem || pItem->IsBroken() || pItem->GetProto()->SubClass==ITEM_SUBCLASS_WEAPON_WAND)
- return;
-
- if( pItem->GetProto()->InventoryType == INVTYPE_THROWN )
- {
- if(pItem->GetMaxStackCount()==1)
- {
- // decrease durability for non-stackable throw weapon
- ((Player*)m_caster)->DurabilityPointLossForEquipSlot(EQUIPMENT_SLOT_RANGED);
- }
- else
- {
- // decrease items amount for stackable throw weapon
- uint32 count = 1;
- ((Player*)m_caster)->DestroyItemCount( pItem, count, true);
- }
- }
- else if(uint32 ammo = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID))
- ((Player*)m_caster)->DestroyItemCount(ammo, 1, true);
- }
-}
-
-SpellCastResult Spell::CheckRuneCost(uint32 runeCostID)
-{
- if(m_spellInfo->powerType != POWER_RUNE || !runeCostID)
- return SPELL_CAST_OK;
-
- if(m_caster->GetTypeId() != TYPEID_PLAYER)
- return SPELL_CAST_OK;
-
- Player *plr = (Player*)m_caster;
-
- if(plr->getClass() != CLASS_DEATH_KNIGHT)
- return SPELL_CAST_OK;
-
- SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(runeCostID);
-
- if(!src)
- return SPELL_CAST_OK;
-
- if(src->NoRuneCost())
- return SPELL_CAST_OK;
-
- int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
-
- for (uint32 i = 0; i < RUNE_DEATH; ++i)
- {
- runeCost[i] = src->RuneCost[i];
- if(Player* modOwner = m_caster->GetSpellModOwner())
- modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, runeCost[i], this);
- }
-
- runeCost[RUNE_DEATH] = MAX_RUNES; // calculated later
-
- for (uint32 i = 0; i < MAX_RUNES; ++i)
- {
- RuneType rune = plr->GetCurrentRune(i);
- if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
- runeCost[rune]--;
- }
-
- for (uint32 i = 0; i < RUNE_DEATH; ++i)
- if(runeCost[i] > 0)
- runeCost[RUNE_DEATH] += runeCost[i];
-
- if(runeCost[RUNE_DEATH] > MAX_RUNES)
- return SPELL_FAILED_NO_POWER; // not sure if result code is correct
-
- return SPELL_CAST_OK;
-}
-
-void Spell::TakeRunePower()
-{
- if(m_caster->GetTypeId() != TYPEID_PLAYER)
- return;
-
- Player *plr = (Player*)m_caster;
-
- if(plr->getClass() != CLASS_DEATH_KNIGHT)
- return;
-
- SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(m_spellInfo->runeCostID);
-
- if(!src || (src->NoRuneCost() && src->NoRunicPowerGain()))
- return;
-
- m_runesState = plr->GetRunesState(); // store previous state
-
- int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
-
- for (uint32 i = 0; i < RUNE_DEATH; ++i)
- {
- runeCost[i] = src->RuneCost[i];
- if(Player* modOwner = m_caster->GetSpellModOwner())
- modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, runeCost[i], this);
- }
-
- runeCost[RUNE_DEATH] = 0; // calculated later
-
- for (uint32 i = 0; i < MAX_RUNES; ++i)
- {
- RuneType rune = plr->GetCurrentRune(i);
- if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
- {
- plr->SetRuneCooldown(i, plr->GetRuneBaseCooldown(i));
- plr->SetLastUsedRune(RuneType(rune));
- runeCost[rune]--;
- }
- }
-
- runeCost[RUNE_DEATH] = runeCost[RUNE_BLOOD] + runeCost[RUNE_UNHOLY] + runeCost[RUNE_FROST];
-
- if(runeCost[RUNE_DEATH] > 0)
- {
- for (uint32 i = 0; i < MAX_RUNES; ++i)
- {
- RuneType rune = plr->GetCurrentRune(i);
- if((plr->GetRuneCooldown(i) == 0) && (rune == RUNE_DEATH))
- {
- plr->SetRuneCooldown(i, plr->GetRuneBaseCooldown(i));
- plr->SetLastUsedRune(RuneType(rune));
- runeCost[rune]--;
-
- plr->RestoreBaseRune(i);
-
- if(runeCost[RUNE_DEATH] == 0)
- break;
- }
- }
- }
-
- // you can gain some runic power when use runes
- float rp = src->runePowerGain;
- rp *= sWorld.getRate(RATE_POWER_RUNICPOWER_INCOME);
- plr->ModifyPower(POWER_RUNIC_POWER, (int32)rp);
-}
-
-void Spell::TakeReagents()
-{
- if(m_IsTriggeredSpell) // reagents used in triggered spell removed by original spell or don't must be removed.
- return;
-
- if (m_caster->GetTypeId() != TYPEID_PLAYER)
- return;
-
- // do not take reagents for these item casts
- if (m_CastItem && m_CastItem->GetProto()->Flags & ITEM_FLAGS_TRIGGERED_CAST)
- return;
-
- Player* p_caster = (Player*)m_caster;
- if (p_caster->CanNoReagentCast(m_spellInfo))
- return;
-
- for (uint32 x = 0; x < 8; ++x)
- {
- if(m_spellInfo->Reagent[x] <= 0)
- continue;
-
- uint32 itemid = m_spellInfo->Reagent[x];
- uint32 itemcount = m_spellInfo->ReagentCount[x];
-
- // if CastItem is also spell reagent
- if (m_CastItem)
- {
- ItemPrototype const *proto = m_CastItem->GetProto();
- if( proto && proto->ItemId == itemid )
- {
- for (int s = 0; s < MAX_ITEM_PROTO_SPELLS; ++s)
- {
- // CastItem will be used up and does not count as reagent
- int32 charges = m_CastItem->GetSpellCharges(s);
- if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
- {
- ++itemcount;
- break;
- }
- }
-
- m_CastItem = NULL;
- }
- }
-
- // if getItemTarget is also spell reagent
- if (m_targets.getItemTargetEntry() == itemid)
- m_targets.setItemTarget(NULL);
-
- p_caster->DestroyItemCount(itemid, itemcount, true);
- }
-}
-
-void Spell::HandleThreatSpells(uint32 spellId)
-{
- if(!m_targets.getUnitTarget() || !spellId)
- return;
-
- if(!m_targets.getUnitTarget()->CanHaveThreatList())
- return;
-
- uint16 threat = spellmgr.GetSpellThreat(spellId);
-
- if(!threat)
- return;
-
- m_targets.getUnitTarget()->AddThreat(m_caster, float(threat));
-
- DEBUG_LOG("Spell %u, rank %u, added an additional %i threat", spellId, spellmgr.GetSpellRank(spellId), threat);
-}
-
-void Spell::HandleEffects(Unit *pUnitTarget,Item *pItemTarget,GameObject *pGOTarget,uint32 i)
-{
-
- if (!sScriptMgr.OnSpellCast(pUnitTarget,pItemTarget,pGOTarget,i,m_spellInfo))
- return;
-
- //effect has been handled, skip it
- if (m_effectMask & (1<<i))
- return;
-
- unitTarget = pUnitTarget;
- itemTarget = pItemTarget;
- gameObjTarget = pGOTarget;
-
- uint8 eff = m_spellInfo->Effect[i];
-
- sLog.outDebug( "Spell: %u Effect : %u", m_spellInfo->Id, eff);
-
- //we do not need DamageMultiplier here.
- damage = CalculateDamage(i, NULL);
-
- if(eff < TOTAL_SPELL_EFFECTS)
- {
- //sLog.outDebug( "WORLD: Spell FX %d < TOTAL_SPELL_EFFECTS ", eff);
- (this->*SpellEffects[eff])(i);
- }
-}
-
-void Spell::TriggerSpell()
-{
- for (TriggerSpells::iterator si=m_TriggerSpells.begin(); si!=m_TriggerSpells.end(); ++si)
- {
- Spell* spell = new Spell(m_caster, (*si), true, m_originalCasterGUID, m_selfContainer, true);
- spell->prepare(&m_targets); // use original spell original targets
- }
-}
-
-SpellCastResult Spell::CheckCast(bool strict)
-{
- // check cooldowns to prevent cheating
- if(m_caster->GetTypeId() == TYPEID_PLAYER && !(m_spellInfo->Attributes & SPELL_ATTR_PASSIVE))
- {
- //can cast triggered (by aura only?) spells while have this flag
- if (!m_IsTriggeredSpell && ((Player*)m_caster)->HasFlag(PLAYER_FLAGS, PLAYER_ALLOW_ONLY_ABILITY))
- return SPELL_FAILED_SPELL_IN_PROGRESS;
-
- if (((Player*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
- {
- if(m_triggeredByAuraSpell)
- return SPELL_FAILED_DONT_REPORT;
- else
- return SPELL_FAILED_NOT_READY;
- }
- }
-
- // only allow triggered spells if at an ended battleground
- if( !m_IsTriggeredSpell && m_caster->GetTypeId() == TYPEID_PLAYER)
- if(BattleGround * bg = ((Player*)m_caster)->GetBattleGround())
- if(bg->GetStatus() == STATUS_WAIT_LEAVE)
- return SPELL_FAILED_DONT_REPORT;
-
- // only check at first call, Stealth auras are already removed at second call
- // for now, ignore triggered spells
- if( strict && !m_IsTriggeredSpell)
- {
- bool checkForm = true;
- // Ignore form req aura
- Unit::AuraEffectList const& ignore = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_SHAPESHIFT);
- for (Unit::AuraEffectList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
- {
- if (!(*i)->IsAffectedOnSpell(m_spellInfo))
- continue;
- checkForm = false;
- break;
- }
- if (checkForm)
- {
- // Cannot be used in this stance/form
- SpellCastResult shapeError = GetErrorAtShapeshiftedCast(m_spellInfo, m_caster->m_form);
- if(shapeError != SPELL_CAST_OK)
- return shapeError;
-
- if ((m_spellInfo->Attributes & SPELL_ATTR_ONLY_STEALTHED) && !(m_caster->HasStealthAura()))
- return SPELL_FAILED_ONLY_STEALTHED;
- }
- }
-
- bool reqCombat=true;
- Unit::AuraEffectList const& stateAuras = m_caster->GetAuraEffectsByType(SPELL_AURA_ABILITY_IGNORE_AURASTATE);
- for (Unit::AuraEffectList::const_iterator j = stateAuras.begin(); j != stateAuras.end(); ++j)
- {
- if((*j)->IsAffectedOnSpell(m_spellInfo))
- {
- if ((*j)->GetMiscValue()==1)
- {
- reqCombat=false;
- break;
- }
- }
- }
-
- // caster state requirements
- // not for triggered spells (needed by execute)
- if (!m_IsTriggeredSpell)
- {
- if(m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraState), m_spellInfo, m_caster))
- return SPELL_FAILED_CASTER_AURASTATE;
- if(m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraStateNot), m_spellInfo, m_caster))
- return SPELL_FAILED_CASTER_AURASTATE;
-
- // Note: spell 62473 requres casterAuraSpell = triggering spell
- if(m_spellInfo->casterAuraSpell && !m_caster->HasAura(m_spellInfo->casterAuraSpell))
- return SPELL_FAILED_CASTER_AURASTATE;
- if(m_spellInfo->excludeCasterAuraSpell && m_caster->HasAura(m_spellInfo->excludeCasterAuraSpell))
- return SPELL_FAILED_CASTER_AURASTATE;
-
- if(reqCombat && m_caster->isInCombat() && IsNonCombatSpell(m_spellInfo))
- return SPELL_FAILED_AFFECTING_COMBAT;
- }
-
- // cancel autorepeat spells if cast start when moving
- // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code)
- if( m_caster->GetTypeId() == TYPEID_PLAYER && ((Player*)m_caster)->isMoving() )
- {
- // skip stuck spell to allow use it in falling case and apply spell limitations at movement
- if( (!((Player*)m_caster)->m_movementInfo.HasMovementFlag(MOVEMENTFLAG_FALLING) || m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK) &&
- (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0) )
- return SPELL_FAILED_MOVING;
- }
-
- if(Unit *target = m_targets.getUnitTarget())
- {
- // target state requirements (not allowed state), apply to self also
- if(!m_IsTriggeredSpell && m_spellInfo->TargetAuraStateNot && target->HasAuraState(AuraState(m_spellInfo->TargetAuraStateNot), m_spellInfo, m_caster))
- return SPELL_FAILED_TARGET_AURASTATE;
-
- if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
- return SPELL_FAILED_TARGET_AURASTATE;
-
- if(m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
- return SPELL_FAILED_TARGET_AURASTATE;
-
- if(!m_IsTriggeredSpell && target == m_caster && m_spellInfo->AttributesEx & SPELL_ATTR_EX_CANT_TARGET_SELF)
- return SPELL_FAILED_BAD_TARGETS;
-
- bool non_caster_target = target != m_caster && !spellmgr.IsSpellWithCasterSourceTargetsOnly(m_spellInfo);
-
- if(non_caster_target)
- {
- // target state requirements (apply to non-self only), to allow cast affects to self like Dirty Deeds
- if(!m_IsTriggeredSpell && m_spellInfo->TargetAuraState && !target->HasAuraState(AuraState(m_spellInfo->TargetAuraState), m_spellInfo, m_caster))
- return SPELL_FAILED_TARGET_AURASTATE;
-
- // Not allow casting on flying player
- if (target->hasUnitState(UNIT_STAT_UNATTACKABLE))
- return SPELL_FAILED_BAD_TARGETS;
-
- if(!m_IsTriggeredSpell && (target->HasAuraType(SPELL_AURA_MOD_STEALTH)
- || target->m_invisibilityMask) && !m_caster->canSeeOrDetect(target, true))
- return SPELL_FAILED_BAD_TARGETS;
-
- if (m_caster->GetTypeId() == TYPEID_PLAYER)
- {
- // Not allow banish not self target
- if (m_spellInfo->Mechanic == MECHANIC_BANISH)
- if (target->GetTypeId() == TYPEID_UNIT &&
- !((Player*)m_caster)->isAllowedToLoot((Creature*)target))
- return SPELL_FAILED_CANT_CAST_ON_TAPPED;
-
- if (m_customAttr & SPELL_ATTR_CU_PICKPOCKET)
- {
- if (target->GetTypeId() == TYPEID_PLAYER)
- return SPELL_FAILED_BAD_TARGETS;
- else if ((target->GetCreatureTypeMask() & CREATURE_TYPEMASK_HUMANOID_OR_UNDEAD) == 0)
- return SPELL_FAILED_TARGET_NO_POCKETS;
- }
-
- // Not allow disarm unarmed player
- if (m_spellInfo->Mechanic == MECHANIC_DISARM)
- {
- if (target->GetTypeId() == TYPEID_PLAYER)
- {
- if(!((Player*)target)->GetWeaponForAttack(BASE_ATTACK) || !((Player*)target)->IsUseEquipedWeapon(true))
- return SPELL_FAILED_TARGET_NO_WEAPONS;
- }
- else if (!target->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID))
- return SPELL_FAILED_TARGET_NO_WEAPONS;
- }
- }
-
- if(!m_IsTriggeredSpell && VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOSInMap(target))
- return SPELL_FAILED_LINE_OF_SIGHT;
-
- }
- else if (m_caster == target)
- {
-
- if (m_caster->GetTypeId() == TYPEID_PLAYER) // Target - is player caster
- {
- // Additional check for some spells
- // If 0 spell effect empty - client not send target data (need use selection)
- // TODO: check it on next client version
- if (m_targets.m_targetMask == TARGET_FLAG_SELF &&
- m_spellInfo->EffectImplicitTargetA[1] == TARGET_UNIT_TARGET_ENEMY)
- {
- if (target = m_caster->GetUnit(*m_caster, ((Player *)m_caster)->GetSelection()))
- m_targets.setUnitTarget(target);
- else
- return SPELL_FAILED_BAD_TARGETS;
- }
- }
- }
-
- // check pet presents
- for (int j = 0; j < 3; ++j)
- {
- if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_UNIT_PET)
- {
- target = m_caster->GetGuardianPet();
- if(!target)
- {
- if(m_triggeredByAuraSpell) // not report pet not existence for triggered spells
- return SPELL_FAILED_DONT_REPORT;
- else
- return SPELL_FAILED_NO_PET;
- }
- break;
- }
- }
-
- //check creature type
- //ignore self casts (including area casts when caster selected as target)
- if(non_caster_target)
- {
- if(!CheckTargetCreatureType(target))
- {
- if(target->GetTypeId() == TYPEID_PLAYER)
- return SPELL_FAILED_TARGET_IS_PLAYER;
- else
- return SPELL_FAILED_BAD_TARGETS;
- }
- }
-
- // who can give me an example to show what is the use of this
- // even if we need check, check by effect rather than whole spell, otherwise 57108,57143 are broken
- /*
- // TODO: this check can be applied and for player to prevent cheating when IsPositiveSpell will return always correct result.
- // check target for pet/charmed casts (not self targeted), self targeted cast used for area effects and etc
- if(non_caster_target && m_caster->GetTypeId() == TYPEID_UNIT && m_caster->GetCharmerOrOwnerGUID())
- {
- // check correctness positive/negative cast target (pet cast real check and cheating check)
- if(IsPositiveSpell(m_spellInfo->Id))
- {
- //dispel positivity is dependant on target, don't check it
- if(m_caster->IsHostileTo(target) && !IsDispel(m_spellInfo))
- return SPELL_FAILED_BAD_TARGETS;
- }
- else
- {
- if(m_caster->IsFriendlyTo(target))
- return SPELL_FAILED_BAD_TARGETS;
- }
- }
- */
-
- if(target)
- if(IsPositiveSpell(m_spellInfo->Id))
- if(target->IsImmunedToSpell(m_spellInfo))
- return SPELL_FAILED_TARGET_AURASTATE;
-
- //Must be behind the target.
- if( m_spellInfo->AttributesEx2 == 0x100000 && (m_spellInfo->AttributesEx & 0x200) == 0x200 && target->HasInArc(M_PI, m_caster)
- //Exclusion for Pounce: Facing Limitation was removed in 2.0.1, but it still uses the same, old Ex-Flags
- && (!(m_spellInfo->SpellFamilyName == SPELLFAMILY_DRUID && m_spellInfo->SpellFamilyFlags.IsEqual(0x20000,0,0)))
- //Mutilate no longer requires you be behind the target as of patch 3.0.3
- && (!(m_spellInfo->SpellFamilyName == SPELLFAMILY_ROGUE && m_spellInfo->SpellFamilyFlags[1] & 0x200000))
- //Exclusion for Throw: Facing limitation was added in 3.2.x, but that shouldn't be
- && (!(m_spellInfo->SpellFamilyName == SPELLFAMILY_ROGUE && m_spellInfo->SpellFamilyFlags[0] & 0x00000001)))
- {
- SendInterrupted(2);
- return SPELL_FAILED_NOT_BEHIND;
- }
-
- //Target must be facing you.
- if((m_spellInfo->Attributes == 0x150010) && !target->HasInArc(M_PI, m_caster) )
- {
- SendInterrupted(2);
- return SPELL_FAILED_NOT_INFRONT;
- }
-
- // check if target is in combat
- if (non_caster_target && (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NOT_IN_COMBAT_TARGET) && target->isInCombat())
- return SPELL_FAILED_TARGET_AFFECTING_COMBAT;
- }
-
- // Spell casted only on battleground
- if ((m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_BATTLEGROUND) && m_caster->GetTypeId() == TYPEID_PLAYER)
- if(!((Player*)m_caster)->InBattleGround())
- return SPELL_FAILED_ONLY_BATTLEGROUNDS;
-
- // do not allow spells to be cast in arenas
- // - with greater than 10 min CD without SPELL_ATTR_EX4_USABLE_IN_ARENA flag
- // - with SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA flag
- if ((m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA) ||
- GetSpellRecoveryTime(m_spellInfo) > 10 * MINUTE * IN_MILISECONDS && !(m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_USABLE_IN_ARENA))
- if(MapEntry const* mapEntry = sMapStore.LookupEntry(m_caster->GetMapId()))
- if(mapEntry->IsBattleArena())
- return SPELL_FAILED_NOT_IN_ARENA;
-
- // zone check
- if(m_caster->GetTypeId() == TYPEID_UNIT || !((Player*)m_caster)->isGameMaster())
- {
- uint32 zone, area;
- m_caster->GetZoneAndAreaId(zone,area);
-
- SpellCastResult locRes= spellmgr.GetSpellAllowedInLocationError(m_spellInfo,m_caster->GetMapId(),zone,area,
- m_caster->GetTypeId() == TYPEID_PLAYER ? ((Player*)m_caster) : NULL);
- if(locRes != SPELL_CAST_OK)
- return locRes;
- }
-
- // not let players cast spells at mount (and let do it to creatures)
- if (m_caster->IsMounted() && m_caster->GetTypeId() == TYPEID_PLAYER && !m_IsTriggeredSpell &&
- !IsPassiveSpell(m_spellInfo->Id) && !(m_spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_MOUNTED))
- {
- if (m_caster->isInFlight())
- return SPELL_FAILED_NOT_ON_TAXI;
- else
- return SPELL_FAILED_NOT_MOUNTED;
- }
-
- // always (except passive spells) check items (focus object can be required for any type casts)
- if (!IsPassiveSpell(m_spellInfo->Id))
- {
- SpellCastResult castResult = CheckItems();
- if(castResult != SPELL_CAST_OK)
- return castResult;
- }
-
- /*//ImpliciteTargetA-B = 38, If fact there is 0 Spell with ImpliciteTargetB=38
- if(m_UniqueTargetInfo.empty()) // skip second CheckCast apply (for delayed spells for example)
- {
- for (uint8 j = 0; j < 3; ++j)
- {
- if( m_spellInfo->EffectImplicitTargetA[j] == TARGET_UNIT_NEARBY_ENTRY ||
- m_spellInfo->EffectImplicitTargetB[j] == TARGET_UNIT_NEARBY_ENTRY && m_spellInfo->EffectImplicitTargetA[j] != TARGET_UNIT_CASTER ||
- m_spellInfo->EffectImplicitTargetA[j] == TARGET_DST_NEARBY_ENTRY ||
- m_spellInfo->EffectImplicitTargetB[j] == TARGET_DST_NEARBY_ENTRY )
- {
- SpellScriptTarget::const_iterator lower = spellmgr.GetBeginSpellScriptTarget(m_spellInfo->Id);
- SpellScriptTarget::const_iterator upper = spellmgr.GetEndSpellScriptTarget(m_spellInfo->Id);
- if(lower==upper)
- sLog.outErrorDb("Spell (ID: %u) has effect EffectImplicitTargetA/EffectImplicitTargetB = TARGET_UNIT_NEARBY_ENTRY or TARGET_DST_NEARBY_ENTRY, but does not have record in `spell_script_target`",m_spellInfo->Id);
-
- SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
- float range = GetSpellMaxRange(srange);
-
- Creature* creatureScriptTarget = NULL;
- GameObject* goScriptTarget = NULL;
-
- for (SpellScriptTarget::const_iterator i_spellST = bounds.first; i_spellST != bounds.second; ++i_spellST)
- {
- switch(i_spellST->second.type)
- {
- case SPELL_TARGET_TYPE_GAMEOBJECT:
- {
- GameObject* p_GameObject = NULL;
-
- if (i_spellST->second.targetEntry)
- {
- CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
- Cell cell(p);
- cell.data.Part.reserved = ALL_DISTRICT;
-
- Trinity::NearestGameObjectEntryInObjectRangeCheck go_check(*m_caster,i_spellST->second.targetEntry,range);
- Trinity::GameObjectLastSearcher<Trinity::NearestGameObjectEntryInObjectRangeCheck> checker(m_caster, p_GameObject,go_check);
-
- TypeContainerVisitor<Trinity::GameObjectLastSearcher<Trinity::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
- CellLock<GridReadGuard> cell_lock(cell, p);
- cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
-
- if (p_GameObject)
- {
- // remember found target and range, next attempt will find more near target with another entry
- creatureScriptTarget = NULL;
- goScriptTarget = p_GameObject;
- range = go_check.GetLastRange();
- }
- }
- else if (focusObject) // Focus Object
- {
- float frange = m_caster->GetDistance(focusObject);
- if (range >= frange)
- {
- creatureScriptTarget = NULL;
- goScriptTarget = focusObject;
- range = frange;
- }
- }
- break;
- }
- case SPELL_TARGET_TYPE_CREATURE:
- case SPELL_TARGET_TYPE_DEAD:
- default:
- {
- Creature *p_Creature = NULL;
-
- CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
- Cell cell(p);
- cell.data.Part.reserved = ALL_DISTRICT;
- cell.SetNoCreate(); // Really don't know what is that???
-
- Trinity::NearestCreatureEntryWithLiveStateInObjectRangeCheck u_check(*m_caster,i_spellST->second.targetEntry,i_spellST->second.type!=SPELL_TARGET_TYPE_DEAD,range);
- Trinity::CreatureLastSearcher<Trinity::NearestCreatureEntryWithLiveStateInObjectRangeCheck> searcher(m_caster, p_Creature, u_check);
-
- TypeContainerVisitor<Trinity::CreatureLastSearcher<Trinity::NearestCreatureEntryWithLiveStateInObjectRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
-
- CellLock<GridReadGuard> cell_lock(cell, p);
- cell_lock->Visit(cell_lock, grid_creature_searcher, *m_caster->GetMap(), *m_caster, range);
-
- if(p_Creature )
- {
- creatureScriptTarget = p_Creature;
- goScriptTarget = NULL;
- range = u_check.GetLastRange();
- }
- break;
- }
- }
- }
-
- if(creatureScriptTarget)
- {
- // store coordinates for TARGET_DST_NEARBY_ENTRY
- if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_DST_NEARBY_ENTRY ||
- m_spellInfo->EffectImplicitTargetB[j] == TARGET_DST_NEARBY_ENTRY )
- {
- m_targets.setDst(creatureScriptTarget->GetPositionX(),creatureScriptTarget->GetPositionY(),creatureScriptTarget->GetPositionZ());
-
- if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_DST_NEARBY_ENTRY && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
- AddUnitTarget(creatureScriptTarget, j);
- }
- // store explicit target for TARGET_UNIT_NEARBY_ENTRY
- else
- AddUnitTarget(creatureScriptTarget, j);
- }
- else if(goScriptTarget)
- {
- // store coordinates for TARGET_DST_NEARBY_ENTRY
- if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_DST_NEARBY_ENTRY ||
- m_spellInfo->EffectImplicitTargetB[j] == TARGET_DST_NEARBY_ENTRY )
- {
- m_targets.setDst(goScriptTarget->GetPositionX(),goScriptTarget->GetPositionY(),goScriptTarget->GetPositionZ());
-
- if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_DST_NEARBY_ENTRY && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
- AddGOTarget(goScriptTarget, j);
- }
- // store explicit target for TARGET_UNIT_NEARBY_ENTRY
- else
- AddGOTarget(goScriptTarget, j);
- }
- //Missing DB Entry or targets for this spellEffect.
- else
- {
- // not report target not existence for triggered spells
- if(m_triggeredByAuraSpell || m_IsTriggeredSpell)
- return SPELL_FAILED_DONT_REPORT;
- else
- return SPELL_FAILED_BAD_TARGETS;
- }
- }
- }
- }*/
-
- if(!m_IsTriggeredSpell)
- {
- SpellCastResult castResult = CheckRange(strict);
- if(castResult != SPELL_CAST_OK)
- return castResult;
-
- castResult = CheckPower();
- if(castResult != SPELL_CAST_OK)
- return castResult;
-
- castResult = CheckCasterAuras();
- if(castResult != SPELL_CAST_OK)
- return castResult;
- }
-
- for (int i = 0; i < 3; i++)
- {
- // for effects of spells that have only one target
- switch(m_spellInfo->Effect[i])
- {
- case SPELL_EFFECT_DUMMY:
- {
- if (m_spellInfo->Id == 51582) // Rocket Boots Engaged
- {
- if(m_caster->IsInWater())
- return SPELL_FAILED_ONLY_ABOVEWATER;
- }
- else if(m_spellInfo->SpellIconID == 156) // Holy Shock
- {
- // spell different for friends and enemies
- // hurt version required facing
- if(m_targets.getUnitTarget() && !m_caster->IsFriendlyTo(m_targets.getUnitTarget()) && !m_caster->HasInArc( M_PI, m_targets.getUnitTarget() ))
- return SPELL_FAILED_UNIT_NOT_INFRONT;
- }
- else if(m_spellInfo->SpellIconID == 33 && m_spellInfo->SpellFamilyName == SPELLFAMILY_SHAMAN && m_spellInfo->SpellFamilyFlags[0] & SPELLFAMILYFLAG_SHAMAN_FIRE_NOVA)
- {
- if (!m_caster->m_SummonSlot[1])
- return SPELL_FAILED_SUCCESS;
- }
- else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && m_spellInfo->SpellFamilyFlags[0] == 0x2000) // Death Coil (DeathKnight)
- {
- Unit* target = m_targets.getUnitTarget();
- if (!target || (target->IsFriendlyTo(m_caster) && target->GetCreatureType() != CREATURE_TYPE_UNDEAD))
- return SPELL_FAILED_BAD_TARGETS;
- }
- else if (m_spellInfo->Id == 19938) // Awaken Peon
- {
- Unit *unit = m_targets.getUnitTarget();
- if(!unit || !unit->HasAura(17743))
- return SPELL_FAILED_BAD_TARGETS;
- }
- else if (m_spellInfo->Id == 52264) // Deliver Stolen Horse
- {
- if(!m_caster->FindNearestCreature(28653,5))
- return SPELL_FAILED_OUT_OF_RANGE;
- }
- else if (m_spellInfo->Id == 31789) // Righteous Defense
- {
- if (m_caster->GetTypeId() != TYPEID_PLAYER)
- return SPELL_FAILED_DONT_REPORT;
-
- Unit* target = m_targets.getUnitTarget();
- if (!target || !target->IsFriendlyTo(m_caster) || target->getAttackers().empty())
- return SPELL_FAILED_BAD_TARGETS;
-
- }
- break;
- }
- case SPELL_EFFECT_LEARN_SPELL:
- {
- if (m_caster->GetTypeId() != TYPEID_PLAYER)
- return SPELL_FAILED_BAD_TARGETS;
-
- if(m_spellInfo->EffectImplicitTargetA[i] != TARGET_UNIT_PET)
- break;
-
- Pet* pet = ((Player*)m_caster)->GetPet();
-
- if(!pet)
- return SPELL_FAILED_NO_PET;
-
- SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
-
- if(!learn_spellproto)
- return SPELL_FAILED_NOT_KNOWN;
-
- if(m_spellInfo->spellLevel > pet->getLevel())
- return SPELL_FAILED_LOWLEVEL;
-
- break;
- }
- case SPELL_EFFECT_LEARN_PET_SPELL:
- {
- if (m_caster->GetTypeId() != TYPEID_PLAYER)
- return SPELL_FAILED_BAD_TARGETS;
-
- Pet* pet = ((Player*)m_caster)->GetPet();
- if(!pet)
- return SPELL_FAILED_NO_PET;
-
- SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
-
- if(!learn_spellproto)
- return SPELL_FAILED_NOT_KNOWN;
-
- if(m_spellInfo->spellLevel > pet->getLevel())
- return SPELL_FAILED_LOWLEVEL;
-
- break;
- }
- case SPELL_EFFECT_APPLY_GLYPH:
- {
- uint32 glyphId = m_spellInfo->EffectMiscValue[i];
- if(GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyphId))
- if(m_caster->HasAura(gp->SpellId))
- return SPELL_FAILED_UNIQUE_GLYPH;
- break;
- }
- case SPELL_EFFECT_FEED_PET:
- {
- if (m_caster->GetTypeId() != TYPEID_PLAYER)
- return SPELL_FAILED_BAD_TARGETS;
-
- Item* foodItem = m_targets.getItemTarget();
- if(!foodItem)
- return SPELL_FAILED_BAD_TARGETS;
-
- Pet* pet = ((Player*)m_caster)->GetPet();
-
- if(!pet)
- return SPELL_FAILED_NO_PET;
-
- if(!pet->HaveInDiet(foodItem->GetProto()))
- return SPELL_FAILED_WRONG_PET_FOOD;
-
- if(!pet->GetCurrentFoodBenefitLevel(foodItem->GetProto()->ItemLevel))
- return SPELL_FAILED_FOOD_LOWLEVEL;
-
- if(m_caster->isInCombat() || pet->isInCombat())
- return SPELL_FAILED_AFFECTING_COMBAT;
-
- break;
- }
- case SPELL_EFFECT_POWER_BURN:
- case SPELL_EFFECT_POWER_DRAIN:
- {
- // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects)
- if(m_caster->GetTypeId() == TYPEID_PLAYER)
- if(Unit* target = m_targets.getUnitTarget())
- if(target != m_caster && target->getPowerType() != m_spellInfo->EffectMiscValue[i])
- return SPELL_FAILED_BAD_TARGETS;
- break;
- }
- case SPELL_EFFECT_CHARGE:
- {
- if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR)
- {
- // Warbringer - can't be handled in proc system - should be done before checkcast root check and charge effect process
- if (strict && m_caster->IsScriptOverriden(m_spellInfo, 6953))
- m_caster->RemoveMovementImpairingAuras();
- }
- if (m_caster->hasUnitState(UNIT_STAT_ROOT))
- return SPELL_FAILED_ROOTED;
- break;
- }
- case SPELL_EFFECT_SKINNING:
- {
- if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() != TYPEID_UNIT)
- return SPELL_FAILED_BAD_TARGETS;
-
- if( !(m_targets.getUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE) )
- return SPELL_FAILED_TARGET_UNSKINNABLE;
-
- Creature* creature = (Creature*)m_targets.getUnitTarget();
- if ( creature->GetCreatureType() != CREATURE_TYPE_CRITTER && ( !creature->lootForBody || !creature->loot.empty() ) )
- {
- return SPELL_FAILED_TARGET_NOT_LOOTED;
- }
-
- uint32 skill = creature->GetCreatureInfo()->GetRequiredLootSkill();
-
- int32 skillValue = ((Player*)m_caster)->GetSkillValue(skill);
- int32 TargetLevel = m_targets.getUnitTarget()->getLevel();
- int32 ReqValue = (skillValue < 100 ? (TargetLevel-10) * 10 : TargetLevel * 5);
- if (ReqValue > skillValue)
- return SPELL_FAILED_LOW_CASTLEVEL;
-
- // chance for fail at orange skinning attempt
- if( (m_selfContainer && (*m_selfContainer) == this) &&
- skillValue < sWorld.GetConfigMaxSkillValue() &&
- (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue - 25, skillValue + 37) )
- return SPELL_FAILED_TRY_AGAIN;
-
- break;
- }
- case SPELL_EFFECT_OPEN_LOCK:
- {
- if( m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT &&
- m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT_ITEM )
- break;
-
- if( m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc.
- // we need a go target in case of TARGET_GAMEOBJECT
- || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT && !m_targets.getGOTarget()
- // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM
- || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT_ITEM && !m_targets.getGOTarget() &&
- (!m_targets.getItemTarget() || !m_targets.getItemTarget()->GetProto()->LockID || m_targets.getItemTarget()->GetOwner() != m_caster ) )
- return SPELL_FAILED_BAD_TARGETS;
-
- // In BattleGround players can use only flags and banners
- if( ((Player*)m_caster)->InBattleGround() &&
- !((Player*)m_caster)->CanUseBattleGroundObject() )
- return SPELL_FAILED_TRY_AGAIN;
-
- // get the lock entry
- uint32 lockId = 0;
- if (GameObject* go = m_targets.getGOTarget())
- {
- lockId = go->GetGOInfo()->GetLockId();
- if (!lockId)
- return SPELL_FAILED_BAD_TARGETS;
- }
- else if(Item* itm = m_targets.getItemTarget())
- lockId = itm->GetProto()->LockID;
-
- SkillType skillId = SKILL_NONE;
- int32 reqSkillValue = 0;
- int32 skillValue = 0;
-
- // check lock compatibility
- SpellCastResult res = CanOpenLock(i, lockId, skillId, reqSkillValue, skillValue);
- if(res != SPELL_CAST_OK)
- return res;
-
- // chance for fail at orange mining/herb/LockPicking gathering attempt
- // second check prevent fail at rechecks
- if(skillId != SKILL_NONE && (!m_selfContainer || ((*m_selfContainer) != this)))
- {
- bool canFailAtMax = skillId != SKILL_HERBALISM && skillId != SKILL_MINING;
-
- // chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill)
- if((canFailAtMax || skillValue < sWorld.GetConfigMaxSkillValue()) && reqSkillValue > irand(skillValue - 25, skillValue + 37))
- return SPELL_FAILED_TRY_AGAIN;
- }
- break;
- }
- case SPELL_EFFECT_SUMMON_DEAD_PET:
- {
- Creature *pet = m_caster->GetGuardianPet();
- if(!pet)
- return SPELL_FAILED_NO_PET;
-
- if(pet->isAlive())
- return SPELL_FAILED_ALREADY_HAVE_SUMMON;
-
- break;
- }
- // This is generic summon effect
- case SPELL_EFFECT_SUMMON:
- {
- SummonPropertiesEntry const *SummonProperties = sSummonPropertiesStore.LookupEntry(m_spellInfo->EffectMiscValueB[i]);
- if(!SummonProperties)
- break;
- switch(SummonProperties->Category)
- {
- case SUMMON_CATEGORY_PET:
- if(m_caster->GetPetGUID())
- return SPELL_FAILED_ALREADY_HAVE_SUMMON;
- case SUMMON_CATEGORY_PUPPET:
- if(m_caster->GetCharmGUID())
- return SPELL_FAILED_ALREADY_HAVE_CHARM;
- break;
- }
- break;
- }
- case SPELL_EFFECT_SUMMON_PET:
- {
- if(m_caster->GetPetGUID()) //let warlock do a replacement summon
- {
- if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->getClass()==CLASS_WARLOCK)
- {
- if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player)
- if(Pet* pet = ((Player*)m_caster)->GetPet())
- pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID());
- }
- else
- return SPELL_FAILED_ALREADY_HAVE_SUMMON;
- }
-
- if(m_caster->GetCharmGUID())
- return SPELL_FAILED_ALREADY_HAVE_CHARM;
-
- break;
- }
- case SPELL_EFFECT_SUMMON_PLAYER:
- {
- if(m_caster->GetTypeId() != TYPEID_PLAYER)
- return SPELL_FAILED_BAD_TARGETS;
- if(!((Player*)m_caster)->GetSelection())
- return SPELL_FAILED_BAD_TARGETS;
-
- Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
- if( !target || ((Player*)m_caster) == target || !target->IsInSameRaidWith((Player*)m_caster) )
- return SPELL_FAILED_BAD_TARGETS;
-
- // check if our map is dungeon
- if( sMapStore.LookupEntry(m_caster->GetMapId())->IsDungeon() )
- {
- InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(m_caster->GetMapId());
- if(!instance)
- return SPELL_FAILED_TARGET_NOT_IN_INSTANCE;
- if(!target->Satisfy(objmgr.GetAccessRequirement(instance->access_id), m_caster->GetMapId()))
- return SPELL_FAILED_BAD_TARGETS;
- }
- break;
- }
- case SPELL_EFFECT_LEAP:
- case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER:
- {
- //Do not allow to cast it before BG starts.
- if(m_caster->GetTypeId() == TYPEID_PLAYER)
- if(BattleGround const *bg = ((Player*)m_caster)->GetBattleGround())
- if(bg->GetStatus() != STATUS_IN_PROGRESS)
- return SPELL_FAILED_TRY_AGAIN;
- break;
- }
- case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF:
- {
- if (m_targets.getUnitTarget() == m_caster)
- return SPELL_FAILED_BAD_TARGETS;
- break;
- }
- default:break;
- }
- }
-
- for (int i = 0; i < 3; i++)
- {
- switch(m_spellInfo->EffectApplyAuraName[i])
- {
- case SPELL_AURA_DUMMY:
- {
- //custom check
- switch(m_spellInfo->Id)
- {
- // Tag Murloc
- case 30877:
- {
- Unit* target = m_targets.getUnitTarget();
- if (!target || target->GetEntry() != 17326)
- return SPELL_FAILED_BAD_TARGETS;
- break;
- }
- case 61336:
- if(m_caster->GetTypeId() != TYPEID_PLAYER || !((Player*)m_caster)->IsInFeralForm())
- return SPELL_FAILED_ONLY_SHAPESHIFT;
- break;
- // Wild Growth
- case 48438:
- case 53248:
- case 53249:
- case 53251:
- {
- if (m_caster->GetTypeId() != TYPEID_PLAYER)
- return SPELL_FAILED_DONT_REPORT;
-
- Unit* target = m_targets.getUnitTarget();
- if (!target || target->GetTypeId() != TYPEID_PLAYER)
- return SPELL_FAILED_BAD_TARGETS;
-
- if (!((Player*)m_caster)->IsInSameRaidWith(((Player*)target)))
- return SPELL_FAILED_TARGET_NOT_IN_RAID;
-
- break;
- }
- case 1515:
- {
- if (m_caster->GetTypeId() != TYPEID_PLAYER)
- return SPELL_FAILED_BAD_TARGETS;
-
- if (!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER)
- return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
-
- Creature* target = (Creature*)m_targets.getUnitTarget();
-
- if (target->getLevel() > m_caster->getLevel())
- return SPELL_FAILED_HIGHLEVEL;
-
- // use SMSG_PET_TAME_FAILURE?
- if (!target->GetCreatureInfo()->isTameable (((Player*)m_caster)->CanTameExoticPets()))
- return SPELL_FAILED_BAD_TARGETS;
-
- if(m_caster->GetPetGUID())
- return SPELL_FAILED_ALREADY_HAVE_SUMMON;
-
- if(m_caster->GetCharmGUID())
- return SPELL_FAILED_ALREADY_HAVE_CHARM;
-
- break;
- }
- case 44795: // Parachute
- {
- float x, y, z;
- m_caster->GetPosition(x, y, z);
- float ground_Z = m_caster->GetMap()->GetVmapHeight(x, y, z);
- if (fabs(ground_Z - z) < 0.1f)
- return SPELL_FAILED_DONT_REPORT;
- break;
- }
- default:
- break;
- }
- break;
- }
- case SPELL_AURA_MOD_POSSESS_PET:
- {
- if(m_caster->GetTypeId() != TYPEID_PLAYER)
- return SPELL_FAILED_NO_PET;
-
- Pet *pet = ((Player*)m_caster)->GetPet();
- if(!pet)
- return SPELL_FAILED_NO_PET;
-
- if(pet->GetCharmerGUID())
- return SPELL_FAILED_CHARMED;
- break;
- }
- case SPELL_AURA_MOD_POSSESS:
- case SPELL_AURA_MOD_CHARM:
- case SPELL_AURA_AOE_CHARM:
- {
- if(m_caster->GetCharmerGUID())
- return SPELL_FAILED_CHARMED;
-
- if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_CHARM
- || m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_POSSESS)
- {
- if(m_caster->GetPetGUID())
- return SPELL_FAILED_ALREADY_HAVE_SUMMON;
-
- if(m_caster->GetCharmGUID())
- return SPELL_FAILED_ALREADY_HAVE_CHARM;
- }
-
- if(Unit *target = m_targets.getUnitTarget())
- {
- if(target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->IsVehicle())
- return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
-
- if(target->GetCharmerGUID())
- return SPELL_FAILED_CHARMED;
-
- int32 damage = CalculateDamage(i, target);
- if(damage && int32(target->getLevel()) > damage)
- return SPELL_FAILED_HIGHLEVEL;
- }
-
- break;
- }
- case SPELL_AURA_MOUNTED:
- {
- if (m_caster->IsInWater())
- return SPELL_FAILED_ONLY_ABOVEWATER;
-
- if (m_caster->GetTypeId() == TYPEID_PLAYER && ((Player*)m_caster)->GetTransport())
- return SPELL_FAILED_NO_MOUNTS_ALLOWED;
-
- // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells
- if (m_caster->GetTypeId() == TYPEID_PLAYER && !sMapStore.LookupEntry(m_caster->GetMapId())->IsMountAllowed() && !m_IsTriggeredSpell && !m_spellInfo->AreaGroupId)
- return SPELL_FAILED_NO_MOUNTS_ALLOWED;
-
- ShapeshiftForm form = m_caster->m_form;
- if( form == FORM_CAT || form == FORM_TREE || form == FORM_TRAVEL ||
- form == FORM_AQUA || form == FORM_BEAR || form == FORM_DIREBEAR ||
- form == FORM_CREATUREBEAR || form == FORM_GHOSTWOLF || form == FORM_FLIGHT ||
- form == FORM_FLIGHT_EPIC || form == FORM_MOONKIN || form == FORM_METAMORPHOSIS )
- return SPELL_FAILED_NOT_SHAPESHIFT;
-
- break;
- }
- case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS:
- {
- if(!m_targets.getUnitTarget())
- return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
-
- // can be casted at non-friendly unit or own pet/charm
- if(m_caster->IsFriendlyTo(m_targets.getUnitTarget()))
- return SPELL_FAILED_TARGET_FRIENDLY;
-
- break;
- }
- case SPELL_AURA_FLY:
- case SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED:
- {
- // not allow cast fly spells if not have req. skills (all spells is self target)
- // allow always ghost flight spells
- if (m_originalCaster && m_originalCaster->GetTypeId() == TYPEID_PLAYER && m_originalCaster->isAlive())
- {
- // 4197 = Wintergrasp || 4395 = Dalaran && 4564 = Krasus Landing
- if (m_originalCaster->GetZoneId() == 4197 || m_originalCaster->GetZoneId() == 4395 && m_originalCaster->GetAreaId() != 4564)
- return m_IsTriggeredSpell ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_NOT_HERE;
- }
- break;
- }
- case SPELL_AURA_RANGED_AP_ATTACKER_CREATURES_BONUS:
- {
- if (!m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetTypeId() != TYPEID_UNIT)
- return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
-
- // can be casted at non-friendly unit or own pet/charm
- if (m_caster->IsFriendlyTo(m_targets.getUnitTarget()))
- return SPELL_FAILED_TARGET_FRIENDLY;
-
- break;
- }
- case SPELL_AURA_PERIODIC_MANA_LEECH:
- {
- if (!m_targets.getUnitTarget())
- return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
-
- if (m_caster->GetTypeId() != TYPEID_PLAYER || m_CastItem)
- break;
-
- if(m_targets.getUnitTarget()->getPowerType() != POWER_MANA)
- return SPELL_FAILED_BAD_TARGETS;
-
- break;
- }
- default:
- break;
- }
- }
-
- // all ok
- return SPELL_CAST_OK;
-}
-
-SpellCastResult Spell::CheckPetCast(Unit* target)
-{
- if(!m_caster->isAlive() && !(m_spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_DEAD))
- return SPELL_FAILED_CASTER_DEAD;
-
- if(m_caster->hasUnitState(UNIT_STAT_CASTING) && !m_IsTriggeredSpell) //prevent spellcast interruption by another spellcast
- return SPELL_FAILED_SPELL_IN_PROGRESS;
- if(m_caster->isInCombat() && IsNonCombatSpell(m_spellInfo))
- return SPELL_FAILED_AFFECTING_COMBAT;
-
- //dead owner (pets still alive when owners ressed?)
- if(Unit *owner = m_caster->GetCharmerOrOwner())
- if(!owner->isAlive())
- return SPELL_FAILED_CASTER_DEAD;
-
- if(!target && m_targets.getUnitTarget())
- target = m_targets.getUnitTarget();
-
- for (uint32 i = 0; i < 3; ++i)
- {
- if(SpellTargetType[m_spellInfo->EffectImplicitTargetA[i]] == TARGET_TYPE_UNIT_TARGET
- || SpellTargetType[m_spellInfo->EffectImplicitTargetA[i]] == TARGET_TYPE_DEST_TARGET)
- {
- if(!target)
- return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
- m_targets.setUnitTarget(target);
- break;
- }
- }
-
- Unit* _target = m_targets.getUnitTarget();
-
- if(_target) //for target dead/target not valid
- {
- if(!_target->isAlive())
- return SPELL_FAILED_BAD_TARGETS;
-
- if(!IsValidSingleTargetSpell(_target))
- return SPELL_FAILED_BAD_TARGETS;
- }
- //cooldown
- if(((Creature*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
- return SPELL_FAILED_NOT_READY;
-
- return CheckCast(true);
-}
-
-SpellCastResult Spell::CheckCasterAuras() const
-{
- // spells totally immuned to caster auras ( wsg flag drop, give marks etc)
- if(m_spellInfo->AttributesEx6& SPELL_ATTR_EX6_IGNORE_CASTER_AURAS)
- return SPELL_CAST_OK;
-
- uint8 school_immune = 0;
- uint32 mechanic_immune = 0;
- uint32 dispel_immune = 0;
-
- // Check if the spell grants school or mechanic immunity.
- // We use bitmasks so the loop is done only once and not on every aura check below.
- if ( m_spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY )
- {
- for (int i = 0; i < 3; ++i)
- {
- if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_SCHOOL_IMMUNITY)
- school_immune |= uint32(m_spellInfo->EffectMiscValue[i]);
- else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MECHANIC_IMMUNITY)
- mechanic_immune |= 1 << uint32(m_spellInfo->EffectMiscValue[i]);
- else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_DISPEL_IMMUNITY)
- dispel_immune |= GetDispellMask(DispelType(m_spellInfo->EffectMiscValue[i]));
- }
- //immune movement impairment and loss of control
- if(m_spellInfo->Id==42292 || m_spellInfo->Id==59752)
- mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
- }
-
- // Check whether the cast should be prevented by any state you might have.
- SpellCastResult prevented_reason = SPELL_CAST_OK;
- // Have to check if there is a stun aura. Otherwise will have problems with ghost aura apply while logging out
- uint32 unitflag = m_caster->GetUInt32Value(UNIT_FIELD_FLAGS); // Get unit state
- if(unitflag & UNIT_FLAG_STUNNED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
- prevented_reason = SPELL_FAILED_STUNNED;
- else if(unitflag & UNIT_FLAG_CONFUSED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
- prevented_reason = SPELL_FAILED_CONFUSED;
- else if(unitflag & UNIT_FLAG_FLEEING && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
- prevented_reason = SPELL_FAILED_FLEEING;
- else if(unitflag & UNIT_FLAG_SILENCED && m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE)
- prevented_reason = SPELL_FAILED_SILENCED;
- else if(unitflag & UNIT_FLAG_PACIFIED && m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY)
- prevented_reason = SPELL_FAILED_PACIFIED;
-
- // Attr must make flag drop spell totally immune from all effects
- if(prevented_reason != SPELL_CAST_OK)
- {
- if(school_immune || mechanic_immune || dispel_immune)
- {
- //Checking auras is needed now, because you are prevented by some state but the spell grants immunity.
- Unit::AuraApplicationMap const& auras = m_caster->GetAppliedAuras();
- for (Unit::AuraApplicationMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
- {
- Aura const * aura = itr->second->GetBase();
- if( GetAllSpellMechanicMask(aura->GetSpellProto()) & mechanic_immune )
- continue;
- if( GetSpellSchoolMask(aura->GetSpellProto()) & school_immune )
- continue;
- if( (1<<(aura->GetSpellProto()->Dispel)) & dispel_immune)
- continue;
-
- //Make a second check for spell failed so the right SPELL_FAILED message is returned.
- //That is needed when your casting is prevented by multiple states and you are only immune to some of them.
- for (uint8 i=0; i<MAX_SPELL_EFFECTS; ++i)
- {
- if (AuraEffect * part = aura->GetEffect(i))
- {
- switch(part->GetAuraType())
- {
- case SPELL_AURA_MOD_STUN:
- if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
- return SPELL_FAILED_STUNNED;
- break;
- case SPELL_AURA_MOD_CONFUSE:
- if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
- return SPELL_FAILED_CONFUSED;
- break;
- case SPELL_AURA_MOD_FEAR:
- if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
- return SPELL_FAILED_FLEEING;
- break;
- case SPELL_AURA_MOD_SILENCE:
- case SPELL_AURA_MOD_PACIFY:
- case SPELL_AURA_MOD_PACIFY_SILENCE:
- if( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
- return SPELL_FAILED_PACIFIED;
- else if ( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
- return SPELL_FAILED_SILENCED;
- break;
- default: break;
- }
- }
- }
- }
- }
- // You are prevented from casting and the spell casted does not grant immunity. Return a failed error.
- else
- return prevented_reason;
- }
- return SPELL_CAST_OK;
-}
-
-bool Spell::CanAutoCast(Unit* target)
-{
- uint64 targetguid = target->GetGUID();
-
- for (uint32 j = 0; j < 3; ++j)
- {
- if(m_spellInfo->Effect[j] == SPELL_EFFECT_APPLY_AURA)
- {
- if( m_spellInfo->StackAmount <= 1)
- {
- if( target->HasAuraEffect(m_spellInfo->Id, j) )
- return false;
- }
- else
- {
- if( AuraEffect * aureff = target->GetAuraEffect(m_spellInfo->Id, j))
- if (aureff->GetBase()->GetStackAmount() >= m_spellInfo->StackAmount)
- return false;
- }
- }
- else if ( IsAreaAuraEffect( m_spellInfo->Effect[j] ))
- {
- if( target->HasAuraEffect(m_spellInfo->Id, j) )
- return false;
- }
- }
-
- SpellCastResult result = CheckPetCast(target);
-
- if(result == SPELL_CAST_OK || result == SPELL_FAILED_UNIT_NOT_INFRONT)
- {
- SelectSpellTargets();
- //check if among target units, our WANTED target is as well (->only self cast spells return false)
- for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
- if( ihit->targetGUID == targetguid )
- return true;
- }
- return false; //target invalid
-}
-
-SpellCastResult Spell::CheckRange(bool strict)
-{
- //float range_mod;
-
- // self cast doesn't need range checking -- also for Starshards fix
- if (m_spellInfo->rangeIndex == 1)
- return SPELL_CAST_OK;
-
- // i do not know why we need this
- /*if (strict) //add radius of caster
- range_mod = 1.25;
- else //add radius of caster and ~5 yds "give"
- range_mod = 6.25;*/
-
- SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
-
- Unit *target = m_targets.getUnitTarget();
- float max_range = m_caster->GetSpellMaxRangeForTarget(target, srange); // + range_mod;
- float min_range = m_caster->GetSpellMinRangeForTarget(target, srange);
- uint32 range_type = GetSpellRangeType(srange);
-
- if(Player* modOwner = m_caster->GetSpellModOwner())
- modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this);
-
- if(target && target != m_caster)
- {
- if(range_type == SPELL_RANGE_MELEE)
- {
- // Because of lag, we can not check too strictly here.
- if(!m_caster->IsWithinMeleeRange(target, max_range/* - 2*MIN_MELEE_REACH*/))
- return SPELL_FAILED_OUT_OF_RANGE;
- }
- else if(!m_caster->IsWithinCombatRange(target, max_range))
- return SPELL_FAILED_OUT_OF_RANGE; //0x5A;
-
- if(range_type == SPELL_RANGE_RANGED)
- {
- if(m_caster->IsWithinMeleeRange(target))
- return SPELL_FAILED_TOO_CLOSE;
- }
- else if(min_range && m_caster->IsWithinCombatRange(target, min_range)) // skip this check if min_range = 0
- return SPELL_FAILED_TOO_CLOSE;
-
- if( m_caster->GetTypeId() == TYPEID_PLAYER &&
- (m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc( M_PI, target ) )
- return SPELL_FAILED_UNIT_NOT_INFRONT;
- }
-
- if(m_targets.HasDst() && !m_targets.HasTraj())
- {
- if(!m_caster->IsWithinDist3d(&m_targets.m_dstPos, max_range))
- return SPELL_FAILED_OUT_OF_RANGE;
- if(min_range && m_caster->IsWithinDist3d(&m_targets.m_dstPos, min_range))
- return SPELL_FAILED_TOO_CLOSE;
- }
-
- return SPELL_CAST_OK;
-}
-
-SpellCastResult Spell::CheckPower()
-{
- // item cast not used power
- if(m_CastItem)
- return SPELL_CAST_OK;
-
- // health as power used - need check health amount
- if(m_spellInfo->powerType == POWER_HEALTH)
- {
- if(m_caster->GetHealth() <= m_powerCost)
- return SPELL_FAILED_CASTER_AURASTATE;
- return SPELL_CAST_OK;
- }
- // Check valid power type
- if( m_spellInfo->powerType >= MAX_POWERS )
- {
- sLog.outError("Spell::CheckPower: Unknown power type '%d'", m_spellInfo->powerType);
- return SPELL_FAILED_UNKNOWN;
- }
-
- //check rune cost only if a spell has PowerType == POWER_RUNE
- if(m_spellInfo->powerType == POWER_RUNE)
- {
- SpellCastResult failReason = CheckRuneCost(m_spellInfo->runeCostID);
- if(failReason != SPELL_CAST_OK)
- return failReason;
- }
-
- // Check power amount
- Powers powerType = Powers(m_spellInfo->powerType);
- if(m_caster->GetPower(powerType) < m_powerCost)
- return SPELL_FAILED_NO_POWER;
- else
- return SPELL_CAST_OK;
-}
-
-SpellCastResult Spell::CheckItems()
-{
- if (m_caster->GetTypeId() != TYPEID_PLAYER)
- return SPELL_CAST_OK;
-
- Player* p_caster = (Player*)m_caster;
-
- if(!m_CastItem)
- {
- if(m_castItemGUID)
- return SPELL_FAILED_ITEM_NOT_READY;
- }
- else
- {
- uint32 itemid = m_CastItem->GetEntry();
- if( !p_caster->HasItemCount(itemid, 1) )
- return SPELL_FAILED_ITEM_NOT_READY;
-
- ItemPrototype const *proto = m_CastItem->GetProto();
- if(!proto)
- return SPELL_FAILED_ITEM_NOT_READY;
-
- for (int i = 0; i < 5; ++i)
- if (proto->Spells[i].SpellCharges)
- if(m_CastItem->GetSpellCharges(i) == 0)
- return SPELL_FAILED_NO_CHARGES_REMAIN;
-
- // consumable cast item checks
- if (proto->Class == ITEM_CLASS_CONSUMABLE && m_targets.getUnitTarget())
- {
- // such items should only fail if there is no suitable effect at all - see Rejuvenation Potions for example
- SpellCastResult failReason = SPELL_CAST_OK;
- for (int i = 0; i < 3; i++)
- {
- // skip check, pet not required like checks, and for TARGET_UNIT_PET m_targets.getUnitTarget() is not the real target but the caster
- if (m_spellInfo->EffectImplicitTargetA[i] == TARGET_UNIT_PET)
- continue;
-
- if (m_spellInfo->Effect[i] == SPELL_EFFECT_HEAL)
- {
- if (m_targets.getUnitTarget()->GetHealth() == m_targets.getUnitTarget()->GetMaxHealth())
- {
- failReason = SPELL_FAILED_ALREADY_AT_FULL_HEALTH;
- continue;
- }
- else
- {
- failReason = SPELL_CAST_OK;
- break;
- }
- }
-
- // Mana Potion, Rage Potion, Thistle Tea(Rogue), ...
- if (m_spellInfo->Effect[i] == SPELL_EFFECT_ENERGIZE)
- {
- if(m_spellInfo->EffectMiscValue[i] < 0 || m_spellInfo->EffectMiscValue[i] >= MAX_POWERS)
- {
- failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER;
- continue;
- }
-
- Powers power = Powers(m_spellInfo->EffectMiscValue[i]);
- if (m_targets.getUnitTarget()->GetPower(power) == m_targets.getUnitTarget()->GetMaxPower(power))
- {
- failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER;
- continue;
- }
- else
- {
- failReason = SPELL_CAST_OK;
- break;
- }
- }
- }
- if (failReason != SPELL_CAST_OK)
- return failReason;
- }
- }
-
- // check target item
- if(m_targets.getItemTargetGUID())
- {
- if(m_caster->GetTypeId() != TYPEID_PLAYER)
- return SPELL_FAILED_BAD_TARGETS;
-
- if(!m_targets.getItemTarget())
- return SPELL_FAILED_ITEM_GONE;
-
- if(!m_targets.getItemTarget()->IsFitToSpellRequirements(m_spellInfo))
- return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
- }
- // if not item target then required item must be equipped
- else
- {
- if(m_caster->GetTypeId() == TYPEID_PLAYER && !((Player*)m_caster)->HasItemFitToSpellReqirements(m_spellInfo))
- return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
- }
-
- // check spell focus object
- if(m_spellInfo->RequiresSpellFocus)
- {
- CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
- Cell cell(p);
- cell.data.Part.reserved = ALL_DISTRICT;
-
- GameObject* ok = NULL;
- Trinity::GameObjectFocusCheck go_check(m_caster,m_spellInfo->RequiresSpellFocus);
- Trinity::GameObjectSearcher<Trinity::GameObjectFocusCheck> checker(m_caster, ok, go_check);
-
- TypeContainerVisitor<Trinity::GameObjectSearcher<Trinity::GameObjectFocusCheck>, GridTypeMapContainer > object_checker(checker);
- Map& map = *m_caster->GetMap();
- cell.Visit(p, object_checker, map, *m_caster, map.GetVisibilityDistance());
-
- if(!ok)
- return SPELL_FAILED_REQUIRES_SPELL_FOCUS;
-
- focusObject = ok; // game object found in range
- }
-
- // do not take reagents for these item casts
- if (!(m_CastItem && m_CastItem->GetProto()->Flags & ITEM_FLAGS_TRIGGERED_CAST))
- {
- // check reagents (ignore triggered spells with reagents processed by original spell) and special reagent ignore case.
- if (!m_IsTriggeredSpell && !p_caster->CanNoReagentCast(m_spellInfo))
- {
- for (uint32 i=0; i<8; i++)
- {
- if(m_spellInfo->Reagent[i] <= 0)
- continue;
-
- uint32 itemid = m_spellInfo->Reagent[i];
- uint32 itemcount = m_spellInfo->ReagentCount[i];
-
- // if CastItem is also spell reagent
- if( m_CastItem && m_CastItem->GetEntry() == itemid )
- {
- ItemPrototype const *proto = m_CastItem->GetProto();
- if(!proto)
- return SPELL_FAILED_ITEM_NOT_READY;
- for (int s=0; s < MAX_ITEM_PROTO_SPELLS; ++s)
- {
- // CastItem will be used up and does not count as reagent
- int32 charges = m_CastItem->GetSpellCharges(s);
- if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
- {
- ++itemcount;
- break;
- }
- }
- }
- if( !p_caster->HasItemCount(itemid,itemcount) )
- return SPELL_FAILED_ITEM_NOT_READY; //0x54
- }
- }
-
- // check totem-item requirements (items presence in inventory)
- uint32 totems = 2;
- for (int i = 0; i < 2 ; ++i)
- {
- if(m_spellInfo->Totem[i] != 0)
- {
- if( p_caster->HasItemCount(m_spellInfo->Totem[i],1) )
- {
- totems -= 1;
- continue;
- }
- }else
- totems -= 1;
- }
- if(totems != 0)
- return SPELL_FAILED_TOTEMS; //0x7C
-
- // Check items for TotemCategory (items presence in inventory)
- uint32 TotemCategory = 2;
- for (int i= 0; i < 2; ++i)
- {
- if(m_spellInfo->TotemCategory[i] != 0)
- {
- if( p_caster->HasItemTotemCategory(m_spellInfo->TotemCategory[i]) )
- {
- TotemCategory -= 1;
- continue;
- }
- }
- else
- TotemCategory -= 1;
- }
- if(TotemCategory != 0)
- return SPELL_FAILED_TOTEM_CATEGORY; //0x7B
- }
-
- // special checks for spell effects
- for (int i = 0; i < 3; i++)
- {
- switch (m_spellInfo->Effect[i])
- {
- case SPELL_EFFECT_CREATE_ITEM:
- {
- if (!m_IsTriggeredSpell && m_spellInfo->EffectItemType[i])
- {
- ItemPosCountVec dest;
- uint8 msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->EffectItemType[i], 1 );
- if (msg != EQUIP_ERR_OK )
- {
- ItemPrototype const *pProto = objmgr.GetItemPrototype(m_spellInfo->EffectItemType[i]);
- if (pProto && !(pProto->ItemLimitCategory))
- {
- p_caster->SendEquipError( msg, NULL, NULL );
- return SPELL_FAILED_DONT_REPORT;
- }
- else
- {
- if (!(m_spellInfo->SpellFamilyName == SPELLFAMILY_MAGE && (m_spellInfo->SpellFamilyFlags[0] & 0x40000000)))
- return SPELL_FAILED_TOO_MANY_OF_ITEM;
- else if (!(p_caster->HasItemCount(m_spellInfo->EffectItemType[i],1)))
- return SPELL_FAILED_TOO_MANY_OF_ITEM;
- else
- p_caster->CastSpell(m_caster,m_spellInfo->CalculateSimpleValue(1),false); // move this to anywhere
- return SPELL_FAILED_DONT_REPORT;
- }
- }
- }
- break;
- }
- case SPELL_EFFECT_ENCHANT_ITEM:
- if(m_spellInfo->EffectItemType[i] && m_targets.getItemTarget()
- && (m_targets.getItemTarget()->IsWeaponVellum() || m_targets.getItemTarget()->IsArmorVellum()))
- {
- // cannot enchant vellum for other player
- if (m_targets.getItemTarget()->GetOwner()!=m_caster)
- return SPELL_FAILED_NOT_TRADEABLE;
- // do not allow to enchant vellum from scroll made by vellum-prevent exploit
- if (m_CastItem && m_CastItem->GetProto()->Flags & ITEM_FLAGS_TRIGGERED_CAST)
- return SPELL_FAILED_TOTEM_CATEGORY;
- ItemPosCountVec dest;
- uint8 msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->EffectItemType[i], 1 );
- if (msg != EQUIP_ERR_OK )
- {
- p_caster->SendEquipError( msg, NULL, NULL );
- return SPELL_FAILED_DONT_REPORT;
- }
- }
- case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC:
- {
- Item* targetItem = m_targets.getItemTarget();
- if(!targetItem)
- return SPELL_FAILED_ITEM_NOT_FOUND;
-
- if( targetItem->GetProto()->ItemLevel < m_spellInfo->baseLevel )
- return SPELL_FAILED_LOWLEVEL;
- // Not allow enchant in trade slot for some enchant type
- if( targetItem->GetOwner() != m_caster )
- {
- uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
- SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
- if(!pEnchant)
- return SPELL_FAILED_ERROR;
- if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
- return SPELL_FAILED_NOT_TRADEABLE;
- }
- break;
- }
- case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
- {
- Item *item = m_targets.getItemTarget();
- if(!item)
- return SPELL_FAILED_ITEM_NOT_FOUND;
- // Not allow enchant in trade slot for some enchant type
- if( item->GetOwner() != m_caster )
- {
- uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
- SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
- if(!pEnchant)
- return SPELL_FAILED_ERROR;
- if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
- return SPELL_FAILED_NOT_TRADEABLE;
- }
- break;
- }
- case SPELL_EFFECT_ENCHANT_HELD_ITEM:
- // check item existence in effect code (not output errors at offhand hold item effect to main hand for example
- break;
- case SPELL_EFFECT_DISENCHANT:
- {
- if(!m_targets.getItemTarget())
- return SPELL_FAILED_CANT_BE_DISENCHANTED;
-
- // prevent disenchanting in trade slot
- if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
- return SPELL_FAILED_CANT_BE_DISENCHANTED;
-
- ItemPrototype const* itemProto = m_targets.getItemTarget()->GetProto();
- if(!itemProto)
- return SPELL_FAILED_CANT_BE_DISENCHANTED;
-
- uint32 item_quality = itemProto->Quality;
- // 2.0.x addon: Check player enchanting level against the item disenchanting requirements
- uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill;
- if (item_disenchantskilllevel == uint32(-1))
- return SPELL_FAILED_CANT_BE_DISENCHANTED;
- if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING))
- return SPELL_FAILED_LOW_CASTLEVEL;
- if(item_quality > 4 || item_quality < 2)
- return SPELL_FAILED_CANT_BE_DISENCHANTED;
- if(itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR)
- return SPELL_FAILED_CANT_BE_DISENCHANTED;
- if (!itemProto->DisenchantID)
- return SPELL_FAILED_CANT_BE_DISENCHANTED;
- break;
- }
- case SPELL_EFFECT_PROSPECTING:
- {
- if(!m_targets.getItemTarget())
- return SPELL_FAILED_CANT_BE_PROSPECTED;
- //ensure item is a prospectable ore
- if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_MINING_SUPP) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
- return SPELL_FAILED_CANT_BE_PROSPECTED;
- //prevent prospecting in trade slot
- if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
- return SPELL_FAILED_CANT_BE_PROSPECTED;
- //Check for enough skill in jewelcrafting
- uint32 item_prospectingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
- if(item_prospectingskilllevel >p_caster->GetSkillValue(SKILL_JEWELCRAFTING))
- return SPELL_FAILED_LOW_CASTLEVEL;
- //make sure the player has the required ores in inventory
- if(m_targets.getItemTarget()->GetCount() < 5)
- return SPELL_FAILED_NEED_MORE_ITEMS;
-
- if(!LootTemplates_Prospecting.HaveLootFor(m_targets.getItemTargetEntry()))
- return SPELL_FAILED_CANT_BE_PROSPECTED;
-
- break;
- }
- case SPELL_EFFECT_MILLING:
- {
- if(!m_targets.getItemTarget())
- return SPELL_FAILED_CANT_BE_MILLED;
- //ensure item is a millable herb
- if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_HERBS) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
- return SPELL_FAILED_CANT_BE_MILLED;
- //prevent milling in trade slot
- if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
- return SPELL_FAILED_CANT_BE_MILLED;
- //Check for enough skill in inscription
- uint32 item_millingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
- if(item_millingskilllevel >p_caster->GetSkillValue(SKILL_INSCRIPTION))
- return SPELL_FAILED_LOW_CASTLEVEL;
- //make sure the player has the required herbs in inventory
- if(m_targets.getItemTarget()->GetCount() < 5)
- return SPELL_FAILED_NEED_MORE_ITEMS;
-
- if(!LootTemplates_Milling.HaveLootFor(m_targets.getItemTargetEntry()))
- return SPELL_FAILED_CANT_BE_MILLED;
-
- break;
- }
- case SPELL_EFFECT_WEAPON_DAMAGE:
- case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
- {
- if(m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER;
- if( m_attackType != RANGED_ATTACK )
- break;
- Item *pItem = ((Player*)m_caster)->GetWeaponForAttack(m_attackType);
- if(!pItem || pItem->IsBroken())
- return SPELL_FAILED_EQUIPPED_ITEM;
-
- switch(pItem->GetProto()->SubClass)
- {
- case ITEM_SUBCLASS_WEAPON_THROWN:
- {
- uint32 ammo = pItem->GetEntry();
- if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
- return SPELL_FAILED_NO_AMMO;
- }; break;
- case ITEM_SUBCLASS_WEAPON_GUN:
- case ITEM_SUBCLASS_WEAPON_BOW:
- case ITEM_SUBCLASS_WEAPON_CROSSBOW:
- {
- uint32 ammo = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
- if(!ammo)
- {
- // Requires No Ammo
- if(m_caster->HasAura(46699))
- break; // skip other checks
-
- return SPELL_FAILED_NO_AMMO;
- }
-
- ItemPrototype const *ammoProto = objmgr.GetItemPrototype( ammo );
- if(!ammoProto)
- return SPELL_FAILED_NO_AMMO;
-
- if(ammoProto->Class != ITEM_CLASS_PROJECTILE)
- return SPELL_FAILED_NO_AMMO;
-
- // check ammo ws. weapon compatibility
- switch(pItem->GetProto()->SubClass)
- {
- case ITEM_SUBCLASS_WEAPON_BOW:
- case ITEM_SUBCLASS_WEAPON_CROSSBOW:
- if(ammoProto->SubClass != ITEM_SUBCLASS_ARROW)
- return SPELL_FAILED_NO_AMMO;
- break;
- case ITEM_SUBCLASS_WEAPON_GUN:
- if(ammoProto->SubClass != ITEM_SUBCLASS_BULLET)
- return SPELL_FAILED_NO_AMMO;
- break;
- default:
- return SPELL_FAILED_NO_AMMO;
- }
-
- if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
- return SPELL_FAILED_NO_AMMO;
- }; break;
- case ITEM_SUBCLASS_WEAPON_WAND:
- break;
- default:
- break;
- }
- break;
- }
- case SPELL_EFFECT_CREATE_MANA_GEM:
- {
- uint32 item_id = m_spellInfo->EffectItemType[i];
- ItemPrototype const *pProto = objmgr.GetItemPrototype(item_id);
-
- if (!pProto)
- return SPELL_FAILED_ITEM_AT_MAX_CHARGES;
-
- if (Item* pitem = p_caster->GetItemByEntry(item_id))
- {
- for(int x = 0; x < MAX_ITEM_PROTO_SPELLS; ++x)
- if (pProto->Spells[x].SpellCharges != 0 && pitem->GetSpellCharges(x) == pProto->Spells[x].SpellCharges)
- return SPELL_FAILED_ITEM_AT_MAX_CHARGES;
- }
- break;
- }
- default:
- break;
- }
- }
-
- // check weapon presence in slots for main/offhand weapons
- if(m_spellInfo->EquippedItemClass >=0)
- {
- // main hand weapon required
- if(m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_MAIN_HAND)
- {
- Item* item = ((Player*)m_caster)->GetWeaponForAttack(BASE_ATTACK);
-
- // skip spell if no weapon in slot or broken
- if(!item || item->IsBroken() )
- return m_IsTriggeredSpell? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS;
-
- // skip spell if weapon not fit to triggered spell
- if(!item->IsFitToSpellRequirements(m_spellInfo))
- return m_IsTriggeredSpell? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS;
- }
-
- // offhand hand weapon required
- if(m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_OFFHAND)
- {
- Item* item = ((Player*)m_caster)->GetWeaponForAttack(OFF_ATTACK);
-
- // skip spell if no weapon in slot or broken
- if(!item || item->IsBroken() )
- return m_IsTriggeredSpell? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS;
-
- // skip spell if weapon not fit to triggered spell
- if(!item->IsFitToSpellRequirements(m_spellInfo))
- return m_IsTriggeredSpell? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS;
- }
- }
-
- return SPELL_CAST_OK;
-}
-
-void Spell::Delayed() // only called in DealDamage()
-{
- if(!m_caster)// || m_caster->GetTypeId() != TYPEID_PLAYER)
- return;
-
- //if (m_spellState == SPELL_STATE_DELAYED)
- // return; // spell is active and can't be time-backed
-
- if(isDelayableNoMore()) // Spells may only be delayed twice
- return;
-
- // spells not loosing casting time ( slam, dynamites, bombs.. )
- //if(!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE))
- // return;
-
- //check pushback reduce
- int32 delaytime = 500; // spellcasting delay is normally 500ms
- int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
- ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this);
- delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
- if(delayReduce >= 100)
- return;
-
- delaytime = delaytime * (100 - delayReduce) / 100;
-
- if(int32(m_timer) + delaytime > m_casttime)
- {
- delaytime = m_casttime - m_timer;
- m_timer = m_casttime;
- }
- else
- m_timer += delaytime;
-
- sLog.outDetail("Spell %u partially interrupted for (%d) ms at damage", m_spellInfo->Id, delaytime);
-
- WorldPacket data(SMSG_SPELL_DELAYED, 8+4);
- data.append(m_caster->GetPackGUID());
- data << uint32(delaytime);
-
- m_caster->SendMessageToSet(&data, true);
-}
-
-void Spell::DelayedChannel()
-{
- if (!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING)
- return;
-
- if (isDelayableNoMore()) // Spells may only be delayed twice
- return;
-
- //check pushback reduce
- int32 delaytime = GetSpellDuration(m_spellInfo) * 25 / 100; // channeling delay is normally 25% of its time per hit
- int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
- ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this);
- delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
- if(delayReduce >= 100)
- return;
-
- delaytime = delaytime * (100 - delayReduce) / 100;
-
- if(int32(m_timer) <= delaytime)
- {
- delaytime = m_timer;
- m_timer = 0;
- }
- else
- m_timer -= delaytime;
-
- sLog.outDebug("Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer);
-
- for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
- if ((*ihit).missCondition == SPELL_MISS_NONE)
- if (Unit* unit = (m_caster->GetGUID() == ihit->targetGUID) ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID))
- unit->DelayOwnedAuras(m_spellInfo->Id, m_originalCasterGUID, delaytime);
-
- // partially interrupt persistent area auras
- if(DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id))
- dynObj->Delay(delaytime);
-
- SendChannelUpdate(m_timer);
-}
-
-void Spell::UpdatePointers()
-{
- if(m_originalCasterGUID == m_caster->GetGUID())
- m_originalCaster = m_caster;
- else
- {
- m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
- if (m_originalCaster && !m_originalCaster->IsInWorld())
- m_originalCaster = NULL;
- }
-
- if (m_castItemGUID && m_caster->GetTypeId() == TYPEID_PLAYER)
- m_CastItem = ((Player*)m_caster)->GetItemByGuid(m_castItemGUID);
-
- m_targets.Update(m_caster);
-}
-
-bool Spell::CheckTargetCreatureType(Unit* target) const
-{
- uint32 spellCreatureTargetMask = m_spellInfo->TargetCreatureType;
-
- // Curse of Doom & Exorcism: not find another way to fix spell target check :/
- if (m_spellInfo->SpellFamilyName==SPELLFAMILY_WARLOCK && m_spellInfo->Category == 1179)
- {
- // not allow cast at player
- if(target->GetTypeId() == TYPEID_PLAYER)
- return false;
-
- spellCreatureTargetMask = 0x7FF;
- }
-
- // Dismiss Pet and Taming Lesson skipped
- if(m_spellInfo->Id == 2641 || m_spellInfo->Id == 23356)
- spellCreatureTargetMask = 0;
-
- // Polymorph and Grounding Totem
- if (target->GetEntry() == 5925 && m_spellInfo->SpellFamilyName == SPELLFAMILY_MAGE && (m_spellInfo->SpellFamilyFlags[0] & 0x1000000) && m_spellInfo->EffectApplyAuraName[0] == SPELL_AURA_MOD_CONFUSE)
- return true;
-
- if (spellCreatureTargetMask)
- {
- uint32 TargetCreatureType = target->GetCreatureTypeMask();
-
- return !TargetCreatureType || (spellCreatureTargetMask & TargetCreatureType);
- }
- return true;
-}
-
-CurrentSpellTypes Spell::GetCurrentContainer()
-{
- if (IsNextMeleeSwingSpell())
- return(CURRENT_MELEE_SPELL);
- else if (IsAutoRepeat())
- return(CURRENT_AUTOREPEAT_SPELL);
- else if (IsChanneledSpell(m_spellInfo))
- return(CURRENT_CHANNELED_SPELL);
- else
- return(CURRENT_GENERIC_SPELL);
-}
-
-bool Spell::CheckTarget(Unit* target, uint32 eff)
-{
- // Check targets for creature type mask and remove not appropriate (skip explicit self target case, maybe need other explicit targets)
- if(m_spellInfo->EffectImplicitTargetA[eff] != TARGET_UNIT_CASTER)
- {
- if (!CheckTargetCreatureType(target))
- return false;
- }
-
- // Check Aura spell req (need for AoE spells)
- if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
- return false;
- if (m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
- return false;
-
- // Check targets for not_selectable unit flag and remove
- // A player can cast spells on his pet (or other controlled unit) though in any state
- if (target != m_caster && target->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
- {
- // any unattackable target skipped
- if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE))
- return false;
-
- // unselectable targets skipped in all cases except TARGET_UNIT_NEARBY_ENTRY targeting
- // in case TARGET_UNIT_NEARBY_ENTRY target selected by server always and can't be cheated
- /*if( target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE) &&
- m_spellInfo->EffectImplicitTargetA[eff] != TARGET_UNIT_NEARBY_ENTRY &&
- m_spellInfo->EffectImplicitTargetB[eff] != TARGET_UNIT_NEARBY_ENTRY )
- return false;*/
- }
-
- //Check player targets and remove if in GM mode or GM invisibility (for not self casting case)
- if( target != m_caster && target->GetTypeId() == TYPEID_PLAYER)
- {
- if(((Player*)target)->GetVisibility() == VISIBILITY_OFF)
- return false;
-
- if(((Player*)target)->isGameMaster() && !IsPositiveSpell(m_spellInfo->Id))
- return false;
- }
-
- switch(m_spellInfo->EffectApplyAuraName[eff])
- {
- case SPELL_AURA_NONE:
- default:
- break;
- case SPELL_AURA_MOD_POSSESS:
- case SPELL_AURA_MOD_CHARM:
- case SPELL_AURA_MOD_POSSESS_PET:
- case SPELL_AURA_AOE_CHARM:
- if(target->GetTypeId() == TYPEID_UNIT && target->IsVehicle())
- return false;
- if(target->GetCharmerGUID())
- return false;
- if(int32 damage = CalculateDamage(eff, target))
- if((int32)target->getLevel() > damage)
- return false;
- break;
- }
-
- //Do not do further checks for triggered spells
- if(m_IsTriggeredSpell)
- return true;
-
- //Check targets for LOS visibility (except spells without range limitations )
- switch(m_spellInfo->Effect[eff])
- {
- case SPELL_EFFECT_SUMMON_PLAYER: // from anywhere
- break;
- case SPELL_EFFECT_DUMMY:
- if(m_spellInfo->Id != 20577) // Cannibalize
- break;
- //fall through
- case SPELL_EFFECT_RESURRECT_NEW:
- // player far away, maybe his corpse near?
- if(target != m_caster && !target->IsWithinLOSInMap(m_caster))
- {
- if(!m_targets.getCorpseTargetGUID())
- return false;
-
- Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster, m_targets.getCorpseTargetGUID());
- if(!corpse)
- return false;
-
- if(target->GetGUID() != corpse->GetOwnerGUID())
- return false;
-
- if(!corpse->IsWithinLOSInMap(m_caster))
- return false;
- }
-
- // all ok by some way or another, skip normal check
- break;
- default: // normal case
- // Get GO cast coordinates if original caster -> GO
- WorldObject *caster = NULL;
- if (IS_GAMEOBJECT_GUID(m_originalCasterGUID))
- caster = m_caster->GetMap()->GetGameObject(m_originalCasterGUID);
- if (!caster)
- caster = m_caster;
- if(target->GetEntry() == 5925)
- return true;
- if(target != m_caster && !target->IsWithinLOSInMap(caster))
- return false;
- break;
- }
-
- return true;
-}
-
-bool Spell::IsNeedSendToClient() const
-{
- return m_spellInfo->SpellVisual[0] || m_spellInfo->SpellVisual[1] || IsChanneledSpell(m_spellInfo) ||
- m_spellInfo->speed > 0.0f || !m_triggeredByAuraSpell && !m_IsTriggeredSpell;
-}
-
-bool Spell::HaveTargetsForEffect( uint8 effect ) const
-{
- for (std::list<TargetInfo>::const_iterator itr = m_UniqueTargetInfo.begin(); itr != m_UniqueTargetInfo.end(); ++itr)
- if(itr->effectMask & (1 << effect))
- return true;
-
- for (std::list<GOTargetInfo>::const_iterator itr = m_UniqueGOTargetInfo.begin(); itr != m_UniqueGOTargetInfo.end(); ++itr)
- if(itr->effectMask & (1 << effect))
- return true;
-
- for (std::list<ItemTargetInfo>::const_iterator itr = m_UniqueItemInfo.begin(); itr != m_UniqueItemInfo.end(); ++itr)
- if(itr->effectMask & (1 << effect))
- return true;
-
- return false;
-}
-
-SpellEvent::SpellEvent(Spell* spell) : BasicEvent()
-{
- m_Spell = spell;
-}
-
-SpellEvent::~SpellEvent()
-{
- if (m_Spell->getState() != SPELL_STATE_FINISHED)
- m_Spell->cancel();
-
- if (m_Spell->IsDeletable())
- {
- delete m_Spell;
- }
- else
- {
- sLog.outError("~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.",
- (m_Spell->GetCaster()->GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature"), m_Spell->GetCaster()->GetGUIDLow(), m_Spell->m_spellInfo->Id);
- }
-}
-
-bool SpellEvent::Execute(uint64 e_time, uint32 p_time)
-{
- // update spell if it is not finished
- if (m_Spell->getState() != SPELL_STATE_FINISHED)
- m_Spell->update(p_time);
-
- // check spell state to process
- switch (m_Spell->getState())
- {
- case SPELL_STATE_FINISHED:
- {
- // spell was finished, check deletable state
- if (m_Spell->IsDeletable())
- {
- // check, if we do have unfinished triggered spells
- return true; // spell is deletable, finish event
- }
- // event will be re-added automatically at the end of routine)
- } break;
-
- case SPELL_STATE_DELAYED:
- {
- // first, check, if we have just started
- if (m_Spell->GetDelayStart() != 0)
- {
- // no, we aren't, do the typical update
- // check, if we have channeled spell on our hands
- /*
- if (IsChanneledSpell(m_Spell->m_spellInfo))
- {
- // evented channeled spell is processed separately, casted once after delay, and not destroyed till finish
- // check, if we have casting anything else except this channeled spell and autorepeat
- if (m_Spell->GetCaster()->IsNonMeleeSpellCasted(false, true, true))
- {
- // another non-melee non-delayed spell is casted now, abort
- m_Spell->cancel();
- }
- else
- {
- // Set last not triggered spell for apply spellmods
- ((Player*)m_Spell->GetCaster())->SetSpellModTakingSpell(m_Spell, true);
- // do the action (pass spell to channeling state)
- m_Spell->handle_immediate();
-
- // And remove after effect handling
- ((Player*)m_Spell->GetCaster())->SetSpellModTakingSpell(m_Spell, false);
- }
- // event will be re-added automatically at the end of routine)
- }
- else
- */
- {
- // run the spell handler and think about what we can do next
- uint64 t_offset = e_time - m_Spell->GetDelayStart();
- uint64 n_offset = m_Spell->handle_delayed(t_offset);
- if (n_offset)
- {
- // re-add us to the queue
- m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false);
- return false; // event not complete
- }
- // event complete
- // finish update event will be re-added automatically at the end of routine)
- }
- }
- else
- {
- // delaying had just started, record the moment
- m_Spell->SetDelayStart(e_time);
- // re-plan the event for the delay moment
- m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false);
- return false; // event not complete
- }
- } break;
-
- default:
- {
- // all other states
- // event will be re-added automatically at the end of routine)
- } break;
- }
-
- // spell processing not complete, plan event on the next update interval
- m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false);
- return false; // event not complete
-}
-
-void SpellEvent::Abort(uint64 /*e_time*/)
-{
- // oops, the spell we try to do is aborted
- if (m_Spell->getState() != SPELL_STATE_FINISHED)
- m_Spell->cancel();
-}
-
-bool SpellEvent::IsDeletable() const
-{
- return m_Spell->IsDeletable();
-}
-
-bool Spell::IsValidSingleTargetEffect(Unit const* target, Targets type) const
-{
- switch (type)
- {
- case TARGET_UNIT_TARGET_ENEMY:
- return !m_caster->IsFriendlyTo(target);
- case TARGET_UNIT_TARGET_ALLY:
- case TARGET_UNIT_PARTY_TARGET:
- return m_caster->IsFriendlyTo(target);
- case TARGET_UNIT_TARGET_PARTY:
- return m_caster != target && m_caster->IsInPartyWith(target);
- case TARGET_UNIT_TARGET_RAID:
- return m_caster->IsInRaidWith(target);
- }
- return true;
-}
-
-bool Spell::IsValidSingleTargetSpell(Unit const* target) const
-{
- if (target->GetMapId() == MAPID_INVALID)
- {
- sLog.outDebug("Spell::IsValidSingleTargetSpell - a spell was cast on '%s' (GUIDLow: %u), but they have an invalid map id!", target->GetName(), target->GetGUIDLow());
- return false;
- }
- for (uint8 i = 0; i < 3; ++i)
- {
- if(!IsValidSingleTargetEffect(target, Targets(m_spellInfo->EffectImplicitTargetA[i])))
- return false;
- // Need to check B?
- //if(!IsValidSingleTargetEffect(m_spellInfo->EffectImplicitTargetB[i], target)
- // return false;
- }
- return true;
-}
-
-void Spell::CalculateDamageDoneForAllTargets()
-{
- float multiplier[3];
- for (uint8 i = 0; i < 3; ++i)
- {
- if (m_applyMultiplierMask & (1 << i))
- {
- // Get multiplier
- multiplier[i] = m_spellInfo->DmgMultiplier[i];
- // Apply multiplier mods
- if(m_originalCaster)
- if(Player* modOwner = m_originalCaster->GetSpellModOwner())
- modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_EFFECT_PAST_FIRST, multiplier[i], this);
- }
- }
-
- bool usesAmmo = true;
- Unit::AuraEffectList const& Auras = m_caster->GetAuraEffectsByType(SPELL_AURA_ABILITY_CONSUME_NO_AMMO);
- for (Unit::AuraEffectList::const_iterator j = Auras.begin(); j != Auras.end(); ++j)
- {
- if((*j)->IsAffectedOnSpell(m_spellInfo))
- usesAmmo=false;
- }
-
- for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
- {
- TargetInfo &target = *ihit;
-
- uint32 mask = target.effectMask;
- if (!mask)
- continue;
-
- Unit* unit = m_caster->GetGUID()==target.targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target.targetGUID);
- if (!unit) // || !unit->isAlive()) do we need to check alive here?
- continue;
-
- if (usesAmmo)
- {
- bool ammoTaken=false;
- for (uint8 i=0; i<3; i++)
- {
- if (!(mask & 1<<i))
- continue;
- switch (m_spellInfo->Effect[i])
- {
- case SPELL_EFFECT_SCHOOL_DAMAGE:
- case SPELL_EFFECT_WEAPON_DAMAGE:
- case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
- case SPELL_EFFECT_NORMALIZED_WEAPON_DMG:
- case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE:
- ammoTaken=true;
- TakeAmmo();
- }
- if (ammoTaken)
- break;
- }
- }
-
- if (target.missCondition==SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
- {
- target.damage += CalculateDamageDone(unit, mask, multiplier);
- target.crit = m_caster->isSpellCrit(unit, m_spellInfo, m_spellSchoolMask, m_attackType);
- }
- else if (target.missCondition == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
- {
- if (target.reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
- {
- target.damage += CalculateDamageDone(m_caster, mask, multiplier);
- target.crit = m_caster->isSpellCrit(m_caster, m_spellInfo, m_spellSchoolMask, m_attackType);
- }
- }
- }
-}
-
-int32 Spell::CalculateDamageDone(Unit *unit, const uint32 effectMask, float *multiplier)
-{
- int32 damageDone = 0;
- unitTarget = unit;
- for (uint32 i = 0; i < 3; ++i)
- {
- if (effectMask & (1<<i))
- {
- m_damage = 0;
- damage = CalculateDamage(i, NULL);
-
- switch(m_spellInfo->Effect[i])
- {
- case SPELL_EFFECT_SCHOOL_DAMAGE:
- SpellDamageSchoolDmg(i);
- break;
- case SPELL_EFFECT_WEAPON_DAMAGE:
- case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
- case SPELL_EFFECT_NORMALIZED_WEAPON_DMG:
- case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE:
- SpellDamageWeaponDmg(i);
- break;
- case SPELL_EFFECT_HEAL:
- SpellDamageHeal(i);
- break;
- }
-
- if(m_damage > 0)
- {
- if(IsAreaEffectTarget[m_spellInfo->EffectImplicitTargetA[i]] || IsAreaEffectTarget[m_spellInfo->EffectImplicitTargetB[i]])
- {
- if(int32 reducedPct = unit->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE))
- m_damage = m_damage * (100 + reducedPct) / 100;
-
- if (m_caster->GetTypeId() == TYPEID_PLAYER)
- {
- uint32 targetAmount = m_UniqueTargetInfo.size();
- if (targetAmount > 10)
- m_damage = m_damage * 10/targetAmount;
- }
- }
- }
- if(m_applyMultiplierMask & (1 << i))
- {
- m_damage *= m_damageMultipliers[i];
- m_damageMultipliers[i] *= multiplier[i];
- }
-
- damageDone += m_damage;
- }
- }
-
- return damageDone;
-}
-
-SpellCastResult Spell::CanOpenLock(uint32 effIndex, uint32 lockId, SkillType& skillId, int32& reqSkillValue, int32& skillValue)
-{
- if(!lockId) // possible case for GO and maybe for items.
- return SPELL_CAST_OK;
-
- // Get LockInfo
- LockEntry const *lockInfo = sLockStore.LookupEntry(lockId);
-
- if (!lockInfo)
- return SPELL_FAILED_BAD_TARGETS;
-
- bool reqKey = false; // some locks not have reqs
-
- for (int j = 0; j < 8; ++j)
- {
- switch(lockInfo->Type[j])
- {
- // check key item (many fit cases can be)
- case LOCK_KEY_ITEM:
- if(lockInfo->Index[j] && m_CastItem && m_CastItem->GetEntry()==lockInfo->Index[j])
- return SPELL_CAST_OK;
- reqKey = true;
- break;
- // check key skill (only single first fit case can be)
- case LOCK_KEY_SKILL:
- {
- reqKey = true;
-
- // wrong locktype, skip
- if(uint32(m_spellInfo->EffectMiscValue[effIndex]) != lockInfo->Index[j])
- continue;
-
- skillId = SkillByLockType(LockType(lockInfo->Index[j]));
-
- if ( skillId != SKILL_NONE )
- {
- // skill bonus provided by casting spell (mostly item spells)
- // add the damage modifier from the spell casted (cheat lock / skeleton key etc.) (use m_currentBasePoints, CalculateDamage returns wrong value)
- uint32 spellSkillBonus = uint32(m_currentBasePoints[effIndex]+1);
- reqSkillValue = lockInfo->Skill[j];
-
- // castitem check: rogue using skeleton keys. the skill values should not be added in this case.
- skillValue = m_CastItem || m_caster->GetTypeId()!= TYPEID_PLAYER ?
- 0 : ((Player*)m_caster)->GetSkillValue(skillId);
-
- skillValue += spellSkillBonus;
-
- if (skillValue < reqSkillValue)
- return SPELL_FAILED_LOW_CASTLEVEL;
- }
-
- return SPELL_CAST_OK;
- }
- }
- }
-
- if(reqKey)
- return SPELL_FAILED_BAD_TARGETS;
-
- return SPELL_CAST_OK;
-}
-
-void Spell::SetSpellValue(SpellValueMod mod, int32 value)
-{
- switch(mod)
- {
- case SPELLVALUE_BASE_POINT0:
- m_spellValue->EffectBasePoints[0] = value - int32(m_spellInfo->EffectBaseDice[0]);
- m_currentBasePoints[0] = m_spellValue->EffectBasePoints[0]; //this should be removed in the future
- break;
- case SPELLVALUE_BASE_POINT1:
- m_spellValue->EffectBasePoints[1] = value - int32(m_spellInfo->EffectBaseDice[1]);
- m_currentBasePoints[1] = m_spellValue->EffectBasePoints[1];
- break;
- case SPELLVALUE_BASE_POINT2:
- m_spellValue->EffectBasePoints[2] = value - int32(m_spellInfo->EffectBaseDice[2]);
- m_currentBasePoints[2] = m_spellValue->EffectBasePoints[2];
- break;
- case SPELLVALUE_RADIUS_MOD:
- m_spellValue->RadiusMod = (float)value / 10000;
- break;
- case SPELLVALUE_MAX_TARGETS:
- m_spellValue->MaxAffectedTargets = (uint32)value;
- break;
- }
-}
-
-float tangent(float x)
-{
- x = tan(x);
- //if(x < std::numeric_limits<float>::max() && x > -std::numeric_limits<float>::max()) return x;
- //if(x >= std::numeric_limits<float>::max()) return std::numeric_limits<float>::max();
- //if(x <= -std::numeric_limits<float>::max()) return -std::numeric_limits<float>::max();
- if(x < 100000.0f && x > -100000.0f) return x;
- if(x >= 100000.0f) return 100000.0f;
- if(x <= 100000.0f) return -100000.0f;
- return 0.0f;
-}
-
-#define DEBUG_TRAJ(a) //a
-
-void Spell::SelectTrajTargets()
-{
- if(!m_targets.HasTraj())
- return;
-
- float dist2d = m_targets.GetDist2d();
- if(!dist2d)
- return;
-
- float dz = m_targets.m_dstPos.m_positionZ - m_targets.m_srcPos.m_positionZ;
-
- UnitList unitList;
- SearchAreaTarget(unitList, dist2d, PUSH_IN_THIN_LINE, SPELL_TARGETS_ANY);
- if(unitList.empty())
- return;
-
- unitList.sort(TargetDistanceOrder(m_caster));
-
- float b = tangent(m_targets.m_elevation);
- float a = (dz - dist2d * b) / (dist2d * dist2d);
- if(a > -0.0001f) a = 0;
- DEBUG_TRAJ(sLog.outError("Spell::SelectTrajTargets: a %f b %f", a, b);)
-
- float bestDist = GetSpellMaxRange(m_spellInfo, false);
-
- UnitList::const_iterator itr = unitList.begin();
- for (; itr != unitList.end(); ++itr)
- {
- if(m_caster == *itr || m_caster->IsOnVehicle(*itr) || (*itr)->GetVehicle())//(*itr)->IsOnVehicle(m_caster))
- continue;
-
- const float size = std::max((*itr)->GetObjectSize() * 0.7f, 1.0f); // 1/sqrt(3)
- // TODO: all calculation should be based on src instead of m_caster
- const float objDist2d = m_targets.m_srcPos.GetExactDist2d(*itr) * cos(m_targets.m_srcPos.GetRelativeAngle(*itr));
- const float dz = (*itr)->GetPositionZ() - m_targets.m_srcPos.m_positionZ;
-
- DEBUG_TRAJ(sLog.outError("Spell::SelectTrajTargets: check %u, dist between %f %f, height between %f %f.", (*itr)->GetEntry(), objDist2d - size, objDist2d + size, dz - size, dz + size);)
-
- float dist = objDist2d - size;
- float height = dist * (a * dist + b);
- DEBUG_TRAJ(sLog.outError("Spell::SelectTrajTargets: dist %f, height %f.", dist, height);)
- if(dist < bestDist && height < dz + size && height > dz - size)
- {
- bestDist = dist > 0 ? dist : 0;
- break;
- }
-
-#define CHECK_DIST {\
- DEBUG_TRAJ(sLog.outError("Spell::SelectTrajTargets: dist %f, height %f.", dist, height);)\
- if(dist > bestDist) continue;\
- if(dist < objDist2d + size && dist > objDist2d - size) { bestDist = dist; break; }\
- }
-
- if(!a)
- {
- height = dz - size;
- dist = height / b;
- CHECK_DIST;
-
- height = dz + size;
- dist = height / b;
- CHECK_DIST;
-
- continue;
- }
-
- height = dz - size;
- float sqrt1 = b * b + 4 * a * height;
- if(sqrt1 > 0)
- {
- sqrt1 = sqrt(sqrt1);
- dist = (sqrt1 - b) / (2 * a);
- CHECK_DIST;
- }
-
- height = dz + size;
- float sqrt2 = b * b + 4 * a * height;
- if(sqrt2 > 0)
- {
- sqrt2 = sqrt(sqrt2);
- dist = (sqrt2 - b) / (2 * a);
- CHECK_DIST;
-
- dist = (-sqrt2 - b) / (2 * a);
- CHECK_DIST;
- }
-
- if(sqrt1 > 0)
- {
- dist = (-sqrt1 - b) / (2 * a);
- CHECK_DIST;
- }
- }
-
- if(m_targets.m_srcPos.GetExactDist2d(&m_targets.m_dstPos) > bestDist)
- {
- float x = m_targets.m_srcPos.m_positionX + cos(m_caster->GetOrientation()) * bestDist;
- float y = m_targets.m_srcPos.m_positionY + sin(m_caster->GetOrientation()) * bestDist;
- float z = m_targets.m_srcPos.m_positionZ + bestDist * (a * bestDist + b);
-
- if(itr != unitList.end())
- {
- float distSq = (*itr)->GetExactDistSq(x, y, z);
- float sizeSq = (*itr)->GetObjectSize();
- sizeSq *= sizeSq;
- DEBUG_TRAJ(sLog.outError("Initial %f %f %f %f %f", x, y, z, distSq, sizeSq);)
- if(distSq > sizeSq)
- {
- float factor = 1 - sqrt(sizeSq / distSq);
- x += factor * ((*itr)->GetPositionX() - x);
- y += factor * ((*itr)->GetPositionY() - y);
- z += factor * ((*itr)->GetPositionZ() - z);
-
- distSq = (*itr)->GetExactDistSq(x, y, z);
- DEBUG_TRAJ(sLog.outError("Initial %f %f %f %f %f", x, y, z, distSq, sizeSq);)
- }
- }
-
- m_targets.setDst(x, y, z, m_caster->GetOrientation());
- }
-}
-
-void Spell::FillRaidOrPartyTargets( UnitList &TagUnitMap, Unit* target, float radius, bool raid, bool withPets, bool withcaster )
-{
- Player *pTarget = target->GetCharmerOrOwnerPlayerOrPlayerItself();
- Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
-
- if (pGroup)
- {
- uint8 subgroup = pTarget->GetSubGroup();
-
- for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
- {
- Player* Target = itr->getSource();
-
- // IsHostileTo check duel and controlled by enemy
- if (Target && (raid || subgroup==Target->GetSubGroup())
- && !m_caster->IsHostileTo(Target))
- {
- if (Target==m_caster && withcaster ||
- Target!=m_caster && m_caster->IsWithinDistInMap(Target, radius))
- TagUnitMap.push_back(Target);
-
- if (withPets)
- if (Pet* pet = Target->GetPet())
- if (pet==m_caster && withcaster ||
- pet!=m_caster && m_caster->IsWithinDistInMap(pet, radius))
- TagUnitMap.push_back(pet);
- }
- }
- }
- else
- {
- Unit* ownerOrSelf = pTarget ? pTarget : target->GetCharmerOrOwnerOrSelf();
- if (ownerOrSelf==m_caster && withcaster ||
- ownerOrSelf!=m_caster && m_caster->IsWithinDistInMap(ownerOrSelf, radius))
- TagUnitMap.push_back(ownerOrSelf);
-
- if (withPets)
- if (Guardian* pet = ownerOrSelf->GetGuardianPet())
- if (pet==m_caster && withcaster ||
- pet!=m_caster && m_caster->IsWithinDistInMap(pet, radius))
- TagUnitMap.push_back(pet);
- }
-}
-
-void Spell::FillRaidOrPartyManaPriorityTargets( UnitList &TagUnitMap, Unit* target, float radius, uint32 count, bool raid, bool withPets, bool withCaster )
-{
- FillRaidOrPartyTargets(TagUnitMap,target,radius,raid,withPets,withCaster);
-
- PrioritizeManaUnitQueue manaUsers;
- for (UnitList::const_iterator itr = TagUnitMap.begin(); itr != TagUnitMap.end() && manaUsers.size() < count; ++itr)
- if ((*itr)->getPowerType() == POWER_MANA && !(*itr)->isDead())
- manaUsers.push(PrioritizeManaUnitWraper(*itr));
-
- TagUnitMap.clear();
- while(!manaUsers.empty())
- {
- TagUnitMap.push_back(manaUsers.top().getUnit());
- manaUsers.pop();
- }
-}
-
-void Spell::FillRaidOrPartyHealthPriorityTargets( UnitList &TagUnitMap, Unit* target, float radius, uint32 count, bool raid, bool withPets, bool withCaster )
-{
- FillRaidOrPartyTargets(TagUnitMap,target,radius,raid,withPets,withCaster);
-
- PrioritizeHealthUnitQueue healthQueue;
- for (UnitList::const_iterator itr = TagUnitMap.begin(); itr != TagUnitMap.end() && healthQueue.size() < count; ++itr)
- if (!(*itr)->isDead())
- healthQueue.push(PrioritizeHealthUnitWraper(*itr));
-
- TagUnitMap.clear();
- while(!healthQueue.empty())
- {
- TagUnitMap.push_back(healthQueue.top().getUnit());
- healthQueue.pop();
- }
-}
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "Common.h"
+#include "Database/DatabaseEnv.h"
+#include "WorldPacket.h"
+#include "WorldSession.h"
+#include "GridNotifiers.h"
+#include "GridNotifiersImpl.h"
+#include "Opcodes.h"
+#include "Log.h"
+#include "UpdateMask.h"
+#include "World.h"
+#include "ObjectMgr.h"
+#include "SpellMgr.h"
+#include "Player.h"
+#include "Pet.h"
+#include "Unit.h"
+#include "Totem.h"
+#include "Spell.h"
+#include "DynamicObject.h"
+#include "Group.h"
+#include "UpdateData.h"
+#include "MapManager.h"
+#include "ObjectAccessor.h"
+#include "CellImpl.h"
+#include "Policies/SingletonImp.h"
+#include "SharedDefines.h"
+#include "LootMgr.h"
+#include "VMapFactory.h"
+#include "BattleGround.h"
+#include "Util.h"
+#include "TemporarySummon.h"
+#include "Vehicle.h"
+#include "SpellAuraEffects.h"
+#include "ScriptMgr.h"
+
+#define SPELL_CHANNEL_UPDATE_INTERVAL (1 * IN_MILISECONDS)
+
+extern pEffect SpellEffects[TOTAL_SPELL_EFFECTS];
+
+bool IsQuestTameSpell(uint32 spellId)
+{
+ SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId);
+ if (!spellproto) return false;
+
+ return spellproto->Effect[0] == SPELL_EFFECT_THREAT
+ && spellproto->Effect[1] == SPELL_EFFECT_APPLY_AURA && spellproto->EffectApplyAuraName[1] == SPELL_AURA_DUMMY;
+}
+
+class PrioritizeManaUnitWraper
+{
+ public:
+ explicit PrioritizeManaUnitWraper(Unit* unit) : i_unit(unit)
+ {
+ uint32 maxmana = unit->GetMaxPower(POWER_MANA);
+ i_percent = maxmana ? unit->GetPower(POWER_MANA) * 100 / maxmana : 101;
+ }
+ Unit* getUnit() const { return i_unit; }
+ uint32 getPercent() const { return i_percent; }
+ private:
+ Unit* i_unit;
+ uint32 i_percent;
+};
+
+struct PrioritizeMana
+{
+ int operator()( PrioritizeManaUnitWraper const& x, PrioritizeManaUnitWraper const& y ) const
+ {
+ return x.getPercent() > y.getPercent();
+ }
+};
+
+typedef std::priority_queue<PrioritizeManaUnitWraper, std::vector<PrioritizeManaUnitWraper>, PrioritizeMana> PrioritizeManaUnitQueue;
+
+class PrioritizeHealthUnitWraper
+{
+public:
+ explicit PrioritizeHealthUnitWraper(Unit* unit) : i_unit(unit)
+ {
+ i_percent = unit->GetHealth() * 100 / unit->GetMaxHealth();
+ }
+ Unit* getUnit() const { return i_unit; }
+ uint32 getPercent() const { return i_percent; }
+private:
+ Unit* i_unit;
+ uint32 i_percent;
+};
+
+struct PrioritizeHealth
+{
+ int operator()( PrioritizeHealthUnitWraper const& x, PrioritizeHealthUnitWraper const& y ) const
+ {
+ return x.getPercent() > y.getPercent();
+ }
+};
+
+typedef std::priority_queue<PrioritizeHealthUnitWraper, std::vector<PrioritizeHealthUnitWraper>, PrioritizeHealth> PrioritizeHealthUnitQueue;
+
+SpellCastTargets::SpellCastTargets() : m_elevation(0), m_speed(0)
+{
+ m_unitTarget = NULL;
+ m_itemTarget = NULL;
+ m_GOTarget = NULL;
+
+ m_unitTargetGUID = 0;
+ m_GOTargetGUID = 0;
+ m_CorpseTargetGUID = 0;
+ m_itemTargetGUID = 0;
+ m_itemTargetEntry = 0;
+
+ m_srcPos.Relocate(0,0,0,0);
+ m_strTarget = "";
+ m_targetMask = 0;
+}
+
+SpellCastTargets::~SpellCastTargets()
+{
+}
+
+void SpellCastTargets::setUnitTarget(Unit *target)
+{
+ if (!target)
+ return;
+
+ m_unitTarget = target;
+ m_unitTargetGUID = target->GetGUID();
+ m_targetMask |= TARGET_FLAG_UNIT;
+}
+
+void SpellCastTargets::setSrc(float x, float y, float z)
+{
+ m_srcPos.Relocate(x, y, z);
+ m_targetMask |= TARGET_FLAG_SOURCE_LOCATION;
+}
+
+void SpellCastTargets::setSrc(Position *pos)
+{
+ if(pos)
+ {
+ m_srcPos.Relocate(pos);
+ m_targetMask |= TARGET_FLAG_SOURCE_LOCATION;
+ }
+}
+
+void SpellCastTargets::setDst(float x, float y, float z, float orientation, uint32 mapId)
+{
+ m_dstPos.Relocate(x, y, z, orientation);
+ m_targetMask |= TARGET_FLAG_DEST_LOCATION;
+ if(mapId != MAPID_INVALID)
+ m_dstPos.m_mapId = mapId;
+}
+
+void SpellCastTargets::setDst(Position *pos)
+{
+ if(pos)
+ {
+ m_dstPos.Relocate(pos);
+ m_targetMask |= TARGET_FLAG_DEST_LOCATION;
+ }
+}
+
+void SpellCastTargets::setGOTarget(GameObject *target)
+{
+ m_GOTarget = target;
+ m_GOTargetGUID = target->GetGUID();
+ // m_targetMask |= TARGET_FLAG_OBJECT;
+}
+
+void SpellCastTargets::setItemTarget(Item* item)
+{
+ if(!item)
+ return;
+
+ m_itemTarget = item;
+ m_itemTargetGUID = item->GetGUID();
+ m_itemTargetEntry = item->GetEntry();
+ m_targetMask |= TARGET_FLAG_ITEM;
+}
+
+void SpellCastTargets::setCorpseTarget(Corpse* corpse)
+{
+ m_CorpseTargetGUID = corpse->GetGUID();
+}
+
+void SpellCastTargets::Update(Unit* caster)
+{
+ m_GOTarget = m_GOTargetGUID ? caster->GetMap()->GetGameObject(m_GOTargetGUID) : NULL;
+ m_unitTarget = m_unitTargetGUID ?
+ ( m_unitTargetGUID == caster->GetGUID() ? caster : ObjectAccessor::GetUnit(*caster, m_unitTargetGUID) ) :
+ NULL;
+
+ m_itemTarget = NULL;
+ if(caster->GetTypeId() == TYPEID_PLAYER)
+ {
+ if(m_targetMask & TARGET_FLAG_ITEM)
+ m_itemTarget = ((Player*)caster)->GetItemByGuid(m_itemTargetGUID);
+ else if(m_targetMask & TARGET_FLAG_TRADE_ITEM)
+ {
+ // here it is not guid but slot
+ Player* pTrader = ((Player*)caster)->GetTrader();
+ if(pTrader && m_itemTargetGUID < TRADE_SLOT_COUNT)
+ m_itemTarget = pTrader->GetItemByGuid(m_itemTargetGUID);
+ }
+ if(m_itemTarget)
+ m_itemTargetEntry = m_itemTarget->GetEntry();
+ }
+}
+
+bool SpellCastTargets::read ( WorldPacket * data, Unit *caster )
+{
+ if(data->rpos() + 4 > data->size())
+ return false;
+
+ //data->hexlike();
+
+ *data >> m_targetMask;
+ //sLog.outDebug("Spell read, target mask = %u", m_targetMask);
+
+ if(m_targetMask == TARGET_FLAG_SELF)
+ return true;
+
+ // TARGET_FLAG_UNK2 is used for non-combat pets, maybe other?
+ if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_UNK2 ))
+ if(!data->readPackGUID(m_unitTargetGUID))
+ return false;
+
+ if( m_targetMask & ( TARGET_FLAG_OBJECT ))
+ if(!data->readPackGUID(m_GOTargetGUID))
+ return false;
+
+ if(( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM )) && caster->GetTypeId() == TYPEID_PLAYER)
+ if(!data->readPackGUID(m_itemTargetGUID))
+ return false;
+
+ if( m_targetMask & (TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
+ if(!data->readPackGUID(m_CorpseTargetGUID))
+ return false;
+
+ if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
+ {
+ if(data->rpos() + 1 + 4 + 4 + 4 > data->size())
+ return false;
+
+ if(!data->readPackGUID(m_unitTargetGUID))
+ return false;
+
+ *data >> m_srcPos.m_positionX >> m_srcPos.m_positionY >> m_srcPos.m_positionZ;
+ if(!m_srcPos.IsPositionValid())
+ return false;
+ }
+ else
+ m_srcPos.Relocate(caster);
+
+ if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
+ {
+ if(data->rpos() + 1 + 4 + 4 + 4 > data->size())
+ return false;
+
+ if(!data->readPackGUID(m_unitTargetGUID))
+ return false;
+
+ *data >> m_dstPos.m_positionX >> m_dstPos.m_positionY >> m_dstPos.m_positionZ;
+ if(!m_dstPos.IsPositionValid())
+ return false;
+
+ if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
+ {
+ if(data->rpos() + 4 + 4 <= data->size())
+ {
+ *data >> m_elevation >> m_speed;
+ // TODO: should also read
+ m_srcPos.m_orientation = caster->GetOrientation();
+ //*data >> uint16 >> uint8 >> uint32 >> uint32;
+ //*data >> float >> float >> float >> float...
+ }
+ }
+ }
+ else
+ m_dstPos.Relocate(caster);
+
+ if( m_targetMask & TARGET_FLAG_STRING )
+ {
+ if(data->rpos() + 1 > data->size())
+ return false;
+
+ *data >> m_strTarget;
+ }
+
+ // find real units/GOs
+ Update(caster);
+ return true;
+}
+
+void SpellCastTargets::write ( WorldPacket * data )
+{
+ *data << uint32(m_targetMask);
+ //sLog.outDebug("Spell write, target mask = %u", m_targetMask);
+
+ if( m_targetMask & ( TARGET_FLAG_UNIT | TARGET_FLAG_PVP_CORPSE | TARGET_FLAG_OBJECT | TARGET_FLAG_CORPSE | TARGET_FLAG_UNK2 ) )
+ {
+ if(m_targetMask & TARGET_FLAG_UNIT)
+ {
+ if(m_unitTarget)
+ data->append(m_unitTarget->GetPackGUID());
+ else
+ *data << uint8(0);
+ }
+ else if( m_targetMask & TARGET_FLAG_OBJECT )
+ {
+ if(m_GOTarget)
+ data->append(m_GOTarget->GetPackGUID());
+ else
+ *data << uint8(0);
+ }
+ else if( m_targetMask & ( TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE ) )
+ data->appendPackGUID(m_CorpseTargetGUID);
+ else
+ *data << uint8(0);
+ }
+
+ if( m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM ) )
+ {
+ if(m_itemTarget)
+ data->append(m_itemTarget->GetPackGUID());
+ else
+ *data << uint8(0);
+ }
+
+ if( m_targetMask & TARGET_FLAG_SOURCE_LOCATION )
+ {
+ if(m_unitTarget)
+ data->append(m_unitTarget->GetPackGUID());
+ else
+ *data << uint8(0);
+
+ *data << m_srcPos.m_positionX << m_srcPos.m_positionY << m_srcPos.m_positionZ;
+ }
+
+ if( m_targetMask & TARGET_FLAG_DEST_LOCATION )
+ {
+ if(m_unitTarget)
+ data->append(m_unitTarget->GetPackGUID());
+ else
+ *data << uint8(0);
+
+ *data << m_dstPos.m_positionX << m_dstPos.m_positionY << m_dstPos.m_positionZ;
+ }
+
+ if( m_targetMask & TARGET_FLAG_STRING )
+ *data << m_strTarget;
+}
+
+Spell::Spell( Unit* Caster, SpellEntry const *info, bool triggered, uint64 originalCasterGUID, Spell** triggeringContainer, bool skipCheck )
+: m_spellInfo(info), m_spellValue(new SpellValue(m_spellInfo))
+, m_caster(Caster)
+{
+ m_customAttr = spellmgr.GetSpellCustomAttr(m_spellInfo->Id);
+ m_skipCheck = skipCheck;
+ m_selfContainer = NULL;
+ m_triggeringContainer = triggeringContainer;
+ m_referencedFromCurrentSpell = false;
+ m_executedCurrently = false;
+ m_needComboPoints = NeedsComboPoints(m_spellInfo);
+ m_comboPointGain = 0;
+ m_delayStart = 0;
+ m_delayAtDamageCount = 0;
+
+ m_applyMultiplierMask = 0;
+ m_effectMask = 0;
+ m_auraScaleMask = 0;
+
+ // Get data for type of attack
+ switch (m_spellInfo->DmgClass)
+ {
+ case SPELL_DAMAGE_CLASS_MELEE:
+ if (m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_OFFHAND)
+ m_attackType = OFF_ATTACK;
+ else
+ m_attackType = BASE_ATTACK;
+ break;
+ case SPELL_DAMAGE_CLASS_RANGED:
+ m_attackType = IsRangedWeaponSpell(m_spellInfo) ? RANGED_ATTACK : BASE_ATTACK;
+ break;
+ default:
+ // Wands
+ if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
+ m_attackType = RANGED_ATTACK;
+ else
+ m_attackType = BASE_ATTACK;
+ break;
+ }
+
+ m_spellSchoolMask = GetSpellSchoolMask(info); // Can be override for some spell (wand shoot for example)
+
+ if(m_attackType == RANGED_ATTACK)
+ {
+ // wand case
+ if((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId() == TYPEID_PLAYER)
+ {
+ if(Item* pItem = ((Player*)m_caster)->GetWeaponForAttack(RANGED_ATTACK))
+ m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetProto()->Damage[0].DamageType);
+ }
+ }
+ // Set health leech amount to zero
+ m_healthLeech = 0;
+
+ if(originalCasterGUID)
+ m_originalCasterGUID = originalCasterGUID;
+ else
+ m_originalCasterGUID = m_caster->GetGUID();
+
+ if(m_originalCasterGUID == m_caster->GetGUID())
+ m_originalCaster = m_caster;
+ else
+ {
+ m_originalCaster = ObjectAccessor::GetUnit(*m_caster, m_originalCasterGUID);
+ if(m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL;
+ }
+
+ for (int i=0; i <3; ++i)
+ m_currentBasePoints[i] = m_spellValue->EffectBasePoints[i];
+
+ m_spellState = SPELL_STATE_NULL;
+
+ m_TriggerSpells.clear();
+ m_IsTriggeredSpell = triggered;
+ //m_AreaAura = false;
+ m_CastItem = NULL;
+
+ unitTarget = NULL;
+ itemTarget = NULL;
+ gameObjTarget = NULL;
+ focusObject = NULL;
+ m_cast_count = 0;
+ m_glyphIndex = 0;
+ m_preCastSpell = 0;
+ m_triggeredByAuraSpell = NULL;
+ m_spellAura = NULL;
+
+ //Auto Shot & Shoot (wand)
+ m_autoRepeat = IsAutoRepeatRangedSpell(m_spellInfo);
+
+ m_runesState = 0;
+ m_powerCost = 0; // setup to correct value in Spell::prepare, don't must be used before.
+ m_casttime = 0; // setup to correct value in Spell::prepare, don't must be used before.
+ m_timer = 0; // will set to castime in prepare
+
+ m_needAliveTargetMask = 0;
+
+ // determine reflection
+ m_canReflect = false;
+
+ if(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && !IsAreaOfEffectSpell(m_spellInfo) && !(m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_CANT_REFLECTED))
+ {
+ for (int j = 0; j < 3; ++j)
+ {
+ if (m_spellInfo->Effect[j] == 0)
+ continue;
+
+ if(!IsPositiveTarget(m_spellInfo->EffectImplicitTargetA[j], m_spellInfo->EffectImplicitTargetB[j]))
+ m_canReflect = true;
+ else
+ m_canReflect = (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NEGATIVE) ? true : false;
+
+ if(m_canReflect)
+ continue;
+ else
+ break;
+ }
+ }
+
+ CleanupTargetList();
+}
+
+Spell::~Spell()
+{
+ if(m_caster && m_caster->GetTypeId() == TYPEID_PLAYER)
+ assert(((Player*)m_caster)->m_spellModTakingSpell != this);
+ delete m_spellValue;
+}
+
+template<typename T>
+WorldObject* Spell::FindCorpseUsing()
+{
+ // non-standard target selection
+ float max_range = GetSpellMaxRange(m_spellInfo, false);
+
+ CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
+ Cell cell(p);
+ cell.data.Part.reserved = ALL_DISTRICT;
+ cell.SetNoCreate();
+
+ WorldObject* result = NULL;
+
+ T u_check(m_caster, max_range);
+ Trinity::WorldObjectSearcher<T> searcher(m_caster, result, u_check);
+
+ TypeContainerVisitor<Trinity::WorldObjectSearcher<T>, GridTypeMapContainer > grid_searcher(searcher);
+ cell.Visit(p, grid_searcher, *m_caster->GetMap(), *m_caster, max_range);
+
+ if (!result)
+ {
+ TypeContainerVisitor<Trinity::WorldObjectSearcher<T>, WorldTypeMapContainer > world_searcher(searcher);
+ cell.Visit(p, world_searcher, *m_caster->GetMap(), *m_caster, max_range);
+ }
+
+ return result;
+}
+
+void Spell::SelectSpellTargets()
+{
+ for (uint32 i = 0; i < 3; ++i)
+ {
+ // not call for empty effect.
+ // Also some spells use not used effect targets for store targets for dummy effect in triggered spells
+ if(!m_spellInfo->Effect[i])
+ continue;
+
+ uint32 effectTargetType = EffectTargetType[m_spellInfo->Effect[i]];
+
+ // is it possible that areaaura is not applied to caster?
+ if(effectTargetType == SPELL_REQUIRE_NONE)
+ continue;
+
+ uint32 targetA = m_spellInfo->EffectImplicitTargetA[i];
+ uint32 targetB = m_spellInfo->EffectImplicitTargetB[i];
+
+ if(targetA)
+ SelectEffectTargets(i, targetA);
+ if(targetB) // In very rare case !A && B
+ SelectEffectTargets(i, targetB);
+
+ if(effectTargetType != SPELL_REQUIRE_UNIT)
+ {
+ if(effectTargetType == SPELL_REQUIRE_CASTER)
+ AddUnitTarget(m_caster, i);
+ else if(effectTargetType == SPELL_REQUIRE_ITEM)
+ {
+ if(m_targets.getItemTarget())
+ AddItemTarget(m_targets.getItemTarget(), i);
+ }
+ continue;
+ }
+
+ if(/*tmpUnitMap.empty() && */m_spellInfo->Targets & TARGET_FLAG_CASTER)
+ {
+ AddUnitTarget(m_caster, i);
+ continue;
+ }
+
+ if(!targetA && !targetB)
+ {
+ if(!GetSpellMaxRangeForFriend(sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex)))
+ {
+ AddUnitTarget(m_caster, i);
+ continue;
+ }
+
+ // add here custom effects that need default target.
+ // FOR EVERY TARGET TYPE THERE IS A DIFFERENT FILL!!
+ switch(m_spellInfo->Effect[i])
+ {
+ case SPELL_EFFECT_DUMMY:
+ {
+ switch(m_spellInfo->Id)
+ {
+ case 20577: // Cannibalize
+ {
+ WorldObject* result = FindCorpseUsing<Trinity::CannibalizeObjectCheck> ();
+
+ if(result)
+ {
+ switch(result->GetTypeId())
+ {
+ case TYPEID_UNIT:
+ case TYPEID_PLAYER:
+ AddUnitTarget((Unit*)result, i);
+ break;
+ case TYPEID_CORPSE:
+ m_targets.setCorpseTarget((Corpse*)result);
+ if(Player* owner = ObjectAccessor::FindPlayer(((Corpse*)result)->GetOwnerGUID()))
+ AddUnitTarget(owner, i);
+ break;
+ }
+ }
+ else
+ {
+ // clear cooldown at fail
+ if(m_caster->GetTypeId() == TYPEID_PLAYER)
+ ((Player*)m_caster)->RemoveSpellCooldown(m_spellInfo->Id, true);
+ SendCastResult(SPELL_FAILED_NO_EDIBLE_CORPSES);
+ finish(false);
+ }
+ break;
+ }
+ default:
+ if(m_targets.getUnitTarget())
+ AddUnitTarget(m_targets.getUnitTarget(), i);
+ else
+ AddUnitTarget(m_caster, i);
+ break;
+ }
+ break;
+ }
+ case SPELL_EFFECT_RESURRECT:
+ case SPELL_EFFECT_CREATE_ITEM:
+ case SPELL_EFFECT_TRIGGER_SPELL:
+ case SPELL_EFFECT_SKILL_STEP:
+ case SPELL_EFFECT_PROFICIENCY:
+ case SPELL_EFFECT_SUMMON_OBJECT_WILD:
+ case SPELL_EFFECT_SELF_RESURRECT:
+ case SPELL_EFFECT_REPUTATION:
+ case SPELL_EFFECT_LEARN_SPELL:
+ case SPELL_EFFECT_SEND_TAXI:
+ if(m_targets.getUnitTarget())
+ AddUnitTarget(m_targets.getUnitTarget(), i);
+ // Triggered spells have additional spell targets - cast them even if no explicit unit target is given (required for spell 50516 for example)
+ else if(m_spellInfo->Effect[i] == SPELL_EFFECT_TRIGGER_SPELL)
+ AddUnitTarget(m_caster, i);
+ break;
+ case SPELL_EFFECT_SUMMON_PLAYER:
+ if(m_caster->GetTypeId() == TYPEID_PLAYER && ((Player*)m_caster)->GetSelection())
+ {
+ Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
+ if(target)
+ AddUnitTarget(target, i);
+ }
+ break;
+ case SPELL_EFFECT_RESURRECT_NEW:
+ if(m_targets.getUnitTarget())
+ AddUnitTarget(m_targets.getUnitTarget(), i);
+ if(m_targets.getCorpseTargetGUID())
+ {
+ Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster, m_targets.getCorpseTargetGUID());
+ if(corpse)
+ {
+ Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
+ if(owner)
+ AddUnitTarget(owner, i);
+ }
+ }
+ break;
+ case SPELL_EFFECT_SUMMON_CHANGE_ITEM:
+ case SPELL_EFFECT_ADD_FARSIGHT:
+ case SPELL_EFFECT_APPLY_GLYPH:
+ case SPELL_EFFECT_STUCK:
+ case SPELL_EFFECT_FEED_PET:
+ case SPELL_EFFECT_DESTROY_ALL_TOTEMS:
+ case SPELL_EFFECT_KILL_CREDIT2: // only one spell: 42793
+ AddUnitTarget(m_caster, i);
+ break;
+ case SPELL_EFFECT_LEARN_PET_SPELL:
+ if(Guardian* pet = m_caster->GetGuardianPet())
+ AddUnitTarget(pet, i);
+ break;
+ /*case SPELL_EFFECT_ENCHANT_ITEM:
+ case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
+ case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC:
+ case SPELL_EFFECT_DISENCHANT:
+ case SPELL_EFFECT_PROSPECTING:
+ case SPELL_EFFECT_MILLING:
+ if(m_targets.getItemTarget())
+ AddItemTarget(m_targets.getItemTarget(), i);
+ break;*/
+ case SPELL_EFFECT_APPLY_AURA:
+ switch(m_spellInfo->EffectApplyAuraName[i])
+ {
+ case SPELL_AURA_ADD_FLAT_MODIFIER: // some spell mods auras have 0 target modes instead expected TARGET_UNIT_CASTER(1) (and present for other ranks for same spell for example)
+ case SPELL_AURA_ADD_PCT_MODIFIER:
+ AddUnitTarget(m_caster, i);
+ break;
+ default: // apply to target in other case
+ break;
+ }
+ break;
+ case SPELL_EFFECT_APPLY_AREA_AURA_PARTY:
+ // AreaAura
+ if(m_spellInfo->Attributes == 0x9050000 || m_spellInfo->Attributes == 0x10000)
+ SelectEffectTargets(i, TARGET_UNIT_PARTY_TARGET);
+ break;
+ case SPELL_EFFECT_SKIN_PLAYER_CORPSE:
+ if(m_targets.getUnitTarget())
+ {
+ AddUnitTarget(m_targets.getUnitTarget(), i);
+ }
+ else if (m_targets.getCorpseTargetGUID())
+ {
+ Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID());
+ if(corpse)
+ {
+ Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID());
+ if(owner)
+ AddUnitTarget(owner, i);
+ }
+ }
+ break;
+ default:
+ AddUnitTarget(m_caster, i);
+ break;
+ }
+ }
+ if(IsChanneledSpell(m_spellInfo))
+ {
+ uint8 mask = (1<<i);
+ for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
+ {
+ if(ihit->effectMask & mask)
+ {
+ m_needAliveTargetMask |= mask;
+ break;
+ }
+ }
+ }
+ else if (m_auraScaleMask)
+ {
+ bool checkLvl = !m_UniqueTargetInfo.empty();
+ for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();)
+ {
+ // remove targets which did not pass min level check
+ if(m_auraScaleMask && ihit->effectMask == m_auraScaleMask)
+ {
+ // Do not check for selfcast
+ if (!ihit->scaleAura && ihit->targetGUID != m_caster->GetGUID())
+ {
+ m_UniqueTargetInfo.erase(ihit++);
+ continue;
+ }
+ }
+ ++ihit;
+ }
+ if (checkLvl && m_UniqueTargetInfo.empty())
+ {
+ SendCastResult(SPELL_FAILED_LOWLEVEL);
+ finish(false);
+ }
+ }
+ }
+
+ if(m_targets.HasDst())
+ {
+ if(m_targets.HasTraj())
+ {
+ float speed = m_targets.GetSpeedXY();
+ if(speed > 0.0f)
+ m_delayMoment = (uint64)floor(m_targets.GetDist2d() / speed * 1000.0f);
+ }
+ else if(m_spellInfo->speed > 0.0f)
+ {
+ float dist = m_caster->GetDistance(m_targets.m_dstPos);
+ m_delayMoment = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
+ }
+ }
+}
+
+void Spell::prepareDataForTriggerSystem(AuraEffect const * triggeredByAura)
+{
+ //==========================================================================================
+ // Now fill data for trigger system, need know:
+ // can spell trigger another or not ( m_canTrigger )
+ // Create base triggers flags for Attacker and Victim ( m_procAttacker, m_procVictim and m_procEx)
+ //==========================================================================================
+
+ m_procVictim = m_procAttacker = 0;
+ // Get data for type of attack and fill base info for trigger
+ switch (m_spellInfo->DmgClass)
+ {
+ case SPELL_DAMAGE_CLASS_MELEE:
+ m_procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_SPELL_HIT;
+ m_procVictim = PROC_FLAG_TAKEN_MELEE_SPELL_HIT;
+ break;
+ case SPELL_DAMAGE_CLASS_RANGED:
+ // Auto attack
+ if (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG)
+ {
+ m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
+ m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
+ }
+ else // Ranged spell attack
+ {
+ m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_SPELL_HIT;
+ m_procVictim = PROC_FLAG_TAKEN_RANGED_SPELL_HIT;
+ }
+ break;
+ default:
+ if (m_spellInfo->EquippedItemClass == ITEM_CLASS_WEAPON &&
+ m_spellInfo->EquippedItemSubClassMask & (1<<ITEM_SUBCLASS_WEAPON_WAND)
+ && m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG) // Wands auto attack
+ {
+ m_procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
+ m_procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
+ }
+ // For other spells trigger procflags are set in Spell::DoAllEffectOnTarget
+ // Because spell positivity is dependant on target
+ }
+ m_procEx= PROC_EX_NONE;
+
+ // Hunter trap spells - activation proc for Lock and Load, Entrapment and Misdirection
+ if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER &&
+ (m_spellInfo->SpellFamilyFlags[0] & 0x18 || // Freezing and Frost Trap, Freezing Arrow
+ m_spellInfo->Id == 57879 || // Snake Trap - done this way to avoid double proc
+ m_spellInfo->SpellFamilyFlags[2] & 0x00024000)) // Explosive and Immolation Trap
+
+ m_procAttacker |= PROC_FLAG_ON_TRAP_ACTIVATION;
+
+ /*
+ Effects which are result of aura proc from triggered spell cannot proc
+ to prevent chain proc of these spells
+ */
+
+ // Ranged autorepeat attack is set as triggered spell - ignore it
+ if (!(m_procAttacker & PROC_FLAG_SUCCESSFUL_RANGED_HIT))
+ {
+ if (m_IsTriggeredSpell &&
+ (m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_TRIGGERED_CAN_TRIGGER ||
+ m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_TRIGGERED_CAN_TRIGGER_2))
+ m_procEx |= PROC_EX_INTERNAL_CANT_PROC;
+ else if (m_IsTriggeredSpell)
+ m_procEx |= PROC_EX_INTERNAL_TRIGGERED;
+ }
+ // Totem casts require spellfamilymask defined in spell_proc_event to proc
+ if (m_originalCaster && m_caster != m_originalCaster && m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->isTotem() && m_caster->IsControlledByPlayer())
+ {
+ m_procEx |= PROC_EX_INTERNAL_REQ_FAMILY;
+ }
+}
+
+void Spell::CleanupTargetList()
+{
+ m_UniqueTargetInfo.clear();
+ m_UniqueGOTargetInfo.clear();
+ m_UniqueItemInfo.clear();
+ m_delayMoment = 0;
+}
+
+void Spell::AddUnitTarget(Unit* pVictim, uint32 effIndex)
+{
+ if (m_spellInfo->Effect[effIndex] == 0)
+ return;
+
+ if (!CheckTarget(pVictim, effIndex))
+ return;
+
+ // Check for effect immune skip if immuned
+ bool immuned = pVictim->IsImmunedToSpellEffect(m_spellInfo, effIndex);
+
+ uint64 targetGUID = pVictim->GetGUID();
+
+ // Lookup target in already in list
+ for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
+ {
+ if (targetGUID == ihit->targetGUID) // Found in list
+ {
+ if (!immuned)
+ ihit->effectMask |= 1 << effIndex; // Add only effect mask if not immuned
+ ihit->scaleAura = false;
+ if (m_auraScaleMask && ihit->effectMask == m_auraScaleMask && m_caster != pVictim)
+ {
+ SpellEntry const * auraSpell = sSpellStore.LookupEntry(spellmgr.GetFirstSpellInChain(m_spellInfo->Id));
+ if ((pVictim->getLevel() + 10) >= auraSpell->spellLevel)
+ ihit->scaleAura = true;
+ }
+ return;
+ }
+ }
+
+ // This is new target calculate data for him
+
+ // Get spell hit result on target
+ TargetInfo target;
+ target.targetGUID = targetGUID; // Store target GUID
+ target.effectMask = immuned ? 0 : 1 << effIndex; // Store index of effect if not immuned
+ target.processed = false; // Effects not apply on target
+ target.alive = pVictim->isAlive();
+ target.damage = 0;
+ target.crit = false;
+ target.scaleAura = false;
+ if (m_auraScaleMask && target.effectMask == m_auraScaleMask && m_caster != pVictim)
+ {
+ SpellEntry const * auraSpell = sSpellStore.LookupEntry(spellmgr.GetFirstSpellInChain(m_spellInfo->Id));
+ if ((pVictim->getLevel() + 10) >= auraSpell->spellLevel)
+ target.scaleAura = true;
+ }
+
+ // Calculate hit result
+ if (m_originalCaster)
+ {
+ target.missCondition = m_originalCaster->SpellHitResult(pVictim, m_spellInfo, m_canReflect);
+ if(m_skipCheck && target.missCondition != SPELL_MISS_IMMUNE)
+ target.missCondition = SPELL_MISS_NONE;
+ }
+ else
+ target.missCondition = SPELL_MISS_EVADE; //SPELL_MISS_NONE;
+
+ // Spell have speed - need calculate incoming time
+ // Incoming time is zero for self casts. At least I think so.
+ if (m_spellInfo->speed > 0.0f && m_caster != pVictim)
+ {
+ // calculate spell incoming interval
+ // TODO: this is a hack
+ float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
+
+ if (dist < 5.0f) dist = 5.0f;
+ target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
+
+ // Calculate minimum incoming time
+ if (m_delayMoment == 0 || m_delayMoment>target.timeDelay)
+ m_delayMoment = target.timeDelay;
+ }
+ else
+ target.timeDelay = 0LL;
+
+ // If target reflect spell back to caster
+ if (target.missCondition == SPELL_MISS_REFLECT)
+ {
+ // Calculate reflected spell result on caster
+ target.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect);
+
+ if (target.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell
+ target.reflectResult = SPELL_MISS_PARRY;
+
+ // Increase time interval for reflected spells by 1.5
+ target.timeDelay += target.timeDelay >> 1;
+ }
+ else
+ target.reflectResult = SPELL_MISS_NONE;
+
+ // Add target to list
+ m_UniqueTargetInfo.push_back(target);
+}
+
+void Spell::AddUnitTarget(uint64 unitGUID, uint32 effIndex)
+{
+ if (Unit* unit = m_caster->GetGUID() == unitGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, unitGUID))
+ AddUnitTarget(unit, effIndex);
+}
+
+void Spell::AddGOTarget(GameObject* pVictim, uint32 effIndex)
+{
+ if( m_spellInfo->Effect[effIndex] == 0 )
+ return;
+
+ uint64 targetGUID = pVictim->GetGUID();
+
+ // Lookup target in already in list
+ for (std::list<GOTargetInfo>::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit)
+ {
+ if (targetGUID == ihit->targetGUID) // Found in list
+ {
+ ihit->effectMask |= 1 << effIndex; // Add only effect mask
+ return;
+ }
+ }
+
+ // This is new target calculate data for him
+
+ GOTargetInfo target;
+ target.targetGUID = targetGUID;
+ target.effectMask = 1 << effIndex;
+ target.processed = false; // Effects not apply on target
+
+ // Spell have speed - need calculate incoming time
+ if (m_spellInfo->speed > 0.0f)
+ {
+ // calculate spell incoming interval
+ float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ());
+ if (dist < 5.0f) dist = 5.0f;
+ target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f);
+ if (m_delayMoment==0 || m_delayMoment>target.timeDelay)
+ m_delayMoment = target.timeDelay;
+ }
+ else
+ target.timeDelay = 0LL;
+
+ // Add target to list
+ m_UniqueGOTargetInfo.push_back(target);
+}
+
+void Spell::AddGOTarget(uint64 goGUID, uint32 effIndex)
+{
+ GameObject* go = m_caster->GetMap()->GetGameObject(goGUID);
+ if (go)
+ AddGOTarget(go, effIndex);
+}
+
+void Spell::AddItemTarget(Item* pitem, uint32 effIndex)
+{
+ if( m_spellInfo->Effect[effIndex] == 0 )
+ return;
+
+ // Lookup target in already in list
+ for (std::list<ItemTargetInfo>::iterator ihit = m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit)
+ {
+ if (pitem == ihit->item) // Found in list
+ {
+ ihit->effectMask |= 1<<effIndex; // Add only effect mask
+ return;
+ }
+ }
+
+ // This is new target add data
+
+ ItemTargetInfo target;
+ target.item = pitem;
+ target.effectMask = 1 << effIndex;
+ m_UniqueItemInfo.push_back(target);
+}
+
+void Spell::DoAllEffectOnTarget(TargetInfo *target)
+{
+ if (!target || target == (TargetInfo*)0x10 || target->processed)
+ return;
+ target->processed = true; // Target checked in apply effects procedure
+
+ // Get mask of effects for target
+ uint32 mask = target->effectMask;
+
+ Unit* unit = m_caster->GetGUID()==target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID);
+ if (!unit)
+ return;
+
+ if(unit->isAlive() != target->alive)
+ return;
+
+ // Get original caster (if exist) and calculate damage/healing from him data
+ Unit *caster = m_originalCaster ? m_originalCaster : m_caster;
+
+ // Skip if m_originalCaster not avaiable
+ if (!caster)
+ return;
+
+ SpellMissInfo missInfo = target->missCondition;
+
+ // Need init unitTarget by default unit (can changed in code on reflect)
+ // Or on missInfo!=SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem)
+ unitTarget = unit;
+
+ // Reset damage/healing counter
+ m_damage = target->damage;
+ m_healing = -target->damage;
+
+ // Fill base trigger info
+ uint32 procAttacker = m_procAttacker;
+ uint32 procVictim = m_procVictim;
+ uint32 procEx = m_procEx;
+
+ m_spellAura = NULL; // Set aura to null for every target-make sure that pointer is not used for unit without aura applied
+
+ //Spells with this flag cannot trigger if effect is casted on self
+ // Slice and Dice, relentless strikes, eviscerate
+ bool canEffectTrigger = unitTarget->CanProc() && (m_spellInfo->AttributesEx4 & (SPELL_ATTR_EX4_CANT_PROC_FROM_SELFCAST) ? m_caster!=unitTarget : true);
+ Unit * spellHitTarget = NULL;
+
+ if (missInfo==SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
+ spellHitTarget = unit;
+ else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
+ {
+ if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
+ {
+ spellHitTarget = m_caster;
+ if(m_caster->GetTypeId() == TYPEID_UNIT)
+ ((Creature*)m_caster)->LowerPlayerDamageReq(target->damage);
+ }
+ }
+
+ if(spellHitTarget)
+ {
+ SpellMissInfo missInfo = DoSpellHitOnUnit(spellHitTarget, mask, target->scaleAura);
+ if(missInfo != SPELL_MISS_NONE)
+ {
+ if(missInfo != SPELL_MISS_MISS)
+ m_caster->SendSpellMiss(unit, m_spellInfo->Id, missInfo);
+ m_damage = 0;
+ spellHitTarget = NULL;
+ }
+ }
+
+ // Do not take combo points on dodge and miss
+ if (m_needComboPoints && m_targets.getUnitTargetGUID() == target->targetGUID)
+ if (missInfo != SPELL_MISS_NONE)
+ m_needComboPoints = false;
+
+ // Trigger info was not filled in spell::preparedatafortriggersystem - we do it now
+ if (canEffectTrigger && !procAttacker && !procVictim)
+ {
+ bool positive = true;
+ if (m_damage > 0)
+ positive = false;
+ else if (!m_healing)
+ {
+ for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i)
+ // If at least one effect negative spell is negative hit
+ if (mask & (1<<i) && !IsPositiveEffect(m_spellInfo->Id, i))
+ {
+ positive = false;
+ break;
+ }
+ }
+ switch(m_spellInfo->DmgClass)
+ {
+ case SPELL_DAMAGE_CLASS_MAGIC:
+ if (positive)
+ {
+ procAttacker |= PROC_FLAG_SUCCESSFUL_POSITIVE_MAGIC_SPELL;
+ procVictim |= PROC_FLAG_TAKEN_POSITIVE_MAGIC_SPELL;
+ }
+ else
+ {
+ procAttacker |= PROC_FLAG_SUCCESSFUL_NEGATIVE_MAGIC_SPELL;
+ procVictim |= PROC_FLAG_TAKEN_NEGATIVE_MAGIC_SPELL;
+ }
+ break;
+ case SPELL_DAMAGE_CLASS_NONE:
+ if (positive)
+ {
+ procAttacker |= PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL_HIT;
+ procVictim |= PROC_FLAG_TAKEN_POSITIVE_SPELL;
+ }
+ else
+ {
+ procAttacker |= PROC_FLAG_SUCCESSFUL_NEGATIVE_SPELL_HIT;
+ procVictim |= PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT;
+ }
+ break;
+ }
+ }
+ // All calculated do it!
+ // Do healing and triggers
+ if (m_healing > 0)
+ {
+ bool crit = caster->isSpellCrit(unitTarget, m_spellInfo, m_spellSchoolMask);
+ uint32 addhealth = m_healing;
+ if (crit)
+ {
+ procEx |= PROC_EX_CRITICAL_HIT;
+ addhealth = caster->SpellCriticalHealingBonus(m_spellInfo, addhealth, NULL);
+ }
+ else
+ procEx |= PROC_EX_NORMAL_HIT;
+
+ // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
+ if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT)
+ caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, addhealth, m_attackType, m_spellInfo, m_triggeredByAuraSpell);
+
+ int32 gain = caster->DealHeal(unitTarget, addhealth, m_spellInfo, crit);
+ unitTarget->getHostilRefManager().threatAssist(caster, float(gain) * 0.5f, m_spellInfo);
+ }
+ // Do damage and triggers
+ else if (m_damage > 0)
+ {
+ // Fill base damage struct (unitTarget - is real spell target)
+ SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
+
+ // Add bonuses and fill damageInfo struct
+ caster->CalculateSpellDamageTaken(&damageInfo, m_damage, m_spellInfo, m_attackType, target->crit);
+ caster->DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb);
+
+ // Send log damage message to client
+ caster->SendSpellNonMeleeDamageLog(&damageInfo);
+
+ procEx |= createProcExtendMask(&damageInfo, missInfo);
+ procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
+
+ // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
+ if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT)
+ {
+ caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo, m_triggeredByAuraSpell);
+ if(caster->GetTypeId() == TYPEID_PLAYER && (m_spellInfo->Attributes & SPELL_ATTR_STOP_ATTACK_TARGET) == 0 &&
+ (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_RANGED))
+ ((Player *)caster)->CastItemCombatSpell(unitTarget, m_attackType, procVictim, procEx);
+ }
+
+ caster->DealSpellDamage(&damageInfo, true);
+
+ // Haunt
+ if(m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags[1] & 0x40000 && m_spellAura && m_spellAura->GetEffect(1))
+ {
+ AuraEffect * aurEff = m_spellAura->GetEffect(1);
+ aurEff->SetAmount(aurEff->GetAmount() * damageInfo.damage / 100);
+ }
+ }
+ // Passive spell hits/misses or active spells only misses (only triggers)
+ else
+ {
+ // Fill base damage struct (unitTarget - is real spell target)
+ SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask);
+ procEx |= createProcExtendMask(&damageInfo, missInfo);
+ // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge)
+ if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT)
+ caster->ProcDamageAndSpell(unit, procAttacker, procVictim, procEx, 0, m_attackType, m_spellInfo, m_triggeredByAuraSpell);
+
+ // Failed Pickpocket, reveal rogue
+ if (missInfo == SPELL_MISS_RESIST
+ && m_customAttr & SPELL_ATTR_CU_PICKPOCKET
+ && unitTarget->GetTypeId() == TYPEID_UNIT)
+ {
+ m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TALK);
+ if (((Creature*)unitTarget)->IsAIEnabled)
+ ((Creature*)unitTarget)->AI()->AttackStart(m_caster);
+ }
+ }
+
+ if(m_caster && !m_caster->IsFriendlyTo(unit) && !IsPositiveSpell(m_spellInfo->Id))
+ {
+ m_caster->CombatStart(unit, !(m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_NO_INITIAL_AGGRO));
+
+ if(m_customAttr & SPELL_ATTR_CU_AURA_CC)
+ if(!unit->IsStandState())
+ unit->SetStandState(UNIT_STAND_STATE_STAND);
+ }
+
+ if(spellHitTarget)
+ {
+ //AI functions
+ if(spellHitTarget->GetTypeId() == TYPEID_UNIT)
+ {
+ if(((Creature*)spellHitTarget)->IsAIEnabled)
+ ((Creature*)spellHitTarget)->AI()->SpellHit(m_caster, m_spellInfo);
+
+ // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
+ // ignore pets or autorepeat/melee casts for speed (not exist quest for spells (hm... )
+ if(m_originalCaster && m_originalCaster->IsControlledByPlayer() && !((Creature*)spellHitTarget)->isPet() && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive())
+ if(Player* p = m_originalCaster->GetCharmerOrOwnerPlayerOrPlayerItself())
+ p->CastedCreatureOrGO(spellHitTarget->GetEntry(),spellHitTarget->GetGUID(),m_spellInfo->Id);
+ }
+
+ if(m_caster && m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->IsAIEnabled)
+ ((Creature*)m_caster)->AI()->SpellHitTarget(spellHitTarget, m_spellInfo);
+
+ // Needs to be called after dealing damage/healing to not remove breaking on damage auras
+ DoTriggersOnSpellHit(spellHitTarget);
+
+ // if target is fallged for pvp also flag caster if a player
+ if(unit->IsPvP())
+ {
+ if (m_caster->GetTypeId() == TYPEID_PLAYER)
+ ((Player*)m_caster)->UpdatePvP(true);
+ }
+
+ }
+}
+
+SpellMissInfo Spell::DoSpellHitOnUnit(Unit *unit, const uint32 effectMask, bool scaleAura)
+{
+ if(!unit || !effectMask)
+ return SPELL_MISS_EVADE;
+
+ // Recheck immune (only for delayed spells)
+ if(m_spellInfo->speed && (unit->IsImmunedToDamage(m_spellInfo) || unit->IsImmunedToSpell(m_spellInfo)))
+ return SPELL_MISS_IMMUNE;
+
+ if (unit->GetTypeId() == TYPEID_PLAYER)
+ {
+ ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id);
+ ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id);
+ }
+
+ if(m_caster->GetTypeId() == TYPEID_PLAYER)
+ {
+ ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, unit);
+ }
+
+ if( m_caster != unit )
+ {
+ // Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells
+ if (m_spellInfo->speed > 0.0f &&
+ unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE) &&
+ unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
+ {
+ return SPELL_MISS_EVADE;
+ }
+
+ if( !m_caster->IsFriendlyTo(unit) )
+ {
+ // reset damage to 0 if target has Invisibility and isn't visible for caster
+ // I do not think this is a correct way to fix it. Sanctuary effect should make all delayed spells invalid
+ // for delayed spells ignore not visible explicit target
+ if(m_spellInfo->speed > 0.0f && unit == m_targets.getUnitTarget()
+ && (unit->m_invisibilityMask || m_caster->m_invisibilityMask)
+ && !m_caster->canSeeOrDetect(unit, true))
+ {
+ // that was causing CombatLog errors
+ // return SPELL_MISS_EVADE;
+ return SPELL_MISS_MISS; // miss = do not send anything here
+ }
+
+ unit->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_HITBYSPELL);
+ //TODO: This is a hack. But we do not know what types of stealth should be interrupted by CC
+ if((m_customAttr & SPELL_ATTR_CU_AURA_CC) && unit->IsControlledByPlayer())
+ unit->RemoveAurasByType(SPELL_AURA_MOD_STEALTH);
+ }
+ else
+ {
+ // for delayed spells ignore negative spells (after duel end) for friendly targets
+ // TODO: this cause soul transfer bugged
+ if(m_spellInfo->speed > 0.0f && unit->GetTypeId() == TYPEID_PLAYER && !IsPositiveSpell(m_spellInfo->Id))
+ {
+ return SPELL_MISS_EVADE;
+ }
+
+ // assisting case, healing and resurrection
+ if(unit->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
+ {
+ m_caster->SetContestedPvP();
+ if(m_caster->GetTypeId() == TYPEID_PLAYER)
+ ((Player*)m_caster)->UpdatePvP(true);
+ }
+ if( unit->isInCombat() && !(m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_NO_INITIAL_AGGRO) )
+ {
+ m_caster->SetInCombatState(unit->GetCombatTimer() > 0, unit);
+ unit->getHostilRefManager().threatAssist(m_caster, 0.0f);
+ }
+ }
+ }
+
+ // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add
+ if(m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo,m_triggeredByAuraSpell))
+ {
+ m_diminishLevel = unit->GetDiminishing(m_diminishGroup);
+ DiminishingReturnsType type = GetDiminishingReturnsGroupType(m_diminishGroup);
+ // Increase Diminishing on unit, current informations for actually casts will use values above
+ if((type == DRTYPE_PLAYER && (unit->GetTypeId() == TYPEID_PLAYER || ((Creature*)unit)->isPet() || ((Creature*)unit)->isPossessedByPlayer())) || type == DRTYPE_ALL)
+ unit->IncrDiminishing(m_diminishGroup);
+ }
+
+ uint8 aura_effmask = 0;
+ for (uint8 i = 0; i < 3; ++i)
+ if (effectMask & (1<<i) && IsUnitOwnedAuraEffect(m_spellInfo->Effect[i]))
+ aura_effmask |= 1<<i;
+
+ if (aura_effmask)
+ {
+ // Select rank for aura with level requirements only in specific cases
+ // Unit has to be target only of aura effect, both caster and target have to be players, target has to be other than unit target
+ SpellEntry const * aurSpellInfo = m_spellInfo;
+ int32 basePoints[3];
+ if (scaleAura)
+ {
+ aurSpellInfo = spellmgr.SelectAuraRankForPlayerLevel(m_spellInfo,unitTarget->getLevel());
+ assert (aurSpellInfo);
+ for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
+ {
+ basePoints[i] = aurSpellInfo->EffectBasePoints[i];
+ if (m_spellInfo->Effect[i] != aurSpellInfo->Effect[i])
+ {
+ aurSpellInfo = m_spellInfo;
+ break;
+ }
+ }
+ }
+
+ if(m_originalCaster)
+ {
+ if (m_spellAura = Aura::TryCreate(aurSpellInfo, effectMask, unit,
+ m_originalCaster,(aurSpellInfo == m_spellInfo)? &m_currentBasePoints[0] : &basePoints[0], m_CastItem))
+ {
+ // Now Reduce spell duration using data received at spell hit
+ int32 duration = m_spellAura->GetMaxDuration();
+ int32 limitduration = GetDiminishingReturnsLimitDuration(m_diminishGroup,aurSpellInfo);
+ unit->ApplyDiminishingToDuration(m_diminishGroup, duration, m_originalCaster, m_diminishLevel,limitduration);
+ ((UnitAura*)m_spellAura)->SetDiminishGroup(m_diminishGroup);
+
+ bool positive = IsPositiveSpell(m_spellAura->GetId());
+ AuraApplication * aurApp = m_spellAura->GetApplicationOfTarget(m_originalCaster->GetGUID());
+ if (aurApp)
+ positive = aurApp->IsPositive();
+
+ duration = m_originalCaster->ModSpellDuration(aurSpellInfo, unit, duration, positive);
+
+ //mod duration of channeled aura by spell haste
+ if (IsChanneledSpell(m_spellInfo))
+ m_originalCaster->ModSpellCastTime(aurSpellInfo, duration, this);
+
+ if(duration != m_spellAura->GetMaxDuration())
+ {
+ m_spellAura->SetMaxDuration(duration);
+ m_spellAura->SetDuration(duration);
+ }
+
+ // Prayer of Mending (jump animation), we need formal caster instead original for correct animation
+ if(aurSpellInfo->SpellFamilyName == SPELLFAMILY_PRIEST)
+ {
+ if(aurSpellInfo->SpellFamilyFlags[1] & 0x000020)
+ m_caster->CastSpell(unit, 41637, true, NULL, NULL, m_originalCasterGUID);
+ }
+ m_spellAura->_RegisterForTargets();
+ }
+ }
+ }
+
+ for (uint32 effectNumber = 0; effectNumber < 3; ++effectNumber)
+ {
+ if (effectMask & (1<<effectNumber))
+ HandleEffects(unit,NULL,NULL,effectNumber);
+ }
+
+ return SPELL_MISS_NONE;
+}
+
+void Spell::DoTriggersOnSpellHit(Unit *unit)
+{
+ // Apply additional spell effects to target
+ if (m_preCastSpell)
+ {
+ // Special spell id
+ // TODO: Handle all of special spells in one place?
+ if(m_preCastSpell==61988)
+ {
+ //Cast Forbearance
+ m_caster->CastSpell(unit,25771, true, m_CastItem);
+ // Cast Avenging Wrath Marker
+ m_caster->CastSpell(unit,61987, true, m_CastItem);
+ }
+ else if (sSpellStore.LookupEntry(m_preCastSpell))
+ m_caster->CastSpell(unit,m_preCastSpell, true, m_CastItem);
+ }
+
+ // spells with this flag can trigger only if not selfcast (eviscerate for example)
+ if (m_ChanceTriggerSpells.size() && (!((m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_CANT_PROC_FROM_SELFCAST) && unit==m_caster)))
+ {
+ int _duration=0;
+ for (ChanceTriggerSpells::const_iterator i = m_ChanceTriggerSpells.begin(); i != m_ChanceTriggerSpells.end(); ++i)
+ {
+ // SPELL_AURA_ADD_TARGET_TRIGGER auras shouldn't trigger auras without duration
+ // set duration equal to triggering spell
+ if(roll_chance_i(i->second))
+ {
+ m_caster->CastSpell(unit, i->first, true);
+ sLog.outDebug("Spell %d triggered spell %d by SPELL_AURA_ADD_TARGET_TRIGGER aura", m_spellInfo->Id, i->first->Id);
+ }
+ if (GetSpellDuration(i->first)==-1)
+ {
+ if (Aura * triggeredAur = unit->GetAura(i->first->Id, m_caster->GetGUID()))
+ {
+ // get duration from aura-only once
+ if (!_duration)
+ {
+ Aura * aur = unit->GetAura(m_spellInfo->Id, m_caster->GetGUID());
+ _duration = aur ? aur->GetDuration() : -1;
+ }
+ triggeredAur->SetDuration(_duration);
+ }
+ }
+ }
+ }
+
+ if(m_customAttr & SPELL_ATTR_CU_LINK_HIT)
+ {
+ if(const std::vector<int32> *spell_triggered = spellmgr.GetSpellLinked(m_spellInfo->Id + SPELL_LINK_HIT))
+ for (std::vector<int32>::const_iterator i = spell_triggered->begin(); i != spell_triggered->end(); ++i)
+ if(*i < 0)
+ unit->RemoveAurasDueToSpell(-(*i));
+ else
+ unit->CastSpell(unit, *i, true, 0, 0, m_caster->GetGUID());
+ }
+}
+
+void Spell::DoAllEffectOnTarget(GOTargetInfo *target)
+{
+ if (target->processed) // Check target
+ return;
+ target->processed = true; // Target checked in apply effects procedure
+
+ uint32 effectMask = target->effectMask;
+ if(!effectMask)
+ return;
+
+ GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID);
+ if(!go)
+ return;
+
+ for (uint32 effectNumber = 0; effectNumber < 3; ++effectNumber)
+ if (effectMask & (1 << effectNumber))
+ HandleEffects(NULL, NULL, go, effectNumber);
+
+ // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished)
+ // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
+ if(m_originalCaster && m_originalCaster->IsControlledByPlayer() && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive() )
+ {
+ if ( Player* p = m_originalCaster->GetCharmerOrOwnerPlayerOrPlayerItself() )
+ p->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id);
+ }
+}
+
+void Spell::DoAllEffectOnTarget(ItemTargetInfo *target)
+{
+ uint32 effectMask = target->effectMask;
+ if(!target->item || !effectMask)
+ return;
+
+ for (uint32 effectNumber = 0; effectNumber < 3; ++effectNumber)
+ if (effectMask & (1 << effectNumber))
+ HandleEffects(NULL, target->item, NULL, effectNumber);
+}
+
+bool Spell::UpdateChanneledTargetList()
+{
+ // Not need check return true
+ if (m_needAliveTargetMask == 0)
+ return true;
+
+ uint8 needAliveTargetMask = m_needAliveTargetMask;
+ uint8 needAuraMask = 0;
+ for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
+ if (m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA)
+ needAuraMask |= 1<<i;
+
+ needAuraMask &= needAliveTargetMask;
+
+ float range;
+ if(needAuraMask)
+ {
+ range = GetSpellMaxRange(m_spellInfo, IsPositiveSpell(m_spellInfo->Id));
+ if(Player * modOwner = m_caster->GetSpellModOwner())
+ modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
+ }
+
+ for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
+ {
+ if( ihit->missCondition == SPELL_MISS_NONE && (needAliveTargetMask & ihit->effectMask) )
+ {
+ Unit *unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
+
+ if (unit && unit->isAlive())
+ {
+ if (needAuraMask & ihit->effectMask)
+ {
+ if(AuraApplication * aurApp = unit->GetAuraApplication(m_spellInfo->Id, m_originalCasterGUID))
+ {
+ if (m_caster != unit && !m_caster->IsWithinDistInMap(unit,range))
+ {
+ ihit->effectMask &= ~aurApp->GetEffectMask();
+ unit->RemoveAura(aurApp);
+ continue;
+ }
+ }
+ else // aura is dispelled
+ continue;
+ }
+
+ needAliveTargetMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target
+ }
+ }
+ }
+
+ // is all effects from m_needAliveTargetMask have alive targets
+ return needAliveTargetMask == 0;
+}
+
+// Helper for Chain Healing
+// Spell target first
+// Raidmates then descending by injury suffered (MaxHealth - Health)
+// Other players/mobs then descending by injury suffered (MaxHealth - Health)
+struct ChainHealingOrder : public std::binary_function<const Unit*, const Unit*, bool>
+{
+ const Unit* MainTarget;
+ ChainHealingOrder(Unit const* Target) : MainTarget(Target) {};
+ // functor for operator ">"
+ bool operator()(Unit const* _Left, Unit const* _Right) const
+ {
+ return (ChainHealingHash(_Left) < ChainHealingHash(_Right));
+ }
+
+ int32 ChainHealingHash(Unit const* Target) const
+ {
+ /*if (Target == MainTarget)
+ return 0;
+ else*/ if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER &&
+ ((Player const*)Target)->IsInSameRaidWith((Player const*)MainTarget))
+ {
+ if (Target->GetHealth() == Target->GetMaxHealth())
+ return 40000;
+ else
+ return 20000 - Target->GetMaxHealth() + Target->GetHealth();
+ }
+ else
+ return 40000 - Target->GetMaxHealth() + Target->GetHealth();
+ }
+};
+
+// Helper for targets nearest to the spell target
+// The spell target is always first unless there is a target at _completely_ the same position (unbelievable case)
+struct TargetDistanceOrder : public std::binary_function<const Unit, const Unit, bool>
+{
+ const Unit* MainTarget;
+ TargetDistanceOrder(const Unit* Target) : MainTarget(Target) {};
+ // functor for operator ">"
+ bool operator()(const Unit* _Left, const Unit* _Right) const
+ {
+ return MainTarget->GetDistanceOrder(_Left,_Right);
+ }
+};
+
+void Spell::SearchChainTarget(std::list<Unit*> &TagUnitMap, float max_range, uint32 num, SpellTargets TargetType)
+{
+ Unit *cur = m_targets.getUnitTarget();
+ if(!cur)
+ return;
+
+ // Get spell max affected targets
+ /*uint32 unMaxTargets = m_spellInfo->MaxAffectedTargets;
+ Unit::AuraList const& mod = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS);
+ for (Unit::AuraList::const_iterator m = mod.begin(); m != mod.end(); ++m)
+ {
+ if (!(*m)->IsAffectedOnSpell(m_spellInfo))
+ continue;
+ unMaxTargets+=(*m)->GetAmount();
+ }*/
+
+ //FIXME: This very like horrible hack and wrong for most spells
+ if(m_spellInfo->DmgClass != SPELL_DAMAGE_CLASS_MELEE)
+ max_range += num * CHAIN_SPELL_JUMP_RADIUS;
+
+ std::list<Unit*> tempUnitMap;
+ if(TargetType == SPELL_TARGETS_CHAINHEAL)
+ {
+ SearchAreaTarget(tempUnitMap, max_range, PUSH_CHAIN, SPELL_TARGETS_ALLY);
+ tempUnitMap.sort(ChainHealingOrder(m_caster));
+ //if(cur->GetHealth() == cur->GetMaxHealth() && tempUnitMap.size())
+ // cur = tempUnitMap.front();
+ }
+ else
+ SearchAreaTarget(tempUnitMap, max_range, PUSH_CHAIN, TargetType);
+ tempUnitMap.remove(cur);
+
+ while(num)
+ {
+ TagUnitMap.push_back(cur);
+ --num;
+
+ if(tempUnitMap.empty())
+ break;
+
+ std::list<Unit*>::iterator next;
+
+ if(TargetType == SPELL_TARGETS_CHAINHEAL)
+ {
+ next = tempUnitMap.begin();
+ while(cur->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS
+ || !cur->IsWithinLOSInMap(*next))
+ {
+ ++next;
+ if(next == tempUnitMap.end())
+ return;
+ }
+ }
+ else
+ {
+ tempUnitMap.sort(TargetDistanceOrder(cur));
+ next = tempUnitMap.begin();
+
+ if(cur->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
+ break;
+ while(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE
+ && !m_caster->isInFrontInMap(*next, max_range)
+ || !m_caster->canSeeOrDetect(*next, false)
+ || !cur->IsWithinLOSInMap(*next))
+ {
+ ++next;
+ if(next == tempUnitMap.end() || cur->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS)
+ return;
+ }
+ }
+
+ cur = *next;
+ tempUnitMap.erase(next);
+ }
+}
+
+void Spell::SearchAreaTarget(std::list<Unit*> &TagUnitMap, float radius, SpellNotifyPushType type, SpellTargets TargetType, uint32 entry)
+{
+ Position *pos;
+ switch(type)
+ {
+ case PUSH_DST_CENTER:
+ CheckDst();
+ pos = &m_targets.m_dstPos;
+ break;
+ case PUSH_SRC_CENTER:
+ CheckSrc();
+ pos = &m_targets.m_srcPos;
+ break;
+ case PUSH_CHAIN:
+ {
+ Unit *target = m_targets.getUnitTarget();
+ if(!target)
+ {
+ sLog.outError( "SPELL: cannot find unit target for spell ID %u\n", m_spellInfo->Id );
+ return;
+ }
+ pos = target;
+ break;
+ }
+ default:
+ pos = m_caster;
+ break;
+ }
+
+ Trinity::SpellNotifierCreatureAndPlayer notifier(m_caster, TagUnitMap, radius, type, TargetType, pos, entry);
+ if((m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_PLAYERS_ONLY)
+ || TargetType == SPELL_TARGETS_ENTRY && !entry)
+ m_caster->GetMap()->VisitWorld(pos->m_positionX, pos->m_positionY, radius, notifier);
+ else
+ m_caster->GetMap()->VisitAll(pos->m_positionX, pos->m_positionY, radius, notifier);
+
+ if(m_customAttr & SPELL_ATTR_CU_EXCLUDE_SELF)
+ TagUnitMap.remove(m_caster);
+}
+
+WorldObject* Spell::SearchNearbyTarget(float range, SpellTargets TargetType)
+{
+ switch(TargetType)
+ {
+ case SPELL_TARGETS_ENTRY:
+ {
+ SpellScriptTargetBounds bounds = spellmgr.GetSpellScriptTargetBounds(m_spellInfo->Id);
+ if(bounds.first==bounds.second)
+ {
+ sLog.outDebug("Spell (ID: %u) (caster Entry: %u) does not have record in `spell_script_target`", m_spellInfo->Id, m_caster->GetEntry());
+ if(IsPositiveSpell(m_spellInfo->Id))
+ return SearchNearbyTarget(range, SPELL_TARGETS_ALLY);
+ else
+ return SearchNearbyTarget(range, SPELL_TARGETS_ENEMY);
+ }
+
+ Creature* creatureScriptTarget = NULL;
+ GameObject* goScriptTarget = NULL;
+
+ for (SpellScriptTarget::const_iterator i_spellST = bounds.first; i_spellST != bounds.second; ++i_spellST)
+ {
+ switch(i_spellST->second.type)
+ {
+ case SPELL_TARGET_TYPE_CONTROLLED:
+ for (Unit::ControlList::iterator itr = m_caster->m_Controlled.begin(); itr != m_caster->m_Controlled.end(); ++itr)
+ if ((*itr)->GetEntry() == i_spellST->second.targetEntry && (*itr)->IsWithinDistInMap(m_caster, range))
+ {
+ goScriptTarget = NULL;
+ creatureScriptTarget = ((Creature *)*itr);
+ range = m_caster->GetDistance(creatureScriptTarget);
+ }
+ break;
+ case SPELL_TARGET_TYPE_GAMEOBJECT:
+ if(i_spellST->second.targetEntry)
+ {
+ if(GameObject *go = m_caster->FindNearestGameObject(i_spellST->second.targetEntry, range))
+ {
+ // remember found target and range, next attempt will find more near target with another entry
+ goScriptTarget = go;
+ creatureScriptTarget = NULL;
+ range = m_caster->GetDistance(goScriptTarget);
+ }
+ }
+ else if( focusObject ) //Focus Object
+ {
+ float frange = m_caster->GetDistance(focusObject);
+ if(range >= frange)
+ {
+ creatureScriptTarget = NULL;
+ goScriptTarget = focusObject;
+ range = frange;
+ }
+ }
+ break;
+ case SPELL_TARGET_TYPE_CREATURE:
+ if(m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetEntry() == i_spellST->second.targetEntry)
+ return m_targets.getUnitTarget();
+ case SPELL_TARGET_TYPE_DEAD:
+ default:
+ if(Creature *cre = m_caster->FindNearestCreature(i_spellST->second.targetEntry, range, i_spellST->second.type != SPELL_TARGET_TYPE_DEAD))
+ {
+ creatureScriptTarget = cre;
+ goScriptTarget = NULL;
+ range = m_caster->GetDistance(creatureScriptTarget);
+ }
+ break;
+ }
+ }
+
+ if(creatureScriptTarget)
+ return creatureScriptTarget;
+ else
+ return goScriptTarget;
+ }
+ default:
+ case SPELL_TARGETS_ENEMY:
+ {
+ Unit *target = NULL;
+ Trinity::AnyUnfriendlyUnitInObjectRangeCheck u_check(m_caster, m_caster, range);
+ Trinity::UnitLastSearcher<Trinity::AnyUnfriendlyUnitInObjectRangeCheck> searcher(m_caster, target, u_check);
+ m_caster->VisitNearbyObject(range, searcher);
+ return target;
+ }
+ case SPELL_TARGETS_ALLY:
+ {
+ Unit *target = NULL;
+ Trinity::AnyFriendlyUnitInObjectRangeCheck u_check(m_caster, m_caster, range);
+ Trinity::UnitLastSearcher<Trinity::AnyFriendlyUnitInObjectRangeCheck> searcher(m_caster, target, u_check);
+ m_caster->VisitNearbyObject(range, searcher);
+ return target;
+ }
+ }
+}
+
+void Spell::SelectEffectTargets(uint32 i, uint32 cur)
+{
+ SpellNotifyPushType pushType = PUSH_NONE;
+ Player *modOwner = NULL;
+ if(m_originalCaster)
+ modOwner = m_originalCaster->GetSpellModOwner();
+
+ switch(SpellTargetType[cur])
+ {
+ case TARGET_TYPE_UNIT_CASTER:
+ {
+ switch(cur)
+ {
+ case TARGET_UNIT_CASTER:
+ AddUnitTarget(m_caster, i);
+ break;
+ case TARGET_UNIT_CASTER_FISHING:
+ {
+ //AddUnitTarget(m_caster, i);
+ float min_dis = GetSpellMinRange(m_spellInfo, true);
+ float max_dis = GetSpellMaxRange(m_spellInfo, true);
+ float dis = rand_norm() * (max_dis - min_dis) + min_dis;
+ float x, y, z;
+ m_caster->GetClosePoint(x, y, z, DEFAULT_WORLD_OBJECT_SIZE, dis);
+ m_targets.setDst(x, y, z, m_caster->GetOrientation());
+ break;
+ }
+ case TARGET_UNIT_MASTER:
+ if(Unit* owner = m_caster->GetCharmerOrOwner())
+ AddUnitTarget(owner, i);
+ break;
+ case TARGET_UNIT_PET:
+ if(Guardian* pet = m_caster->GetGuardianPet())
+ AddUnitTarget(pet, i);
+ break;
+ case TARGET_UNIT_PARTY_CASTER:
+ case TARGET_UNIT_RAID_CASTER:
+ pushType = PUSH_CASTER_CENTER;
+ break;
+ case TARGET_UNIT_VEHICLE:
+ if(Unit *vehicle = m_caster->GetVehicleBase())
+ AddUnitTarget(vehicle, i);
+ break;
+ case TARGET_UNIT_PASSENGER_0:
+ case TARGET_UNIT_PASSENGER_1:
+ case TARGET_UNIT_PASSENGER_2:
+ case TARGET_UNIT_PASSENGER_3:
+ case TARGET_UNIT_PASSENGER_4:
+ case TARGET_UNIT_PASSENGER_5:
+ case TARGET_UNIT_PASSENGER_6:
+ case TARGET_UNIT_PASSENGER_7:
+ if(m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->IsVehicle())
+ if(Unit *unit = m_caster->GetVehicleKit()->GetPassenger(cur - TARGET_UNIT_PASSENGER_0))
+ AddUnitTarget(unit, i);
+ break;
+ }
+ break;
+ }
+
+ case TARGET_TYPE_UNIT_TARGET:
+ {
+ Unit *target = m_targets.getUnitTarget();
+ if(!target)
+ {
+ sLog.outError("SPELL: no unit target for spell ID %u", m_spellInfo->Id);
+ break;
+ }
+
+ switch(cur)
+ {
+ case TARGET_UNIT_TARGET_ENEMY:
+ if(Unit *magnet = m_caster->SelectMagnetTarget(target, m_spellInfo))
+ if(magnet != target)
+ m_targets.setUnitTarget(magnet);
+ pushType = PUSH_CHAIN;
+ break;
+ case TARGET_UNIT_TARGET_ANY:
+ if(!IsPositiveSpell(m_spellInfo->Id))
+ if(Unit *magnet = m_caster->SelectMagnetTarget(target, m_spellInfo))
+ if(magnet != target)
+ m_targets.setUnitTarget(magnet);
+ pushType = PUSH_CHAIN;
+ break;
+ case TARGET_UNIT_CHAINHEAL:
+ pushType = PUSH_CHAIN;
+ break;
+ case TARGET_UNIT_TARGET_ALLY:
+ case TARGET_UNIT_TARGET_RAID:
+ case TARGET_UNIT_TARGET_PARTY:
+ case TARGET_UNIT_MINIPET:
+ case TARGET_UNIT_UNK_92:
+ AddUnitTarget(target, i);
+ break;
+ case TARGET_UNIT_PARTY_TARGET:
+ case TARGET_UNIT_CLASS_TARGET:
+ pushType = PUSH_CASTER_CENTER; // not real
+ break;
+ }
+ break;
+ }
+
+ case TARGET_TYPE_UNIT_NEARBY:
+ {
+ WorldObject *target = NULL;
+ float range;
+
+ switch(cur)
+ {
+ case TARGET_UNIT_NEARBY_ENEMY:
+ range = GetSpellMaxRange(m_spellInfo, false);
+ if(modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
+ target = SearchNearbyTarget(range, SPELL_TARGETS_ENEMY);
+ break;
+ case TARGET_UNIT_NEARBY_ALLY:
+ case TARGET_UNIT_NEARBY_ALLY_UNK:
+ case TARGET_UNIT_NEARBY_RAID:
+ range = GetSpellMaxRange(m_spellInfo, true);
+ if(modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
+ target = SearchNearbyTarget(range, SPELL_TARGETS_ALLY);
+ break;
+ case TARGET_UNIT_NEARBY_ENTRY:
+ case TARGET_GAMEOBJECT_NEARBY_ENTRY:
+ range = GetSpellMaxRange(m_spellInfo, IsPositiveSpell(m_spellInfo->Id));
+ if(modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
+ target = SearchNearbyTarget(range, SPELL_TARGETS_ENTRY);
+ break;
+ }
+
+ if(!target)
+ return;
+ else if(target->GetTypeId() == TYPEID_GAMEOBJECT)
+ AddGOTarget((GameObject*)target, i);
+ else
+ {
+ pushType = PUSH_CHAIN;
+
+ if(m_targets.getUnitTarget() != target)
+ m_targets.setUnitTarget((Unit*)target);
+ }
+
+ break;
+ }
+
+ case TARGET_TYPE_AREA_SRC:
+ pushType = PUSH_SRC_CENTER;
+ break;
+
+ case TARGET_TYPE_AREA_DST:
+ pushType = PUSH_DST_CENTER;
+ break;
+
+ case TARGET_TYPE_AREA_CONE:
+ if(m_customAttr & SPELL_ATTR_CU_CONE_BACK)
+ pushType = PUSH_IN_BACK;
+ else if(m_customAttr & SPELL_ATTR_CU_CONE_LINE)
+ pushType = PUSH_IN_LINE;
+ else
+ pushType = PUSH_IN_FRONT;
+ break;
+
+ case TARGET_TYPE_DEST_CASTER: //4+8+2
+ {
+ if (cur == TARGET_SRC_CASTER)
+ {
+ m_targets.setSrc(m_caster);
+ break;
+ }
+ else if (cur == TARGET_DST_CASTER)
+ {
+ m_targets.setDst(m_caster);
+ break;
+ }
+
+ float angle, dist;
+
+ float objSize = m_caster->GetObjectSize();
+ dist = GetSpellRadiusForFriend(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
+ if(dist < objSize)
+ dist = objSize;
+ else if(cur == TARGET_DEST_CASTER_RANDOM)
+ dist = objSize + (dist - objSize) * rand_norm();
+
+ switch(cur)
+ {
+ case TARGET_DEST_CASTER_FRONT_LEFT: angle = -M_PI/4; break;
+ case TARGET_DEST_CASTER_BACK_LEFT: angle = -3*M_PI/4; break;
+ case TARGET_DEST_CASTER_BACK_RIGHT: angle = 3*M_PI/4; break;
+ case TARGET_DEST_CASTER_FRONT_RIGHT:angle = M_PI/4; break;
+ case TARGET_MINION:
+ case TARGET_DEST_CASTER_FRONT_LEAP:
+ case TARGET_DEST_CASTER_FRONT: angle = 0.0f; break;
+ case TARGET_DEST_CASTER_BACK: angle = M_PI; break;
+ case TARGET_DEST_CASTER_RIGHT: angle = M_PI/2; break;
+ case TARGET_DEST_CASTER_LEFT: angle = -M_PI/2; break;
+ default: angle = rand_norm()*2*M_PI; break;
+ }
+
+ Position pos;
+ m_caster->GetNearPosition(pos, dist, angle);
+ m_targets.setDst(&pos); // also flag
+ break;
+ }
+
+ case TARGET_TYPE_DEST_TARGET: //2+8+2
+ {
+ Unit *target = m_targets.getUnitTarget();
+ if(!target)
+ {
+ sLog.outError("SPELL: no unit target for spell ID %u\n", m_spellInfo->Id);
+ break;
+ }
+
+ if(cur == TARGET_DST_TARGET_ENEMY || cur == TARGET_DEST_TARGET_ANY)
+ {
+ m_targets.setDst(target);
+ break;
+ }
+
+ float angle, dist;
+
+ float objSize = target->GetObjectSize();
+ dist = target->GetSpellRadiusForTarget(target, sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
+ if(dist < objSize)
+ dist = objSize;
+ else if(cur == TARGET_DEST_CASTER_RANDOM)
+ dist = objSize + (dist - objSize) * rand_norm();
+
+ switch(cur)
+ {
+ case TARGET_DEST_TARGET_FRONT: angle = 0.0f; break;
+ case TARGET_DEST_TARGET_BACK: angle = M_PI; break;
+ case TARGET_DEST_TARGET_RIGHT: angle = M_PI/2; break;
+ case TARGET_DEST_TARGET_LEFT: angle = -M_PI/2; break;
+ case TARGET_DEST_TARGET_FRONT_LEFT: angle = -M_PI/4; break;
+ case TARGET_DEST_TARGET_BACK_LEFT: angle = -3*M_PI/4; break;
+ case TARGET_DEST_TARGET_BACK_RIGHT: angle = 3*M_PI/4; break;
+ case TARGET_DEST_TARGET_FRONT_RIGHT:angle = M_PI/4; break;
+ default: angle = rand_norm()*2*M_PI; break;
+ }
+
+ Position pos;
+ target->GetNearPosition(pos, dist, angle);
+ m_targets.setDst(&pos);
+ break;
+ }
+
+ case TARGET_TYPE_DEST_DEST: //5+8+1
+ {
+ if(!m_targets.HasDst())
+ {
+ sLog.outError("SPELL: no destination for spell ID %u\n", m_spellInfo->Id);
+ break;
+ }
+
+ float angle;
+ switch(cur)
+ {
+ case TARGET_DEST_DYNOBJ_ENEMY:
+ case TARGET_DEST_DYNOBJ_ALLY:
+ case TARGET_DEST_DYNOBJ_NONE:
+ case TARGET_DEST_DEST:
+ return;
+ case TARGET_DEST_TRAJ:
+ SelectTrajTargets();
+ return;
+ case TARGET_DEST_DEST_FRONT: angle = 0.0f; break;
+ case TARGET_DEST_DEST_BACK: angle = M_PI; break;
+ case TARGET_DEST_DEST_RIGHT: angle = M_PI/2; break;
+ case TARGET_DEST_DEST_LEFT: angle = -M_PI/2; break;
+ case TARGET_DEST_DEST_FRONT_LEFT: angle = -M_PI/4; break;
+ case TARGET_DEST_DEST_BACK_LEFT: angle = -3*M_PI/4; break;
+ case TARGET_DEST_DEST_BACK_RIGHT: angle = 3*M_PI/4; break;
+ case TARGET_DEST_DEST_FRONT_RIGHT:angle = M_PI/4; break;
+ default: angle = rand_norm()*2*M_PI; break;
+ }
+
+ float dist;
+ dist = GetSpellRadiusForFriend(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
+ if (cur == TARGET_DEST_DEST_RANDOM || cur == TARGET_DEST_DEST_RANDOM_DIR_DIST)
+ dist *= rand_norm();
+
+ // must has dst, no need to set flag
+ m_caster->MovePosition(m_targets.m_dstPos, dist, angle);
+ break;
+ }
+
+ case TARGET_TYPE_DEST_SPECIAL:
+ {
+ switch(cur)
+ {
+ case TARGET_DST_DB:
+ if(SpellTargetPosition const* st = spellmgr.GetSpellTargetPosition(m_spellInfo->Id))
+ {
+ //TODO: fix this check
+ if(m_spellInfo->Effect[0] == SPELL_EFFECT_TELEPORT_UNITS
+ || m_spellInfo->Effect[1] == SPELL_EFFECT_TELEPORT_UNITS
+ || m_spellInfo->Effect[2] == SPELL_EFFECT_TELEPORT_UNITS)
+ m_targets.setDst(st->target_X, st->target_Y, st->target_Z, st->target_Orientation, (int32)st->target_mapId);
+ else if(st->target_mapId == m_caster->GetMapId())
+ m_targets.setDst(st->target_X, st->target_Y, st->target_Z, st->target_Orientation);
+ }
+ else
+ {
+ sLog.outDebug( "SPELL: unknown target coordinates for spell ID %u", m_spellInfo->Id );
+ Unit *target = NULL;
+ if(uint64 guid = m_caster->GetUInt64Value(UNIT_FIELD_TARGET))
+ target = ObjectAccessor::GetUnit(*m_caster, guid);
+ m_targets.setDst(target ? target : m_caster);
+ }
+ break;
+ case TARGET_DST_HOME:
+ if(m_caster->GetTypeId() == TYPEID_PLAYER)
+ m_targets.setDst(((Player*)m_caster)->m_homebindX,((Player*)m_caster)->m_homebindY,((Player*)m_caster)->m_homebindZ, ((Player*)m_caster)->GetOrientation(), ((Player*)m_caster)->m_homebindMapId);
+ break;
+ case TARGET_DST_NEARBY_ENTRY:
+ {
+ float range = GetSpellMaxRange(m_spellInfo, IsPositiveSpell(m_spellInfo->Id));
+ if(modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
+
+ if(WorldObject *target = SearchNearbyTarget(range, SPELL_TARGETS_ENTRY))
+ m_targets.setDst(target);
+ break;
+ }
+ }
+ break;
+ }
+
+ case TARGET_TYPE_CHANNEL:
+ {
+ if (!m_originalCaster || !m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL))
+ {
+ sLog.outError( "SPELL: no current channeled spell for spell ID %u", m_spellInfo->Id );
+ break;
+ }
+
+ switch (cur)
+ {
+ case TARGET_UNIT_CHANNEL:
+ // in some cases unittarget is invalid and crash. do not know why it happens.
+ if (Unit* target = Unit::GetUnit(*m_caster, m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_targets.getUnitTargetGUID()))
+ AddUnitTarget(target, i);
+ else
+ sLog.outError( "SPELL: cannot find channel spell target for spell ID %u", m_spellInfo->Id );
+ break;
+ case TARGET_DEST_CHANNEL:
+ if (m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_targets.HasDst())
+ m_targets = m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_targets;
+ else if (Unit* target = Unit::GetUnit(*m_caster, m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_targets.getUnitTargetGUID()))
+ m_targets.setDst(target);
+ else
+ sLog.outError( "SPELL: cannot find channel spell destination for spell ID %u", m_spellInfo->Id );
+ break;
+ }
+ break;
+ }
+
+ default:
+ {
+ switch (cur)
+ {
+ case TARGET_GAMEOBJECT:
+ if(m_targets.getGOTarget())
+ AddGOTarget(m_targets.getGOTarget(), i);
+ break;
+ case TARGET_GAMEOBJECT_ITEM:
+ if (m_targets.getGOTargetGUID())
+ AddGOTarget(m_targets.getGOTarget(), i);
+ else if (m_targets.getItemTarget())
+ AddItemTarget(m_targets.getItemTarget(), i);
+ break;
+ case TARGET_UNIT_DRIVER:
+ if (Unit * driver = m_targets.getUnitTarget())
+ if (driver->IsOnVehicle(driver))
+ AddUnitTarget(driver, i);
+ break;
+ default:
+ sLog.outError("Unhandled spell target %u", cur);
+ break;
+ }
+ break;
+ }
+ }
+
+ if (pushType == PUSH_CHAIN) // Chain
+ {
+ Unit *target = m_targets.getUnitTarget();
+ if (!target)
+ {
+ sLog.outError("SPELL: no chain unit target for spell ID %u", m_spellInfo->Id);
+ return;
+ }
+
+ //Chain: 2, 6, 22, 25, 45, 77
+ uint32 maxTargets = m_spellInfo->EffectChainTarget[i];
+ if (modOwner)
+ modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, maxTargets, this);
+
+ if (maxTargets > 1)
+ {
+ //otherwise, this multiplier is used for something else
+ m_damageMultipliers[i] = 1.0f;
+ m_applyMultiplierMask |= 1 << i;
+
+ float range;
+ std::list<Unit*> unitList;
+
+ switch (cur)
+ {
+ case TARGET_UNIT_NEARBY_ENEMY:
+ case TARGET_UNIT_TARGET_ENEMY:
+ case TARGET_UNIT_NEARBY_ENTRY: // fix me
+ range = GetSpellMaxRange(m_spellInfo, false);
+ if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
+ SearchChainTarget(unitList, range, maxTargets, SPELL_TARGETS_ENEMY);
+ break;
+ case TARGET_UNIT_CHAINHEAL:
+ case TARGET_UNIT_NEARBY_ALLY: // fix me
+ case TARGET_UNIT_NEARBY_ALLY_UNK:
+ case TARGET_UNIT_NEARBY_RAID:
+ range = GetSpellMaxRange(m_spellInfo, true);
+ if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
+ SearchChainTarget(unitList, range, maxTargets, SPELL_TARGETS_CHAINHEAL);
+ break;
+ }
+
+ for (std::list<Unit*>::iterator itr = unitList.begin(); itr != unitList.end(); ++itr)
+ AddUnitTarget(*itr, i);
+ }
+ else
+ AddUnitTarget(target, i);
+ }
+ else if (pushType)
+ {
+ // Dummy, just for client
+ if(EffectTargetType[m_spellInfo->Effect[i]] != SPELL_REQUIRE_UNIT)
+ return;
+
+ float radius;
+ SpellTargets targetType;
+ switch(cur)
+ {
+ case TARGET_UNIT_AREA_ENEMY_SRC:
+ case TARGET_UNIT_AREA_ENEMY_DST:
+ case TARGET_UNIT_CONE_ENEMY:
+ case TARGET_UNIT_CONE_ENEMY_UNKNOWN:
+ case TARGET_UNIT_AREA_PATH:
+ radius = GetSpellRadius(m_spellInfo, i, false);
+ targetType = SPELL_TARGETS_ENEMY;
+ break;
+ case TARGET_UNIT_AREA_ALLY_SRC:
+ case TARGET_UNIT_AREA_ALLY_DST:
+ case TARGET_UNIT_CONE_ALLY:
+ radius = GetSpellRadius(m_spellInfo, i, true);
+ targetType = SPELL_TARGETS_ALLY;
+ break;
+ case TARGET_UNIT_AREA_ENTRY_DST:
+ case TARGET_UNIT_AREA_ENTRY_SRC:
+ case TARGET_UNIT_CONE_ENTRY: // fix me
+ radius = GetSpellRadius(m_spellInfo, i, IsPositiveSpell(m_spellInfo->Id));
+ targetType = SPELL_TARGETS_ENTRY;
+ break;
+ default:
+ radius = GetSpellRadius(m_spellInfo, i, true);
+ targetType = SPELL_TARGETS_NONE;
+ break;
+ }
+
+ if(modOwner)
+ modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius, this);
+ radius *= m_spellValue->RadiusMod;
+
+ std::list<Unit*> unitList;
+ if(targetType == SPELL_TARGETS_ENTRY)
+ {
+ SpellScriptTargetBounds bounds = spellmgr.GetSpellScriptTargetBounds(m_spellInfo->Id);
+ if(bounds.first == bounds.second)
+ {
+ // Custom entries
+ // TODO: move these to sql
+ switch (m_spellInfo->Id)
+ {
+ case 46584: // Raise Dead
+ {
+ m_targets.m_targetMask &= ~TARGET_FLAG_DEST_LOCATION;
+ if (WorldObject* result = FindCorpseUsing<Trinity::RaiseDeadObjectCheck> ())
+ {
+ switch(result->GetTypeId())
+ {
+ case TYPEID_UNIT:
+ m_targets.setDst(result);
+ }
+ }
+ break;
+ }
+ // Corpse Explosion
+ case 49158:
+ case 51325:
+ case 51326:
+ case 51327:
+ case 51328:
+ // Search for ghoul if our ghoul or dead body not valid unit target
+ if (!(m_targets.getUnitTarget() && (m_targets.getUnitTarget()->GetEntry() == 26125 && m_targets.getUnitTarget()->GetOwnerGUID() == m_caster->GetGUID()
+ || (m_targets.getUnitTarget()->getDeathState() == CORPSE
+ && m_targets.getUnitTarget()->GetDisplayId() == m_targets.getUnitTarget()->GetNativeDisplayId()
+ && m_targets.getUnitTarget()->GetTypeId() == TYPEID_UNIT
+ && !((Creature*)m_targets.getUnitTarget())->isDeadByDefault()
+ && !(m_targets.getUnitTarget()->GetCreatureTypeMask() & CREATURE_TYPEMASK_MECHANICAL_OR_ELEMENTAL))
+ && m_targets.getUnitTarget()->GetDisplayId() == m_targets.getUnitTarget()->GetNativeDisplayId())))
+ {
+ CleanupTargetList();
+
+ WorldObject* result = FindCorpseUsing <Trinity::ExplodeCorpseObjectCheck> ();
+
+ if (result)
+ {
+ switch (result->GetTypeId())
+ {
+ case TYPEID_UNIT:
+ case TYPEID_PLAYER:
+ m_targets.setUnitTarget((Unit*)result);
+ break;
+ }
+ }
+ else
+ {
+ if (m_caster->GetTypeId() == TYPEID_PLAYER)
+ ((Player*)m_caster)->RemoveSpellCooldown(m_spellInfo->Id,true);
+ SendCastResult(SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW);
+ finish(false);
+ }
+ }
+ break;
+
+ default:
+ sLog.outDebug("Spell (ID: %u) (caster Entry: %u) does not have record in `spell_script_target`", m_spellInfo->Id, m_caster->GetEntry());
+
+ if(m_spellInfo->Effect[i] == SPELL_EFFECT_TELEPORT_UNITS)
+ SearchAreaTarget(unitList, radius, pushType, SPELL_TARGETS_ENTRY, 0);
+ else if(IsPositiveEffect(m_spellInfo->Id, i))
+ SearchAreaTarget(unitList, radius, pushType, SPELL_TARGETS_ALLY);
+ else
+ SearchAreaTarget(unitList, radius, pushType, SPELL_TARGETS_ENEMY);
+ }
+ }
+ // let it be done in one check?
+ else
+ {
+ for (SpellScriptTarget::const_iterator i_spellST = bounds.first; i_spellST != bounds.second; ++i_spellST)
+ {
+ if(i_spellST->second.type == SPELL_TARGET_TYPE_CREATURE)
+ SearchAreaTarget(unitList, radius, pushType, SPELL_TARGETS_ENTRY, i_spellST->second.targetEntry);
+ else if (i_spellST->second.type == SPELL_TARGET_TYPE_CONTROLLED)
+ {
+ for (Unit::ControlList::iterator itr = m_caster->m_Controlled.begin(); itr != m_caster->m_Controlled.end(); ++itr)
+ if ((*itr)->GetEntry() == i_spellST->second.targetEntry &&
+ /*(*itr)->IsWithinDistInMap(m_caster, radius)*/ (*itr)->IsInMap(m_caster)) // For 60243 and 52173 need skip radius check or use range (no radius entry for effect)
+ unitList.push_back(*itr);
+ }
+ }
+ }
+ }
+ else if (targetType)
+ SearchAreaTarget(unitList, radius, pushType, targetType);
+ else
+ {
+ switch (cur)
+ {
+ case TARGET_UNIT_AREA_PARTY_SRC:
+ case TARGET_UNIT_AREA_PARTY_DST:
+ m_caster->GetPartyMemberInDist(unitList, radius); //fix me
+ break;
+ case TARGET_OBJECT_AREA_SRC: // fix me
+ case TARGET_OBJECT_AREA_DST:
+ {
+ float x, y, z;
+ if(cur == TARGET_OBJECT_AREA_SRC)
+ {
+ if(m_targets.HasSrc())
+ m_targets.m_srcPos.GetPosition(x, y, z);
+ else
+ break;
+ }
+ else
+ {
+ if(m_targets.HasDst())
+ m_targets.m_dstPos.GetPosition(x, y, z);
+ else
+ break;
+ }
+
+ Trinity::GameObjectInRangeCheck check(x, y, z, radius + 50);
+ std::list<GameObject*> goList;
+ Trinity::GameObjectListSearcher<Trinity::GameObjectInRangeCheck> searcher(m_caster, goList, check);
+ m_caster->GetMap()->VisitGrid(x, y, radius, searcher);
+ for (std::list<GameObject*>::iterator itr = goList.begin(); itr != goList.end(); ++itr)
+ AddGOTarget(*itr, i);
+ break;
+ }
+ case TARGET_UNIT_PARTY_TARGET:
+ m_targets.getUnitTarget()->GetPartyMemberInDist(unitList, radius);
+ break;
+ case TARGET_UNIT_PARTY_CASTER:
+ m_caster->GetPartyMemberInDist(unitList, radius);
+ break;
+ case TARGET_UNIT_RAID_CASTER:
+ m_caster->GetRaidMember(unitList, radius);
+ break;
+ case TARGET_UNIT_CLASS_TARGET:
+ {
+ Player* targetPlayer = m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER
+ ? (Player*)m_targets.getUnitTarget() : NULL;
+
+ Group* pGroup = targetPlayer ? targetPlayer->GetGroup() : NULL;
+ if(pGroup)
+ {
+ for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
+ {
+ Player* Target = itr->getSource();
+
+ // IsHostileTo check duel and controlled by enemy
+ if( Target && targetPlayer->IsWithinDistInMap(Target, radius) &&
+ targetPlayer->getClass() == Target->getClass() &&
+ !m_caster->IsHostileTo(Target) )
+ {
+ AddUnitTarget(Target, i);
+ }
+ }
+ }
+ else if(m_targets.getUnitTarget())
+ AddUnitTarget(m_targets.getUnitTarget(), i);
+ break;
+ }
+ }
+ }
+
+ if(!unitList.empty())
+ {
+ if(uint32 maxTargets = m_spellValue->MaxAffectedTargets)
+ {
+ Unit::AuraEffectList const& Auras = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS);
+ for (Unit::AuraEffectList::const_iterator j = Auras.begin(); j != Auras.end(); ++j)
+ if((*j)->IsAffectedOnSpell(m_spellInfo))
+ maxTargets += (*j)->GetAmount();
+
+ if(m_spellInfo->Id == 5246) //Intimidating Shout
+ unitList.remove(m_targets.getUnitTarget());
+ Trinity::RandomResizeList(unitList, m_spellValue->MaxAffectedTargets);
+ }
+ else
+ {
+ switch (m_spellInfo->Id)
+ {
+ case 27285: // Seed of Corruption proc spell
+ unitList.remove(m_targets.getUnitTarget());
+ break;
+ case 55789: // Improved Icy Talons
+ case 59725: // Improved Spell Reflection - aoe aura
+ unitList.remove(m_caster);
+ break;
+ case 57669: //Replenishment (special target selection) 10 targets with lowest mana
+ {
+ typedef std::priority_queue<PrioritizeManaUnitWraper, std::vector<PrioritizeManaUnitWraper>, PrioritizeMana> TopMana;
+ TopMana manaUsers;
+ for (std::list<Unit*>::iterator itr = unitList.begin() ; itr != unitList.end(); ++itr)
+ {
+ if ((*itr)->getPowerType() == POWER_MANA)
+ {
+ PrioritizeManaUnitWraper WTarget(*itr);
+ manaUsers.push(WTarget);
+ }
+ }
+
+ unitList.clear();
+ while(!manaUsers.empty() && unitList.size()<10)
+ {
+ unitList.push_back(manaUsers.top().getUnit());
+ manaUsers.pop();
+ }
+ break;
+ }
+ case 52759: // Ancestral Awakening
+ {
+ typedef std::priority_queue<PrioritizeHealthUnitWraper, std::vector<PrioritizeHealthUnitWraper>, PrioritizeHealth> TopHealth;
+ TopHealth healedMembers;
+ for (std::list<Unit*>::iterator itr = unitList.begin() ; itr != unitList.end(); ++itr)
+ {
+ PrioritizeHealthUnitWraper WTarget(*itr);
+ healedMembers.push(WTarget);
+ }
+
+ unitList.clear();
+ while(!healedMembers.empty() && unitList.size()<1)
+ {
+ unitList.push_back(healedMembers.top().getUnit());
+ healedMembers.pop();
+ }
+ break;
+ }
+ }
+ if (m_spellInfo->EffectImplicitTargetA[i] == TARGET_DEST_TARGET_ANY
+ && m_spellInfo->EffectImplicitTargetB[i] == TARGET_UNIT_AREA_ALLY_DST)// Wild Growth, Circle of Healing, Glyph of holy light target special selection
+ {
+ typedef std::priority_queue<PrioritizeHealthUnitWraper, std::vector<PrioritizeHealthUnitWraper>, PrioritizeHealth> TopHealth;
+ TopHealth healedMembers;
+ for (std::list<Unit*>::iterator itr = unitList.begin() ; itr != unitList.end(); ++itr)
+ {
+ if ((*itr)->IsInRaidWith(m_targets.getUnitTarget()))
+ {
+ PrioritizeHealthUnitWraper WTarget(*itr);
+ healedMembers.push(WTarget);
+ }
+ }
+
+ unitList.clear();
+ uint32 maxsize = 5;
+
+ if (m_spellInfo->SpellFamilyName == SPELLFAMILY_DRUID && m_spellInfo->SpellFamilyFlags[1] & 0x04000000) // Wild Growth
+ maxsize += m_caster->HasAura(62970) ? 1 : 0; // Glyph of Wild Growth
+
+ if (m_spellInfo->SpellFamilyName == SPELLFAMILY_PRIEST && m_spellInfo->SpellFamilyFlags[0] & 0x10000000 && m_spellInfo->SpellIconID == 2214) // Circle of Healing
+ maxsize += m_caster->HasAura(55675) ? 1 : 0; // Glyph of Circle of Healing
+
+ while(!healedMembers.empty() && unitList.size()<maxsize)
+ {
+ unitList.push_back(healedMembers.top().getUnit());
+ healedMembers.pop();
+ }
+ }
+ // Death Pact
+ if (m_spellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && m_spellInfo->SpellFamilyFlags[0] & 0x00080000)
+ {
+ Unit * unit_to_add = NULL;
+ for (std::list<Unit*>::iterator itr = unitList.begin() ; itr != unitList.end(); ++itr)
+ {
+ if ((*itr)->GetTypeId() == TYPEID_UNIT
+ && (*itr)->GetOwnerGUID() == m_caster->GetGUID()
+ && ((Creature*)(*itr))->GetCreatureInfo()->type == CREATURE_TYPE_UNDEAD)
+ {
+ unit_to_add = (*itr);
+ break;
+ }
+ }
+ if (unit_to_add)
+ {
+ unitList.clear();
+ unitList.push_back(unit_to_add);
+ }
+ // Pet not found - remove cooldown
+ else
+ {
+ if (modOwner->GetTypeId() == TYPEID_PLAYER)
+ modOwner->RemoveSpellCooldown(m_spellInfo->Id,true);
+ SendCastResult(SPELL_FAILED_NO_PET);
+ finish(false);
+ }
+ }
+ }
+ for (std::list<Unit*>::iterator itr = unitList.begin(); itr != unitList.end(); ++itr)
+ AddUnitTarget(*itr, i);
+ }
+ }
+}
+
+void Spell::prepare(SpellCastTargets const* targets, AuraEffect const * triggeredByAura)
+{
+ if (m_CastItem)
+ m_castItemGUID = m_CastItem->GetGUID();
+ else
+ m_castItemGUID = 0;
+
+ m_targets = *targets;
+
+ if (!m_targets.getUnitTargetGUID() && m_spellInfo->Targets & TARGET_FLAG_UNIT)
+ {
+ Unit *target = NULL;
+ if(m_caster->GetTypeId() == TYPEID_UNIT)
+ target = m_caster->getVictim();
+ else
+ target = ObjectAccessor::GetUnit(*m_caster, ((Player*)m_caster)->GetSelection());
+
+ if (target && IsValidSingleTargetSpell(target))
+ m_targets.setUnitTarget(target);
+ else
+ {
+ SendCastResult(SPELL_FAILED_BAD_TARGETS);
+ finish(false);
+ return;
+ }
+ }
+
+ // Fill aura scaling information
+ if (m_caster->IsControlledByPlayer() && !IsPassiveSpell(m_spellInfo->Id) && m_spellInfo->spellLevel && !IsChanneledSpell(m_spellInfo) && !m_IsTriggeredSpell)
+ {
+ for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
+ {
+ if (m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA)
+ {
+ // Change aura with ranks only if basepoints are taken from spellInfo and aura is positive
+ if (IsPositiveEffect(m_spellInfo->Id, i))
+ {
+ m_auraScaleMask |= (1<<i);
+ if (m_currentBasePoints[i] != m_spellInfo->EffectBasePoints[i])
+ {
+ m_auraScaleMask = 0;
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ m_spellState = SPELL_STATE_PREPARING;
+
+ if(triggeredByAura)
+ m_triggeredByAuraSpell = triggeredByAura->GetSpellProto();
+
+ // create and add update event for this spell
+ SpellEvent* Event = new SpellEvent(this);
+ m_caster->m_Events.AddEvent(Event, m_caster->m_Events.CalculateTime(1));
+
+ //Prevent casting at cast another spell (ServerSide check)
+ if(m_caster->IsNonMeleeSpellCasted(false, true, true) && m_cast_count)
+ {
+ SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS);
+ finish(false);
+ return;
+ }
+
+ if(m_caster->GetTypeId() == TYPEID_PLAYER)
+ {
+ if(objmgr.IsPlayerSpellDisabled(m_spellInfo->Id))
+ {
+ SendCastResult(SPELL_FAILED_SPELL_UNAVAILABLE);
+ finish(false);
+ return;
+ }
+ }
+ else if (m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->isPet())
+ {
+ if(objmgr.IsPetSpellDisabled(m_spellInfo->Id))
+ {
+ SendCastResult(SPELL_FAILED_SPELL_UNAVAILABLE);
+ finish(false);
+ return;
+ }
+ }
+ else
+ {
+ if(objmgr.IsCreatureSpellDisabled(m_spellInfo->Id))
+ {
+ finish(false);
+ return;
+ }
+ }
+
+ if (m_caster->GetTypeId() == TYPEID_PLAYER)
+ ((Player*)m_caster)->SetSpellModTakingSpell(this, true);
+ // Fill cost data (not use power for item casts
+ m_powerCost = m_CastItem ? 0 : CalculatePowerCost(m_spellInfo, m_caster, m_spellSchoolMask);
+ if (m_caster->GetTypeId() == TYPEID_PLAYER)
+ ((Player*)m_caster)->SetSpellModTakingSpell(this, false);
+
+ SpellCastResult result = CheckCast(true);
+ if(result != SPELL_CAST_OK && !IsAutoRepeat()) //always cast autorepeat dummy for triggering
+ {
+ if(triggeredByAura)
+ {
+ SendChannelUpdate(0);
+ triggeredByAura->GetBase()->SetDuration(0);
+ }
+ SendCastResult(result);
+
+ finish(false);
+ return;
+ }
+
+ // Prepare data for triggers
+ prepareDataForTriggerSystem(triggeredByAura);
+
+ // Set combo point requirement
+ if (m_IsTriggeredSpell || m_CastItem || !m_caster->m_movedPlayer)
+ m_needComboPoints = false;
+
+ // calculate cast time (calculated after first CheckCast check to prevent charge counting for first CheckCast fail)
+ m_casttime = GetSpellCastTime(m_spellInfo, this);
+ //m_caster->ModSpellCastTime(m_spellInfo, m_casttime, this);
+
+ // set timer base at cast time
+ ReSetTimer();
+
+ sLog.outDebug("Spell::prepare: spell id %u source %u caster %d triggered %u mask %u", m_spellInfo->Id, m_caster->GetEntry(), m_originalCaster ? m_originalCaster->GetEntry() : -1, m_IsTriggeredSpell ? 1 : 0, m_targets.m_targetMask);
+ //if(m_targets.getUnitTarget())
+ // sLog.outError("Spell::prepare: unit target %u", m_targets.getUnitTarget()->GetEntry());
+ //if(m_targets.HasDst())
+ // sLog.outError("Spell::prepare: pos target %f %f %f", m_targets.m_dstPos.m_positionX, m_targets.m_dstPos.m_positionY, m_targets.m_dstPos.m_positionZ);
+
+ //Containers for channeled spells have to be set
+ //TODO:Apply this to all casted spells if needed
+ // Why check duration? 29350: channelled triggers channelled
+ if(m_IsTriggeredSpell && (!IsChanneledSpell(m_spellInfo) || !GetSpellMaxDuration(m_spellInfo)))
+ cast(true);
+ else
+ {
+ // stealth must be removed at cast starting (at show channel bar)
+ // skip triggered spell (item equip spell casting and other not explicit character casts/item uses)
+ if(!m_IsTriggeredSpell && isSpellBreakStealth(m_spellInfo) )
+ {
+ m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CAST);
+ for (uint32 i = 0; i < 3; ++i)
+ {
+ if(EffectTargetType[m_spellInfo->Effect[i]] == SPELL_REQUIRE_UNIT)
+ {
+ m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_SPELL_ATTACK);
+ break;
+ }
+ }
+ }
+
+ m_caster->SetCurrentCastedSpell( this );
+ SendSpellStart();
+
+ if(!m_casttime && !m_spellInfo->StartRecoveryTime
+ && !m_castItemGUID //item: first cast may destroy item and second cast causes crash
+ && GetCurrentContainer() == CURRENT_GENERIC_SPELL)
+ cast(true);
+ }
+}
+
+void Spell::cancel()
+{
+ if(m_spellState == SPELL_STATE_FINISHED)
+ return;
+
+ SetReferencedFromCurrent(false);
+ if(m_selfContainer && *m_selfContainer == this)
+ *m_selfContainer = NULL;
+
+ uint32 oldState = m_spellState;
+ m_spellState = SPELL_STATE_FINISHED;
+
+ m_autoRepeat = false;
+ switch (oldState)
+ {
+ case SPELL_STATE_PREPARING:
+ case SPELL_STATE_DELAYED:
+ {
+ SendInterrupted(0);
+ SendCastResult(SPELL_FAILED_INTERRUPTED);
+ } break;
+
+ case SPELL_STATE_CASTING:
+ {
+ for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
+ if ((*ihit).missCondition == SPELL_MISS_NONE)
+ if (Unit* unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID))
+ unit->RemoveOwnedAura(m_spellInfo->Id, m_originalCasterGUID, 0, AURA_REMOVE_BY_CANCEL);
+
+ SendChannelUpdate(0);
+ SendInterrupted(0);
+ SendCastResult(SPELL_FAILED_INTERRUPTED);
+
+ // spell is canceled-take mods and clear list
+ if (m_caster->GetTypeId() == TYPEID_PLAYER)
+ ((Player*)m_caster)->RemoveSpellMods(this);
+
+ m_appliedMods.clear();
+ } break;
+
+ default:
+ {
+ } break;
+ }
+
+ m_caster->RemoveDynObject(m_spellInfo->Id);
+ m_caster->RemoveGameObject(m_spellInfo->Id,true);
+
+ //set state back so finish will be processed
+ m_spellState = oldState;
+
+ finish(false);
+}
+
+void Spell::cast(bool skipCheck)
+{
+ // update pointers base at GUIDs to prevent access to non-existed already object
+ UpdatePointers();
+
+ if(Unit *target = m_targets.getUnitTarget())
+ {
+ // three check: prepare, cast (m_casttime > 0), hit (delayed)
+ if(m_casttime && target->isAlive()
+ && (target->m_invisibilityMask || m_caster->m_invisibilityMask
+ || target->GetVisibility() == VISIBILITY_GROUP_STEALTH)
+ && !target->IsFriendlyTo(m_caster) && !m_caster->canSeeOrDetect(target, true))
+ {
+ SendCastResult(SPELL_FAILED_BAD_TARGETS);
+ SendInterrupted(0);
+ finish(false);
+ return;
+ }
+ }
+ else
+ {
+ // cancel at lost main target unit
+ if(m_targets.getUnitTargetGUID() && m_targets.getUnitTargetGUID() != m_caster->GetGUID())
+ {
+ cancel();
+ return;
+ }
+ }
+
+ SetExecutedCurrently(true);
+
+ if(m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster)
+ m_caster->SetInFront(m_targets.getUnitTarget());
+
+ // Should this be done for original caster?
+ if (m_caster->GetTypeId() == TYPEID_PLAYER)
+ {
+ // Set spell which will drop charges for triggered cast spells
+ // if not successfully casted, will be remove in finish(false)
+ ((Player*)m_caster)->SetSpellModTakingSpell(this, true);
+ }
+
+ // triggered cast called from Spell::prepare where it was already checked
+ if(!m_IsTriggeredSpell || !skipCheck)
+ {
+ SpellCastResult castResult = CheckCast(false);
+ if(castResult != SPELL_CAST_OK)
+ {
+ SendCastResult(castResult);
+ SendInterrupted(0);
+ //restore spell mods
+ if (m_caster->GetTypeId() == TYPEID_PLAYER)
+ {
+ ((Player*)m_caster)->RestoreSpellMods(this);
+ // cleanup after mod system
+ // triggered spell pointer can be not removed in some cases
+ ((Player*)m_caster)->SetSpellModTakingSpell(this, false);
+ }
+ finish(false);
+ SetExecutedCurrently(false);
+ return;
+ }
+ }
+
+ SelectSpellTargets();
+
+ // Spell may be finished after target map check
+ if(m_spellState == SPELL_STATE_FINISHED)
+ {
+ SendInterrupted(0);
+ //restore spell mods
+ if (m_caster->GetTypeId() == TYPEID_PLAYER)
+ {
+ ((Player*)m_caster)->RestoreSpellMods(this);
+ // cleanup after mod system
+ // triggered spell pointer can be not removed in some cases
+ ((Player*)m_caster)->SetSpellModTakingSpell(this, false);
+ }
+ finish(false);
+ SetExecutedCurrently(false);
+ return;
+ }
+
+ if(m_spellInfo->SpellFamilyName)
+ {
+ if (m_spellInfo->excludeCasterAuraSpell && !IsPositiveSpell(m_spellInfo->excludeCasterAuraSpell))
+ m_preCastSpell = m_spellInfo->excludeCasterAuraSpell;
+ else if (m_spellInfo->excludeTargetAuraSpell && !IsPositiveSpell(m_spellInfo->excludeTargetAuraSpell))
+ m_preCastSpell = m_spellInfo->excludeTargetAuraSpell;
+ }
+ switch (m_spellInfo->SpellFamilyName)
+ {
+ case SPELLFAMILY_GENERIC:
+ {
+ if (m_spellInfo->Mechanic == MECHANIC_BANDAGE) // Bandages
+ m_preCastSpell = 11196; // Recently Bandaged
+ break;
+ }
+ case SPELLFAMILY_MAGE:
+ {
+ // Permafrost
+ if (m_spellInfo->SpellFamilyFlags[1] & 0x00001000 || m_spellInfo->SpellFamilyFlags[0] & 0x00100220)
+ m_preCastSpell = 68391;
+ break;
+ }
+ }
+ // traded items have trade slot instead of guid in m_itemTargetGUID
+ // set to real guid to be sent later to the client
+ m_targets.updateTradeSlotItem();
+
+ if (m_caster->GetTypeId() == TYPEID_PLAYER)
+ {
+ if (!m_IsTriggeredSpell && m_CastItem)
+ ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM, m_CastItem->GetEntry());
+
+ ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id);
+ }
+
+ if(!m_IsTriggeredSpell)
+ {
+ // Powers have to be taken before SendSpellGo
+ TakePower();
+ TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot
+ }
+
+ // are there any spells need to be triggered after hit?
+ // handle SPELL_AURA_ADD_TARGET_TRIGGER auras
+ Unit::AuraEffectList const& targetTriggers = m_caster->GetAuraEffectsByType(SPELL_AURA_ADD_TARGET_TRIGGER);
+ for (Unit::AuraEffectList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i)
+ {
+ if (!(*i)->IsAffectedOnSpell(m_spellInfo))
+ continue;
+ SpellEntry const *auraSpellInfo = (*i)->GetSpellProto();
+ uint32 auraSpellIdx = (*i)->GetEffIndex();
+ if(SpellEntry const *spellInfo = sSpellStore.LookupEntry(auraSpellInfo->EffectTriggerSpell[auraSpellIdx]))
+ {
+ // Calculate chance at that moment (can be depend for example from combo points)
+ int32 chance = m_caster->CalculateSpellDamage(auraSpellInfo, auraSpellIdx, (*i)->GetBaseAmount(), NULL);
+ m_ChanceTriggerSpells.push_back(std::make_pair(spellInfo, chance * (*i)->GetBase()->GetStackAmount()));
+ }
+ }
+
+ if(m_customAttr & SPELL_ATTR_CU_DIRECT_DAMAGE)
+ CalculateDamageDoneForAllTargets();
+
+ // CAST SPELL
+ SendSpellCooldown();
+
+ for (uint32 i = 0; i < 3; ++i)
+ {
+ switch(m_spellInfo->Effect[i])
+ {
+ case SPELL_EFFECT_CHARGE:
+ case SPELL_EFFECT_JUMP:
+ case SPELL_EFFECT_JUMP2:
+ case SPELL_EFFECT_LEAP_BACK:
+ case SPELL_EFFECT_ACTIVATE_RUNE:
+ HandleEffects(NULL,NULL,NULL,i);
+ m_effectMask |= (1<<i);
+ break;
+ }
+ }
+
+ // we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()...
+ SendSpellGo();
+
+ // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells
+ if (m_spellInfo->speed > 0.0f && !IsChanneledSpell(m_spellInfo) || m_spellInfo->Id == 14157)
+ {
+ // Remove used for cast item if need (it can be already NULL after TakeReagents call
+ // in case delayed spell remove item at cast delay start
+ TakeCastItem();
+
+ // Okay, maps created, now prepare flags
+ m_immediateHandled = false;
+ m_spellState = SPELL_STATE_DELAYED;
+ SetDelayStart(0);
+
+ if(m_caster->hasUnitState(UNIT_STAT_CASTING) && !m_caster->IsNonMeleeSpellCasted(false, false, true))
+ m_caster->clearUnitState(UNIT_STAT_CASTING);
+ }
+ else
+ {
+ // Immediate spell, no big deal
+ handle_immediate();
+ }
+
+ if(m_customAttr & SPELL_ATTR_CU_LINK_CAST)
+ {
+ if(const std::vector<int32> *spell_triggered = spellmgr.GetSpellLinked(m_spellInfo->Id))
+ for (std::vector<int32>::const_iterator i = spell_triggered->begin(); i != spell_triggered->end(); ++i)
+ if(*i < 0)
+ m_caster->RemoveAurasDueToSpell(-(*i));
+ else
+ m_caster->CastSpell(m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster, *i, true);
+
+ }
+ if (m_caster->GetTypeId() == TYPEID_PLAYER)
+ ((Player*)m_caster)->SetSpellModTakingSpell(this, false);
+
+ SetExecutedCurrently(false);
+}
+
+void Spell::handle_immediate()
+{
+ // start channeling if applicable
+ if(IsChanneledSpell(m_spellInfo))
+ {
+ int32 duration = GetSpellDuration(m_spellInfo);
+ if (duration)
+ {
+ // Apply haste mods
+ m_caster->ModSpellCastTime(m_spellInfo, duration, this);
+ // Apply duration mod
+ if(Player* modOwner = m_caster->GetSpellModOwner())
+ modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration);
+ m_spellState = SPELL_STATE_CASTING;
+ m_caster->AddInterruptMask(m_spellInfo->ChannelInterruptFlags);
+ SendChannelStart(duration);
+ }
+ }
+
+ // process immediate effects (items, ground, etc.) also initialize some variables
+ _handle_immediate_phase();
+
+ for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
+ DoAllEffectOnTarget(&(*ihit));
+
+ for (std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit)
+ DoAllEffectOnTarget(&(*ihit));
+
+ // spell is finished, perform some last features of the spell here
+ _handle_finish_phase();
+
+ // Remove used for cast item if need (it can be already NULL after TakeReagents call
+ TakeCastItem();
+
+ if(m_spellState != SPELL_STATE_CASTING)
+ finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell)
+}
+
+uint64 Spell::handle_delayed(uint64 t_offset)
+{
+ UpdatePointers();
+
+ if (m_caster->GetTypeId() == TYPEID_PLAYER)
+ ((Player*)m_caster)->SetSpellModTakingSpell(this, true);
+
+ uint64 next_time = 0;
+
+ if (!m_immediateHandled)
+ {
+ _handle_immediate_phase();
+ m_immediateHandled = true;
+ }
+
+ bool single_missile = (m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION);
+
+ // now recheck units targeting correctness (need before any effects apply to prevent adding immunity at first effect not allow apply second spell effect and similar cases)
+ for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
+ {
+ if (ihit->processed == false)
+ {
+ if ( single_missile || ihit->timeDelay <= t_offset )
+ DoAllEffectOnTarget(&(*ihit));
+ else if( next_time == 0 || ihit->timeDelay < next_time )
+ next_time = ihit->timeDelay;
+ }
+ }
+
+ // now recheck gameobject targeting correctness
+ for (std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit)
+ {
+ if (ighit->processed == false)
+ {
+ if ( single_missile || ighit->timeDelay <= t_offset )
+ DoAllEffectOnTarget(&(*ighit));
+ else if( next_time == 0 || ighit->timeDelay < next_time )
+ next_time = ighit->timeDelay;
+ }
+ }
+
+ if (m_caster->GetTypeId() == TYPEID_PLAYER)
+ ((Player*)m_caster)->SetSpellModTakingSpell(this, false);
+
+ // All targets passed - need finish phase
+ if (next_time == 0)
+ {
+ // spell is finished, perform some last features of the spell here
+ _handle_finish_phase();
+
+ finish(true); // successfully finish spell cast
+
+ // return zero, spell is finished now
+ return 0;
+ }
+ else
+ {
+ // spell is unfinished, return next execution time
+ return next_time;
+ }
+}
+
+void Spell::_handle_immediate_phase()
+{
+ m_spellAura = NULL;
+ // handle some immediate features of the spell here
+ HandleThreatSpells(m_spellInfo->Id);
+
+ m_needSpellLog = IsNeedSendToClient();
+ for (uint32 j = 0; j < 3; ++j)
+ {
+ if(m_spellInfo->Effect[j] == 0)
+ continue;
+
+ // apply Send Event effect to ground in case empty target lists
+ if( m_spellInfo->Effect[j] == SPELL_EFFECT_SEND_EVENT && !HaveTargetsForEffect(j) )
+ {
+ HandleEffects(NULL, NULL, NULL, j);
+ continue;
+ }
+
+ // Don't do spell log, if is school damage spell
+ if(m_spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE || m_spellInfo->Effect[j] == 0)
+ m_needSpellLog = false;
+ }
+
+ // initialize Diminishing Returns Data
+ m_diminishLevel = DIMINISHING_LEVEL_1;
+ m_diminishGroup = DIMINISHING_NONE;
+
+ // process items
+ for (std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit)
+ DoAllEffectOnTarget(&(*ihit));
+
+ if(!m_originalCaster)
+ return;
+ uint8 oldEffMask = m_effectMask;
+ // process ground
+ for (uint32 j = 0; j < 3; ++j)
+ {
+ if(EffectTargetType[m_spellInfo->Effect[j]] == SPELL_REQUIRE_DEST)
+ {
+ if(!m_targets.HasDst()) // FIXME: this will ignore dest set in effect
+ m_targets.setDst(m_caster);
+ HandleEffects(m_originalCaster, NULL, NULL, j);
+ m_effectMask |= (1<<j);
+ }
+ else if(EffectTargetType[m_spellInfo->Effect[j]] == SPELL_REQUIRE_NONE)
+ {
+ HandleEffects(m_originalCaster, NULL, NULL, j);
+ m_effectMask |= (1<<j);
+ }
+ }
+ if (oldEffMask != m_effectMask && m_UniqueTargetInfo.empty())
+ {
+ uint32 procAttacker = m_procAttacker;
+ if (!procAttacker)
+ {
+ bool positive = true;
+ for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i)
+ // If at least one effect negative spell is negative hit
+ if (m_effectMask & (1<<i) && !IsPositiveEffect(m_spellInfo->Id, i))
+ {
+ positive = false;
+ break;
+ }
+ switch(m_spellInfo->DmgClass)
+ {
+ case SPELL_DAMAGE_CLASS_MAGIC:
+ if (positive)
+ procAttacker |= PROC_FLAG_SUCCESSFUL_POSITIVE_MAGIC_SPELL;
+ else
+ procAttacker |= PROC_FLAG_SUCCESSFUL_NEGATIVE_MAGIC_SPELL;
+ break;
+ case SPELL_DAMAGE_CLASS_NONE:
+ if (positive)
+ procAttacker |= PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL_HIT;
+ else
+ procAttacker |= PROC_FLAG_SUCCESSFUL_NEGATIVE_SPELL_HIT;
+ break;
+ }
+ }
+ // Proc damage for spells which have only dest targets (2484 should proc 51486 for example)
+ m_originalCaster->ProcDamageAndSpell(0, procAttacker, 0, m_procEx | PROC_EX_NORMAL_HIT, 0, BASE_ATTACK, m_spellInfo, m_triggeredByAuraSpell);
+ }
+}
+
+void Spell::_handle_finish_phase()
+{
+ if(m_caster->m_movedPlayer)
+ {
+ // Take for real after all targets are processed
+ if (m_needComboPoints)
+ m_caster->m_movedPlayer->ClearComboPoints();
+
+ // Real add combo points from effects
+ if (m_comboPointGain)
+ m_caster->m_movedPlayer->GainSpellComboPoints(m_comboPointGain);
+ }
+
+ // spell log
+ if(m_needSpellLog)
+ SendLogExecute();
+}
+
+void Spell::SendSpellCooldown()
+{
+ if(m_caster->GetTypeId() != TYPEID_PLAYER)
+ return;
+
+ Player* _player = (Player*)m_caster;
+
+ // mana/health/etc potions, disabled by client (until combat out as declarate)
+ if (m_CastItem && m_CastItem->IsPotion())
+ {
+ // need in some way provided data for Spell::finish SendCooldownEvent
+ _player->SetLastPotionId(m_CastItem->GetEntry());
+ return;
+ }
+
+ // have infinity cooldown but set at aura apply // do not set cooldown for triggered spells (needed by reincarnation)
+ if(m_spellInfo->Attributes & (SPELL_ATTR_DISABLED_WHILE_ACTIVE | SPELL_ATTR_PASSIVE ) || m_IsTriggeredSpell)
+ return;
+
+ _player->AddSpellAndCategoryCooldowns(m_spellInfo,m_CastItem ? m_CastItem->GetEntry() : 0, this);
+}
+
+void Spell::update(uint32 difftime)
+{
+ // update pointers based at it's GUIDs
+ UpdatePointers();
+
+ if(m_targets.getUnitTargetGUID() && !m_targets.getUnitTarget())
+ {
+ sLog.outDebug("Spell %u is cancelled due to removal of target.", m_spellInfo->Id);
+ cancel();
+ return;
+ }
+
+ // check if the player caster has moved before the spell finished
+ if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) &&
+ m_caster->isMoving() && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT) &&
+ (m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING)))
+ {
+ // don't cancel for melee, autorepeat, triggered and instant spells
+ if(!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !m_IsTriggeredSpell)
+ cancel();
+ }
+
+ switch(m_spellState)
+ {
+ case SPELL_STATE_PREPARING:
+ {
+ if(m_timer)
+ {
+ if(difftime >= m_timer)
+ m_timer = 0;
+ else
+ m_timer -= difftime;
+ }
+
+ if(m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat())
+ cast(m_spellInfo->CastingTimeIndex == 1);
+ } break;
+ case SPELL_STATE_CASTING:
+ {
+ if(m_timer > 0)
+ {
+ // check if there are alive targets left
+ if (!UpdateChanneledTargetList())
+ {
+ sLog.outDebug("Channeled spell %d is removed due to lack of targets", m_spellInfo->Id);
+ SendChannelUpdate(0);
+ finish();
+ }
+
+ if(difftime >= m_timer)
+ m_timer = 0;
+ else
+ m_timer -= difftime;
+ }
+
+ if(m_timer == 0)
+ {
+ SendChannelUpdate(0);
+
+ // channeled spell processed independently for quest targeting
+ // cast at creature (or GO) quest objectives update at successful cast channel finished
+ // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... )
+ if( !IsAutoRepeat() && !IsNextMeleeSwingSpell() )
+ {
+ if ( Player* p = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself() )
+ {
+ for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
+ {
+ TargetInfo* target = &*ihit;
+ if(!IS_CRE_OR_VEH_GUID(target->targetGUID))
+ continue;
+
+ Unit* unit = m_caster->GetGUID() == target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target->targetGUID);
+ if (unit == NULL)
+ continue;
+
+ p->CastedCreatureOrGO(unit->GetEntry(), unit->GetGUID(), m_spellInfo->Id);
+ }
+
+ for (std::list<GOTargetInfo>::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit)
+ {
+ GOTargetInfo* target = &*ihit;
+
+ GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID);
+ if(!go)
+ continue;
+
+ p->CastedCreatureOrGO(go->GetEntry(), go->GetGUID(), m_spellInfo->Id);
+ }
+ }
+ }
+
+ finish();
+ }
+ } break;
+ default:
+ {
+ }break;
+ }
+}
+
+void Spell::finish(bool ok)
+{
+ if(!m_caster)
+ return;
+
+ if(m_spellState == SPELL_STATE_FINISHED)
+ return;
+ m_spellState = SPELL_STATE_FINISHED;
+
+ if(IsChanneledSpell(m_spellInfo))
+ m_caster->UpdateInterruptMask();
+
+ if(m_caster->hasUnitState(UNIT_STAT_CASTING) && !m_caster->IsNonMeleeSpellCasted(false, false, true))
+ m_caster->clearUnitState(UNIT_STAT_CASTING);
+
+ // Unsummon summon as possessed creatures on spell cancel
+ if(IsChanneledSpell(m_spellInfo) && m_caster->GetTypeId() == TYPEID_PLAYER)
+ {
+ if(Unit *charm = m_caster->GetCharm())
+ if(charm->GetTypeId() == TYPEID_UNIT
+ && ((Creature*)charm)->HasUnitTypeMask(UNIT_MASK_PUPPET)
+ && charm->GetUInt32Value(UNIT_CREATED_BY_SPELL) == m_spellInfo->Id)
+ ((Puppet*)charm)->UnSummon();
+ }
+
+ if(!ok)
+ return;
+
+ if (m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->isSummon())
+ {
+ // Unsummon statue
+ uint32 spell = m_caster->GetUInt32Value(UNIT_CREATED_BY_SPELL);
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell );
+ if (spellInfo && spellInfo->SpellIconID==2056)
+ {
+ sLog.outDebug("Statue %d is unsummoned in spell %d finish", m_caster->GetGUIDLow(), m_spellInfo->Id);
+ m_caster->setDeathState(JUST_DIED);
+ return;
+ }
+ }
+
+ // Okay to remove extra attacks
+ if(IsSpellHaveEffect(m_spellInfo, SPELL_EFFECT_ADD_EXTRA_ATTACKS))
+ m_caster->m_extraAttacks = 0;
+
+ // Heal caster for all health leech from all targets
+ if (m_healthLeech)
+ m_caster->DealHeal(m_caster, uint32(m_healthLeech), m_spellInfo);
+
+ if (IsMeleeAttackResetSpell())
+ {
+ bool found = false;
+ Unit::AuraEffectList const& vIgnoreReset = m_caster->GetAuraEffectsByType(SPELL_AURA_IGNORE_MELEE_RESET);
+ for (Unit::AuraEffectList::const_iterator i = vIgnoreReset.begin(); i != vIgnoreReset.end(); ++i)
+ {
+ if ((*i)->IsAffectedOnSpell(m_spellInfo))
+ {
+ found = true;
+ break;
+ }
+ }
+ if (!found)
+ {
+ m_caster->resetAttackTimer(BASE_ATTACK);
+ if(m_caster->haveOffhandWeapon())
+ m_caster->resetAttackTimer(OFF_ATTACK);
+ if(!(m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_NOT_RESET_AUTOSHOT))
+ m_caster->resetAttackTimer(RANGED_ATTACK);
+ }
+ }
+
+ // potions disabled by client, send event "not in combat" if need
+ if (m_caster->GetTypeId() == TYPEID_PLAYER)
+ {
+ if (!m_triggeredByAuraSpell)
+ ((Player*)m_caster)->UpdatePotionCooldown(this);
+
+ // triggered spell pointer can be not set in some cases
+ // this is needed for proper apply of triggered spell mods
+ ((Player*)m_caster)->SetSpellModTakingSpell(this, true);
+ }
+
+ // call triggered spell only at successful cast (after clear combo points -> for add some if need)
+ // I assume what he means is that some triggered spells may add combo points
+ if(!m_TriggerSpells.empty())
+ TriggerSpell();
+
+ // Take mods after trigger spell (needed for 14177 to affect 48664)
+ // mods are taken only on succesfull cast and independantly from targets of the spell
+ if (m_caster->GetTypeId() == TYPEID_PLAYER)
+ {
+ ((Player*)m_caster)->RemoveSpellMods(this);
+ ((Player*)m_caster)->SetSpellModTakingSpell(this, false);
+ }
+
+ // Stop Attack for some spells
+ if( m_spellInfo->Attributes & SPELL_ATTR_STOP_ATTACK_TARGET )
+ m_caster->AttackStop();
+}
+
+void Spell::SendCastResult(SpellCastResult result)
+{
+ if(result == SPELL_CAST_OK)
+ return;
+
+ if (m_caster->GetTypeId() != TYPEID_PLAYER)
+ return;
+
+ if(((Player*)m_caster)->GetSession()->PlayerLoading()) // don't send cast results at loading time
+ return;
+
+ SendCastResult((Player*)m_caster,m_spellInfo,m_cast_count,result);
+}
+
+void Spell::SendCastResult(Player* caster, SpellEntry const* spellInfo, uint8 cast_count, SpellCastResult result)
+{
+ if(result == SPELL_CAST_OK)
+ return;
+
+ WorldPacket data(SMSG_CAST_FAILED, (4+1+1));
+ data << uint8(cast_count); // single cast or multi 2.3 (0/1)
+ data << uint32(spellInfo->Id);
+ data << uint8(result); // problem
+ switch (result)
+ {
+ case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
+ data << uint32(spellInfo->RequiresSpellFocus);
+ break;
+ case SPELL_FAILED_REQUIRES_AREA:
+ // hardcode areas limitation case
+ switch(spellInfo->Id)
+ {
+ case 41617: // Cenarion Mana Salve
+ case 41619: // Cenarion Healing Salve
+ data << uint32(3905);
+ break;
+ case 41618: // Bottled Nethergon Energy
+ case 41620: // Bottled Nethergon Vapor
+ data << uint32(3842);
+ break;
+ case 45373: // Bloodberry Elixir
+ data << uint32(4075);
+ break;
+ default: // default case (don't must be)
+ data << uint32(0);
+ break;
+ }
+ break;
+ case SPELL_FAILED_TOTEMS:
+ if(spellInfo->Totem[0])
+ data << uint32(spellInfo->Totem[0]);
+ if(spellInfo->Totem[1])
+ data << uint32(spellInfo->Totem[1]);
+ break;
+ case SPELL_FAILED_TOTEM_CATEGORY:
+ if(spellInfo->TotemCategory[0])
+ data << uint32(spellInfo->TotemCategory[0]);
+ if(spellInfo->TotemCategory[1])
+ data << uint32(spellInfo->TotemCategory[1]);
+ break;
+ case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
+ data << uint32(spellInfo->EquippedItemClass);
+ data << uint32(spellInfo->EquippedItemSubClassMask);
+ //data << uint32(spellInfo->EquippedItemInventoryTypeMask);
+ break;
+ case SPELL_FAILED_TOO_MANY_OF_ITEM:
+ {
+ uint32 item;
+ for(int8 x=0;x < 3;x++)
+ if (spellInfo->EffectItemType[x])
+ item = spellInfo->EffectItemType[x];
+ ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
+ if (pProto && pProto->ItemLimitCategory)
+ data << uint32(pProto->ItemLimitCategory);
+ break;
+ }
+ default:
+ break;
+ }
+ caster->GetSession()->SendPacket(&data);
+}
+
+void Spell::SendSpellStart()
+{
+ if(!IsNeedSendToClient())
+ return;
+
+ //sLog.outDebug("Sending SMSG_SPELL_START id=%u", m_spellInfo->Id);
+
+ uint32 castFlags = CAST_FLAG_UNKNOWN_2;
+ if(m_spellInfo->Attributes & SPELL_ATTR_REQ_AMMO)
+ castFlags |= CAST_FLAG_AMMO;
+ if ((m_caster->GetTypeId() == TYPEID_PLAYER ||
+ (m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->isPet()))
+ && m_spellInfo->powerType != POWER_HEALTH )
+ castFlags |= CAST_FLAG_POWER_LEFT_SELF;
+
+ if(m_spellInfo->runeCostID && m_spellInfo->powerType == POWER_RUNE)
+ castFlags |= CAST_FLAG_UNKNOWN_19;
+
+ WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2));
+ if(m_CastItem)
+ data.append(m_CastItem->GetPackGUID());
+ else
+ data.append(m_caster->GetPackGUID());
+
+ data.append(m_caster->GetPackGUID());
+ data << uint8(m_cast_count); // pending spell cast?
+ data << uint32(m_spellInfo->Id); // spellId
+ data << uint32(castFlags); // cast flags
+ data << uint32(m_timer); // delay?
+
+ m_targets.write(&data);
+
+ if(castFlags & CAST_FLAG_POWER_LEFT_SELF)
+ data << uint32(m_caster->GetPower((Powers)m_spellInfo->powerType));
+
+ if ( castFlags & CAST_FLAG_AMMO )
+ WriteAmmoToPacket(&data);
+
+ if ( castFlags & CAST_FLAG_UNKNOWN_23 )
+ {
+ data << uint32(0);
+ data << uint32(0);
+ }
+
+ m_caster->SendMessageToSet(&data, true);
+}
+
+void Spell::SendSpellGo()
+{
+ // not send invisible spell casting
+ if(!IsNeedSendToClient())
+ return;
+
+ //sLog.outDebug("Sending SMSG_SPELL_GO id=%u", m_spellInfo->Id);
+
+ uint32 castFlags = CAST_FLAG_UNKNOWN_9;
+
+ // triggered spells with spell visual != 0
+ if((m_IsTriggeredSpell && !IsAutoRepeatRangedSpell(m_spellInfo)) || m_triggeredByAuraSpell)
+ castFlags |= CAST_FLAG_PENDING;
+
+ if(m_spellInfo->Attributes & SPELL_ATTR_REQ_AMMO)
+ castFlags |= CAST_FLAG_AMMO; // arrows/bullets visual
+ if ((m_caster->GetTypeId() == TYPEID_PLAYER ||
+ (m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->isPet()))
+ && m_spellInfo->powerType != POWER_HEALTH )
+ castFlags |= CAST_FLAG_POWER_LEFT_SELF; // should only be sent to self, but the current messaging doesn't make that possible
+
+ if((m_caster->GetTypeId() == TYPEID_PLAYER)
+ && (m_caster->getClass() == CLASS_DEATH_KNIGHT)
+ && m_spellInfo->runeCostID
+ && m_spellInfo->powerType == POWER_RUNE)
+ {
+ castFlags |= CAST_FLAG_UNKNOWN_19; // same as in SMSG_SPELL_START
+ castFlags |= CAST_FLAG_RUNE_LIST; // rune cooldowns list
+ castFlags |= CAST_FLAG_UNKNOWN_9; // ??
+ }
+
+ if (IsSpellHaveEffect(m_spellInfo, SPELL_EFFECT_ACTIVATE_RUNE))
+ {
+ castFlags |= CAST_FLAG_RUNE_LIST; // rune cooldowns list
+ castFlags |= CAST_FLAG_UNKNOWN_19; // same as in SMSG_SPELL_START
+ }
+
+ WorldPacket data(SMSG_SPELL_GO, 50); // guess size
+
+ if(m_CastItem)
+ data.append(m_CastItem->GetPackGUID());
+ else
+ data.append(m_caster->GetPackGUID());
+
+ data.append(m_caster->GetPackGUID());
+ data << uint8(m_cast_count); // pending spell cast?
+ data << uint32(m_spellInfo->Id); // spellId
+ data << uint32(castFlags); // cast flags
+ data << uint32(getMSTime()); // timestamp
+
+ WriteSpellGoTargets(&data);
+
+ m_targets.write(&data);
+
+ if(castFlags & CAST_FLAG_POWER_LEFT_SELF)
+ data << uint32(m_caster->GetPower((Powers)m_spellInfo->powerType));
+
+ if ( castFlags & CAST_FLAG_RUNE_LIST ) // rune cooldowns list
+ {
+ uint8 v1 = m_runesState;
+ uint8 v2 = ((Player*)m_caster)->GetRunesState();
+ data << uint8(v1); // runes state before
+ data << uint8(v2); // runes state after
+ for (uint8 i = 0; i < MAX_RUNES; ++i)
+ {
+ uint8 m = (1 << i);
+ if(m & v1) // usable before...
+ if(!(m & v2)) // ...but on cooldown now...
+ data << uint8(0); // some unknown byte (time?)
+ }
+ }
+
+ if ( castFlags & CAST_FLAG_UNKNOWN_18 ) // unknown wotlk
+ {
+ data << float(0);
+ data << uint32(0);
+ }
+
+ if ( castFlags & CAST_FLAG_AMMO )
+ WriteAmmoToPacket(&data);
+
+ if ( castFlags & CAST_FLAG_UNKNOWN_20 ) // unknown wotlk
+ {
+ data << uint32(0);
+ data << uint32(0);
+ }
+
+ if ( m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION )
+ {
+ data << uint8(0);
+ }
+
+ m_caster->SendMessageToSet(&data, true);
+}
+
+void Spell::WriteAmmoToPacket( WorldPacket * data )
+{
+ uint32 ammoInventoryType = 0;
+ uint32 ammoDisplayID = 0;
+
+ if (m_caster->GetTypeId() == TYPEID_PLAYER)
+ {
+ Item *pItem = ((Player*)m_caster)->GetWeaponForAttack( RANGED_ATTACK );
+ if(pItem)
+ {
+ ammoInventoryType = pItem->GetProto()->InventoryType;
+ if( ammoInventoryType == INVTYPE_THROWN )
+ ammoDisplayID = pItem->GetProto()->DisplayInfoID;
+ else
+ {
+ uint32 ammoID = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
+ if(ammoID)
+ {
+ ItemPrototype const *pProto = objmgr.GetItemPrototype( ammoID );
+ if(pProto)
+ {
+ ammoDisplayID = pProto->DisplayInfoID;
+ ammoInventoryType = pProto->InventoryType;
+ }
+ }
+ else if(m_caster->HasAura(46699)) // Requires No Ammo
+ {
+ ammoDisplayID = 5996; // normal arrow
+ ammoInventoryType = INVTYPE_AMMO;
+ }
+ }
+ }
+ }
+ else
+ {
+ for (uint8 i = 0; i < 3; ++i)
+ {
+ if(uint32 item_id = m_caster->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i))
+ {
+ if(ItemEntry const * itemEntry = sItemStore.LookupEntry(item_id))
+ {
+ if(itemEntry->Class==ITEM_CLASS_WEAPON)
+ {
+ switch(itemEntry->SubClass)
+ {
+ case ITEM_SUBCLASS_WEAPON_THROWN:
+ ammoDisplayID = itemEntry->DisplayId;
+ ammoInventoryType = itemEntry->InventoryType;
+ break;
+ case ITEM_SUBCLASS_WEAPON_BOW:
+ case ITEM_SUBCLASS_WEAPON_CROSSBOW:
+ ammoDisplayID = 5996; // is this need fixing?
+ ammoInventoryType = INVTYPE_AMMO;
+ break;
+ case ITEM_SUBCLASS_WEAPON_GUN:
+ ammoDisplayID = 5998; // is this need fixing?
+ ammoInventoryType = INVTYPE_AMMO;
+ break;
+ }
+
+ if(ammoDisplayID)
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ *data << uint32(ammoDisplayID);
+ *data << uint32(ammoInventoryType);
+}
+
+void Spell::WriteSpellGoTargets( WorldPacket * data )
+{
+ // This function also fill data for channeled spells:
+ // m_needAliveTargetMask req for stop channelig if one target die
+ uint32 hit = m_UniqueGOTargetInfo.size(); // Always hits on GO
+ uint32 miss = 0;
+ for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
+ {
+ if ((*ihit).effectMask == 0) // No effect apply - all immuned add state
+ {
+ // possibly SPELL_MISS_IMMUNE2 for this??
+ ihit->missCondition = SPELL_MISS_IMMUNE2;
+ ++miss;
+ }
+ else if ((*ihit).missCondition == SPELL_MISS_NONE)
+ ++hit;
+ else
+ ++miss;
+ }
+
+ *data << (uint8)hit;
+ for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
+ {
+ if ((*ihit).missCondition == SPELL_MISS_NONE) // Add only hits
+ {
+ *data << uint64(ihit->targetGUID);
+ m_needAliveTargetMask |=ihit->effectMask;
+ }
+ }
+
+ for (std::list<GOTargetInfo>::const_iterator ighit = m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit)
+ *data << uint64(ighit->targetGUID); // Always hits
+
+ *data << (uint8)miss;
+ for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
+ {
+ if( ihit->missCondition != SPELL_MISS_NONE ) // Add only miss
+ {
+ *data << uint64(ihit->targetGUID);
+ *data << uint8(ihit->missCondition);
+ if( ihit->missCondition == SPELL_MISS_REFLECT )
+ *data << uint8(ihit->reflectResult);
+ }
+ }
+ // Reset m_needAliveTargetMask for non channeled spell
+ if(!IsChanneledSpell(m_spellInfo))
+ m_needAliveTargetMask = 0;
+}
+
+void Spell::SendLogExecute()
+{
+ Unit *target = m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster;
+
+ WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8));
+
+ if(m_caster->GetTypeId() == TYPEID_PLAYER)
+ data.append(m_caster->GetPackGUID());
+ else
+ data.append(target->GetPackGUID());
+
+ data << uint32(m_spellInfo->Id);
+ uint32 count1 = 1;
+ data << uint32(count1); // count1 (effect count?)
+ for (uint32 i = 0; i < count1; ++i)
+ {
+ data << uint32(m_spellInfo->Effect[0]); // spell effect
+ uint32 count2 = 1;
+ data << uint32(count2); // count2 (target count?)
+ for (uint32 j = 0; j < count2; ++j)
+ {
+ switch(m_spellInfo->Effect[0])
+ {
+ case SPELL_EFFECT_POWER_DRAIN:
+ if(Unit *unit = m_targets.getUnitTarget())
+ data.append(unit->GetPackGUID());
+ else
+ data << uint8(0);
+ data << uint32(0);
+ data << uint32(0);
+ data << float(0);
+ break;
+ case SPELL_EFFECT_ADD_EXTRA_ATTACKS:
+ if(Unit *unit = m_targets.getUnitTarget())
+ data.append(unit->GetPackGUID());
+ else
+ data << uint8(0);
+ data << uint32(m_caster->m_extraAttacks);
+ break;
+ case SPELL_EFFECT_INTERRUPT_CAST:
+ if(Unit *unit = m_targets.getUnitTarget())
+ data.append(unit->GetPackGUID());
+ else
+ data << uint8(0);
+ data << uint32(0); // spellid
+ break;
+ case SPELL_EFFECT_DURABILITY_DAMAGE:
+ if(Unit *unit = m_targets.getUnitTarget())
+ data.append(unit->GetPackGUID());
+ else
+ data << uint8(0);
+ data << uint32(0);
+ data << uint32(0);
+ break;
+ case SPELL_EFFECT_OPEN_LOCK:
+ if(Item *item = m_targets.getItemTarget())
+ data.append(item->GetPackGUID());
+ else
+ data << uint8(0);
+ break;
+ case SPELL_EFFECT_CREATE_ITEM:
+ case SPELL_EFFECT_CREATE_ITEM_2:
+ data << uint32(m_spellInfo->EffectItemType[0]);
+ break;
+ case SPELL_EFFECT_SUMMON:
+ case SPELL_EFFECT_TRANS_DOOR:
+ case SPELL_EFFECT_SUMMON_PET:
+ case SPELL_EFFECT_SUMMON_OBJECT_WILD:
+ case SPELL_EFFECT_CREATE_HOUSE:
+ case SPELL_EFFECT_DUEL:
+ case SPELL_EFFECT_SUMMON_OBJECT_SLOT1:
+ case SPELL_EFFECT_SUMMON_OBJECT_SLOT2:
+ case SPELL_EFFECT_SUMMON_OBJECT_SLOT3:
+ case SPELL_EFFECT_SUMMON_OBJECT_SLOT4:
+ if(Unit *unit = m_targets.getUnitTarget())
+ data.append(unit->GetPackGUID());
+ else if(m_targets.getItemTargetGUID())
+ data.appendPackGUID(m_targets.getItemTargetGUID());
+ else if(GameObject *go = m_targets.getGOTarget())
+ data.append(go->GetPackGUID());
+ else
+ data << uint8(0); // guid
+ break;
+ case SPELL_EFFECT_FEED_PET:
+ data << uint32(m_targets.getItemTargetEntry());
+ break;
+ case SPELL_EFFECT_DISMISS_PET:
+ if(Unit *unit = m_targets.getUnitTarget())
+ data.append(unit->GetPackGUID());
+ else
+ data << uint8(0);
+ break;
+ case SPELL_EFFECT_RESURRECT:
+ case SPELL_EFFECT_RESURRECT_NEW:
+ if(Unit *unit = m_targets.getUnitTarget())
+ data.append(unit->GetPackGUID());
+ else
+ data << uint8(0);
+ break;
+ default:
+ return;
+ }
+ }
+ }
+
+ m_caster->SendMessageToSet(&data, true);
+}
+
+void Spell::SendInterrupted(uint8 result)
+{
+ WorldPacket data(SMSG_SPELL_FAILURE, (8+4+1));
+ data.append(m_caster->GetPackGUID());
+ data << uint8(m_cast_count);
+ data << uint32(m_spellInfo->Id);
+ data << uint8(result);
+ m_caster->SendMessageToSet(&data, true);
+
+ data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+4));
+ data.append(m_caster->GetPackGUID());
+ data << uint8(m_cast_count);
+ data << uint32(m_spellInfo->Id);
+ data << uint8(result);
+ m_caster->SendMessageToSet(&data, true);
+}
+
+void Spell::SendChannelUpdate(uint32 time)
+{
+ if(time == 0)
+ {
+ m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
+ m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, 0);
+ }
+
+ if (m_caster->GetTypeId() != TYPEID_PLAYER)
+ return;
+
+ WorldPacket data( MSG_CHANNEL_UPDATE, 8+4 );
+ data.append(m_caster->GetPackGUID());
+ data << uint32(time);
+
+ m_caster->SendMessageToSet(&data, true);
+}
+
+void Spell::SendChannelStart(uint32 duration)
+{
+ WorldObject* target = NULL;
+
+ // select first not resisted target from target list for _0_ effect
+ if(!m_UniqueTargetInfo.empty())
+ {
+ for (std::list<TargetInfo>::const_iterator itr = m_UniqueTargetInfo.begin(); itr != m_UniqueTargetInfo.end(); ++itr)
+ {
+ if( (itr->effectMask & (1 << 0)) && itr->reflectResult == SPELL_MISS_NONE && itr->targetGUID != m_caster->GetGUID())
+ {
+ target = ObjectAccessor::GetUnit(*m_caster, itr->targetGUID);
+ break;
+ }
+ }
+ }
+ else if(!m_UniqueGOTargetInfo.empty())
+ {
+ for (std::list<GOTargetInfo>::const_iterator itr = m_UniqueGOTargetInfo.begin(); itr != m_UniqueGOTargetInfo.end(); ++itr)
+ {
+ if(itr->effectMask & (1 << 0) )
+ {
+ target = m_caster->GetMap()->GetGameObject(itr->targetGUID);
+ break;
+ }
+ }
+ }
+
+ WorldPacket data( MSG_CHANNEL_START, (8+4+4) );
+ data.append(m_caster->GetPackGUID());
+ data << uint32(m_spellInfo->Id);
+ data << uint32(duration);
+
+ m_caster->SendMessageToSet(&data, true);
+
+ m_timer = duration;
+ if(target)
+ m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, target->GetGUID());
+ m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id);
+}
+
+void Spell::SendResurrectRequest(Player* target)
+{
+ // Both players and NPCs can resurrect using spells - have a look at creature 28487 for example
+ // However, the packet structure differs slightly
+
+ const char* sentName = m_caster->GetTypeId() == TYPEID_PLAYER ? "" : m_caster->GetNameForLocaleIdx(target->GetSession()->GetSessionDbLocaleIndex());
+
+ WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+strlen(sentName)+1+1+1));
+ data << uint64(m_caster->GetGUID());
+ data << uint32(strlen(sentName) + 1);
+
+ data << sentName;
+ data << uint8(0);
+
+ data << uint8(m_caster->GetTypeId() == TYPEID_PLAYER ? 0 : 1);
+ target->GetSession()->SendPacket(&data);
+}
+
+void Spell::SendPlaySpellVisual(uint32 SpellID)
+{
+ if (m_caster->GetTypeId() != TYPEID_PLAYER)
+ return;
+
+ WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 8 + 4);
+ data << uint64(m_caster->GetGUID());
+ data << uint32(SpellID); // spell visual id?
+ ((Player*)m_caster)->GetSession()->SendPacket(&data);
+}
+
+void Spell::TakeCastItem()
+{
+ if(!m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER)
+ return;
+
+ // not remove cast item at triggered spell (equipping, weapon damage, etc)
+ if(m_IsTriggeredSpell)
+ return;
+
+ ItemPrototype const *proto = m_CastItem->GetProto();
+
+ if(!proto)
+ {
+ // This code is to avoid a crash
+ // I'm not sure, if this is really an error, but I guess every item needs a prototype
+ sLog.outError("Cast item has no item prototype highId=%d, lowId=%d",m_CastItem->GetGUIDHigh(), m_CastItem->GetGUIDLow());
+ return;
+ }
+
+ bool expendable = false;
+ bool withoutCharges = false;
+
+ for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
+ {
+ if (proto->Spells[i].SpellId)
+ {
+ // item has limited charges
+ if (proto->Spells[i].SpellCharges)
+ {
+ if (proto->Spells[i].SpellCharges < 0)
+ expendable = true;
+
+ int32 charges = m_CastItem->GetSpellCharges(i);
+
+ // item has charges left
+ if (charges)
+ {
+ (charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use
+ if (proto->Stackable == 1)
+ m_CastItem->SetSpellCharges(i, charges);
+ m_CastItem->SetState(ITEM_CHANGED, (Player*)m_caster);
+ }
+
+ // all charges used
+ withoutCharges = (charges == 0);
+ }
+ }
+ }
+
+ if (expendable && withoutCharges)
+ {
+ uint32 count = 1;
+ ((Player*)m_caster)->DestroyItemCount(m_CastItem, count, true);
+
+ // prevent crash at access to deleted m_targets.getItemTarget
+ if(m_CastItem==m_targets.getItemTarget())
+ m_targets.setItemTarget(NULL);
+
+ m_CastItem = NULL;
+ }
+}
+
+void Spell::TakePower()
+{
+ if(m_CastItem || m_triggeredByAuraSpell)
+ return;
+
+ bool hit = true;
+ if(m_caster->GetTypeId() == TYPEID_PLAYER)
+ {
+ if(m_spellInfo->powerType == POWER_RAGE || m_spellInfo->powerType == POWER_ENERGY)
+ if(uint64 targetGUID = m_targets.getUnitTargetGUID())
+ for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
+ if(ihit->targetGUID == targetGUID)
+ {
+ if(ihit->missCondition != SPELL_MISS_NONE && ihit->missCondition != SPELL_MISS_MISS/* && ihit->targetGUID!=m_caster->GetGUID()*/)
+ hit = false;
+ if (ihit->missCondition != SPELL_MISS_NONE)
+ {
+ //lower spell cost on fail (by talent aura)
+ if(Player *modOwner = ((Player*)m_caster)->GetSpellModOwner())
+ modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_SPELL_COST_REFUND_ON_FAIL, m_powerCost);
+ }
+ break;
+ }
+ }
+
+ Powers powerType = Powers(m_spellInfo->powerType);
+
+ if(hit && powerType == POWER_RUNE)
+ {
+ TakeRunePower();
+ return;
+ }
+
+ if (!m_powerCost)
+ return;
+
+ // health as power used
+ if(m_spellInfo->powerType == POWER_HEALTH)
+ {
+ m_caster->ModifyHealth( -(int32)m_powerCost );
+ return;
+ }
+
+ if(m_spellInfo->powerType >= MAX_POWERS)
+ {
+ sLog.outError("Spell::TakePower: Unknown power type '%d'", m_spellInfo->powerType);
+ return;
+ }
+
+ if(hit)
+ m_caster->ModifyPower(powerType, -m_powerCost);
+ else
+ m_caster->ModifyPower(powerType, -irand(0, m_powerCost/4));
+
+ // Set the five second timer
+ if (powerType == POWER_MANA && m_powerCost > 0)
+ m_caster->SetLastManaUse(getMSTime());
+}
+
+void Spell::TakeAmmo()
+{
+ if(m_attackType == RANGED_ATTACK && m_caster->GetTypeId() == TYPEID_PLAYER)
+ {
+ Item *pItem = ((Player*)m_caster)->GetWeaponForAttack( RANGED_ATTACK );
+
+ // wands don't have ammo
+ if(!pItem || pItem->IsBroken() || pItem->GetProto()->SubClass==ITEM_SUBCLASS_WEAPON_WAND)
+ return;
+
+ if( pItem->GetProto()->InventoryType == INVTYPE_THROWN )
+ {
+ if(pItem->GetMaxStackCount()==1)
+ {
+ // decrease durability for non-stackable throw weapon
+ ((Player*)m_caster)->DurabilityPointLossForEquipSlot(EQUIPMENT_SLOT_RANGED);
+ }
+ else
+ {
+ // decrease items amount for stackable throw weapon
+ uint32 count = 1;
+ ((Player*)m_caster)->DestroyItemCount( pItem, count, true);
+ }
+ }
+ else if(uint32 ammo = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID))
+ ((Player*)m_caster)->DestroyItemCount(ammo, 1, true);
+ }
+}
+
+SpellCastResult Spell::CheckRuneCost(uint32 runeCostID)
+{
+ if(m_spellInfo->powerType != POWER_RUNE || !runeCostID)
+ return SPELL_CAST_OK;
+
+ if(m_caster->GetTypeId() != TYPEID_PLAYER)
+ return SPELL_CAST_OK;
+
+ Player *plr = (Player*)m_caster;
+
+ if(plr->getClass() != CLASS_DEATH_KNIGHT)
+ return SPELL_CAST_OK;
+
+ SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(runeCostID);
+
+ if(!src)
+ return SPELL_CAST_OK;
+
+ if(src->NoRuneCost())
+ return SPELL_CAST_OK;
+
+ int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
+
+ for (uint32 i = 0; i < RUNE_DEATH; ++i)
+ {
+ runeCost[i] = src->RuneCost[i];
+ if(Player* modOwner = m_caster->GetSpellModOwner())
+ modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, runeCost[i], this);
+ }
+
+ runeCost[RUNE_DEATH] = MAX_RUNES; // calculated later
+
+ for (uint32 i = 0; i < MAX_RUNES; ++i)
+ {
+ RuneType rune = plr->GetCurrentRune(i);
+ if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
+ runeCost[rune]--;
+ }
+
+ for (uint32 i = 0; i < RUNE_DEATH; ++i)
+ if(runeCost[i] > 0)
+ runeCost[RUNE_DEATH] += runeCost[i];
+
+ if(runeCost[RUNE_DEATH] > MAX_RUNES)
+ return SPELL_FAILED_NO_POWER; // not sure if result code is correct
+
+ return SPELL_CAST_OK;
+}
+
+void Spell::TakeRunePower()
+{
+ if(m_caster->GetTypeId() != TYPEID_PLAYER)
+ return;
+
+ Player *plr = (Player*)m_caster;
+
+ if(plr->getClass() != CLASS_DEATH_KNIGHT)
+ return;
+
+ SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(m_spellInfo->runeCostID);
+
+ if(!src || (src->NoRuneCost() && src->NoRunicPowerGain()))
+ return;
+
+ m_runesState = plr->GetRunesState(); // store previous state
+
+ int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death
+
+ for (uint32 i = 0; i < RUNE_DEATH; ++i)
+ {
+ runeCost[i] = src->RuneCost[i];
+ if(Player* modOwner = m_caster->GetSpellModOwner())
+ modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, runeCost[i], this);
+ }
+
+ runeCost[RUNE_DEATH] = 0; // calculated later
+
+ for (uint32 i = 0; i < MAX_RUNES; ++i)
+ {
+ RuneType rune = plr->GetCurrentRune(i);
+ if((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0))
+ {
+ plr->SetRuneCooldown(i, plr->GetRuneBaseCooldown(i));
+ plr->SetLastUsedRune(RuneType(rune));
+ runeCost[rune]--;
+ }
+ }
+
+ runeCost[RUNE_DEATH] = runeCost[RUNE_BLOOD] + runeCost[RUNE_UNHOLY] + runeCost[RUNE_FROST];
+
+ if(runeCost[RUNE_DEATH] > 0)
+ {
+ for (uint32 i = 0; i < MAX_RUNES; ++i)
+ {
+ RuneType rune = plr->GetCurrentRune(i);
+ if((plr->GetRuneCooldown(i) == 0) && (rune == RUNE_DEATH))
+ {
+ plr->SetRuneCooldown(i, plr->GetRuneBaseCooldown(i));
+ plr->SetLastUsedRune(RuneType(rune));
+ runeCost[rune]--;
+
+ plr->RestoreBaseRune(i);
+
+ if(runeCost[RUNE_DEATH] == 0)
+ break;
+ }
+ }
+ }
+
+ // you can gain some runic power when use runes
+ float rp = src->runePowerGain;
+ rp *= sWorld.getRate(RATE_POWER_RUNICPOWER_INCOME);
+ plr->ModifyPower(POWER_RUNIC_POWER, (int32)rp);
+}
+
+void Spell::TakeReagents()
+{
+ if(m_IsTriggeredSpell) // reagents used in triggered spell removed by original spell or don't must be removed.
+ return;
+
+ if (m_caster->GetTypeId() != TYPEID_PLAYER)
+ return;
+
+ // do not take reagents for these item casts
+ if (m_CastItem && m_CastItem->GetProto()->Flags & ITEM_FLAGS_TRIGGERED_CAST)
+ return;
+
+ Player* p_caster = (Player*)m_caster;
+ if (p_caster->CanNoReagentCast(m_spellInfo))
+ return;
+
+ for (uint32 x = 0; x < 8; ++x)
+ {
+ if(m_spellInfo->Reagent[x] <= 0)
+ continue;
+
+ uint32 itemid = m_spellInfo->Reagent[x];
+ uint32 itemcount = m_spellInfo->ReagentCount[x];
+
+ // if CastItem is also spell reagent
+ if (m_CastItem)
+ {
+ ItemPrototype const *proto = m_CastItem->GetProto();
+ if( proto && proto->ItemId == itemid )
+ {
+ for (int s = 0; s < MAX_ITEM_PROTO_SPELLS; ++s)
+ {
+ // CastItem will be used up and does not count as reagent
+ int32 charges = m_CastItem->GetSpellCharges(s);
+ if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
+ {
+ ++itemcount;
+ break;
+ }
+ }
+
+ m_CastItem = NULL;
+ }
+ }
+
+ // if getItemTarget is also spell reagent
+ if (m_targets.getItemTargetEntry() == itemid)
+ m_targets.setItemTarget(NULL);
+
+ p_caster->DestroyItemCount(itemid, itemcount, true);
+ }
+}
+
+void Spell::HandleThreatSpells(uint32 spellId)
+{
+ if(!m_targets.getUnitTarget() || !spellId)
+ return;
+
+ if(!m_targets.getUnitTarget()->CanHaveThreatList())
+ return;
+
+ uint16 threat = spellmgr.GetSpellThreat(spellId);
+
+ if(!threat)
+ return;
+
+ m_targets.getUnitTarget()->AddThreat(m_caster, float(threat));
+
+ DEBUG_LOG("Spell %u, rank %u, added an additional %i threat", spellId, spellmgr.GetSpellRank(spellId), threat);
+}
+
+void Spell::HandleEffects(Unit *pUnitTarget,Item *pItemTarget,GameObject *pGOTarget,uint32 i)
+{
+
+ if (!sScriptMgr.OnSpellCast(pUnitTarget,pItemTarget,pGOTarget,i,m_spellInfo))
+ return;
+
+ //effect has been handled, skip it
+ if (m_effectMask & (1<<i))
+ return;
+
+ unitTarget = pUnitTarget;
+ itemTarget = pItemTarget;
+ gameObjTarget = pGOTarget;
+
+ uint8 eff = m_spellInfo->Effect[i];
+
+ sLog.outDebug( "Spell: %u Effect : %u", m_spellInfo->Id, eff);
+
+ //we do not need DamageMultiplier here.
+ damage = CalculateDamage(i, NULL);
+
+ if(eff < TOTAL_SPELL_EFFECTS)
+ {
+ //sLog.outDebug( "WORLD: Spell FX %d < TOTAL_SPELL_EFFECTS ", eff);
+ (this->*SpellEffects[eff])(i);
+ }
+}
+
+void Spell::TriggerSpell()
+{
+ for (TriggerSpells::iterator si=m_TriggerSpells.begin(); si!=m_TriggerSpells.end(); ++si)
+ {
+ Spell* spell = new Spell(m_caster, (*si), true, m_originalCasterGUID, m_selfContainer, true);
+ spell->prepare(&m_targets); // use original spell original targets
+ }
+}
+
+SpellCastResult Spell::CheckCast(bool strict)
+{
+ // check cooldowns to prevent cheating
+ if(m_caster->GetTypeId() == TYPEID_PLAYER && !(m_spellInfo->Attributes & SPELL_ATTR_PASSIVE))
+ {
+ //can cast triggered (by aura only?) spells while have this flag
+ if (!m_IsTriggeredSpell && ((Player*)m_caster)->HasFlag(PLAYER_FLAGS, PLAYER_ALLOW_ONLY_ABILITY))
+ return SPELL_FAILED_SPELL_IN_PROGRESS;
+
+ if (((Player*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
+ {
+ if(m_triggeredByAuraSpell)
+ return SPELL_FAILED_DONT_REPORT;
+ else
+ return SPELL_FAILED_NOT_READY;
+ }
+ }
+
+ // only allow triggered spells if at an ended battleground
+ if( !m_IsTriggeredSpell && m_caster->GetTypeId() == TYPEID_PLAYER)
+ if(BattleGround * bg = ((Player*)m_caster)->GetBattleGround())
+ if(bg->GetStatus() == STATUS_WAIT_LEAVE)
+ return SPELL_FAILED_DONT_REPORT;
+
+ // only check at first call, Stealth auras are already removed at second call
+ // for now, ignore triggered spells
+ if( strict && !m_IsTriggeredSpell)
+ {
+ bool checkForm = true;
+ // Ignore form req aura
+ Unit::AuraEffectList const& ignore = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_SHAPESHIFT);
+ for (Unit::AuraEffectList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
+ {
+ if (!(*i)->IsAffectedOnSpell(m_spellInfo))
+ continue;
+ checkForm = false;
+ break;
+ }
+ if (checkForm)
+ {
+ // Cannot be used in this stance/form
+ SpellCastResult shapeError = GetErrorAtShapeshiftedCast(m_spellInfo, m_caster->m_form);
+ if(shapeError != SPELL_CAST_OK)
+ return shapeError;
+
+ if ((m_spellInfo->Attributes & SPELL_ATTR_ONLY_STEALTHED) && !(m_caster->HasStealthAura()))
+ return SPELL_FAILED_ONLY_STEALTHED;
+ }
+ }
+
+ bool reqCombat=true;
+ Unit::AuraEffectList const& stateAuras = m_caster->GetAuraEffectsByType(SPELL_AURA_ABILITY_IGNORE_AURASTATE);
+ for (Unit::AuraEffectList::const_iterator j = stateAuras.begin(); j != stateAuras.end(); ++j)
+ {
+ if((*j)->IsAffectedOnSpell(m_spellInfo))
+ {
+ if ((*j)->GetMiscValue()==1)
+ {
+ reqCombat=false;
+ break;
+ }
+ }
+ }
+
+ // caster state requirements
+ // not for triggered spells (needed by execute)
+ if (!m_IsTriggeredSpell)
+ {
+ if(m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraState), m_spellInfo, m_caster))
+ return SPELL_FAILED_CASTER_AURASTATE;
+ if(m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraStateNot), m_spellInfo, m_caster))
+ return SPELL_FAILED_CASTER_AURASTATE;
+
+ // Note: spell 62473 requres casterAuraSpell = triggering spell
+ if(m_spellInfo->casterAuraSpell && !m_caster->HasAura(m_spellInfo->casterAuraSpell))
+ return SPELL_FAILED_CASTER_AURASTATE;
+ if(m_spellInfo->excludeCasterAuraSpell && m_caster->HasAura(m_spellInfo->excludeCasterAuraSpell))
+ return SPELL_FAILED_CASTER_AURASTATE;
+
+ if(reqCombat && m_caster->isInCombat() && IsNonCombatSpell(m_spellInfo))
+ return SPELL_FAILED_AFFECTING_COMBAT;
+ }
+
+ // cancel autorepeat spells if cast start when moving
+ // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code)
+ if( m_caster->GetTypeId() == TYPEID_PLAYER && ((Player*)m_caster)->isMoving() )
+ {
+ // skip stuck spell to allow use it in falling case and apply spell limitations at movement
+ if( (!((Player*)m_caster)->m_movementInfo.HasMovementFlag(MOVEMENTFLAG_FALLING) || m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK) &&
+ (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0) )
+ return SPELL_FAILED_MOVING;
+ }
+
+ if(Unit *target = m_targets.getUnitTarget())
+ {
+ // target state requirements (not allowed state), apply to self also
+ if(!m_IsTriggeredSpell && m_spellInfo->TargetAuraStateNot && target->HasAuraState(AuraState(m_spellInfo->TargetAuraStateNot), m_spellInfo, m_caster))
+ return SPELL_FAILED_TARGET_AURASTATE;
+
+ if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
+ return SPELL_FAILED_TARGET_AURASTATE;
+
+ if(m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
+ return SPELL_FAILED_TARGET_AURASTATE;
+
+ if(!m_IsTriggeredSpell && target == m_caster && m_spellInfo->AttributesEx & SPELL_ATTR_EX_CANT_TARGET_SELF)
+ return SPELL_FAILED_BAD_TARGETS;
+
+ bool non_caster_target = target != m_caster && !spellmgr.IsSpellWithCasterSourceTargetsOnly(m_spellInfo);
+
+ if(non_caster_target)
+ {
+ // target state requirements (apply to non-self only), to allow cast affects to self like Dirty Deeds
+ if(!m_IsTriggeredSpell && m_spellInfo->TargetAuraState && !target->HasAuraState(AuraState(m_spellInfo->TargetAuraState), m_spellInfo, m_caster))
+ return SPELL_FAILED_TARGET_AURASTATE;
+
+ // Not allow casting on flying player
+ if (target->hasUnitState(UNIT_STAT_UNATTACKABLE))
+ return SPELL_FAILED_BAD_TARGETS;
+
+ if(!m_IsTriggeredSpell && (target->HasAuraType(SPELL_AURA_MOD_STEALTH)
+ || target->m_invisibilityMask) && !m_caster->canSeeOrDetect(target, true))
+ return SPELL_FAILED_BAD_TARGETS;
+
+ if (m_caster->GetTypeId() == TYPEID_PLAYER)
+ {
+ // Not allow banish not self target
+ if (m_spellInfo->Mechanic == MECHANIC_BANISH)
+ if (target->GetTypeId() == TYPEID_UNIT &&
+ !((Player*)m_caster)->isAllowedToLoot((Creature*)target))
+ return SPELL_FAILED_CANT_CAST_ON_TAPPED;
+
+ if (m_customAttr & SPELL_ATTR_CU_PICKPOCKET)
+ {
+ if (target->GetTypeId() == TYPEID_PLAYER)
+ return SPELL_FAILED_BAD_TARGETS;
+ else if ((target->GetCreatureTypeMask() & CREATURE_TYPEMASK_HUMANOID_OR_UNDEAD) == 0)
+ return SPELL_FAILED_TARGET_NO_POCKETS;
+ }
+
+ // Not allow disarm unarmed player
+ if (m_spellInfo->Mechanic == MECHANIC_DISARM)
+ {
+ if (target->GetTypeId() == TYPEID_PLAYER)
+ {
+ if(!((Player*)target)->GetWeaponForAttack(BASE_ATTACK) || !((Player*)target)->IsUseEquipedWeapon(true))
+ return SPELL_FAILED_TARGET_NO_WEAPONS;
+ }
+ else if (!target->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID))
+ return SPELL_FAILED_TARGET_NO_WEAPONS;
+ }
+ }
+
+ if(!m_IsTriggeredSpell && VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOSInMap(target))
+ return SPELL_FAILED_LINE_OF_SIGHT;
+
+ }
+ else if (m_caster == target)
+ {
+
+ if (m_caster->GetTypeId() == TYPEID_PLAYER) // Target - is player caster
+ {
+ // Additional check for some spells
+ // If 0 spell effect empty - client not send target data (need use selection)
+ // TODO: check it on next client version
+ if (m_targets.m_targetMask == TARGET_FLAG_SELF &&
+ m_spellInfo->EffectImplicitTargetA[1] == TARGET_UNIT_TARGET_ENEMY)
+ {
+ if (target = m_caster->GetUnit(*m_caster, ((Player *)m_caster)->GetSelection()))
+ m_targets.setUnitTarget(target);
+ else
+ return SPELL_FAILED_BAD_TARGETS;
+ }
+ }
+ }
+
+ // check pet presents
+ for (int j = 0; j < 3; ++j)
+ {
+ if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_UNIT_PET)
+ {
+ target = m_caster->GetGuardianPet();
+ if(!target)
+ {
+ if(m_triggeredByAuraSpell) // not report pet not existence for triggered spells
+ return SPELL_FAILED_DONT_REPORT;
+ else
+ return SPELL_FAILED_NO_PET;
+ }
+ break;
+ }
+ }
+
+ //check creature type
+ //ignore self casts (including area casts when caster selected as target)
+ if(non_caster_target)
+ {
+ if(!CheckTargetCreatureType(target))
+ {
+ if(target->GetTypeId() == TYPEID_PLAYER)
+ return SPELL_FAILED_TARGET_IS_PLAYER;
+ else
+ return SPELL_FAILED_BAD_TARGETS;
+ }
+ }
+
+ // who can give me an example to show what is the use of this
+ // even if we need check, check by effect rather than whole spell, otherwise 57108,57143 are broken
+ /*
+ // TODO: this check can be applied and for player to prevent cheating when IsPositiveSpell will return always correct result.
+ // check target for pet/charmed casts (not self targeted), self targeted cast used for area effects and etc
+ if(non_caster_target && m_caster->GetTypeId() == TYPEID_UNIT && m_caster->GetCharmerOrOwnerGUID())
+ {
+ // check correctness positive/negative cast target (pet cast real check and cheating check)
+ if(IsPositiveSpell(m_spellInfo->Id))
+ {
+ //dispel positivity is dependant on target, don't check it
+ if(m_caster->IsHostileTo(target) && !IsDispel(m_spellInfo))
+ return SPELL_FAILED_BAD_TARGETS;
+ }
+ else
+ {
+ if(m_caster->IsFriendlyTo(target))
+ return SPELL_FAILED_BAD_TARGETS;
+ }
+ }
+ */
+
+ if(target)
+ if(IsPositiveSpell(m_spellInfo->Id))
+ if(target->IsImmunedToSpell(m_spellInfo))
+ return SPELL_FAILED_TARGET_AURASTATE;
+
+ //Must be behind the target.
+ if( m_spellInfo->AttributesEx2 == 0x100000 && (m_spellInfo->AttributesEx & 0x200) == 0x200 && target->HasInArc(M_PI, m_caster)
+ //Exclusion for Pounce: Facing Limitation was removed in 2.0.1, but it still uses the same, old Ex-Flags
+ && (!(m_spellInfo->SpellFamilyName == SPELLFAMILY_DRUID && m_spellInfo->SpellFamilyFlags.IsEqual(0x20000,0,0)))
+ //Mutilate no longer requires you be behind the target as of patch 3.0.3
+ && (!(m_spellInfo->SpellFamilyName == SPELLFAMILY_ROGUE && m_spellInfo->SpellFamilyFlags[1] & 0x200000))
+ //Exclusion for Throw: Facing limitation was added in 3.2.x, but that shouldn't be
+ && (!(m_spellInfo->SpellFamilyName == SPELLFAMILY_ROGUE && m_spellInfo->SpellFamilyFlags[0] & 0x00000001)))
+ {
+ SendInterrupted(2);
+ return SPELL_FAILED_NOT_BEHIND;
+ }
+
+ //Target must be facing you.
+ if((m_spellInfo->Attributes == 0x150010) && !target->HasInArc(M_PI, m_caster) )
+ {
+ SendInterrupted(2);
+ return SPELL_FAILED_NOT_INFRONT;
+ }
+
+ // check if target is in combat
+ if (non_caster_target && (m_spellInfo->AttributesEx & SPELL_ATTR_EX_NOT_IN_COMBAT_TARGET) && target->isInCombat())
+ return SPELL_FAILED_TARGET_AFFECTING_COMBAT;
+ }
+
+ // Spell casted only on battleground
+ if ((m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_BATTLEGROUND) && m_caster->GetTypeId() == TYPEID_PLAYER)
+ if(!((Player*)m_caster)->InBattleGround())
+ return SPELL_FAILED_ONLY_BATTLEGROUNDS;
+
+ // do not allow spells to be cast in arenas
+ // - with greater than 10 min CD without SPELL_ATTR_EX4_USABLE_IN_ARENA flag
+ // - with SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA flag
+ if ((m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_NOT_USABLE_IN_ARENA) ||
+ GetSpellRecoveryTime(m_spellInfo) > 10 * MINUTE * IN_MILISECONDS && !(m_spellInfo->AttributesEx4 & SPELL_ATTR_EX4_USABLE_IN_ARENA))
+ if(MapEntry const* mapEntry = sMapStore.LookupEntry(m_caster->GetMapId()))
+ if(mapEntry->IsBattleArena())
+ return SPELL_FAILED_NOT_IN_ARENA;
+
+ // zone check
+ if(m_caster->GetTypeId() == TYPEID_UNIT || !((Player*)m_caster)->isGameMaster())
+ {
+ uint32 zone, area;
+ m_caster->GetZoneAndAreaId(zone,area);
+
+ SpellCastResult locRes= spellmgr.GetSpellAllowedInLocationError(m_spellInfo,m_caster->GetMapId(),zone,area,
+ m_caster->GetTypeId() == TYPEID_PLAYER ? ((Player*)m_caster) : NULL);
+ if(locRes != SPELL_CAST_OK)
+ return locRes;
+ }
+
+ // not let players cast spells at mount (and let do it to creatures)
+ if (m_caster->IsMounted() && m_caster->GetTypeId() == TYPEID_PLAYER && !m_IsTriggeredSpell &&
+ !IsPassiveSpell(m_spellInfo->Id) && !(m_spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_MOUNTED))
+ {
+ if (m_caster->isInFlight())
+ return SPELL_FAILED_NOT_ON_TAXI;
+ else
+ return SPELL_FAILED_NOT_MOUNTED;
+ }
+
+ // always (except passive spells) check items (focus object can be required for any type casts)
+ if (!IsPassiveSpell(m_spellInfo->Id))
+ {
+ SpellCastResult castResult = CheckItems();
+ if(castResult != SPELL_CAST_OK)
+ return castResult;
+ }
+
+ /*//ImpliciteTargetA-B = 38, If fact there is 0 Spell with ImpliciteTargetB=38
+ if(m_UniqueTargetInfo.empty()) // skip second CheckCast apply (for delayed spells for example)
+ {
+ for (uint8 j = 0; j < 3; ++j)
+ {
+ if( m_spellInfo->EffectImplicitTargetA[j] == TARGET_UNIT_NEARBY_ENTRY ||
+ m_spellInfo->EffectImplicitTargetB[j] == TARGET_UNIT_NEARBY_ENTRY && m_spellInfo->EffectImplicitTargetA[j] != TARGET_UNIT_CASTER ||
+ m_spellInfo->EffectImplicitTargetA[j] == TARGET_DST_NEARBY_ENTRY ||
+ m_spellInfo->EffectImplicitTargetB[j] == TARGET_DST_NEARBY_ENTRY )
+ {
+ SpellScriptTarget::const_iterator lower = spellmgr.GetBeginSpellScriptTarget(m_spellInfo->Id);
+ SpellScriptTarget::const_iterator upper = spellmgr.GetEndSpellScriptTarget(m_spellInfo->Id);
+ if(lower==upper)
+ sLog.outErrorDb("Spell (ID: %u) has effect EffectImplicitTargetA/EffectImplicitTargetB = TARGET_UNIT_NEARBY_ENTRY or TARGET_DST_NEARBY_ENTRY, but does not have record in `spell_script_target`",m_spellInfo->Id);
+
+ SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
+ float range = GetSpellMaxRange(srange);
+
+ Creature* creatureScriptTarget = NULL;
+ GameObject* goScriptTarget = NULL;
+
+ for (SpellScriptTarget::const_iterator i_spellST = bounds.first; i_spellST != bounds.second; ++i_spellST)
+ {
+ switch(i_spellST->second.type)
+ {
+ case SPELL_TARGET_TYPE_GAMEOBJECT:
+ {
+ GameObject* p_GameObject = NULL;
+
+ if (i_spellST->second.targetEntry)
+ {
+ CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
+ Cell cell(p);
+ cell.data.Part.reserved = ALL_DISTRICT;
+
+ Trinity::NearestGameObjectEntryInObjectRangeCheck go_check(*m_caster,i_spellST->second.targetEntry,range);
+ Trinity::GameObjectLastSearcher<Trinity::NearestGameObjectEntryInObjectRangeCheck> checker(m_caster, p_GameObject,go_check);
+
+ TypeContainerVisitor<Trinity::GameObjectLastSearcher<Trinity::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
+ CellLock<GridReadGuard> cell_lock(cell, p);
+ cell_lock->Visit(cell_lock, object_checker, *m_caster->GetMap());
+
+ if (p_GameObject)
+ {
+ // remember found target and range, next attempt will find more near target with another entry
+ creatureScriptTarget = NULL;
+ goScriptTarget = p_GameObject;
+ range = go_check.GetLastRange();
+ }
+ }
+ else if (focusObject) // Focus Object
+ {
+ float frange = m_caster->GetDistance(focusObject);
+ if (range >= frange)
+ {
+ creatureScriptTarget = NULL;
+ goScriptTarget = focusObject;
+ range = frange;
+ }
+ }
+ break;
+ }
+ case SPELL_TARGET_TYPE_CREATURE:
+ case SPELL_TARGET_TYPE_DEAD:
+ default:
+ {
+ Creature *p_Creature = NULL;
+
+ CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
+ Cell cell(p);
+ cell.data.Part.reserved = ALL_DISTRICT;
+ cell.SetNoCreate(); // Really don't know what is that???
+
+ Trinity::NearestCreatureEntryWithLiveStateInObjectRangeCheck u_check(*m_caster,i_spellST->second.targetEntry,i_spellST->second.type!=SPELL_TARGET_TYPE_DEAD,range);
+ Trinity::CreatureLastSearcher<Trinity::NearestCreatureEntryWithLiveStateInObjectRangeCheck> searcher(m_caster, p_Creature, u_check);
+
+ TypeContainerVisitor<Trinity::CreatureLastSearcher<Trinity::NearestCreatureEntryWithLiveStateInObjectRangeCheck>, GridTypeMapContainer > grid_creature_searcher(searcher);
+
+ CellLock<GridReadGuard> cell_lock(cell, p);
+ cell_lock->Visit(cell_lock, grid_creature_searcher, *m_caster->GetMap(), *m_caster, range);
+
+ if(p_Creature )
+ {
+ creatureScriptTarget = p_Creature;
+ goScriptTarget = NULL;
+ range = u_check.GetLastRange();
+ }
+ break;
+ }
+ }
+ }
+
+ if(creatureScriptTarget)
+ {
+ // store coordinates for TARGET_DST_NEARBY_ENTRY
+ if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_DST_NEARBY_ENTRY ||
+ m_spellInfo->EffectImplicitTargetB[j] == TARGET_DST_NEARBY_ENTRY )
+ {
+ m_targets.setDst(creatureScriptTarget->GetPositionX(),creatureScriptTarget->GetPositionY(),creatureScriptTarget->GetPositionZ());
+
+ if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_DST_NEARBY_ENTRY && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
+ AddUnitTarget(creatureScriptTarget, j);
+ }
+ // store explicit target for TARGET_UNIT_NEARBY_ENTRY
+ else
+ AddUnitTarget(creatureScriptTarget, j);
+ }
+ else if(goScriptTarget)
+ {
+ // store coordinates for TARGET_DST_NEARBY_ENTRY
+ if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_DST_NEARBY_ENTRY ||
+ m_spellInfo->EffectImplicitTargetB[j] == TARGET_DST_NEARBY_ENTRY )
+ {
+ m_targets.setDst(goScriptTarget->GetPositionX(),goScriptTarget->GetPositionY(),goScriptTarget->GetPositionZ());
+
+ if(m_spellInfo->EffectImplicitTargetA[j] == TARGET_DST_NEARBY_ENTRY && m_spellInfo->EffectImplicitTargetB[j] == 0 && m_spellInfo->Effect[j]!=SPELL_EFFECT_PERSISTENT_AREA_AURA)
+ AddGOTarget(goScriptTarget, j);
+ }
+ // store explicit target for TARGET_UNIT_NEARBY_ENTRY
+ else
+ AddGOTarget(goScriptTarget, j);
+ }
+ //Missing DB Entry or targets for this spellEffect.
+ else
+ {
+ // not report target not existence for triggered spells
+ if(m_triggeredByAuraSpell || m_IsTriggeredSpell)
+ return SPELL_FAILED_DONT_REPORT;
+ else
+ return SPELL_FAILED_BAD_TARGETS;
+ }
+ }
+ }
+ }*/
+
+ if(!m_IsTriggeredSpell)
+ {
+ SpellCastResult castResult = CheckRange(strict);
+ if(castResult != SPELL_CAST_OK)
+ return castResult;
+
+ castResult = CheckPower();
+ if(castResult != SPELL_CAST_OK)
+ return castResult;
+
+ castResult = CheckCasterAuras();
+ if(castResult != SPELL_CAST_OK)
+ return castResult;
+ }
+
+ for (int i = 0; i < 3; i++)
+ {
+ // for effects of spells that have only one target
+ switch(m_spellInfo->Effect[i])
+ {
+ case SPELL_EFFECT_DUMMY:
+ {
+ if (m_spellInfo->Id == 51582) // Rocket Boots Engaged
+ {
+ if(m_caster->IsInWater())
+ return SPELL_FAILED_ONLY_ABOVEWATER;
+ }
+ else if(m_spellInfo->SpellIconID == 156) // Holy Shock
+ {
+ // spell different for friends and enemies
+ // hurt version required facing
+ if(m_targets.getUnitTarget() && !m_caster->IsFriendlyTo(m_targets.getUnitTarget()) && !m_caster->HasInArc( M_PI, m_targets.getUnitTarget() ))
+ return SPELL_FAILED_UNIT_NOT_INFRONT;
+ }
+ else if(m_spellInfo->SpellIconID == 33 && m_spellInfo->SpellFamilyName == SPELLFAMILY_SHAMAN && m_spellInfo->SpellFamilyFlags[0] & SPELLFAMILYFLAG_SHAMAN_FIRE_NOVA)
+ {
+ if (!m_caster->m_SummonSlot[1])
+ return SPELL_FAILED_SUCCESS;
+ }
+ else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && m_spellInfo->SpellFamilyFlags[0] == 0x2000) // Death Coil (DeathKnight)
+ {
+ Unit* target = m_targets.getUnitTarget();
+ if (!target || (target->IsFriendlyTo(m_caster) && target->GetCreatureType() != CREATURE_TYPE_UNDEAD))
+ return SPELL_FAILED_BAD_TARGETS;
+ }
+ else if (m_spellInfo->Id == 19938) // Awaken Peon
+ {
+ Unit *unit = m_targets.getUnitTarget();
+ if(!unit || !unit->HasAura(17743))
+ return SPELL_FAILED_BAD_TARGETS;
+ }
+ else if (m_spellInfo->Id == 52264) // Deliver Stolen Horse
+ {
+ if(!m_caster->FindNearestCreature(28653,5))
+ return SPELL_FAILED_OUT_OF_RANGE;
+ }
+ else if (m_spellInfo->Id == 31789) // Righteous Defense
+ {
+ if (m_caster->GetTypeId() != TYPEID_PLAYER)
+ return SPELL_FAILED_DONT_REPORT;
+
+ Unit* target = m_targets.getUnitTarget();
+ if (!target || !target->IsFriendlyTo(m_caster) || target->getAttackers().empty())
+ return SPELL_FAILED_BAD_TARGETS;
+
+ }
+ break;
+ }
+ case SPELL_EFFECT_LEARN_SPELL:
+ {
+ if (m_caster->GetTypeId() != TYPEID_PLAYER)
+ return SPELL_FAILED_BAD_TARGETS;
+
+ if(m_spellInfo->EffectImplicitTargetA[i] != TARGET_UNIT_PET)
+ break;
+
+ Pet* pet = ((Player*)m_caster)->GetPet();
+
+ if(!pet)
+ return SPELL_FAILED_NO_PET;
+
+ SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
+
+ if(!learn_spellproto)
+ return SPELL_FAILED_NOT_KNOWN;
+
+ if(m_spellInfo->spellLevel > pet->getLevel())
+ return SPELL_FAILED_LOWLEVEL;
+
+ break;
+ }
+ case SPELL_EFFECT_LEARN_PET_SPELL:
+ {
+ if (m_caster->GetTypeId() != TYPEID_PLAYER)
+ return SPELL_FAILED_BAD_TARGETS;
+
+ Pet* pet = ((Player*)m_caster)->GetPet();
+ if(!pet)
+ return SPELL_FAILED_NO_PET;
+
+ SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]);
+
+ if(!learn_spellproto)
+ return SPELL_FAILED_NOT_KNOWN;
+
+ if(m_spellInfo->spellLevel > pet->getLevel())
+ return SPELL_FAILED_LOWLEVEL;
+
+ break;
+ }
+ case SPELL_EFFECT_APPLY_GLYPH:
+ {
+ uint32 glyphId = m_spellInfo->EffectMiscValue[i];
+ if(GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyphId))
+ if(m_caster->HasAura(gp->SpellId))
+ return SPELL_FAILED_UNIQUE_GLYPH;
+ break;
+ }
+ case SPELL_EFFECT_FEED_PET:
+ {
+ if (m_caster->GetTypeId() != TYPEID_PLAYER)
+ return SPELL_FAILED_BAD_TARGETS;
+
+ Item* foodItem = m_targets.getItemTarget();
+ if(!foodItem)
+ return SPELL_FAILED_BAD_TARGETS;
+
+ Pet* pet = ((Player*)m_caster)->GetPet();
+
+ if(!pet)
+ return SPELL_FAILED_NO_PET;
+
+ if(!pet->HaveInDiet(foodItem->GetProto()))
+ return SPELL_FAILED_WRONG_PET_FOOD;
+
+ if(!pet->GetCurrentFoodBenefitLevel(foodItem->GetProto()->ItemLevel))
+ return SPELL_FAILED_FOOD_LOWLEVEL;
+
+ if(m_caster->isInCombat() || pet->isInCombat())
+ return SPELL_FAILED_AFFECTING_COMBAT;
+
+ break;
+ }
+ case SPELL_EFFECT_POWER_BURN:
+ case SPELL_EFFECT_POWER_DRAIN:
+ {
+ // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects)
+ if(m_caster->GetTypeId() == TYPEID_PLAYER)
+ if(Unit* target = m_targets.getUnitTarget())
+ if(target != m_caster && target->getPowerType() != m_spellInfo->EffectMiscValue[i])
+ return SPELL_FAILED_BAD_TARGETS;
+ break;
+ }
+ case SPELL_EFFECT_CHARGE:
+ {
+ if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR)
+ {
+ // Warbringer - can't be handled in proc system - should be done before checkcast root check and charge effect process
+ if (strict && m_caster->IsScriptOverriden(m_spellInfo, 6953))
+ m_caster->RemoveMovementImpairingAuras();
+ }
+ if (m_caster->hasUnitState(UNIT_STAT_ROOT))
+ return SPELL_FAILED_ROOTED;
+ break;
+ }
+ case SPELL_EFFECT_SKINNING:
+ {
+ if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() != TYPEID_UNIT)
+ return SPELL_FAILED_BAD_TARGETS;
+
+ if( !(m_targets.getUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE) )
+ return SPELL_FAILED_TARGET_UNSKINNABLE;
+
+ Creature* creature = (Creature*)m_targets.getUnitTarget();
+ if ( creature->GetCreatureType() != CREATURE_TYPE_CRITTER && ( !creature->lootForBody || !creature->loot.empty() ) )
+ {
+ return SPELL_FAILED_TARGET_NOT_LOOTED;
+ }
+
+ uint32 skill = creature->GetCreatureInfo()->GetRequiredLootSkill();
+
+ int32 skillValue = ((Player*)m_caster)->GetSkillValue(skill);
+ int32 TargetLevel = m_targets.getUnitTarget()->getLevel();
+ int32 ReqValue = (skillValue < 100 ? (TargetLevel-10) * 10 : TargetLevel * 5);
+ if (ReqValue > skillValue)
+ return SPELL_FAILED_LOW_CASTLEVEL;
+
+ // chance for fail at orange skinning attempt
+ if( (m_selfContainer && (*m_selfContainer) == this) &&
+ skillValue < sWorld.GetConfigMaxSkillValue() &&
+ (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue - 25, skillValue + 37) )
+ return SPELL_FAILED_TRY_AGAIN;
+
+ break;
+ }
+ case SPELL_EFFECT_OPEN_LOCK:
+ {
+ if( m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT &&
+ m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT_ITEM )
+ break;
+
+ if( m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc.
+ // we need a go target in case of TARGET_GAMEOBJECT
+ || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT && !m_targets.getGOTarget()
+ // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM
+ || m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT_ITEM && !m_targets.getGOTarget() &&
+ (!m_targets.getItemTarget() || !m_targets.getItemTarget()->GetProto()->LockID || m_targets.getItemTarget()->GetOwner() != m_caster ) )
+ return SPELL_FAILED_BAD_TARGETS;
+
+ // In BattleGround players can use only flags and banners
+ if( ((Player*)m_caster)->InBattleGround() &&
+ !((Player*)m_caster)->CanUseBattleGroundObject() )
+ return SPELL_FAILED_TRY_AGAIN;
+
+ // get the lock entry
+ uint32 lockId = 0;
+ if (GameObject* go = m_targets.getGOTarget())
+ {
+ lockId = go->GetGOInfo()->GetLockId();
+ if (!lockId)
+ return SPELL_FAILED_BAD_TARGETS;
+ }
+ else if(Item* itm = m_targets.getItemTarget())
+ lockId = itm->GetProto()->LockID;
+
+ SkillType skillId = SKILL_NONE;
+ int32 reqSkillValue = 0;
+ int32 skillValue = 0;
+
+ // check lock compatibility
+ SpellCastResult res = CanOpenLock(i, lockId, skillId, reqSkillValue, skillValue);
+ if(res != SPELL_CAST_OK)
+ return res;
+
+ // chance for fail at orange mining/herb/LockPicking gathering attempt
+ // second check prevent fail at rechecks
+ if(skillId != SKILL_NONE && (!m_selfContainer || ((*m_selfContainer) != this)))
+ {
+ bool canFailAtMax = skillId != SKILL_HERBALISM && skillId != SKILL_MINING;
+
+ // chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill)
+ if((canFailAtMax || skillValue < sWorld.GetConfigMaxSkillValue()) && reqSkillValue > irand(skillValue - 25, skillValue + 37))
+ return SPELL_FAILED_TRY_AGAIN;
+ }
+ break;
+ }
+ case SPELL_EFFECT_SUMMON_DEAD_PET:
+ {
+ Creature *pet = m_caster->GetGuardianPet();
+ if(!pet)
+ return SPELL_FAILED_NO_PET;
+
+ if(pet->isAlive())
+ return SPELL_FAILED_ALREADY_HAVE_SUMMON;
+
+ break;
+ }
+ // This is generic summon effect
+ case SPELL_EFFECT_SUMMON:
+ {
+ SummonPropertiesEntry const *SummonProperties = sSummonPropertiesStore.LookupEntry(m_spellInfo->EffectMiscValueB[i]);
+ if(!SummonProperties)
+ break;
+ switch(SummonProperties->Category)
+ {
+ case SUMMON_CATEGORY_PET:
+ if(m_caster->GetPetGUID())
+ return SPELL_FAILED_ALREADY_HAVE_SUMMON;
+ case SUMMON_CATEGORY_PUPPET:
+ if(m_caster->GetCharmGUID())
+ return SPELL_FAILED_ALREADY_HAVE_CHARM;
+ break;
+ }
+ break;
+ }
+ case SPELL_EFFECT_SUMMON_PET:
+ {
+ if(m_caster->GetPetGUID()) //let warlock do a replacement summon
+ {
+ if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->getClass()==CLASS_WARLOCK)
+ {
+ if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player)
+ if(Pet* pet = ((Player*)m_caster)->GetPet())
+ pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID());
+ }
+ else
+ return SPELL_FAILED_ALREADY_HAVE_SUMMON;
+ }
+
+ if(m_caster->GetCharmGUID())
+ return SPELL_FAILED_ALREADY_HAVE_CHARM;
+
+ break;
+ }
+ case SPELL_EFFECT_SUMMON_PLAYER:
+ {
+ if(m_caster->GetTypeId() != TYPEID_PLAYER)
+ return SPELL_FAILED_BAD_TARGETS;
+ if(!((Player*)m_caster)->GetSelection())
+ return SPELL_FAILED_BAD_TARGETS;
+
+ Player* target = objmgr.GetPlayer(((Player*)m_caster)->GetSelection());
+ if( !target || ((Player*)m_caster) == target || !target->IsInSameRaidWith((Player*)m_caster) )
+ return SPELL_FAILED_BAD_TARGETS;
+
+ // check if our map is dungeon
+ if( sMapStore.LookupEntry(m_caster->GetMapId())->IsDungeon() )
+ {
+ InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(m_caster->GetMapId());
+ if(!instance)
+ return SPELL_FAILED_TARGET_NOT_IN_INSTANCE;
+ if(!target->Satisfy(objmgr.GetAccessRequirement(instance->access_id), m_caster->GetMapId()))
+ return SPELL_FAILED_BAD_TARGETS;
+ }
+ break;
+ }
+ case SPELL_EFFECT_LEAP:
+ case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER:
+ {
+ //Do not allow to cast it before BG starts.
+ if(m_caster->GetTypeId() == TYPEID_PLAYER)
+ if(BattleGround const *bg = ((Player*)m_caster)->GetBattleGround())
+ if(bg->GetStatus() != STATUS_IN_PROGRESS)
+ return SPELL_FAILED_TRY_AGAIN;
+ break;
+ }
+ case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF:
+ {
+ if (m_targets.getUnitTarget() == m_caster)
+ return SPELL_FAILED_BAD_TARGETS;
+ break;
+ }
+ default:break;
+ }
+ }
+
+ for (int i = 0; i < 3; i++)
+ {
+ switch(m_spellInfo->EffectApplyAuraName[i])
+ {
+ case SPELL_AURA_DUMMY:
+ {
+ //custom check
+ switch(m_spellInfo->Id)
+ {
+ // Tag Murloc
+ case 30877:
+ {
+ Unit* target = m_targets.getUnitTarget();
+ if (!target || target->GetEntry() != 17326)
+ return SPELL_FAILED_BAD_TARGETS;
+ break;
+ }
+ case 61336:
+ if(m_caster->GetTypeId() != TYPEID_PLAYER || !((Player*)m_caster)->IsInFeralForm())
+ return SPELL_FAILED_ONLY_SHAPESHIFT;
+ break;
+ // Wild Growth
+ case 48438:
+ case 53248:
+ case 53249:
+ case 53251:
+ {
+ if (m_caster->GetTypeId() != TYPEID_PLAYER)
+ return SPELL_FAILED_DONT_REPORT;
+
+ Unit* target = m_targets.getUnitTarget();
+ if (!target || target->GetTypeId() != TYPEID_PLAYER)
+ return SPELL_FAILED_BAD_TARGETS;
+
+ if (!((Player*)m_caster)->IsInSameRaidWith(((Player*)target)))
+ return SPELL_FAILED_TARGET_NOT_IN_RAID;
+
+ break;
+ }
+ case 1515:
+ {
+ if (m_caster->GetTypeId() != TYPEID_PLAYER)
+ return SPELL_FAILED_BAD_TARGETS;
+
+ if (!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER)
+ return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
+
+ Creature* target = (Creature*)m_targets.getUnitTarget();
+
+ if (target->getLevel() > m_caster->getLevel())
+ return SPELL_FAILED_HIGHLEVEL;
+
+ // use SMSG_PET_TAME_FAILURE?
+ if (!target->GetCreatureInfo()->isTameable (((Player*)m_caster)->CanTameExoticPets()))
+ return SPELL_FAILED_BAD_TARGETS;
+
+ if(m_caster->GetPetGUID())
+ return SPELL_FAILED_ALREADY_HAVE_SUMMON;
+
+ if(m_caster->GetCharmGUID())
+ return SPELL_FAILED_ALREADY_HAVE_CHARM;
+
+ break;
+ }
+ case 44795: // Parachute
+ {
+ float x, y, z;
+ m_caster->GetPosition(x, y, z);
+ float ground_Z = m_caster->GetMap()->GetVmapHeight(x, y, z);
+ if (fabs(ground_Z - z) < 0.1f)
+ return SPELL_FAILED_DONT_REPORT;
+ break;
+ }
+ default:
+ break;
+ }
+ break;
+ }
+ case SPELL_AURA_MOD_POSSESS_PET:
+ {
+ if(m_caster->GetTypeId() != TYPEID_PLAYER)
+ return SPELL_FAILED_NO_PET;
+
+ Pet *pet = ((Player*)m_caster)->GetPet();
+ if(!pet)
+ return SPELL_FAILED_NO_PET;
+
+ if(pet->GetCharmerGUID())
+ return SPELL_FAILED_CHARMED;
+ break;
+ }
+ case SPELL_AURA_MOD_POSSESS:
+ case SPELL_AURA_MOD_CHARM:
+ case SPELL_AURA_AOE_CHARM:
+ {
+ if(m_caster->GetCharmerGUID())
+ return SPELL_FAILED_CHARMED;
+
+ if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_CHARM
+ || m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_POSSESS)
+ {
+ if(m_caster->GetPetGUID())
+ return SPELL_FAILED_ALREADY_HAVE_SUMMON;
+
+ if(m_caster->GetCharmGUID())
+ return SPELL_FAILED_ALREADY_HAVE_CHARM;
+ }
+
+ if(Unit *target = m_targets.getUnitTarget())
+ {
+ if(target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->IsVehicle())
+ return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
+
+ if(target->GetCharmerGUID())
+ return SPELL_FAILED_CHARMED;
+
+ int32 damage = CalculateDamage(i, target);
+ if(damage && int32(target->getLevel()) > damage)
+ return SPELL_FAILED_HIGHLEVEL;
+ }
+
+ break;
+ }
+ case SPELL_AURA_MOUNTED:
+ {
+ if (m_caster->IsInWater())
+ return SPELL_FAILED_ONLY_ABOVEWATER;
+
+ if (m_caster->GetTypeId() == TYPEID_PLAYER && ((Player*)m_caster)->GetTransport())
+ return SPELL_FAILED_NO_MOUNTS_ALLOWED;
+
+ // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells
+ if (m_caster->GetTypeId() == TYPEID_PLAYER && !sMapStore.LookupEntry(m_caster->GetMapId())->IsMountAllowed() && !m_IsTriggeredSpell && !m_spellInfo->AreaGroupId)
+ return SPELL_FAILED_NO_MOUNTS_ALLOWED;
+
+ ShapeshiftForm form = m_caster->m_form;
+ if( form == FORM_CAT || form == FORM_TREE || form == FORM_TRAVEL ||
+ form == FORM_AQUA || form == FORM_BEAR || form == FORM_DIREBEAR ||
+ form == FORM_CREATUREBEAR || form == FORM_GHOSTWOLF || form == FORM_FLIGHT ||
+ form == FORM_FLIGHT_EPIC || form == FORM_MOONKIN || form == FORM_METAMORPHOSIS )
+ return SPELL_FAILED_NOT_SHAPESHIFT;
+
+ break;
+ }
+ case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS:
+ {
+ if(!m_targets.getUnitTarget())
+ return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
+
+ // can be casted at non-friendly unit or own pet/charm
+ if(m_caster->IsFriendlyTo(m_targets.getUnitTarget()))
+ return SPELL_FAILED_TARGET_FRIENDLY;
+
+ break;
+ }
+ case SPELL_AURA_FLY:
+ case SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED:
+ {
+ // not allow cast fly spells if not have req. skills (all spells is self target)
+ // allow always ghost flight spells
+ if (m_originalCaster && m_originalCaster->GetTypeId() == TYPEID_PLAYER && m_originalCaster->isAlive())
+ {
+ // 4197 = Wintergrasp || 4395 = Dalaran && 4564 = Krasus Landing
+ if (m_originalCaster->GetZoneId() == 4197 || m_originalCaster->GetZoneId() == 4395 && m_originalCaster->GetAreaId() != 4564)
+ return m_IsTriggeredSpell ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_NOT_HERE;
+ }
+ break;
+ }
+ case SPELL_AURA_RANGED_AP_ATTACKER_CREATURES_BONUS:
+ {
+ if (!m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetTypeId() != TYPEID_UNIT)
+ return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
+
+ // can be casted at non-friendly unit or own pet/charm
+ if (m_caster->IsFriendlyTo(m_targets.getUnitTarget()))
+ return SPELL_FAILED_TARGET_FRIENDLY;
+
+ break;
+ }
+ case SPELL_AURA_PERIODIC_MANA_LEECH:
+ {
+ if (!m_targets.getUnitTarget())
+ return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
+
+ if (m_caster->GetTypeId() != TYPEID_PLAYER || m_CastItem)
+ break;
+
+ if(m_targets.getUnitTarget()->getPowerType() != POWER_MANA)
+ return SPELL_FAILED_BAD_TARGETS;
+
+ break;
+ }
+ default:
+ break;
+ }
+ }
+
+ // all ok
+ return SPELL_CAST_OK;
+}
+
+SpellCastResult Spell::CheckPetCast(Unit* target)
+{
+ if(!m_caster->isAlive() && !(m_spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_DEAD))
+ return SPELL_FAILED_CASTER_DEAD;
+
+ if(m_caster->hasUnitState(UNIT_STAT_CASTING) && !m_IsTriggeredSpell) //prevent spellcast interruption by another spellcast
+ return SPELL_FAILED_SPELL_IN_PROGRESS;
+ if(m_caster->isInCombat() && IsNonCombatSpell(m_spellInfo))
+ return SPELL_FAILED_AFFECTING_COMBAT;
+
+ //dead owner (pets still alive when owners ressed?)
+ if(Unit *owner = m_caster->GetCharmerOrOwner())
+ if(!owner->isAlive())
+ return SPELL_FAILED_CASTER_DEAD;
+
+ if(!target && m_targets.getUnitTarget())
+ target = m_targets.getUnitTarget();
+
+ for (uint32 i = 0; i < 3; ++i)
+ {
+ if(SpellTargetType[m_spellInfo->EffectImplicitTargetA[i]] == TARGET_TYPE_UNIT_TARGET
+ || SpellTargetType[m_spellInfo->EffectImplicitTargetA[i]] == TARGET_TYPE_DEST_TARGET)
+ {
+ if(!target)
+ return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
+ m_targets.setUnitTarget(target);
+ break;
+ }
+ }
+
+ Unit* _target = m_targets.getUnitTarget();
+
+ if(_target) //for target dead/target not valid
+ {
+ if(!_target->isAlive())
+ return SPELL_FAILED_BAD_TARGETS;
+
+ if(!IsValidSingleTargetSpell(_target))
+ return SPELL_FAILED_BAD_TARGETS;
+ }
+ //cooldown
+ if(((Creature*)m_caster)->HasSpellCooldown(m_spellInfo->Id))
+ return SPELL_FAILED_NOT_READY;
+
+ return CheckCast(true);
+}
+
+SpellCastResult Spell::CheckCasterAuras() const
+{
+ // spells totally immuned to caster auras ( wsg flag drop, give marks etc)
+ if(m_spellInfo->AttributesEx6& SPELL_ATTR_EX6_IGNORE_CASTER_AURAS)
+ return SPELL_CAST_OK;
+
+ uint8 school_immune = 0;
+ uint32 mechanic_immune = 0;
+ uint32 dispel_immune = 0;
+
+ // Check if the spell grants school or mechanic immunity.
+ // We use bitmasks so the loop is done only once and not on every aura check below.
+ if ( m_spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY )
+ {
+ for (int i = 0; i < 3; ++i)
+ {
+ if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_SCHOOL_IMMUNITY)
+ school_immune |= uint32(m_spellInfo->EffectMiscValue[i]);
+ else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MECHANIC_IMMUNITY)
+ mechanic_immune |= 1 << uint32(m_spellInfo->EffectMiscValue[i]);
+ else if(m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_DISPEL_IMMUNITY)
+ dispel_immune |= GetDispellMask(DispelType(m_spellInfo->EffectMiscValue[i]));
+ }
+ //immune movement impairment and loss of control
+ if(m_spellInfo->Id==42292 || m_spellInfo->Id==59752)
+ mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK;
+ }
+
+ // Check whether the cast should be prevented by any state you might have.
+ SpellCastResult prevented_reason = SPELL_CAST_OK;
+ // Have to check if there is a stun aura. Otherwise will have problems with ghost aura apply while logging out
+ uint32 unitflag = m_caster->GetUInt32Value(UNIT_FIELD_FLAGS); // Get unit state
+ if(unitflag & UNIT_FLAG_STUNNED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
+ prevented_reason = SPELL_FAILED_STUNNED;
+ else if(unitflag & UNIT_FLAG_CONFUSED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
+ prevented_reason = SPELL_FAILED_CONFUSED;
+ else if(unitflag & UNIT_FLAG_FLEEING && !(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
+ prevented_reason = SPELL_FAILED_FLEEING;
+ else if(unitflag & UNIT_FLAG_SILENCED && m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE)
+ prevented_reason = SPELL_FAILED_SILENCED;
+ else if(unitflag & UNIT_FLAG_PACIFIED && m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY)
+ prevented_reason = SPELL_FAILED_PACIFIED;
+
+ // Attr must make flag drop spell totally immune from all effects
+ if(prevented_reason != SPELL_CAST_OK)
+ {
+ if(school_immune || mechanic_immune || dispel_immune)
+ {
+ //Checking auras is needed now, because you are prevented by some state but the spell grants immunity.
+ Unit::AuraApplicationMap const& auras = m_caster->GetAppliedAuras();
+ for (Unit::AuraApplicationMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
+ {
+ Aura const * aura = itr->second->GetBase();
+ if( GetAllSpellMechanicMask(aura->GetSpellProto()) & mechanic_immune )
+ continue;
+ if( GetSpellSchoolMask(aura->GetSpellProto()) & school_immune )
+ continue;
+ if( (1<<(aura->GetSpellProto()->Dispel)) & dispel_immune)
+ continue;
+
+ //Make a second check for spell failed so the right SPELL_FAILED message is returned.
+ //That is needed when your casting is prevented by multiple states and you are only immune to some of them.
+ for (uint8 i=0; i<MAX_SPELL_EFFECTS; ++i)
+ {
+ if (AuraEffect * part = aura->GetEffect(i))
+ {
+ switch(part->GetAuraType())
+ {
+ case SPELL_AURA_MOD_STUN:
+ if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_STUNNED))
+ return SPELL_FAILED_STUNNED;
+ break;
+ case SPELL_AURA_MOD_CONFUSE:
+ if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED))
+ return SPELL_FAILED_CONFUSED;
+ break;
+ case SPELL_AURA_MOD_FEAR:
+ if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR_EX5_USABLE_WHILE_FEARED))
+ return SPELL_FAILED_FLEEING;
+ break;
+ case SPELL_AURA_MOD_SILENCE:
+ case SPELL_AURA_MOD_PACIFY:
+ case SPELL_AURA_MOD_PACIFY_SILENCE:
+ if( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_PACIFY)
+ return SPELL_FAILED_PACIFIED;
+ else if ( m_spellInfo->PreventionType==SPELL_PREVENTION_TYPE_SILENCE)
+ return SPELL_FAILED_SILENCED;
+ break;
+ default: break;
+ }
+ }
+ }
+ }
+ }
+ // You are prevented from casting and the spell casted does not grant immunity. Return a failed error.
+ else
+ return prevented_reason;
+ }
+ return SPELL_CAST_OK;
+}
+
+bool Spell::CanAutoCast(Unit* target)
+{
+ uint64 targetguid = target->GetGUID();
+
+ for (uint32 j = 0; j < 3; ++j)
+ {
+ if(m_spellInfo->Effect[j] == SPELL_EFFECT_APPLY_AURA)
+ {
+ if( m_spellInfo->StackAmount <= 1)
+ {
+ if( target->HasAuraEffect(m_spellInfo->Id, j) )
+ return false;
+ }
+ else
+ {
+ if( AuraEffect * aureff = target->GetAuraEffect(m_spellInfo->Id, j))
+ if (aureff->GetBase()->GetStackAmount() >= m_spellInfo->StackAmount)
+ return false;
+ }
+ }
+ else if ( IsAreaAuraEffect( m_spellInfo->Effect[j] ))
+ {
+ if( target->HasAuraEffect(m_spellInfo->Id, j) )
+ return false;
+ }
+ }
+
+ SpellCastResult result = CheckPetCast(target);
+
+ if(result == SPELL_CAST_OK || result == SPELL_FAILED_UNIT_NOT_INFRONT)
+ {
+ SelectSpellTargets();
+ //check if among target units, our WANTED target is as well (->only self cast spells return false)
+ for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
+ if( ihit->targetGUID == targetguid )
+ return true;
+ }
+ return false; //target invalid
+}
+
+SpellCastResult Spell::CheckRange(bool strict)
+{
+ //float range_mod;
+
+ // self cast doesn't need range checking -- also for Starshards fix
+ if (m_spellInfo->rangeIndex == 1)
+ return SPELL_CAST_OK;
+
+ // i do not know why we need this
+ /*if (strict) //add radius of caster
+ range_mod = 1.25;
+ else //add radius of caster and ~5 yds "give"
+ range_mod = 6.25;*/
+
+ SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex);
+
+ Unit *target = m_targets.getUnitTarget();
+ float max_range = m_caster->GetSpellMaxRangeForTarget(target, srange); // + range_mod;
+ float min_range = m_caster->GetSpellMinRangeForTarget(target, srange);
+ uint32 range_type = GetSpellRangeType(srange);
+
+ if(Player* modOwner = m_caster->GetSpellModOwner())
+ modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this);
+
+ if(target && target != m_caster)
+ {
+ if(range_type == SPELL_RANGE_MELEE)
+ {
+ // Because of lag, we can not check too strictly here.
+ if(!m_caster->IsWithinMeleeRange(target, max_range/* - 2*MIN_MELEE_REACH*/))
+ return SPELL_FAILED_OUT_OF_RANGE;
+ }
+ else if(!m_caster->IsWithinCombatRange(target, max_range))
+ return SPELL_FAILED_OUT_OF_RANGE; //0x5A;
+
+ if(range_type == SPELL_RANGE_RANGED)
+ {
+ if(m_caster->IsWithinMeleeRange(target))
+ return SPELL_FAILED_TOO_CLOSE;
+ }
+ else if(min_range && m_caster->IsWithinCombatRange(target, min_range)) // skip this check if min_range = 0
+ return SPELL_FAILED_TOO_CLOSE;
+
+ if( m_caster->GetTypeId() == TYPEID_PLAYER &&
+ (m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc( M_PI, target ) )
+ return SPELL_FAILED_UNIT_NOT_INFRONT;
+ }
+
+ if(m_targets.HasDst() && !m_targets.HasTraj())
+ {
+ if(!m_caster->IsWithinDist3d(&m_targets.m_dstPos, max_range))
+ return SPELL_FAILED_OUT_OF_RANGE;
+ if(min_range && m_caster->IsWithinDist3d(&m_targets.m_dstPos, min_range))
+ return SPELL_FAILED_TOO_CLOSE;
+ }
+
+ return SPELL_CAST_OK;
+}
+
+SpellCastResult Spell::CheckPower()
+{
+ // item cast not used power
+ if(m_CastItem)
+ return SPELL_CAST_OK;
+
+ // health as power used - need check health amount
+ if(m_spellInfo->powerType == POWER_HEALTH)
+ {
+ if(m_caster->GetHealth() <= m_powerCost)
+ return SPELL_FAILED_CASTER_AURASTATE;
+ return SPELL_CAST_OK;
+ }
+ // Check valid power type
+ if( m_spellInfo->powerType >= MAX_POWERS )
+ {
+ sLog.outError("Spell::CheckPower: Unknown power type '%d'", m_spellInfo->powerType);
+ return SPELL_FAILED_UNKNOWN;
+ }
+
+ //check rune cost only if a spell has PowerType == POWER_RUNE
+ if(m_spellInfo->powerType == POWER_RUNE)
+ {
+ SpellCastResult failReason = CheckRuneCost(m_spellInfo->runeCostID);
+ if(failReason != SPELL_CAST_OK)
+ return failReason;
+ }
+
+ // Check power amount
+ Powers powerType = Powers(m_spellInfo->powerType);
+ if(m_caster->GetPower(powerType) < m_powerCost)
+ return SPELL_FAILED_NO_POWER;
+ else
+ return SPELL_CAST_OK;
+}
+
+SpellCastResult Spell::CheckItems()
+{
+ if (m_caster->GetTypeId() != TYPEID_PLAYER)
+ return SPELL_CAST_OK;
+
+ Player* p_caster = (Player*)m_caster;
+
+ if(!m_CastItem)
+ {
+ if(m_castItemGUID)
+ return SPELL_FAILED_ITEM_NOT_READY;
+ }
+ else
+ {
+ uint32 itemid = m_CastItem->GetEntry();
+ if( !p_caster->HasItemCount(itemid, 1) )
+ return SPELL_FAILED_ITEM_NOT_READY;
+
+ ItemPrototype const *proto = m_CastItem->GetProto();
+ if(!proto)
+ return SPELL_FAILED_ITEM_NOT_READY;
+
+ for (int i = 0; i < 5; ++i)
+ if (proto->Spells[i].SpellCharges)
+ if(m_CastItem->GetSpellCharges(i) == 0)
+ return SPELL_FAILED_NO_CHARGES_REMAIN;
+
+ // consumable cast item checks
+ if (proto->Class == ITEM_CLASS_CONSUMABLE && m_targets.getUnitTarget())
+ {
+ // such items should only fail if there is no suitable effect at all - see Rejuvenation Potions for example
+ SpellCastResult failReason = SPELL_CAST_OK;
+ for (int i = 0; i < 3; i++)
+ {
+ // skip check, pet not required like checks, and for TARGET_UNIT_PET m_targets.getUnitTarget() is not the real target but the caster
+ if (m_spellInfo->EffectImplicitTargetA[i] == TARGET_UNIT_PET)
+ continue;
+
+ if (m_spellInfo->Effect[i] == SPELL_EFFECT_HEAL)
+ {
+ if (m_targets.getUnitTarget()->GetHealth() == m_targets.getUnitTarget()->GetMaxHealth())
+ {
+ failReason = SPELL_FAILED_ALREADY_AT_FULL_HEALTH;
+ continue;
+ }
+ else
+ {
+ failReason = SPELL_CAST_OK;
+ break;
+ }
+ }
+
+ // Mana Potion, Rage Potion, Thistle Tea(Rogue), ...
+ if (m_spellInfo->Effect[i] == SPELL_EFFECT_ENERGIZE)
+ {
+ if(m_spellInfo->EffectMiscValue[i] < 0 || m_spellInfo->EffectMiscValue[i] >= MAX_POWERS)
+ {
+ failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER;
+ continue;
+ }
+
+ Powers power = Powers(m_spellInfo->EffectMiscValue[i]);
+ if (m_targets.getUnitTarget()->GetPower(power) == m_targets.getUnitTarget()->GetMaxPower(power))
+ {
+ failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER;
+ continue;
+ }
+ else
+ {
+ failReason = SPELL_CAST_OK;
+ break;
+ }
+ }
+ }
+ if (failReason != SPELL_CAST_OK)
+ return failReason;
+ }
+ }
+
+ // check target item
+ if(m_targets.getItemTargetGUID())
+ {
+ if(m_caster->GetTypeId() != TYPEID_PLAYER)
+ return SPELL_FAILED_BAD_TARGETS;
+
+ if(!m_targets.getItemTarget())
+ return SPELL_FAILED_ITEM_GONE;
+
+ if(!m_targets.getItemTarget()->IsFitToSpellRequirements(m_spellInfo))
+ return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
+ }
+ // if not item target then required item must be equipped
+ else
+ {
+ if(m_caster->GetTypeId() == TYPEID_PLAYER && !((Player*)m_caster)->HasItemFitToSpellReqirements(m_spellInfo))
+ return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
+ }
+
+ // check spell focus object
+ if(m_spellInfo->RequiresSpellFocus)
+ {
+ CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY()));
+ Cell cell(p);
+ cell.data.Part.reserved = ALL_DISTRICT;
+
+ GameObject* ok = NULL;
+ Trinity::GameObjectFocusCheck go_check(m_caster,m_spellInfo->RequiresSpellFocus);
+ Trinity::GameObjectSearcher<Trinity::GameObjectFocusCheck> checker(m_caster, ok, go_check);
+
+ TypeContainerVisitor<Trinity::GameObjectSearcher<Trinity::GameObjectFocusCheck>, GridTypeMapContainer > object_checker(checker);
+ Map& map = *m_caster->GetMap();
+ cell.Visit(p, object_checker, map, *m_caster, map.GetVisibilityDistance());
+
+ if(!ok)
+ return SPELL_FAILED_REQUIRES_SPELL_FOCUS;
+
+ focusObject = ok; // game object found in range
+ }
+
+ // do not take reagents for these item casts
+ if (!(m_CastItem && m_CastItem->GetProto()->Flags & ITEM_FLAGS_TRIGGERED_CAST))
+ {
+ // check reagents (ignore triggered spells with reagents processed by original spell) and special reagent ignore case.
+ if (!m_IsTriggeredSpell && !p_caster->CanNoReagentCast(m_spellInfo))
+ {
+ for (uint32 i=0; i<8; i++)
+ {
+ if(m_spellInfo->Reagent[i] <= 0)
+ continue;
+
+ uint32 itemid = m_spellInfo->Reagent[i];
+ uint32 itemcount = m_spellInfo->ReagentCount[i];
+
+ // if CastItem is also spell reagent
+ if( m_CastItem && m_CastItem->GetEntry() == itemid )
+ {
+ ItemPrototype const *proto = m_CastItem->GetProto();
+ if(!proto)
+ return SPELL_FAILED_ITEM_NOT_READY;
+ for (int s=0; s < MAX_ITEM_PROTO_SPELLS; ++s)
+ {
+ // CastItem will be used up and does not count as reagent
+ int32 charges = m_CastItem->GetSpellCharges(s);
+ if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2)
+ {
+ ++itemcount;
+ break;
+ }
+ }
+ }
+ if( !p_caster->HasItemCount(itemid,itemcount) )
+ return SPELL_FAILED_ITEM_NOT_READY; //0x54
+ }
+ }
+
+ // check totem-item requirements (items presence in inventory)
+ uint32 totems = 2;
+ for (int i = 0; i < 2 ; ++i)
+ {
+ if(m_spellInfo->Totem[i] != 0)
+ {
+ if( p_caster->HasItemCount(m_spellInfo->Totem[i],1) )
+ {
+ totems -= 1;
+ continue;
+ }
+ }else
+ totems -= 1;
+ }
+ if(totems != 0)
+ return SPELL_FAILED_TOTEMS; //0x7C
+
+ // Check items for TotemCategory (items presence in inventory)
+ uint32 TotemCategory = 2;
+ for (int i= 0; i < 2; ++i)
+ {
+ if(m_spellInfo->TotemCategory[i] != 0)
+ {
+ if( p_caster->HasItemTotemCategory(m_spellInfo->TotemCategory[i]) )
+ {
+ TotemCategory -= 1;
+ continue;
+ }
+ }
+ else
+ TotemCategory -= 1;
+ }
+ if(TotemCategory != 0)
+ return SPELL_FAILED_TOTEM_CATEGORY; //0x7B
+ }
+
+ // special checks for spell effects
+ for (int i = 0; i < 3; i++)
+ {
+ switch (m_spellInfo->Effect[i])
+ {
+ case SPELL_EFFECT_CREATE_ITEM:
+ {
+ if (!m_IsTriggeredSpell && m_spellInfo->EffectItemType[i])
+ {
+ ItemPosCountVec dest;
+ uint8 msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->EffectItemType[i], 1 );
+ if (msg != EQUIP_ERR_OK )
+ {
+ ItemPrototype const *pProto = objmgr.GetItemPrototype(m_spellInfo->EffectItemType[i]);
+ if (pProto && !(pProto->ItemLimitCategory))
+ {
+ p_caster->SendEquipError( msg, NULL, NULL );
+ return SPELL_FAILED_DONT_REPORT;
+ }
+ else
+ {
+ if (!(m_spellInfo->SpellFamilyName == SPELLFAMILY_MAGE && (m_spellInfo->SpellFamilyFlags[0] & 0x40000000)))
+ return SPELL_FAILED_TOO_MANY_OF_ITEM;
+ else if (!(p_caster->HasItemCount(m_spellInfo->EffectItemType[i],1)))
+ return SPELL_FAILED_TOO_MANY_OF_ITEM;
+ else
+ p_caster->CastSpell(m_caster,m_spellInfo->CalculateSimpleValue(1),false); // move this to anywhere
+ return SPELL_FAILED_DONT_REPORT;
+ }
+ }
+ }
+ break;
+ }
+ case SPELL_EFFECT_ENCHANT_ITEM:
+ if(m_spellInfo->EffectItemType[i] && m_targets.getItemTarget()
+ && (m_targets.getItemTarget()->IsWeaponVellum() || m_targets.getItemTarget()->IsArmorVellum()))
+ {
+ // cannot enchant vellum for other player
+ if (m_targets.getItemTarget()->GetOwner()!=m_caster)
+ return SPELL_FAILED_NOT_TRADEABLE;
+ // do not allow to enchant vellum from scroll made by vellum-prevent exploit
+ if (m_CastItem && m_CastItem->GetProto()->Flags & ITEM_FLAGS_TRIGGERED_CAST)
+ return SPELL_FAILED_TOTEM_CATEGORY;
+ ItemPosCountVec dest;
+ uint8 msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->EffectItemType[i], 1 );
+ if (msg != EQUIP_ERR_OK )
+ {
+ p_caster->SendEquipError( msg, NULL, NULL );
+ return SPELL_FAILED_DONT_REPORT;
+ }
+ }
+ case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC:
+ {
+ Item* targetItem = m_targets.getItemTarget();
+ if(!targetItem)
+ return SPELL_FAILED_ITEM_NOT_FOUND;
+
+ if( targetItem->GetProto()->ItemLevel < m_spellInfo->baseLevel )
+ return SPELL_FAILED_LOWLEVEL;
+ // Not allow enchant in trade slot for some enchant type
+ if( targetItem->GetOwner() != m_caster )
+ {
+ uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
+ SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
+ if(!pEnchant)
+ return SPELL_FAILED_ERROR;
+ if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
+ return SPELL_FAILED_NOT_TRADEABLE;
+ }
+ break;
+ }
+ case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
+ {
+ Item *item = m_targets.getItemTarget();
+ if(!item)
+ return SPELL_FAILED_ITEM_NOT_FOUND;
+ // Not allow enchant in trade slot for some enchant type
+ if( item->GetOwner() != m_caster )
+ {
+ uint32 enchant_id = m_spellInfo->EffectMiscValue[i];
+ SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
+ if(!pEnchant)
+ return SPELL_FAILED_ERROR;
+ if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND)
+ return SPELL_FAILED_NOT_TRADEABLE;
+ }
+ break;
+ }
+ case SPELL_EFFECT_ENCHANT_HELD_ITEM:
+ // check item existence in effect code (not output errors at offhand hold item effect to main hand for example
+ break;
+ case SPELL_EFFECT_DISENCHANT:
+ {
+ if(!m_targets.getItemTarget())
+ return SPELL_FAILED_CANT_BE_DISENCHANTED;
+
+ // prevent disenchanting in trade slot
+ if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
+ return SPELL_FAILED_CANT_BE_DISENCHANTED;
+
+ ItemPrototype const* itemProto = m_targets.getItemTarget()->GetProto();
+ if(!itemProto)
+ return SPELL_FAILED_CANT_BE_DISENCHANTED;
+
+ uint32 item_quality = itemProto->Quality;
+ // 2.0.x addon: Check player enchanting level against the item disenchanting requirements
+ uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill;
+ if (item_disenchantskilllevel == uint32(-1))
+ return SPELL_FAILED_CANT_BE_DISENCHANTED;
+ if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING))
+ return SPELL_FAILED_LOW_CASTLEVEL;
+ if(item_quality > 4 || item_quality < 2)
+ return SPELL_FAILED_CANT_BE_DISENCHANTED;
+ if(itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR)
+ return SPELL_FAILED_CANT_BE_DISENCHANTED;
+ if (!itemProto->DisenchantID)
+ return SPELL_FAILED_CANT_BE_DISENCHANTED;
+ break;
+ }
+ case SPELL_EFFECT_PROSPECTING:
+ {
+ if(!m_targets.getItemTarget())
+ return SPELL_FAILED_CANT_BE_PROSPECTED;
+ //ensure item is a prospectable ore
+ if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_MINING_SUPP) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
+ return SPELL_FAILED_CANT_BE_PROSPECTED;
+ //prevent prospecting in trade slot
+ if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
+ return SPELL_FAILED_CANT_BE_PROSPECTED;
+ //Check for enough skill in jewelcrafting
+ uint32 item_prospectingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
+ if(item_prospectingskilllevel >p_caster->GetSkillValue(SKILL_JEWELCRAFTING))
+ return SPELL_FAILED_LOW_CASTLEVEL;
+ //make sure the player has the required ores in inventory
+ if(m_targets.getItemTarget()->GetCount() < 5)
+ return SPELL_FAILED_NEED_MORE_ITEMS;
+
+ if(!LootTemplates_Prospecting.HaveLootFor(m_targets.getItemTargetEntry()))
+ return SPELL_FAILED_CANT_BE_PROSPECTED;
+
+ break;
+ }
+ case SPELL_EFFECT_MILLING:
+ {
+ if(!m_targets.getItemTarget())
+ return SPELL_FAILED_CANT_BE_MILLED;
+ //ensure item is a millable herb
+ if(!(m_targets.getItemTarget()->GetProto()->BagFamily & BAG_FAMILY_MASK_HERBS) || m_targets.getItemTarget()->GetProto()->Class != ITEM_CLASS_TRADE_GOODS)
+ return SPELL_FAILED_CANT_BE_MILLED;
+ //prevent milling in trade slot
+ if( m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID() )
+ return SPELL_FAILED_CANT_BE_MILLED;
+ //Check for enough skill in inscription
+ uint32 item_millingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank;
+ if(item_millingskilllevel >p_caster->GetSkillValue(SKILL_INSCRIPTION))
+ return SPELL_FAILED_LOW_CASTLEVEL;
+ //make sure the player has the required herbs in inventory
+ if(m_targets.getItemTarget()->GetCount() < 5)
+ return SPELL_FAILED_NEED_MORE_ITEMS;
+
+ if(!LootTemplates_Milling.HaveLootFor(m_targets.getItemTargetEntry()))
+ return SPELL_FAILED_CANT_BE_MILLED;
+
+ break;
+ }
+ case SPELL_EFFECT_WEAPON_DAMAGE:
+ case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
+ {
+ if(m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER;
+ if( m_attackType != RANGED_ATTACK )
+ break;
+ Item *pItem = ((Player*)m_caster)->GetWeaponForAttack(m_attackType);
+ if(!pItem || pItem->IsBroken())
+ return SPELL_FAILED_EQUIPPED_ITEM;
+
+ switch(pItem->GetProto()->SubClass)
+ {
+ case ITEM_SUBCLASS_WEAPON_THROWN:
+ {
+ uint32 ammo = pItem->GetEntry();
+ if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
+ return SPELL_FAILED_NO_AMMO;
+ }; break;
+ case ITEM_SUBCLASS_WEAPON_GUN:
+ case ITEM_SUBCLASS_WEAPON_BOW:
+ case ITEM_SUBCLASS_WEAPON_CROSSBOW:
+ {
+ uint32 ammo = ((Player*)m_caster)->GetUInt32Value(PLAYER_AMMO_ID);
+ if(!ammo)
+ {
+ // Requires No Ammo
+ if(m_caster->HasAura(46699))
+ break; // skip other checks
+
+ return SPELL_FAILED_NO_AMMO;
+ }
+
+ ItemPrototype const *ammoProto = objmgr.GetItemPrototype( ammo );
+ if(!ammoProto)
+ return SPELL_FAILED_NO_AMMO;
+
+ if(ammoProto->Class != ITEM_CLASS_PROJECTILE)
+ return SPELL_FAILED_NO_AMMO;
+
+ // check ammo ws. weapon compatibility
+ switch(pItem->GetProto()->SubClass)
+ {
+ case ITEM_SUBCLASS_WEAPON_BOW:
+ case ITEM_SUBCLASS_WEAPON_CROSSBOW:
+ if(ammoProto->SubClass != ITEM_SUBCLASS_ARROW)
+ return SPELL_FAILED_NO_AMMO;
+ break;
+ case ITEM_SUBCLASS_WEAPON_GUN:
+ if(ammoProto->SubClass != ITEM_SUBCLASS_BULLET)
+ return SPELL_FAILED_NO_AMMO;
+ break;
+ default:
+ return SPELL_FAILED_NO_AMMO;
+ }
+
+ if( !((Player*)m_caster)->HasItemCount( ammo, 1 ) )
+ return SPELL_FAILED_NO_AMMO;
+ }; break;
+ case ITEM_SUBCLASS_WEAPON_WAND:
+ break;
+ default:
+ break;
+ }
+ break;
+ }
+ case SPELL_EFFECT_CREATE_MANA_GEM:
+ {
+ uint32 item_id = m_spellInfo->EffectItemType[i];
+ ItemPrototype const *pProto = objmgr.GetItemPrototype(item_id);
+
+ if (!pProto)
+ return SPELL_FAILED_ITEM_AT_MAX_CHARGES;
+
+ if (Item* pitem = p_caster->GetItemByEntry(item_id))
+ {
+ for(int x = 0; x < MAX_ITEM_PROTO_SPELLS; ++x)
+ if (pProto->Spells[x].SpellCharges != 0 && pitem->GetSpellCharges(x) == pProto->Spells[x].SpellCharges)
+ return SPELL_FAILED_ITEM_AT_MAX_CHARGES;
+ }
+ break;
+ }
+ default:
+ break;
+ }
+ }
+
+ // check weapon presence in slots for main/offhand weapons
+ if(m_spellInfo->EquippedItemClass >=0)
+ {
+ // main hand weapon required
+ if(m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_MAIN_HAND)
+ {
+ Item* item = ((Player*)m_caster)->GetWeaponForAttack(BASE_ATTACK);
+
+ // skip spell if no weapon in slot or broken
+ if(!item || item->IsBroken() )
+ return m_IsTriggeredSpell? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS;
+
+ // skip spell if weapon not fit to triggered spell
+ if(!item->IsFitToSpellRequirements(m_spellInfo))
+ return m_IsTriggeredSpell? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS;
+ }
+
+ // offhand hand weapon required
+ if(m_spellInfo->AttributesEx3 & SPELL_ATTR_EX3_REQ_OFFHAND)
+ {
+ Item* item = ((Player*)m_caster)->GetWeaponForAttack(OFF_ATTACK);
+
+ // skip spell if no weapon in slot or broken
+ if(!item || item->IsBroken() )
+ return m_IsTriggeredSpell? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS;
+
+ // skip spell if weapon not fit to triggered spell
+ if(!item->IsFitToSpellRequirements(m_spellInfo))
+ return m_IsTriggeredSpell? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS;
+ }
+ }
+
+ return SPELL_CAST_OK;
+}
+
+void Spell::Delayed() // only called in DealDamage()
+{
+ if(!m_caster)// || m_caster->GetTypeId() != TYPEID_PLAYER)
+ return;
+
+ //if (m_spellState == SPELL_STATE_DELAYED)
+ // return; // spell is active and can't be time-backed
+
+ if(isDelayableNoMore()) // Spells may only be delayed twice
+ return;
+
+ // spells not loosing casting time ( slam, dynamites, bombs.. )
+ //if(!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE))
+ // return;
+
+ //check pushback reduce
+ int32 delaytime = 500; // spellcasting delay is normally 500ms
+ int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
+ ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this);
+ delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
+ if(delayReduce >= 100)
+ return;
+
+ delaytime = delaytime * (100 - delayReduce) / 100;
+
+ if(int32(m_timer) + delaytime > m_casttime)
+ {
+ delaytime = m_casttime - m_timer;
+ m_timer = m_casttime;
+ }
+ else
+ m_timer += delaytime;
+
+ sLog.outDetail("Spell %u partially interrupted for (%d) ms at damage", m_spellInfo->Id, delaytime);
+
+ WorldPacket data(SMSG_SPELL_DELAYED, 8+4);
+ data.append(m_caster->GetPackGUID());
+ data << uint32(delaytime);
+
+ m_caster->SendMessageToSet(&data, true);
+}
+
+void Spell::DelayedChannel()
+{
+ if (!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING)
+ return;
+
+ if (isDelayableNoMore()) // Spells may only be delayed twice
+ return;
+
+ //check pushback reduce
+ int32 delaytime = GetSpellDuration(m_spellInfo) * 25 / 100; // channeling delay is normally 25% of its time per hit
+ int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
+ ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this);
+ delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
+ if(delayReduce >= 100)
+ return;
+
+ delaytime = delaytime * (100 - delayReduce) / 100;
+
+ if(int32(m_timer) <= delaytime)
+ {
+ delaytime = m_timer;
+ m_timer = 0;
+ }
+ else
+ m_timer -= delaytime;
+
+ sLog.outDebug("Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer);
+
+ for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
+ if ((*ihit).missCondition == SPELL_MISS_NONE)
+ if (Unit* unit = (m_caster->GetGUID() == ihit->targetGUID) ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID))
+ unit->DelayOwnedAuras(m_spellInfo->Id, m_originalCasterGUID, delaytime);
+
+ // partially interrupt persistent area auras
+ if(DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id))
+ dynObj->Delay(delaytime);
+
+ SendChannelUpdate(m_timer);
+}
+
+void Spell::UpdatePointers()
+{
+ if(m_originalCasterGUID == m_caster->GetGUID())
+ m_originalCaster = m_caster;
+ else
+ {
+ m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID);
+ if (m_originalCaster && !m_originalCaster->IsInWorld())
+ m_originalCaster = NULL;
+ }
+
+ if (m_castItemGUID && m_caster->GetTypeId() == TYPEID_PLAYER)
+ m_CastItem = ((Player*)m_caster)->GetItemByGuid(m_castItemGUID);
+
+ m_targets.Update(m_caster);
+}
+
+bool Spell::CheckTargetCreatureType(Unit* target) const
+{
+ uint32 spellCreatureTargetMask = m_spellInfo->TargetCreatureType;
+
+ // Curse of Doom & Exorcism: not find another way to fix spell target check :/
+ if (m_spellInfo->SpellFamilyName==SPELLFAMILY_WARLOCK && m_spellInfo->Category == 1179)
+ {
+ // not allow cast at player
+ if(target->GetTypeId() == TYPEID_PLAYER)
+ return false;
+
+ spellCreatureTargetMask = 0x7FF;
+ }
+
+ // Dismiss Pet and Taming Lesson skipped
+ if(m_spellInfo->Id == 2641 || m_spellInfo->Id == 23356)
+ spellCreatureTargetMask = 0;
+
+ // Polymorph and Grounding Totem
+ if (target->GetEntry() == 5925 && m_spellInfo->SpellFamilyName == SPELLFAMILY_MAGE && (m_spellInfo->SpellFamilyFlags[0] & 0x1000000) && m_spellInfo->EffectApplyAuraName[0] == SPELL_AURA_MOD_CONFUSE)
+ return true;
+
+ if (spellCreatureTargetMask)
+ {
+ uint32 TargetCreatureType = target->GetCreatureTypeMask();
+
+ return !TargetCreatureType || (spellCreatureTargetMask & TargetCreatureType);
+ }
+ return true;
+}
+
+CurrentSpellTypes Spell::GetCurrentContainer()
+{
+ if (IsNextMeleeSwingSpell())
+ return(CURRENT_MELEE_SPELL);
+ else if (IsAutoRepeat())
+ return(CURRENT_AUTOREPEAT_SPELL);
+ else if (IsChanneledSpell(m_spellInfo))
+ return(CURRENT_CHANNELED_SPELL);
+ else
+ return(CURRENT_GENERIC_SPELL);
+}
+
+bool Spell::CheckTarget(Unit* target, uint32 eff)
+{
+ // Check targets for creature type mask and remove not appropriate (skip explicit self target case, maybe need other explicit targets)
+ if(m_spellInfo->EffectImplicitTargetA[eff] != TARGET_UNIT_CASTER)
+ {
+ if (!CheckTargetCreatureType(target))
+ return false;
+ }
+
+ // Check Aura spell req (need for AoE spells)
+ if(m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell))
+ return false;
+ if (m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell))
+ return false;
+
+ // Check targets for not_selectable unit flag and remove
+ // A player can cast spells on his pet (or other controlled unit) though in any state
+ if (target != m_caster && target->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
+ {
+ // any unattackable target skipped
+ if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE))
+ return false;
+
+ // unselectable targets skipped in all cases except TARGET_UNIT_NEARBY_ENTRY targeting
+ // in case TARGET_UNIT_NEARBY_ENTRY target selected by server always and can't be cheated
+ /*if( target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE) &&
+ m_spellInfo->EffectImplicitTargetA[eff] != TARGET_UNIT_NEARBY_ENTRY &&
+ m_spellInfo->EffectImplicitTargetB[eff] != TARGET_UNIT_NEARBY_ENTRY )
+ return false;*/
+ }
+
+ //Check player targets and remove if in GM mode or GM invisibility (for not self casting case)
+ if( target != m_caster && target->GetTypeId() == TYPEID_PLAYER)
+ {
+ if(((Player*)target)->GetVisibility() == VISIBILITY_OFF)
+ return false;
+
+ if(((Player*)target)->isGameMaster() && !IsPositiveSpell(m_spellInfo->Id))
+ return false;
+ }
+
+ switch(m_spellInfo->EffectApplyAuraName[eff])
+ {
+ case SPELL_AURA_NONE:
+ default:
+ break;
+ case SPELL_AURA_MOD_POSSESS:
+ case SPELL_AURA_MOD_CHARM:
+ case SPELL_AURA_MOD_POSSESS_PET:
+ case SPELL_AURA_AOE_CHARM:
+ if(target->GetTypeId() == TYPEID_UNIT && target->IsVehicle())
+ return false;
+ if(target->GetCharmerGUID())
+ return false;
+ if(int32 damage = CalculateDamage(eff, target))
+ if((int32)target->getLevel() > damage)
+ return false;
+ break;
+ }
+
+ //Do not do further checks for triggered spells
+ if(m_IsTriggeredSpell)
+ return true;
+
+ //Check targets for LOS visibility (except spells without range limitations )
+ switch(m_spellInfo->Effect[eff])
+ {
+ case SPELL_EFFECT_SUMMON_PLAYER: // from anywhere
+ break;
+ case SPELL_EFFECT_DUMMY:
+ if(m_spellInfo->Id != 20577) // Cannibalize
+ break;
+ //fall through
+ case SPELL_EFFECT_RESURRECT_NEW:
+ // player far away, maybe his corpse near?
+ if(target != m_caster && !target->IsWithinLOSInMap(m_caster))
+ {
+ if(!m_targets.getCorpseTargetGUID())
+ return false;
+
+ Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster, m_targets.getCorpseTargetGUID());
+ if(!corpse)
+ return false;
+
+ if(target->GetGUID() != corpse->GetOwnerGUID())
+ return false;
+
+ if(!corpse->IsWithinLOSInMap(m_caster))
+ return false;
+ }
+
+ // all ok by some way or another, skip normal check
+ break;
+ default: // normal case
+ // Get GO cast coordinates if original caster -> GO
+ WorldObject *caster = NULL;
+ if (IS_GAMEOBJECT_GUID(m_originalCasterGUID))
+ caster = m_caster->GetMap()->GetGameObject(m_originalCasterGUID);
+ if (!caster)
+ caster = m_caster;
+ if(target->GetEntry() == 5925)
+ return true;
+ if(target != m_caster && !target->IsWithinLOSInMap(caster))
+ return false;
+ break;
+ }
+
+ return true;
+}
+
+bool Spell::IsNeedSendToClient() const
+{
+ return m_spellInfo->SpellVisual[0] || m_spellInfo->SpellVisual[1] || IsChanneledSpell(m_spellInfo) ||
+ m_spellInfo->speed > 0.0f || !m_triggeredByAuraSpell && !m_IsTriggeredSpell;
+}
+
+bool Spell::HaveTargetsForEffect( uint8 effect ) const
+{
+ for (std::list<TargetInfo>::const_iterator itr = m_UniqueTargetInfo.begin(); itr != m_UniqueTargetInfo.end(); ++itr)
+ if(itr->effectMask & (1 << effect))
+ return true;
+
+ for (std::list<GOTargetInfo>::const_iterator itr = m_UniqueGOTargetInfo.begin(); itr != m_UniqueGOTargetInfo.end(); ++itr)
+ if(itr->effectMask & (1 << effect))
+ return true;
+
+ for (std::list<ItemTargetInfo>::const_iterator itr = m_UniqueItemInfo.begin(); itr != m_UniqueItemInfo.end(); ++itr)
+ if(itr->effectMask & (1 << effect))
+ return true;
+
+ return false;
+}
+
+SpellEvent::SpellEvent(Spell* spell) : BasicEvent()
+{
+ m_Spell = spell;
+}
+
+SpellEvent::~SpellEvent()
+{
+ if (m_Spell->getState() != SPELL_STATE_FINISHED)
+ m_Spell->cancel();
+
+ if (m_Spell->IsDeletable())
+ {
+ delete m_Spell;
+ }
+ else
+ {
+ sLog.outError("~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.",
+ (m_Spell->GetCaster()->GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature"), m_Spell->GetCaster()->GetGUIDLow(), m_Spell->m_spellInfo->Id);
+ }
+}
+
+bool SpellEvent::Execute(uint64 e_time, uint32 p_time)
+{
+ // update spell if it is not finished
+ if (m_Spell->getState() != SPELL_STATE_FINISHED)
+ m_Spell->update(p_time);
+
+ // check spell state to process
+ switch (m_Spell->getState())
+ {
+ case SPELL_STATE_FINISHED:
+ {
+ // spell was finished, check deletable state
+ if (m_Spell->IsDeletable())
+ {
+ // check, if we do have unfinished triggered spells
+ return true; // spell is deletable, finish event
+ }
+ // event will be re-added automatically at the end of routine)
+ } break;
+
+ case SPELL_STATE_DELAYED:
+ {
+ // first, check, if we have just started
+ if (m_Spell->GetDelayStart() != 0)
+ {
+ // no, we aren't, do the typical update
+ // check, if we have channeled spell on our hands
+ /*
+ if (IsChanneledSpell(m_Spell->m_spellInfo))
+ {
+ // evented channeled spell is processed separately, casted once after delay, and not destroyed till finish
+ // check, if we have casting anything else except this channeled spell and autorepeat
+ if (m_Spell->GetCaster()->IsNonMeleeSpellCasted(false, true, true))
+ {
+ // another non-melee non-delayed spell is casted now, abort
+ m_Spell->cancel();
+ }
+ else
+ {
+ // Set last not triggered spell for apply spellmods
+ ((Player*)m_Spell->GetCaster())->SetSpellModTakingSpell(m_Spell, true);
+ // do the action (pass spell to channeling state)
+ m_Spell->handle_immediate();
+
+ // And remove after effect handling
+ ((Player*)m_Spell->GetCaster())->SetSpellModTakingSpell(m_Spell, false);
+ }
+ // event will be re-added automatically at the end of routine)
+ }
+ else
+ */
+ {
+ // run the spell handler and think about what we can do next
+ uint64 t_offset = e_time - m_Spell->GetDelayStart();
+ uint64 n_offset = m_Spell->handle_delayed(t_offset);
+ if (n_offset)
+ {
+ // re-add us to the queue
+ m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false);
+ return false; // event not complete
+ }
+ // event complete
+ // finish update event will be re-added automatically at the end of routine)
+ }
+ }
+ else
+ {
+ // delaying had just started, record the moment
+ m_Spell->SetDelayStart(e_time);
+ // re-plan the event for the delay moment
+ m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false);
+ return false; // event not complete
+ }
+ } break;
+
+ default:
+ {
+ // all other states
+ // event will be re-added automatically at the end of routine)
+ } break;
+ }
+
+ // spell processing not complete, plan event on the next update interval
+ m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false);
+ return false; // event not complete
+}
+
+void SpellEvent::Abort(uint64 /*e_time*/)
+{
+ // oops, the spell we try to do is aborted
+ if (m_Spell->getState() != SPELL_STATE_FINISHED)
+ m_Spell->cancel();
+}
+
+bool SpellEvent::IsDeletable() const
+{
+ return m_Spell->IsDeletable();
+}
+
+bool Spell::IsValidSingleTargetEffect(Unit const* target, Targets type) const
+{
+ switch (type)
+ {
+ case TARGET_UNIT_TARGET_ENEMY:
+ return !m_caster->IsFriendlyTo(target);
+ case TARGET_UNIT_TARGET_ALLY:
+ case TARGET_UNIT_PARTY_TARGET:
+ return m_caster->IsFriendlyTo(target);
+ case TARGET_UNIT_TARGET_PARTY:
+ return m_caster != target && m_caster->IsInPartyWith(target);
+ case TARGET_UNIT_TARGET_RAID:
+ return m_caster->IsInRaidWith(target);
+ }
+ return true;
+}
+
+bool Spell::IsValidSingleTargetSpell(Unit const* target) const
+{
+ if (target->GetMapId() == MAPID_INVALID)
+ {
+ sLog.outDebug("Spell::IsValidSingleTargetSpell - a spell was cast on '%s' (GUIDLow: %u), but they have an invalid map id!", target->GetName(), target->GetGUIDLow());
+ return false;
+ }
+ for (uint8 i = 0; i < 3; ++i)
+ {
+ if(!IsValidSingleTargetEffect(target, Targets(m_spellInfo->EffectImplicitTargetA[i])))
+ return false;
+ // Need to check B?
+ //if(!IsValidSingleTargetEffect(m_spellInfo->EffectImplicitTargetB[i], target)
+ // return false;
+ }
+ return true;
+}
+
+void Spell::CalculateDamageDoneForAllTargets()
+{
+ float multiplier[3];
+ for (uint8 i = 0; i < 3; ++i)
+ {
+ if (m_applyMultiplierMask & (1 << i))
+ {
+ // Get multiplier
+ multiplier[i] = m_spellInfo->DmgMultiplier[i];
+ // Apply multiplier mods
+ if(m_originalCaster)
+ if(Player* modOwner = m_originalCaster->GetSpellModOwner())
+ modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_EFFECT_PAST_FIRST, multiplier[i], this);
+ }
+ }
+
+ bool usesAmmo = true;
+ Unit::AuraEffectList const& Auras = m_caster->GetAuraEffectsByType(SPELL_AURA_ABILITY_CONSUME_NO_AMMO);
+ for (Unit::AuraEffectList::const_iterator j = Auras.begin(); j != Auras.end(); ++j)
+ {
+ if((*j)->IsAffectedOnSpell(m_spellInfo))
+ usesAmmo=false;
+ }
+
+ for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
+ {
+ TargetInfo &target = *ihit;
+
+ uint32 mask = target.effectMask;
+ if (!mask)
+ continue;
+
+ Unit* unit = m_caster->GetGUID()==target.targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target.targetGUID);
+ if (!unit) // || !unit->isAlive()) do we need to check alive here?
+ continue;
+
+ if (usesAmmo)
+ {
+ bool ammoTaken=false;
+ for (uint8 i=0; i<3; i++)
+ {
+ if (!(mask & 1<<i))
+ continue;
+ switch (m_spellInfo->Effect[i])
+ {
+ case SPELL_EFFECT_SCHOOL_DAMAGE:
+ case SPELL_EFFECT_WEAPON_DAMAGE:
+ case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
+ case SPELL_EFFECT_NORMALIZED_WEAPON_DMG:
+ case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE:
+ ammoTaken=true;
+ TakeAmmo();
+ }
+ if (ammoTaken)
+ break;
+ }
+ }
+
+ if (target.missCondition==SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
+ {
+ target.damage += CalculateDamageDone(unit, mask, multiplier);
+ target.crit = m_caster->isSpellCrit(unit, m_spellInfo, m_spellSchoolMask, m_attackType);
+ }
+ else if (target.missCondition == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
+ {
+ if (target.reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
+ {
+ target.damage += CalculateDamageDone(m_caster, mask, multiplier);
+ target.crit = m_caster->isSpellCrit(m_caster, m_spellInfo, m_spellSchoolMask, m_attackType);
+ }
+ }
+ }
+}
+
+int32 Spell::CalculateDamageDone(Unit *unit, const uint32 effectMask, float *multiplier)
+{
+ int32 damageDone = 0;
+ unitTarget = unit;
+ for (uint32 i = 0; i < 3; ++i)
+ {
+ if (effectMask & (1<<i))
+ {
+ m_damage = 0;
+ damage = CalculateDamage(i, NULL);
+
+ switch(m_spellInfo->Effect[i])
+ {
+ case SPELL_EFFECT_SCHOOL_DAMAGE:
+ SpellDamageSchoolDmg(i);
+ break;
+ case SPELL_EFFECT_WEAPON_DAMAGE:
+ case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
+ case SPELL_EFFECT_NORMALIZED_WEAPON_DMG:
+ case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE:
+ SpellDamageWeaponDmg(i);
+ break;
+ case SPELL_EFFECT_HEAL:
+ SpellDamageHeal(i);
+ break;
+ }
+
+ if(m_damage > 0)
+ {
+ if(IsAreaEffectTarget[m_spellInfo->EffectImplicitTargetA[i]] || IsAreaEffectTarget[m_spellInfo->EffectImplicitTargetB[i]])
+ {
+ if(int32 reducedPct = unit->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE))
+ m_damage = m_damage * (100 + reducedPct) / 100;
+
+ if (m_caster->GetTypeId() == TYPEID_PLAYER)
+ {
+ uint32 targetAmount = m_UniqueTargetInfo.size();
+ if (targetAmount > 10)
+ m_damage = m_damage * 10/targetAmount;
+ }
+ }
+ }
+ if(m_applyMultiplierMask & (1 << i))
+ {
+ m_damage *= m_damageMultipliers[i];
+ m_damageMultipliers[i] *= multiplier[i];
+ }
+
+ damageDone += m_damage;
+ }
+ }
+
+ return damageDone;
+}
+
+SpellCastResult Spell::CanOpenLock(uint32 effIndex, uint32 lockId, SkillType& skillId, int32& reqSkillValue, int32& skillValue)
+{
+ if(!lockId) // possible case for GO and maybe for items.
+ return SPELL_CAST_OK;
+
+ // Get LockInfo
+ LockEntry const *lockInfo = sLockStore.LookupEntry(lockId);
+
+ if (!lockInfo)
+ return SPELL_FAILED_BAD_TARGETS;
+
+ bool reqKey = false; // some locks not have reqs
+
+ for (int j = 0; j < 8; ++j)
+ {
+ switch(lockInfo->Type[j])
+ {
+ // check key item (many fit cases can be)
+ case LOCK_KEY_ITEM:
+ if(lockInfo->Index[j] && m_CastItem && m_CastItem->GetEntry()==lockInfo->Index[j])
+ return SPELL_CAST_OK;
+ reqKey = true;
+ break;
+ // check key skill (only single first fit case can be)
+ case LOCK_KEY_SKILL:
+ {
+ reqKey = true;
+
+ // wrong locktype, skip
+ if(uint32(m_spellInfo->EffectMiscValue[effIndex]) != lockInfo->Index[j])
+ continue;
+
+ skillId = SkillByLockType(LockType(lockInfo->Index[j]));
+
+ if ( skillId != SKILL_NONE )
+ {
+ // skill bonus provided by casting spell (mostly item spells)
+ // add the damage modifier from the spell casted (cheat lock / skeleton key etc.) (use m_currentBasePoints, CalculateDamage returns wrong value)
+ uint32 spellSkillBonus = uint32(m_currentBasePoints[effIndex]+1);
+ reqSkillValue = lockInfo->Skill[j];
+
+ // castitem check: rogue using skeleton keys. the skill values should not be added in this case.
+ skillValue = m_CastItem || m_caster->GetTypeId()!= TYPEID_PLAYER ?
+ 0 : ((Player*)m_caster)->GetSkillValue(skillId);
+
+ skillValue += spellSkillBonus;
+
+ if (skillValue < reqSkillValue)
+ return SPELL_FAILED_LOW_CASTLEVEL;
+ }
+
+ return SPELL_CAST_OK;
+ }
+ }
+ }
+
+ if(reqKey)
+ return SPELL_FAILED_BAD_TARGETS;
+
+ return SPELL_CAST_OK;
+}
+
+void Spell::SetSpellValue(SpellValueMod mod, int32 value)
+{
+ switch(mod)
+ {
+ case SPELLVALUE_BASE_POINT0:
+ m_spellValue->EffectBasePoints[0] = value - int32(m_spellInfo->EffectBaseDice[0]);
+ m_currentBasePoints[0] = m_spellValue->EffectBasePoints[0]; //this should be removed in the future
+ break;
+ case SPELLVALUE_BASE_POINT1:
+ m_spellValue->EffectBasePoints[1] = value - int32(m_spellInfo->EffectBaseDice[1]);
+ m_currentBasePoints[1] = m_spellValue->EffectBasePoints[1];
+ break;
+ case SPELLVALUE_BASE_POINT2:
+ m_spellValue->EffectBasePoints[2] = value - int32(m_spellInfo->EffectBaseDice[2]);
+ m_currentBasePoints[2] = m_spellValue->EffectBasePoints[2];
+ break;
+ case SPELLVALUE_RADIUS_MOD:
+ m_spellValue->RadiusMod = (float)value / 10000;
+ break;
+ case SPELLVALUE_MAX_TARGETS:
+ m_spellValue->MaxAffectedTargets = (uint32)value;
+ break;
+ }
+}
+
+float tangent(float x)
+{
+ x = tan(x);
+ //if(x < std::numeric_limits<float>::max() && x > -std::numeric_limits<float>::max()) return x;
+ //if(x >= std::numeric_limits<float>::max()) return std::numeric_limits<float>::max();
+ //if(x <= -std::numeric_limits<float>::max()) return -std::numeric_limits<float>::max();
+ if(x < 100000.0f && x > -100000.0f) return x;
+ if(x >= 100000.0f) return 100000.0f;
+ if(x <= 100000.0f) return -100000.0f;
+ return 0.0f;
+}
+
+#define DEBUG_TRAJ(a) //a
+
+void Spell::SelectTrajTargets()
+{
+ if(!m_targets.HasTraj())
+ return;
+
+ float dist2d = m_targets.GetDist2d();
+ if(!dist2d)
+ return;
+
+ float dz = m_targets.m_dstPos.m_positionZ - m_targets.m_srcPos.m_positionZ;
+
+ UnitList unitList;
+ SearchAreaTarget(unitList, dist2d, PUSH_IN_THIN_LINE, SPELL_TARGETS_ANY);
+ if(unitList.empty())
+ return;
+
+ unitList.sort(TargetDistanceOrder(m_caster));
+
+ float b = tangent(m_targets.m_elevation);
+ float a = (dz - dist2d * b) / (dist2d * dist2d);
+ if(a > -0.0001f) a = 0;
+ DEBUG_TRAJ(sLog.outError("Spell::SelectTrajTargets: a %f b %f", a, b);)
+
+ float bestDist = GetSpellMaxRange(m_spellInfo, false);
+
+ UnitList::const_iterator itr = unitList.begin();
+ for (; itr != unitList.end(); ++itr)
+ {
+ if(m_caster == *itr || m_caster->IsOnVehicle(*itr) || (*itr)->GetVehicle())//(*itr)->IsOnVehicle(m_caster))
+ continue;
+
+ const float size = std::max((*itr)->GetObjectSize() * 0.7f, 1.0f); // 1/sqrt(3)
+ // TODO: all calculation should be based on src instead of m_caster
+ const float objDist2d = m_targets.m_srcPos.GetExactDist2d(*itr) * cos(m_targets.m_srcPos.GetRelativeAngle(*itr));
+ const float dz = (*itr)->GetPositionZ() - m_targets.m_srcPos.m_positionZ;
+
+ DEBUG_TRAJ(sLog.outError("Spell::SelectTrajTargets: check %u, dist between %f %f, height between %f %f.", (*itr)->GetEntry(), objDist2d - size, objDist2d + size, dz - size, dz + size);)
+
+ float dist = objDist2d - size;
+ float height = dist * (a * dist + b);
+ DEBUG_TRAJ(sLog.outError("Spell::SelectTrajTargets: dist %f, height %f.", dist, height);)
+ if(dist < bestDist && height < dz + size && height > dz - size)
+ {
+ bestDist = dist > 0 ? dist : 0;
+ break;
+ }
+
+#define CHECK_DIST {\
+ DEBUG_TRAJ(sLog.outError("Spell::SelectTrajTargets: dist %f, height %f.", dist, height);)\
+ if(dist > bestDist) continue;\
+ if(dist < objDist2d + size && dist > objDist2d - size) { bestDist = dist; break; }\
+ }
+
+ if(!a)
+ {
+ height = dz - size;
+ dist = height / b;
+ CHECK_DIST;
+
+ height = dz + size;
+ dist = height / b;
+ CHECK_DIST;
+
+ continue;
+ }
+
+ height = dz - size;
+ float sqrt1 = b * b + 4 * a * height;
+ if(sqrt1 > 0)
+ {
+ sqrt1 = sqrt(sqrt1);
+ dist = (sqrt1 - b) / (2 * a);
+ CHECK_DIST;
+ }
+
+ height = dz + size;
+ float sqrt2 = b * b + 4 * a * height;
+ if(sqrt2 > 0)
+ {
+ sqrt2 = sqrt(sqrt2);
+ dist = (sqrt2 - b) / (2 * a);
+ CHECK_DIST;
+
+ dist = (-sqrt2 - b) / (2 * a);
+ CHECK_DIST;
+ }
+
+ if(sqrt1 > 0)
+ {
+ dist = (-sqrt1 - b) / (2 * a);
+ CHECK_DIST;
+ }
+ }
+
+ if(m_targets.m_srcPos.GetExactDist2d(&m_targets.m_dstPos) > bestDist)
+ {
+ float x = m_targets.m_srcPos.m_positionX + cos(m_caster->GetOrientation()) * bestDist;
+ float y = m_targets.m_srcPos.m_positionY + sin(m_caster->GetOrientation()) * bestDist;
+ float z = m_targets.m_srcPos.m_positionZ + bestDist * (a * bestDist + b);
+
+ if(itr != unitList.end())
+ {
+ float distSq = (*itr)->GetExactDistSq(x, y, z);
+ float sizeSq = (*itr)->GetObjectSize();
+ sizeSq *= sizeSq;
+ DEBUG_TRAJ(sLog.outError("Initial %f %f %f %f %f", x, y, z, distSq, sizeSq);)
+ if(distSq > sizeSq)
+ {
+ float factor = 1 - sqrt(sizeSq / distSq);
+ x += factor * ((*itr)->GetPositionX() - x);
+ y += factor * ((*itr)->GetPositionY() - y);
+ z += factor * ((*itr)->GetPositionZ() - z);
+
+ distSq = (*itr)->GetExactDistSq(x, y, z);
+ DEBUG_TRAJ(sLog.outError("Initial %f %f %f %f %f", x, y, z, distSq, sizeSq);)
+ }
+ }
+
+ m_targets.setDst(x, y, z, m_caster->GetOrientation());
+ }
+}
+
+void Spell::FillRaidOrPartyTargets( UnitList &TagUnitMap, Unit* target, float radius, bool raid, bool withPets, bool withcaster )
+{
+ Player *pTarget = target->GetCharmerOrOwnerPlayerOrPlayerItself();
+ Group *pGroup = pTarget ? pTarget->GetGroup() : NULL;
+
+ if (pGroup)
+ {
+ uint8 subgroup = pTarget->GetSubGroup();
+
+ for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
+ {
+ Player* Target = itr->getSource();
+
+ // IsHostileTo check duel and controlled by enemy
+ if (Target && (raid || subgroup==Target->GetSubGroup())
+ && !m_caster->IsHostileTo(Target))
+ {
+ if (Target==m_caster && withcaster ||
+ Target!=m_caster && m_caster->IsWithinDistInMap(Target, radius))
+ TagUnitMap.push_back(Target);
+
+ if (withPets)
+ if (Pet* pet = Target->GetPet())
+ if (pet==m_caster && withcaster ||
+ pet!=m_caster && m_caster->IsWithinDistInMap(pet, radius))
+ TagUnitMap.push_back(pet);
+ }
+ }
+ }
+ else
+ {
+ Unit* ownerOrSelf = pTarget ? pTarget : target->GetCharmerOrOwnerOrSelf();
+ if (ownerOrSelf==m_caster && withcaster ||
+ ownerOrSelf!=m_caster && m_caster->IsWithinDistInMap(ownerOrSelf, radius))
+ TagUnitMap.push_back(ownerOrSelf);
+
+ if (withPets)
+ if (Guardian* pet = ownerOrSelf->GetGuardianPet())
+ if (pet==m_caster && withcaster ||
+ pet!=m_caster && m_caster->IsWithinDistInMap(pet, radius))
+ TagUnitMap.push_back(pet);
+ }
+}
+
+void Spell::FillRaidOrPartyManaPriorityTargets( UnitList &TagUnitMap, Unit* target, float radius, uint32 count, bool raid, bool withPets, bool withCaster )
+{
+ FillRaidOrPartyTargets(TagUnitMap,target,radius,raid,withPets,withCaster);
+
+ PrioritizeManaUnitQueue manaUsers;
+ for (UnitList::const_iterator itr = TagUnitMap.begin(); itr != TagUnitMap.end() && manaUsers.size() < count; ++itr)
+ if ((*itr)->getPowerType() == POWER_MANA && !(*itr)->isDead())
+ manaUsers.push(PrioritizeManaUnitWraper(*itr));
+
+ TagUnitMap.clear();
+ while(!manaUsers.empty())
+ {
+ TagUnitMap.push_back(manaUsers.top().getUnit());
+ manaUsers.pop();
+ }
+}
+
+void Spell::FillRaidOrPartyHealthPriorityTargets( UnitList &TagUnitMap, Unit* target, float radius, uint32 count, bool raid, bool withPets, bool withCaster )
+{
+ FillRaidOrPartyTargets(TagUnitMap,target,radius,raid,withPets,withCaster);
+
+ PrioritizeHealthUnitQueue healthQueue;
+ for (UnitList::const_iterator itr = TagUnitMap.begin(); itr != TagUnitMap.end() && healthQueue.size() < count; ++itr)
+ if (!(*itr)->isDead())
+ healthQueue.push(PrioritizeHealthUnitWraper(*itr));
+
+ TagUnitMap.clear();
+ while(!healthQueue.empty())
+ {
+ TagUnitMap.push_back(healthQueue.top().getUnit());
+ healthQueue.pop();
+ }
+}
diff --git a/src/game/Unit.cpp b/src/game/Unit.cpp
index 0c300f934c5..1411b62b8f1 100644
--- a/src/game/Unit.cpp
+++ b/src/game/Unit.cpp
@@ -1,16290 +1,16290 @@
-/*
- * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
- *
- * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-#include "Common.h"
-#include "Log.h"
-#include "Opcodes.h"
-#include "WorldPacket.h"
-#include "WorldSession.h"
-#include "World.h"
-#include "ObjectMgr.h"
-#include "SpellMgr.h"
-#include "Unit.h"
-#include "QuestDef.h"
-#include "Player.h"
-#include "Creature.h"
-#include "Spell.h"
-#include "Group.h"
-#include "SpellAuras.h"
-#include "SpellAuraEffects.h"
-#include "MapManager.h"
-#include "ObjectAccessor.h"
-#include "CreatureAI.h"
-#include "Formulas.h"
-#include "Pet.h"
-#include "Util.h"
-#include "Totem.h"
-#include "BattleGround.h"
-#include "OutdoorPvP.h"
-#include "InstanceSaveMgr.h"
-#include "GridNotifiersImpl.h"
-#include "CellImpl.h"
-#include "Path.h"
-#include "CreatureGroups.h"
-#include "PetAI.h"
-#include "PassiveAI.h"
-#include "Traveller.h"
-#include "TemporarySummon.h"
-#include "Vehicle.h"
-#include "Transports.h"
-
-#include <math.h>
-
-float baseMoveSpeed[MAX_MOVE_TYPE] =
-{
- 2.5f, // MOVE_WALK
- 7.0f, // MOVE_RUN
- 2.5f, // MOVE_RUN_BACK
- 4.722222f, // MOVE_SWIM
- 4.5f, // MOVE_SWIM_BACK
- 3.141594f, // MOVE_TURN_RATE
- 7.0f, // MOVE_FLIGHT
- 4.5f, // MOVE_FLIGHT_BACK
- 3.14f // MOVE_PITCH_RATE
-};
-float playerBaseMoveSpeed[MAX_MOVE_TYPE] = {
- 2.5f, // MOVE_WALK
- 7.0f, // MOVE_RUN
- 2.5f, // MOVE_RUN_BACK
- 4.722222f, // MOVE_SWIM
- 4.5f, // MOVE_SWIM_BACK
- 3.141594f, // MOVE_TURN_RATE
- 7.0f, // MOVE_FLIGHT
- 4.5f, // MOVE_FLIGHT_BACK
- 3.14f // MOVE_PITCH_RATE
-};
-
-// Used for prepare can/can`t triggr aura
-static bool InitTriggerAuraData();
-// Define can trigger auras
-static bool isTriggerAura[TOTAL_AURAS];
-// Define can`t trigger auras (need for disable second trigger)
-static bool isNonTriggerAura[TOTAL_AURAS];
-// Prepare lists
-static bool procPrepared = InitTriggerAuraData();
-
-Unit::Unit()
-: WorldObject(), i_motionMaster(this), m_ThreatManager(this), m_HostilRefManager(this)
-, IsAIEnabled(false), NeedChangeAI(false)
-, i_AI(NULL), i_disabledAI(NULL), m_removedAurasCount(0), m_vehicle(NULL), m_transport(NULL)
-, m_ControlledByPlayer(false), m_procDeep(0), m_unitTypeMask(UNIT_MASK_NONE), m_vehicleKit(NULL)
-, m_movedPlayer(NULL)
-{
- m_objectType |= TYPEMASK_UNIT;
- m_objectTypeId = TYPEID_UNIT;
-
- m_updateFlag = (UPDATEFLAG_HIGHGUID | UPDATEFLAG_LIVING | UPDATEFLAG_HAS_POSITION);
-
- m_attackTimer[BASE_ATTACK] = 0;
- m_attackTimer[OFF_ATTACK] = 0;
- m_attackTimer[RANGED_ATTACK] = 0;
- m_modAttackSpeedPct[BASE_ATTACK] = 1.0f;
- m_modAttackSpeedPct[OFF_ATTACK] = 1.0f;
- m_modAttackSpeedPct[RANGED_ATTACK] = 1.0f;
-
- m_extraAttacks = 0;
- m_canDualWield = false;
-
- m_state = 0;
- m_form = FORM_NONE;
- m_deathState = ALIVE;
-
- for (uint8 i = 0; i < CURRENT_MAX_SPELL; ++i)
- m_currentSpells[i] = NULL;
-
- m_addDmgOnce = 0;
-
- for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i)
- m_SummonSlot[i] = 0;
-
- m_ObjectSlot[0] = m_ObjectSlot[1] = m_ObjectSlot[2] = m_ObjectSlot[3] = 0;
-
- m_auraUpdateIterator = m_ownedAuras.end();
- m_Visibility = VISIBILITY_ON;
-
- m_interruptMask = 0;
- m_detectInvisibilityMask = 0;
- m_invisibilityMask = 0;
- m_transform = 0;
- m_ShapeShiftFormSpellId = 0;
- m_canModifyStats = false;
-
- for (uint8 i = 0; i < MAX_SPELL_IMMUNITY; ++i)
- m_spellImmune[i].clear();
- for (uint8 i = 0; i < UNIT_MOD_END; ++i)
- {
- m_auraModifiersGroup[i][BASE_VALUE] = 0.0f;
- m_auraModifiersGroup[i][BASE_PCT] = 1.0f;
- m_auraModifiersGroup[i][TOTAL_VALUE] = 0.0f;
- m_auraModifiersGroup[i][TOTAL_PCT] = 1.0f;
- }
- // implement 50% base damage from offhand
- m_auraModifiersGroup[UNIT_MOD_DAMAGE_OFFHAND][TOTAL_PCT] = 0.5f;
-
- for (uint8 i = 0; i < MAX_ATTACK; ++i)
- {
- m_weaponDamage[i][MINDAMAGE] = BASE_MINDAMAGE;
- m_weaponDamage[i][MAXDAMAGE] = BASE_MAXDAMAGE;
- }
- for (uint8 i = 0; i < MAX_STATS; ++i)
- m_createStats[i] = 0.0f;
-
- m_attacking = NULL;
- m_modMeleeHitChance = 0.0f;
- m_modRangedHitChance = 0.0f;
- m_modSpellHitChance = 0.0f;
- m_baseSpellCritChance = 5;
-
- m_CombatTimer = 0;
- m_lastManaUse = 0;
-
- //m_victimThreat = 0.0f;
- for (uint8 i = 0; i < MAX_SPELL_SCHOOL; ++i)
- m_threatModifier[i] = 1.0f;
- m_isSorted = true;
- for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i)
- m_speed_rate[i] = 1.0f;
-
- m_charmInfo = NULL;
- //m_unit_movement_flags = 0;
- m_reducedThreatPercent = 0;
- m_misdirectionTargetGUID = 0;
-
- // remove aurastates allowing special moves
- for (uint8 i = 0; i < MAX_REACTIVE; ++i)
- m_reactiveTimer[i] = 0;
-
- m_cleanupDone = false;
-}
-
-Unit::~Unit()
-{
- // set current spells as deletable
- for (uint8 i = 0; i < CURRENT_MAX_SPELL; ++i)
- {
- if (m_currentSpells[i])
- {
- m_currentSpells[i]->SetReferencedFromCurrent(false);
- m_currentSpells[i] = NULL;
- }
- }
-
- RemoveAllGameObjects();
- RemoveAllDynObjects();
- _DeleteRemovedAuras();
-
- if (m_charmInfo)
- delete m_charmInfo;
- if (m_vehicleKit)
- delete m_vehicleKit;
-
- assert(!m_attacking);
- assert(m_attackers.empty());
- assert(m_sharedVision.empty());
- assert(m_Controlled.empty());
- assert(m_appliedAuras.empty());
- assert(m_ownedAuras.empty());
- assert(m_removedAuras.empty());
-}
-
-void Unit::Update(uint32 p_time)
-{
- /*if (p_time > m_AurasCheck)
- {
- m_AurasCheck = 2000;
- _UpdateAura();
- } else
- m_AurasCheck -= p_time;*/
-
- // WARNING! Order of execution here is important, do not change.
- // Spells must be processed with event system BEFORE they go to _UpdateSpells.
- // Or else we may have some SPELL_STATE_FINISHED spells stalled in pointers, that is bad.
- m_Events.Update(p_time);
-
- if (!IsInWorld())
- return;
-
- _UpdateSpells(p_time);
-
- // If this is set during update SetCantProc(false) call is missing somewhere in the code
- // Having this would prevent spells from being proced, so let's crash
- assert(!m_procDeep);
-
- if (CanHaveThreatList() && getThreatManager().isNeedUpdateToClient(p_time))
- SendThreatListUpdate();
-
- // update combat timer only for players and pets (only pets with PetAI)
- if (isInCombat() && (GetTypeId() == TYPEID_PLAYER || (((Creature *)this)->isPet() && IsControlledByPlayer())))
- {
- // Check UNIT_STAT_MELEE_ATTACKING or UNIT_STAT_CHASE (without UNIT_STAT_FOLLOW in this case) so pets can reach far away
- // targets without stopping half way there and running off.
- // These flags are reset after target dies or another command is given.
- if (m_HostilRefManager.isEmpty())
- {
- // m_CombatTimer set at aura start and it will be freeze until aura removing
- if (m_CombatTimer <= p_time)
- ClearInCombat();
- else
- m_CombatTimer -= p_time;
- }
- }
-
- //not implemented before 3.0.2
- //if (!hasUnitState(UNIT_STAT_CASTING))
- {
- if (uint32 base_att = getAttackTimer(BASE_ATTACK))
- setAttackTimer(BASE_ATTACK, (p_time >= base_att ? 0 : base_att - p_time));
- if (uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
- setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time));
- if (uint32 off_att = getAttackTimer(OFF_ATTACK))
- setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time));
- }
-
- // update abilities available only for fraction of time
- UpdateReactives(p_time);
-
- ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, GetHealth() < GetMaxHealth()*0.20f);
- ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, GetHealth() < GetMaxHealth()*0.35f);
- ModifyAuraState(AURA_STATE_HEALTH_ABOVE_75_PERCENT, GetHealth() > GetMaxHealth()*0.75f);
-
- i_motionMaster.UpdateMotion(p_time);
-}
-
-bool Unit::haveOffhandWeapon() const
-{
- if (GetTypeId() == TYPEID_PLAYER)
- return ((Player*)this)->GetWeaponForAttack(OFF_ATTACK,true);
- else
- return m_canDualWield;
-}
-
-void Unit::SendMonsterMoveWithSpeedToCurrentDestination(Player* player)
-{
- float x, y, z;
- if (GetMotionMaster()->GetDestination(x, y, z))
- SendMonsterMoveWithSpeed(x, y, z, 0, player);
-}
-
-void Unit::SendMonsterMoveWithSpeed(float x, float y, float z, uint32 transitTime, Player* player)
-{
- if (!transitTime)
- {
- if (GetTypeId() == TYPEID_PLAYER)
- {
- Traveller<Player> traveller(*(Player*)this);
- transitTime = traveller.GetTotalTrevelTimeTo(x,y,z);
- }
- else
- {
- Traveller<Creature> traveller(*(Creature*)this);
- transitTime = traveller.GetTotalTrevelTimeTo(x,y,z);
- }
- }
- //float orientation = (float)atan2((double)dy, (double)dx);
- SendMonsterMove(x, y, z, transitTime, player);
-}
-
-void Unit::SendMonsterStop()
-{
- WorldPacket data(SMSG_MONSTER_MOVE, (17 + GetPackGUID().size()));
- data.append(GetPackGUID());
- data << uint8(0); // new in 3.1
- data << GetPositionX() << GetPositionY() << GetPositionZ();
- data << getMSTime();
- data << uint8(1);
- SendMessageToSet(&data, true);
-
- clearUnitState(UNIT_STAT_MOVE);
-}
-
-void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint32 Time, Player* player)
-{
- WorldPacket data( SMSG_MONSTER_MOVE, 1+12+4+1+4+4+4+12+GetPackGUID().size());
- data.append(GetPackGUID());
-
- data << uint8(0); // new in 3.1
- data << GetPositionX() << GetPositionY() << GetPositionZ();
- data << getMSTime();
-
- data << uint8(0);
- data << uint32((GetUnitMovementFlags() & MOVEMENTFLAG_LEVITATING) ? MOVEFLAG_FLY : MOVEFLAG_WALK);
- data << Time; // Time in between points
- data << uint32(1); // 1 single waypoint
- data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B
-
- if (player)
- player->GetSession()->SendPacket(&data);
- else
- SendMessageToSet(&data, true);
-
- addUnitState(UNIT_STAT_MOVE);
-}
-
-void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint32 MoveFlags, uint32 time, float speedZ, Player *player)
-{
- WorldPacket data( SMSG_MONSTER_MOVE, 12+4+1+4+4+4+12+GetPackGUID().size());
- data.append(GetPackGUID());
-
- data << uint8(0); // new in 3.1
- data << GetPositionX() << GetPositionY() << GetPositionZ();
- data << getMSTime();
-
- data << uint8(0);
- data << MoveFlags;
-
- if (MoveFlags & MOVEFLAG_JUMP)
- {
- data << time;
- data << speedZ;
- data << (uint32)0; // walk time after jump
- }
- else
- data << time;
-
- data << uint32(1); // 1 single waypoint
- data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B
-
- if (player)
- player->GetSession()->SendPacket(&data);
- else
- SendMessageToSet(&data, true);
-}
-
-/*void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint8 type, uint32 MovementFlags, uint32 Time, Player* player)
-{
- float moveTime = Time;
-
- WorldPacket data(SMSG_MONSTER_MOVE, (41 + GetPackGUID().size()));
- data.append(GetPackGUID());
- data << uint8(0); // new in 3.1
- data << GetPositionX() << GetPositionY() << GetPositionZ();
- data << uint32(getMSTime());
-
- data << uint8(type); // unknown
- switch(type)
- {
- case 0: // normal packet
- break;
- case 1: // stop packet (raw pos?)
- SendMessageToSet(&data, true);
- return;
- case 2: // facing spot, not used currently
- data << float(0);
- data << float(0);
- data << float(0);
- break;
- case 3: // not used currently
- data << uint64(0); // probably target guid (facing target?)
- break;
- case 4: // not used currently
- data << float(0); // facing angle
- break;
- }
-
- data << uint32(MovementFlags);
-
- if (MovementFlags & MONSTER_MOVE_WALK)
- moveTime *= 1.05f;
-
- data << uint32(moveTime); // Time in between points
- data << uint32(1); // 1 single waypoint
- data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B
-
- if (player)
- player->GetSession()->SendPacket(&data);
- else
- SendMessageToSet(&data, true);
-}*/
-
-void Unit::SendMonsterMoveByPath(Path const& path, uint32 start, uint32 end)
-{
- uint32 traveltime = uint32(path.GetTotalLength(start, end) * 32);
-
- uint32 pathSize = end - start;
-
- WorldPacket data( SMSG_MONSTER_MOVE, (GetPackGUID().size()+1+4+4+4+4+1+4+4+4+pathSize*4*3) );
- data.append(GetPackGUID());
- data << uint8(0);
- data << GetPositionX();
- data << GetPositionY();
- data << GetPositionZ();
- data << uint32(getMSTime());
- data << uint8( 0 );
- data << uint32(((GetUnitMovementFlags() & MOVEMENTFLAG_LEVITATING) || isInFlight())? (MOVEFLAG_FLY|MOVEFLAG_WALK) : MOVEFLAG_WALK);
- data << uint32( traveltime );
- data << uint32( pathSize );
- data.append((char*)path.GetNodes(start), pathSize * 4 * 3);
- SendMessageToSet(&data, true);
-//MONSTER_MOVE_SPLINE_FLY
- addUnitState(UNIT_STAT_MOVE);
-}
-
-void Unit::SendMonsterMoveTransport(Unit *vehicleOwner)
-{
- WorldPacket data(SMSG_MONSTER_MOVE_TRANSPORT, GetPackGUID().size()+vehicleOwner->GetPackGUID().size());
- data.append(GetPackGUID());
- data.append(vehicleOwner->GetPackGUID());
- data << int8(GetTransSeat());
- data << uint8(0);
- data << GetPositionX() - vehicleOwner->GetPositionX();
- data << GetPositionY() - vehicleOwner->GetPositionY();
- data << GetPositionZ() - vehicleOwner->GetPositionZ();
- data << uint32(getMSTime());
- data << uint8(4);
- data << GetTransOffsetO();
- data << uint32(MOVEFLAG_ENTER_TRANSPORT);
- data << uint32(0);// move time
- data << uint32(0);//GetTransOffsetX();
- data << uint32(0);//GetTransOffsetY();
- data << uint32(0);//GetTransOffsetZ();
- SendMessageToSet(&data, true);
-}
-
-void Unit::resetAttackTimer(WeaponAttackType type)
-{
- m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]);
-}
-
-bool Unit::IsWithinCombatRange(const Unit *obj, float dist2compare) const
-{
- if (!obj || !IsInMap(obj)) return false;
-
- float dx = GetPositionX() - obj->GetPositionX();
- float dy = GetPositionY() - obj->GetPositionY();
- float dz = GetPositionZ() - obj->GetPositionZ();
- float distsq = dx*dx + dy*dy + dz*dz;
-
- float sizefactor = GetCombatReach() + obj->GetCombatReach();
- float maxdist = dist2compare + sizefactor;
-
- return distsq < maxdist * maxdist;
-}
-
-bool Unit::IsWithinMeleeRange(const Unit *obj, float dist) const
-{
- if (!obj || !IsInMap(obj)) return false;
-
- float dx = GetPositionX() - obj->GetPositionX();
- float dy = GetPositionY() - obj->GetPositionY();
- float dz = GetPositionZ() - obj->GetPositionZ();
- float distsq = dx*dx + dy*dy + dz*dz;
-
- float sizefactor = GetMeleeReach() + obj->GetMeleeReach();
- float maxdist = dist + sizefactor;
-
- return distsq < maxdist * maxdist;
-}
-
-void Unit::GetRandomContactPoint(const Unit* obj, float &x, float &y, float &z, float distance2dMin, float distance2dMax) const
-{
- float combat_reach = GetCombatReach();
- if(combat_reach < 0.1) // sometimes bugged for players
- {
- //sLog.outError("Unit %u (Type: %u) has invalid combat_reach %f",GetGUIDLow(),GetTypeId(),combat_reach);
- //if (GetTypeId() == TYPEID_UNIT)
- // sLog.outError("Creature entry %u has invalid combat_reach", ((Creature*)this)->GetEntry());
- combat_reach = DEFAULT_COMBAT_REACH;
- }
- uint32 attacker_number = getAttackers().size();
- if (attacker_number > 0)
- --attacker_number;
- GetNearPoint(obj,x,y,z,obj->GetCombatReach(), distance2dMin+(distance2dMax-distance2dMin)*rand_norm()
- , GetAngle(obj) + (attacker_number ? (M_PI/2 - M_PI * rand_norm()) * float(attacker_number) / combat_reach * 0.3 : 0));
-}
-
-void Unit::UpdateInterruptMask()
-{
- m_interruptMask = 0;
- for(AuraApplicationList::const_iterator i = m_interruptableAuras.begin(); i != m_interruptableAuras.end(); ++i)
- m_interruptMask |= (*i)->GetBase()->GetSpellProto()->AuraInterruptFlags;
-
- if (Spell* spell = m_currentSpells[CURRENT_CHANNELED_SPELL])
- if (spell->getState() == SPELL_STATE_CASTING)
- m_interruptMask |= spell->m_spellInfo->ChannelInterruptFlags;
-}
-
-bool Unit::HasAuraTypeWithFamilyFlags(AuraType auraType, uint32 familyName, uint32 familyFlags) const
-{
- if (!HasAuraType(auraType))
- return false;
- AuraEffectList const &auras = GetAuraEffectsByType(auraType);
- for (AuraEffectList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
- if (SpellEntry const *iterSpellProto = (*itr)->GetSpellProto())
- if (iterSpellProto->SpellFamilyName == familyName && iterSpellProto->SpellFamilyFlags[0] & familyFlags)
- return true;
- return false;
-}
-
-void Unit::DealDamageMods(Unit *pVictim, uint32 &damage, uint32* absorb)
-{
- if (!pVictim->isAlive() || pVictim->hasUnitState(UNIT_STAT_UNATTACKABLE) || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
- {
- if (absorb)
- absorb += damage;
- damage = 0;
- return;
- }
-
- //You don't lose health from damage taken from another player while in a sanctuary
- //You still see it in the combat log though
- if (pVictim != this && IsControlledByPlayer() && pVictim->IsControlledByPlayer())
- {
- const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
- if (area && area->IsSanctuary()) //sanctuary
- {
- if (absorb)
- absorb += damage;
- damage = 0;
- }
- }
-
- uint32 originalDamage = damage;
-
- //Script Event damage Deal
- //if (GetTypeId() == TYPEID_UNIT && ((Creature *)this)->AI())
- // ((Creature *)this)->AI()->DamageDeal(pVictim, damage);
- //Script Event damage taken
- //if (pVictim->GetTypeId() == TYPEID_UNIT && ((Creature *)pVictim)->IsAIEnabled)
- // ((Creature *)pVictim)->AI()->DamageTaken(this, damage);
-
- if (absorb && originalDamage > damage)
- absorb += (originalDamage - damage);
-}
-
-uint32 Unit::DealDamage(Unit *pVictim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellEntry const *spellProto, bool durabilityLoss)
-{
- // if attacker is a player and spell is not empty/fail
- if (GetTypeId() == TYPEID_PLAYER && spellProto)
- {
- // on divine storm dealed damage - heal
- if (spellProto->SpellFamilyName == SPELLFAMILY_PALADIN && spellProto->SpellFamilyFlags[1] & 0x20000)
- {
- Unit *pRaidGrpMember = GetNextRandomRaidMemberOrPet(30.0f);
-
- int32 divineDmg = damage * (25 + (HasAura(63220) ? 15 : 0)) / 100; //25%, if has Glyph of Divine Storm -> 40%
-
- if (!pRaidGrpMember)
- pRaidGrpMember = this;
-
- CastCustomSpell(pRaidGrpMember, 54172, &divineDmg, 0, 0, true);
- }
- }
-
- if (pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsAIEnabled)
- ((Creature*)pVictim)->AI()->DamageTaken(this, damage);
-
- if (damagetype != NODAMAGE)
- {
- // interrupting auras with AURA_INTERRUPT_FLAG_DAMAGE before checking !damage (absorbed damage breaks that type of auras)
- pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TAKE_DAMAGE, spellProto ? spellProto->Id : 0);
- }
-
-
- // Rage from Damage made (only from direct weapon damage)
- if (cleanDamage && damagetype==DIRECT_DAMAGE && this != pVictim && getPowerType() == POWER_RAGE)
- {
- uint32 weaponSpeedHitFactor;
- uint32 rage_damage = damage + cleanDamage->absorbed_damage;
-
- switch(cleanDamage->attackType)
- {
- case BASE_ATTACK:
- {
- if (cleanDamage->hitOutCome == MELEE_HIT_CRIT)
- weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 7);
- else
- weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
-
- RewardRage(rage_damage, weaponSpeedHitFactor, true);
-
- break;
- }
- case OFF_ATTACK:
- {
- if (cleanDamage->hitOutCome == MELEE_HIT_CRIT)
- weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
- else
- weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 1.75f);
-
- RewardRage(rage_damage, weaponSpeedHitFactor, true);
-
- break;
- }
- case RANGED_ATTACK:
- break;
- }
- }
-
- if (!damage)
- {
- // Rage from absorbed damage
- if (cleanDamage && cleanDamage->absorbed_damage && pVictim->getPowerType() == POWER_RAGE)
- pVictim->RewardRage(cleanDamage->absorbed_damage, 0, false);
-
- return 0;
- }
-
- // no xp,health if type 8 /critters/
- if (pVictim->GetTypeId() != TYPEID_PLAYER && pVictim->GetCreatureType() == CREATURE_TYPE_CRITTER)
- {
- // allow loot only if has loot_id in creature_template
- if (damage >= pVictim->GetHealth())
- {
- pVictim->setDeathState(JUST_DIED);
- pVictim->SetHealth(0);
-
- CreatureInfo const* cInfo = ((Creature*)pVictim)->GetCreatureInfo();
- if (cInfo && cInfo->lootid)
- pVictim->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
-
- // some critters required for quests (need normal entry instead possible heroic in any cases)
- if (GetTypeId() == TYPEID_PLAYER)
- if (CreatureInfo const* normalInfo = objmgr.GetCreatureTemplate(pVictim->GetEntry()))
- ((Player*)this)->KilledMonster(normalInfo,pVictim->GetGUID());
- }
- else
- pVictim->ModifyHealth(- (int32)damage);
-
- return damage;
- }
-
- DEBUG_LOG("DealDamageStart");
-
- uint32 health = pVictim->GetHealth();
- sLog.outDetail("deal dmg:%d to health:%d ",damage,health);
-
- // duel ends when player has 1 or less hp
- bool duel_hasEnded = false;
- if (pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->duel && damage >= (health-1))
- {
- // prevent kill only if killed in duel and killed by opponent or opponent controlled creature
- if (((Player*)pVictim)->duel->opponent==this || ((Player*)pVictim)->duel->opponent->GetGUID() == GetOwnerGUID())
- damage = health-1;
-
- duel_hasEnded = true;
- }
-
- if (GetTypeId() == TYPEID_PLAYER && this != pVictim)
- {
- Player *killer = ((Player*)this);
-
- // in bg, count dmg if victim is also a player
- if (pVictim->GetTypeId() == TYPEID_PLAYER)
- {
- if (BattleGround *bg = killer->GetBattleGround())
- {
- // FIXME: kept by compatibility. don't know in BG if the restriction apply.
- bg->UpdatePlayerScore(killer, SCORE_DAMAGE_DONE, damage);
- }
- }
-
- killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE, damage, 0, pVictim);
- killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT, damage);
- }
-
- if (pVictim->GetTypeId() == TYPEID_PLAYER)
- ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED, damage);
- else if (!pVictim->IsControlledByPlayer())
- {
- //!pVictim->HasFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER)
- if (!((Creature*)pVictim)->hasLootRecipient())
- ((Creature*)pVictim)->SetLootRecipient(this);
-
- if (IsControlledByPlayer())
- ((Creature*)pVictim)->LowerPlayerDamageReq(health < damage ? health : damage);
- }
-
- if (health <= damage)
- {
- DEBUG_LOG("DealDamage: victim just died");
-
- if (pVictim->GetTypeId() == TYPEID_PLAYER)
- ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, health);
-
- Kill(pVictim, durabilityLoss);
-
- //Hook for OnPVPKill Event
- if (pVictim->GetTypeId() == TYPEID_PLAYER && this->GetTypeId() == TYPEID_PLAYER)
- {
- Player *killer = ((Player*)this);
- Player *killed = ((Player*)pVictim);
- killer->GetSession()->HandleOnPVPKill(killed);
- }
- if (pVictim->GetTypeId() == TYPEID_UNIT && this->GetTypeId() == TYPEID_PLAYER)
- {
- Player *killer = ((Player*)this);
- Creature *pCreature = ((Creature*)pVictim);
- killer->GetSession()->HandleOnCreatureKill(pCreature);
- }
- }
- else // if (health <= damage)
- {
- DEBUG_LOG("DealDamageAlive");
-
- if (pVictim->GetTypeId() == TYPEID_PLAYER)
- ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, damage);
-
- pVictim->ModifyHealth(- (int32)damage);
-
- if (damagetype == DIRECT_DAMAGE || damagetype == SPELL_DIRECT_DAMAGE)
- {
- //TODO: This is from procflag, I do not know which spell needs this
- //Maim?
- //if (!spellProto || !(spellProto->AuraInterruptFlags&AURA_INTERRUPT_FLAG_DIRECT_DAMAGE))
- pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DIRECT_DAMAGE, spellProto ? spellProto->Id : 0);
- }
- if (pVictim->GetTypeId() != TYPEID_PLAYER)
- {
- if (spellProto && IsDamageToThreatSpell(spellProto))
- pVictim->AddThreat(this, damage*2, damageSchoolMask, spellProto);
- else
- pVictim->AddThreat(this, damage, damageSchoolMask, spellProto);
- }
- else // victim is a player
- {
- // random durability for items (HIT TAKEN)
- if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
- {
- EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
- ((Player*)pVictim)->DurabilityPointLossForEquipSlot(slot);
- }
- }
-
- // Rage from damage received
- if (this != pVictim && pVictim->getPowerType() == POWER_RAGE)
- {
- uint32 rage_damage = damage + (cleanDamage ? cleanDamage->absorbed_damage : 0);
- pVictim->RewardRage(rage_damage, 0, false);
- }
-
- if (GetTypeId() == TYPEID_PLAYER)
- {
- // random durability for items (HIT DONE)
- if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
- {
- EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
- ((Player*)this)->DurabilityPointLossForEquipSlot(slot);
- }
- }
-
- if (damagetype != NODAMAGE && damage)// && pVictim->GetTypeId() == TYPEID_PLAYER)
- {
- if (pVictim != this && pVictim->GetTypeId() == TYPEID_PLAYER) // does not support creature push_back
- {
- if (damagetype != DOT)
- {
- if (Spell* spell = pVictim->m_currentSpells[CURRENT_GENERIC_SPELL])
- {
- if (spell->getState() == SPELL_STATE_PREPARING)
- {
- uint32 interruptFlags = spell->m_spellInfo->InterruptFlags;
- if (interruptFlags & SPELL_INTERRUPT_FLAG_ABORT_ON_DMG)
- pVictim->InterruptNonMeleeSpells(false);
- else if (interruptFlags & SPELL_INTERRUPT_FLAG_PUSH_BACK)
- spell->Delayed();
- }
- }
- }
-
- if (Spell* spell = pVictim->m_currentSpells[CURRENT_CHANNELED_SPELL])
- {
- if (spell->getState() == SPELL_STATE_CASTING)
- {
- uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags;
- if (channelInterruptFlags & CHANNEL_FLAG_DELAY)
- spell->DelayedChannel();
- }
- }
- }
- }
-
- // last damage from duel opponent
- if (duel_hasEnded)
- {
- assert(pVictim->GetTypeId() == TYPEID_PLAYER);
- Player *he = (Player*)pVictim;
-
- assert(he->duel);
-
- he->SetHealth(1);
-
- he->duel->opponent->CombatStopWithPets(true);
- he->CombatStopWithPets(true);
-
- he->CastSpell(he, 7267, true); // beg
- he->DuelComplete(DUEL_WON);
- }
- }
-
- DEBUG_LOG("DealDamageEnd returned %d damage", damage);
-
- return damage;
-}
-
-void Unit::CastStop(uint32 except_spellid)
-{
- for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
- if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id!=except_spellid)
- InterruptSpell(CurrentSpellTypes(i),false);
-}
-
-void Unit::CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem, AuraEffect const * triggeredByAura, uint64 originalCaster)
-{
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
-
- if (!spellInfo)
- {
- sLog.outError("CastSpell: unknown spell id %i by caster: %s %u)", spellId,(GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
- return;
- }
-
- CastSpell(Victim,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
-}
-
-void Unit::CastSpell(Unit* Victim,SpellEntry const *spellInfo, bool triggered, Item *castItem, AuraEffect const * triggeredByAura, uint64 originalCaster)
-{
- if (!spellInfo)
- {
- sLog.outError("CastSpell: unknown spell by caster: %s %u)", (GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
- return;
- }
-
- if (!originalCaster && GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isTotem() && IsControlledByPlayer())
- if (Unit * owner = GetOwner())
- originalCaster=owner->GetGUID();
-
- SpellCastTargets targets;
- uint32 targetMask = spellInfo->Targets;
- //if (targetMask & (TARGET_FLAG_UNIT|TARGET_FLAG_UNK2))
- for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
- {
- if (SpellTargetType[spellInfo->EffectImplicitTargetA[i]] == TARGET_TYPE_UNIT_TARGET)
- {
- /*SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
- if (srange && GetSpellMaxRange(srange) == 0.0f)
- {
- Victim = this;
- break;
- }
- else */if (!Victim)
- {
- sLog.outError("CastSpell: spell id %i by caster: %s %u) does not have unit target", spellInfo->Id,(GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
- return;
- }
- else
- break;
- }
- }
- targets.setUnitTarget(Victim);
-
- if (targetMask & (TARGET_FLAG_SOURCE_LOCATION|TARGET_FLAG_DEST_LOCATION))
- {
- if (!Victim)
- {
- sLog.outError("CastSpell: spell id %i by caster: %s %u) does not have destination", spellInfo->Id,(GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
- return;
- }
- targets.setDst(Victim);
- }
-
- if (castItem)
- DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
-
- if (!originalCaster && triggeredByAura)
- originalCaster = triggeredByAura->GetCasterGUID();
-
- Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
-
- spell->m_CastItem = castItem;
- spell->prepare(&targets, triggeredByAura);
-}
-
-void Unit::CastCustomSpell(Unit* target, uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, AuraEffect const * triggeredByAura, uint64 originalCaster)
-{
- CustomSpellValues values;
- if (bp0)
- values.AddSpellMod(SPELLVALUE_BASE_POINT0, *bp0);
- if (bp1)
- values.AddSpellMod(SPELLVALUE_BASE_POINT1, *bp1);
- if (bp2)
- values.AddSpellMod(SPELLVALUE_BASE_POINT2, *bp2);
- CastCustomSpell(spellId, values, target, triggered, castItem, triggeredByAura, originalCaster);
-}
-
-void Unit::CastCustomSpell(uint32 spellId, SpellValueMod mod, int32 value, Unit* target, bool triggered, Item *castItem, AuraEffect const * triggeredByAura, uint64 originalCaster)
-{
- CustomSpellValues values;
- values.AddSpellMod(mod, value);
- CastCustomSpell(spellId, values, target, triggered, castItem, triggeredByAura, originalCaster);
-}
-
-void Unit::CastCustomSpell(uint32 spellId, CustomSpellValues const &value, Unit* Victim, bool triggered, Item *castItem, AuraEffect const * triggeredByAura, uint64 originalCaster)
-{
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
- if (!spellInfo)
- {
- sLog.outError("CastSpell: unknown spell id %i by caster: %s %u)", spellId,(GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
- return;
- }
-
- SpellCastTargets targets;
- uint32 targetMask = spellInfo->Targets;
-
- //check unit target
- for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
- {
- if (SpellTargetType[spellInfo->EffectImplicitTargetA[i]] == TARGET_TYPE_UNIT_TARGET)
- {
- if (!Victim)
- {
- sLog.outError("CastSpell: spell id %i by caster: %s %u) does not have unit target", spellInfo->Id,(GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
- return;
- }
- else
- break;
- }
- }
- targets.setUnitTarget(Victim);
-
- //check destination
- if (targetMask & (TARGET_FLAG_SOURCE_LOCATION|TARGET_FLAG_DEST_LOCATION))
- {
- if (!Victim)
- {
- sLog.outError("CastSpell: spell id %i by caster: %s %u) does not have destination", spellInfo->Id,(GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
- return;
- }
- targets.setDst(Victim);
- }
-
- if (!originalCaster && triggeredByAura)
- originalCaster = triggeredByAura->GetCasterGUID();
-
- Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
-
- if (castItem)
- {
- DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
- spell->m_CastItem = castItem;
- }
-
- for (CustomSpellValues::const_iterator itr = value.begin(); itr != value.end(); ++itr)
- spell->SetSpellValue(itr->first, itr->second);
-
- spell->prepare(&targets, triggeredByAura);
-}
-
-// used for scripting
-void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item *castItem, AuraEffect const * triggeredByAura, uint64 originalCaster, Unit* OriginalVictim)
-{
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
-
- if (!spellInfo)
- {
- sLog.outError("CastSpell(x,y,z): unknown spell id %i by caster: %s %u)", spellId,(GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
- return;
- }
-
- if (castItem)
- DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
-
- if (!originalCaster && triggeredByAura)
- originalCaster = triggeredByAura->GetCasterGUID();
-
- Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
-
- SpellCastTargets targets;
- targets.setDst(x, y, z, GetOrientation());
- if (OriginalVictim)
- targets.setUnitTarget(OriginalVictim);
- spell->m_CastItem = castItem;
- spell->prepare(&targets, triggeredByAura);
-}
-
-// used for scripting
-void Unit::CastSpell(GameObject *go, uint32 spellId, bool triggered, Item *castItem, AuraEffect* triggeredByAura, uint64 originalCaster)
-{
- if (!go)
- return;
-
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
-
- if (!spellInfo)
- {
- sLog.outError("CastSpell(x,y,z): unknown spell id %i by caster: %s %u)", spellId,(GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
- return;
- }
-
- if (!(spellInfo->Targets & ( TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK)))
- {
- sLog.outError("CastSpell: spell id %i by caster: %s %u) is not gameobject spell", spellId,(GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
- return;
- }
-
- if (castItem)
- DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
-
- if (!originalCaster && triggeredByAura)
- originalCaster = triggeredByAura->GetCasterGUID();
-
- Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
-
- SpellCastTargets targets;
- targets.setGOTarget(go);
- spell->m_CastItem = castItem;
- spell->prepare(&targets, triggeredByAura);
-}
-
-// Obsolete func need remove, here only for comotability vs another patches
-uint32 Unit::SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage)
-{
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellID);
- SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, spellInfo->SchoolMask);
- damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
- CalculateSpellDamageTaken(&damageInfo, damage, spellInfo);
- DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb);
- SendSpellNonMeleeDamageLog(&damageInfo);
- DealSpellDamage(&damageInfo, true);
- return damageInfo.damage;
-}
-
-void Unit::CalculateSpellDamageTaken(SpellNonMeleeDamage *damageInfo, int32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType, bool crit)
-{
- if (damage < 0)
- return;
-
- if (spellInfo->AttributesEx4 & SPELL_ATTR_EX4_FIXED_DAMAGE)
- {
- damageInfo->damage = damage;
- return;
- }
-
- Unit *pVictim = damageInfo->target;
- if (!pVictim || !pVictim->isAlive())
- return;
-
- SpellSchoolMask damageSchoolMask = SpellSchoolMask(damageInfo->schoolMask);
- uint32 crTypeMask = pVictim->GetCreatureTypeMask();
-
- if (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL)
- damage = CalcArmorReducedDamage(pVictim, damage, spellInfo, attackType);
-
- bool blocked = false;
- // Per-school calc
- switch (spellInfo->DmgClass)
- {
- // Melee and Ranged Spells
- case SPELL_DAMAGE_CLASS_RANGED:
- case SPELL_DAMAGE_CLASS_MELEE:
- {
- // Physical Damage
- if (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL)
- {
- // Get blocked status
- blocked = isSpellBlocked(pVictim, spellInfo, attackType);
- }
-
- if (crit)
- {
- damageInfo->HitInfo |= SPELL_HIT_TYPE_CRIT;
-
- // Calculate crit bonus
- uint32 crit_bonus = damage;
- // Apply crit_damage bonus for melee spells
- if (Player* modOwner = GetSpellModOwner())
- modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
- damage += crit_bonus;
-
- // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
- int32 critPctDamageMod = 0;
- if (attackType == RANGED_ATTACK)
- critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
- else
- {
- critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
- critPctDamageMod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
- }
- // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
- critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
-
- if (critPctDamageMod != 0)
- damage = int32(damage * float((100.0f + critPctDamageMod)/100.0f));
-
- // Resilience - reduce crit damage
- if (attackType != RANGED_ATTACK)
- damage -= pVictim->GetMeleeCritDamageReduction(damage);
- else
- damage -= pVictim->GetRangedCritDamageReduction(damage);
- }
- // Spell weapon based damage CAN BE crit & blocked at same time
- if (blocked)
- {
- damageInfo->blocked = uint32(pVictim->GetShieldBlockValue());
- //double blocked amount if block is critical
- if (isBlockCritical())
- damageInfo->blocked+=damageInfo->blocked;
- if (damage < damageInfo->blocked)
- damageInfo->blocked = damage;
- damage -= damageInfo->blocked;
- }
- }
- break;
- // Magical Attacks
- case SPELL_DAMAGE_CLASS_NONE:
- case SPELL_DAMAGE_CLASS_MAGIC:
- {
- // If crit add critical bonus
- if (crit)
- {
- damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
- damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim);
- // Resilience - reduce crit damage
- damage -= pVictim->GetSpellCritDamageReduction(damage);
- }
- }
- break;
- }
-
- // only from players
- if (GetTypeId() == TYPEID_PLAYER)
- damage -= pVictim->GetSpellDamageReduction(damage);
-
- // Calculate absorb resist
- if (damage > 0)
- {
- switch (spellInfo->SpellIconID)
- {
- // Chaos Bolt - "Chaos Bolt cannot be resisted, and pierces through all absorption effects."
- case 3178:
- break;
- default:
- CalcAbsorbResist(pVictim, damageSchoolMask, SPELL_DIRECT_DAMAGE, damage, &damageInfo->absorb, &damageInfo->resist, spellInfo);
- damage -= damageInfo->absorb + damageInfo->resist;
- break;
- }
- }
- else
- damage = 0;
- damageInfo->damage = damage;
-}
-
-void Unit::DealSpellDamage(SpellNonMeleeDamage *damageInfo, bool durabilityLoss)
-{
- if (damageInfo==0)
- return;
-
- Unit *pVictim = damageInfo->target;
-
- if (!pVictim)
- return;
-
- if (!pVictim->isAlive() || pVictim->hasUnitState(UNIT_STAT_UNATTACKABLE) || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
- return;
-
- SpellEntry const *spellProto = sSpellStore.LookupEntry(damageInfo->SpellID);
- if (spellProto == NULL)
- {
- sLog.outDebug("Unit::DealSpellDamage have wrong damageInfo->SpellID: %u", damageInfo->SpellID);
- return;
- }
-
- //You don't lose health from damage taken from another player while in a sanctuary
- //You still see it in the combat log though
- if (pVictim != this && IsControlledByPlayer() && pVictim->IsControlledByPlayer())
- {
- const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
- if (area && area->IsSanctuary()) // sanctuary
- return;
- }
-
- // Call default DealDamage
- CleanDamage cleanDamage(damageInfo->cleanDamage, damageInfo->absorb, BASE_ATTACK, MELEE_HIT_NORMAL);
- DealDamage(pVictim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, SpellSchoolMask(damageInfo->schoolMask), spellProto, durabilityLoss);
-}
-
-//TODO for melee need create structure as in
-void Unit::CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType)
-{
- damageInfo->attacker = this;
- damageInfo->target = pVictim;
- damageInfo->damageSchoolMask = GetMeleeDamageSchoolMask();
- damageInfo->attackType = attackType;
- damageInfo->damage = 0;
- damageInfo->cleanDamage = 0;
- damageInfo->absorb = 0;
- damageInfo->resist = 0;
- damageInfo->blocked_amount = 0;
-
- damageInfo->TargetState = 0;
- damageInfo->HitInfo = 0;
- damageInfo->procAttacker = PROC_FLAG_NONE;
- damageInfo->procVictim = PROC_FLAG_NONE;
- damageInfo->procEx = PROC_EX_NONE;
- damageInfo->hitOutCome = MELEE_HIT_EVADE;
-
- if (!pVictim)
- return;
- if (!isAlive() || !pVictim->isAlive())
- return;
-
- // Select HitInfo/procAttacker/procVictim flag based on attack type
- switch (attackType)
- {
- case BASE_ATTACK:
- damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_HIT;
- damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;
- damageInfo->HitInfo = HITINFO_NORMALSWING2;
- break;
- case OFF_ATTACK:
- damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_HIT | PROC_FLAG_SUCCESSFUL_OFFHAND_HIT;
- damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;//|PROC_FLAG_TAKEN_OFFHAND_HIT // not used
- damageInfo->HitInfo = HITINFO_LEFTSWING;
- break;
- case RANGED_ATTACK:
- damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
- damageInfo->procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
- damageInfo->HitInfo = HITINFO_UNK2;// test
- break;
- default:
- break;
- }
-
- // Physical Immune check
- if (damageInfo->target->IsImmunedToDamage(SpellSchoolMask(damageInfo->damageSchoolMask)))
- {
- damageInfo->HitInfo |= HITINFO_NORMALSWING;
- damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE;
-
- damageInfo->procEx |= PROC_EX_IMMUNE;
- damageInfo->damage = 0;
- damageInfo->cleanDamage = 0;
- return;
- }
- damage += CalculateDamage(damageInfo->attackType, false, true);
- // Add melee damage bonus
- MeleeDamageBonus(damageInfo->target, &damage, damageInfo->attackType);
- // Calculate armor reduction
- damageInfo->damage = CalcArmorReducedDamage(damageInfo->target, damage, NULL , damageInfo->attackType);
- damageInfo->cleanDamage += damage - damageInfo->damage;
-
- damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType);
-
- // Disable parry or dodge for ranged attack
- if (damageInfo->attackType == RANGED_ATTACK)
- {
- if (damageInfo->hitOutCome == MELEE_HIT_PARRY)
- damageInfo->hitOutCome = MELEE_HIT_NORMAL;
- else if (damageInfo->hitOutCome == MELEE_HIT_DODGE)
- damageInfo->hitOutCome = MELEE_HIT_MISS;
- }
-
- switch (damageInfo->hitOutCome)
- {
- case MELEE_HIT_EVADE:
- {
- damageInfo->HitInfo |= HITINFO_MISS|HITINFO_SWINGNOHITSOUND;
- damageInfo->TargetState = VICTIMSTATE_EVADES;
-
- damageInfo->procEx|=PROC_EX_EVADE;
- damageInfo->damage = 0;
- damageInfo->cleanDamage = 0;
- return;
- }
- case MELEE_HIT_MISS:
- {
- damageInfo->HitInfo |= HITINFO_MISS;
- damageInfo->TargetState = VICTIMSTATE_NORMAL;
-
- damageInfo->procEx |= PROC_EX_MISS;
- damageInfo->damage = 0;
- damageInfo->cleanDamage = 0;
- break;
- }
- case MELEE_HIT_NORMAL:
- damageInfo->TargetState = VICTIMSTATE_NORMAL;
- damageInfo->procEx|=PROC_EX_NORMAL_HIT;
- break;
- case MELEE_HIT_CRIT:
- {
- damageInfo->HitInfo |= HITINFO_CRITICALHIT;
- damageInfo->TargetState = VICTIMSTATE_NORMAL;
-
- damageInfo->procEx |= PROC_EX_CRITICAL_HIT;
- // Crit bonus calc
- damageInfo->damage += damageInfo->damage;
- int32 mod = 0;
- // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
- if (damageInfo->attackType == RANGED_ATTACK)
- mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
- else
- {
- mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
- mod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
- }
-
- uint32 crTypeMask = damageInfo->target->GetCreatureTypeMask();
-
- // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
- mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
- if (mod != 0)
- damageInfo->damage = int32((damageInfo->damage) * float((100.0f + mod)/100.0f));
-
- // Resilience - reduce crit damage
- uint32 resilienceReduction;
- if (attackType != RANGED_ATTACK)
- resilienceReduction = pVictim->GetMeleeCritDamageReduction(damageInfo->damage);
- else
- resilienceReduction = pVictim->GetRangedCritDamageReduction(damageInfo->damage);
-
- damageInfo->damage -= resilienceReduction;
- damageInfo->cleanDamage += resilienceReduction;
- break;
- }
- case MELEE_HIT_PARRY:
- damageInfo->TargetState = VICTIMSTATE_PARRY;
- damageInfo->procEx |= PROC_EX_PARRY;
- damageInfo->cleanDamage += damageInfo->damage;
- damageInfo->damage = 0;
- break;
-
- case MELEE_HIT_DODGE:
- damageInfo->TargetState = VICTIMSTATE_DODGE;
- damageInfo->procEx |= PROC_EX_DODGE;
- damageInfo->cleanDamage += damageInfo->damage;
- damageInfo->damage = 0;
- break;
- case MELEE_HIT_BLOCK:
- {
- damageInfo->TargetState = VICTIMSTATE_NORMAL;
- damageInfo->HitInfo |= HITINFO_BLOCK;
- damageInfo->procEx |= PROC_EX_BLOCK;
- damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue();
- //double blocked amount if block is critical
- if (isBlockCritical())
- damageInfo->blocked_amount+=damageInfo->blocked_amount;
- if (damageInfo->blocked_amount >= damageInfo->damage)
- {
- damageInfo->TargetState = VICTIMSTATE_BLOCKS;
- damageInfo->blocked_amount = damageInfo->damage;
- damageInfo->procEx |= PROC_EX_FULL_BLOCK;
- }
- else
- damageInfo->procEx |= PROC_EX_NORMAL_HIT;
- damageInfo->damage -= damageInfo->blocked_amount;
- damageInfo->cleanDamage += damageInfo->blocked_amount;
- break;
- }
- case MELEE_HIT_GLANCING:
- {
- damageInfo->HitInfo |= HITINFO_GLANCING;
- damageInfo->TargetState = VICTIMSTATE_NORMAL;
- damageInfo->procEx |= PROC_EX_NORMAL_HIT;
- int32 leveldif = int32(pVictim->getLevel()) - int32(getLevel());
- if (leveldif > 3) leveldif = 3;
- float reducePercent = 1 - leveldif * 0.1f;
- damageInfo->cleanDamage += damageInfo->damage-uint32(reducePercent * damageInfo->damage);
- damageInfo->damage = uint32(reducePercent * damageInfo->damage);
- break;
- }
- case MELEE_HIT_CRUSHING:
- {
- damageInfo->HitInfo |= HITINFO_CRUSHING;
- damageInfo->TargetState = VICTIMSTATE_NORMAL;
- damageInfo->procEx |= PROC_EX_NORMAL_HIT;
- // 150% normal damage
- damageInfo->damage += (damageInfo->damage / 2);
- break;
- }
- default:
- break;
- }
-
- // only from players
- if (GetTypeId() == TYPEID_PLAYER)
- {
- if (attackType != RANGED_ATTACK)
- damage -= pVictim->GetMeleeDamageReduction(damage);
- else
- damage -= pVictim->GetRangedDamageReduction(damage);
- }
-
- // Calculate absorb resist
- if (int32(damageInfo->damage) > 0)
- {
- damageInfo->procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
- // Calculate absorb & resists
- CalcAbsorbResist(damageInfo->target, SpellSchoolMask(damageInfo->damageSchoolMask), DIRECT_DAMAGE, damageInfo->damage, &damageInfo->absorb, &damageInfo->resist);
- damageInfo->damage -= damageInfo->absorb + damageInfo->resist;
- if (damageInfo->absorb)
- {
- damageInfo->HitInfo |= HITINFO_ABSORB;
- damageInfo->procEx |= PROC_EX_ABSORB;
- }
- if (damageInfo->resist)
- damageInfo->HitInfo |= HITINFO_RESIST;
- }
- else // Impossible get negative result but....
- damageInfo->damage = 0;
-}
-
-void Unit::DealMeleeDamage(CalcDamageInfo *damageInfo, bool durabilityLoss)
-{
- if (!damageInfo)
- return;
- Unit *pVictim = damageInfo->target;
-
- if (!pVictim)
- return;
-
- if (!pVictim->isAlive() || pVictim->hasUnitState(UNIT_STAT_UNATTACKABLE) || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
- return;
-
- //You don't lose health from damage taken from another player while in a sanctuary
- //You still see it in the combat log though
- if (pVictim != this && IsControlledByPlayer() && pVictim->IsControlledByPlayer())
- {
- const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
- if (area && area->IsSanctuary()) // sanctuary
- return;
- }
-
- // Hmmmm dont like this emotes client must by self do all animations
- if (damageInfo->HitInfo&HITINFO_CRITICALHIT)
- pVictim->HandleEmoteCommand(EMOTE_ONESHOT_WOUNDCRITICAL);
- if (damageInfo->blocked_amount && damageInfo->TargetState != VICTIMSTATE_BLOCKS)
- pVictim->HandleEmoteCommand(EMOTE_ONESHOT_PARRYSHIELD);
-
- if (damageInfo->TargetState == VICTIMSTATE_PARRY)
- {
- // Get attack timers
- float offtime = float(pVictim->getAttackTimer(OFF_ATTACK));
- float basetime = float(pVictim->getAttackTimer(BASE_ATTACK));
- // Reduce attack time
- if (pVictim->haveOffhandWeapon() && offtime < basetime)
- {
- float percent20 = pVictim->GetAttackTime(OFF_ATTACK) * 0.20f;
- float percent60 = 3.0f * percent20;
- if (offtime > percent20 && offtime <= percent60)
- pVictim->setAttackTimer(OFF_ATTACK, uint32(percent20));
- else if (offtime > percent60)
- {
- offtime -= 2.0f * percent20;
- pVictim->setAttackTimer(OFF_ATTACK, uint32(offtime));
- }
- }
- else
- {
- float percent20 = pVictim->GetAttackTime(BASE_ATTACK) * 0.20;
- float percent60 = 3.0f * percent20;
- if (basetime > percent20 && basetime <= percent60)
- pVictim->setAttackTimer(BASE_ATTACK, uint32(percent20));
- else if (basetime > percent60)
- {
- basetime -= 2.0f * percent20;
- pVictim->setAttackTimer(BASE_ATTACK, uint32(basetime));
- }
- }
- }
-
- // Call default DealDamage
- CleanDamage cleanDamage(damageInfo->cleanDamage,damageInfo->absorb,damageInfo->attackType,damageInfo->hitOutCome);
- DealDamage(pVictim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->damageSchoolMask), NULL, durabilityLoss);
-
- // If this is a creature and it attacks from behind it has a probability to daze it's victim
- if ((damageInfo->hitOutCome==MELEE_HIT_CRIT || damageInfo->hitOutCome==MELEE_HIT_CRUSHING || damageInfo->hitOutCome==MELEE_HIT_NORMAL || damageInfo->hitOutCome==MELEE_HIT_GLANCING) &&
- GetTypeId() != TYPEID_PLAYER && !((Creature*)this)->IsControlledByPlayer() && !pVictim->HasInArc(M_PI, this)
- && (pVictim->GetTypeId() == TYPEID_PLAYER || !((Creature*)pVictim)->isWorldBoss()))
- {
- // -probability is between 0% and 40%
- // 20% base chance
- float Probability = 20.0f;
-
- //there is a newbie protection, at level 10 just 7% base chance; assuming linear function
- if (pVictim->getLevel() < 30)
- Probability = 0.65f*pVictim->getLevel()+0.5f;
-
- uint32 VictimDefense=pVictim->GetDefenseSkillValue();
- uint32 AttackerMeleeSkill=GetUnitMeleeSkill();
-
- Probability *= AttackerMeleeSkill/(float)VictimDefense;
-
- if (Probability > 40.0f)
- Probability = 40.0f;
-
- if (roll_chance_f(Probability))
- CastSpell(pVictim, 1604, true);
- }
-
- if (GetTypeId() == TYPEID_PLAYER)
- ((Player *)this)->CastItemCombatSpell(pVictim, damageInfo->attackType, damageInfo->procVictim, damageInfo->procEx);
-
- // Do effect if any damage done to target
- if (damageInfo->damage)
- {
- // victim's damage shield
- std::set<AuraEffect*> alreadyDone;
- uint32 removedAuras = pVictim->m_removedAurasCount;
- AuraEffectList const& vDamageShields = pVictim->GetAuraEffectsByType(SPELL_AURA_DAMAGE_SHIELD);
- for (AuraEffectList::const_iterator i = vDamageShields.begin(), next = vDamageShields.begin(); i != vDamageShields.end(); i = next)
- {
- ++next;
- if (alreadyDone.find(*i) == alreadyDone.end())
- {
- alreadyDone.insert(*i);
- uint32 damage=(*i)->GetAmount();
- SpellEntry const *i_spellProto = (*i)->GetSpellProto();
- //Calculate absorb resist ??? no data in opcode for this possibly unable to absorb or resist?
- //uint32 absorb;
- //uint32 resist;
- //CalcAbsorbResist(pVictim, SpellSchools(spellProto->School), SPELL_DIRECT_DAMAGE, damage, &absorb, &resist);
- //damage-=absorb + resist;
-
- pVictim->DealDamageMods(this,damage,NULL);
-
- WorldPacket data(SMSG_SPELLDAMAGESHIELD,(8+8+4+4+4+4));
- data << uint64(pVictim->GetGUID());
- data << uint64(GetGUID());
- data << uint32(i_spellProto->Id);
- data << uint32(damage); // Damage
- data << uint32(0); // Overkill
- data << uint32(i_spellProto->SchoolMask);
- pVictim->SendMessageToSet(&data, true );
-
- pVictim->DealDamage(this, damage, 0, SPELL_DIRECT_DAMAGE, GetSpellSchoolMask(i_spellProto), i_spellProto, true);
-
- if (pVictim->m_removedAurasCount > removedAuras)
- {
- removedAuras = pVictim->m_removedAurasCount;
- next = vDamageShields.begin();
- }
- }
- }
- }
-}
-
-void Unit::HandleEmoteCommand(uint32 anim_id)
-{
- WorldPacket data( SMSG_EMOTE, 4 + 8 );
- data << uint32(anim_id);
- data << uint64(GetGUID());
- SendMessageToSet(&data, true);
-}
-
-uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType)
-{
- uint32 newdamage = 0;
- float armor = pVictim->GetArmor();
-
- // Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura
- armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL);
-
- if (spellInfo)
- if (Player *modOwner = GetSpellModOwner())
- modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_IGNORE_ARMOR, armor);
-
- AuraEffectList const& ResIgnoreAurasAb = GetAuraEffectsByType(SPELL_AURA_MOD_ABILITY_IGNORE_TARGET_RESIST);
- for (AuraEffectList::const_iterator j = ResIgnoreAurasAb.begin(); j != ResIgnoreAurasAb.end(); ++j)
- {
- if ((*j)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL
- && (*j)->IsAffectedOnSpell(spellInfo))
- armor= int32(float(armor) * (float(100-(*j)->GetAmount())/100.0f));
- }
-
- AuraEffectList const& ResIgnoreAuras = GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_TARGET_RESIST);
- for (AuraEffectList::const_iterator j = ResIgnoreAuras.begin(); j != ResIgnoreAuras.end(); ++j)
- {
- if ((*j)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL)
- armor= int32(float(armor) * (float(100-(*j)->GetAmount())/100.0f));
- }
-
- if (GetTypeId() == TYPEID_PLAYER)
- {
- AuraEffectList const& ResIgnoreAuras = GetAuraEffectsByType(SPELL_AURA_MOD_ARMOR_PENETRATION_PCT);
- for (AuraEffectList::const_iterator itr = ResIgnoreAuras.begin(); itr != ResIgnoreAuras.end(); ++itr)
- {
- // item neutral spell
- if ((*itr)->GetSpellProto()->EquippedItemClass == -1)
- {
- armor = int32(float(armor) * (float(100-(*itr)->GetAmount())/100.0f));
- continue;
- }
-
- // item dependent spell - check curent weapons
- for (int i = 0; i < MAX_ATTACK; ++i)
- {
- Item *weapon = ((Player *)this)->GetWeaponForAttack(WeaponAttackType(i));
-
- if (weapon && weapon->IsFitToSpellRequirements((*itr)->GetSpellProto()))
- {
- armor= int32(float(armor) * (float(100-(*itr)->GetAmount())/100.0f));
- break;
- }
- }
- }
- }
-
- // Apply Player CR_ARMOR_PENETRATION rating
- if (GetTypeId() == TYPEID_PLAYER)
- {
- float maxArmorPen=0;
- if (getLevel()<60)
- maxArmorPen=400+85*pVictim->getLevel();
- else
- maxArmorPen=400+85*pVictim->getLevel()+4.5*85*(pVictim->getLevel()-59);
- // Cap armor penetration to this number
- maxArmorPen = std::min(((armor+maxArmorPen)/3),armor);
- // Figure out how much armor do we ignore
- float armorPen = maxArmorPen*((Player*)this)->GetRatingBonusValue(CR_ARMOR_PENETRATION) / 100.0f;
- // Got the value, apply it
- armor -= armorPen;
- }
- // Ignore enemy armor by SPELL_AURA_MOD_TARGET_ARMOR_PCT
- //armor *= 1.0f - GetTotalAuraModifier(SPELL_AURA_MOD_ARMOR_PENETRATION_PCT) / 100.0f;
-
- if (armor < 0.0f)
- armor = 0.0f;
-
- float levelModifier = getLevel();
- if (levelModifier > 59)
- levelModifier = levelModifier + (4.5f * (levelModifier-59));
-
- float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40);
- tmpvalue = tmpvalue/(1.0f + tmpvalue);
-
- if (tmpvalue < 0.0f)
- tmpvalue = 0.0f;
- if (tmpvalue > 0.75f)
- tmpvalue = 0.75f;
-
- newdamage = uint32(damage - (damage * tmpvalue));
-
- return (newdamage > 1) ? newdamage : 1;
-}
-
-void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist, SpellEntry const *spellInfo)
-{
- if (!pVictim || !pVictim->isAlive() || !damage)
- return;
-
- // Magic damage, check for resists
- if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL) == 0)
- {
- float baseVictimResistance = (float) pVictim->GetResistance(GetFirstSchoolInMask(schoolMask));
- float ignoredResistance = (float) GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask);
- float victimResistance = baseVictimResistance + ignoredResistance;
-
- uint32 BOSS_LEVEL = 83;
- float BOSS_RESISTANCE_CONSTANT = 510.0;
- uint32 level = getLevel();
- float resistanceConstant = 0.0f;
-
- if (level == BOSS_LEVEL)
- {
- resistanceConstant = BOSS_RESISTANCE_CONSTANT;
- }
- else
- {
- resistanceConstant = level * 5.0f;
- }
-
- float averageResist = victimResistance / (victimResistance + resistanceConstant);
- float discreteResistProbability[11];
- for (int i = 0; i < 11; i++)
- {
- discreteResistProbability[i] = 0.5f - 2.5f * abs(0.1f * i - averageResist);
- if (discreteResistProbability[i] < 0.0f)
- {
- discreteResistProbability[i] = 0.0f;
- }
- }
-
- if (averageResist <= 0.1f)
- {
- discreteResistProbability[0] = 1.0f - 7.5f * averageResist;
- discreteResistProbability[1] = 5.0f * averageResist;
- discreteResistProbability[2] = 2.5f * averageResist;
- }
-
- float r = rand_norm();
- int i = 0;
- float probabilitySum = discreteResistProbability[0];
- while (r >= probabilitySum && i < 10)
- {
- i++;
- probabilitySum += discreteResistProbability[i];
- }
- uint32 damageResisted = damage * i / 10;
-
- *resist += damageResisted;
-
- AuraEffectList const &ResIgnoreAurasAb = GetAuraEffectsByType(SPELL_AURA_MOD_ABILITY_IGNORE_TARGET_RESIST);
- for (AuraEffectList::const_iterator j = ResIgnoreAurasAb.begin(); j != ResIgnoreAurasAb.end(); ++j)
- {
- if ((*j)->GetMiscValue() & schoolMask
- && (*j)->IsAffectedOnSpell(spellInfo))
- *resist= int32(float(*resist) * (float(100-(*j)->GetAmount())/100.0f));
- }
-
- AuraEffectList const &ResIgnoreAuras = GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_TARGET_RESIST);
- for (AuraEffectList::const_iterator j = ResIgnoreAuras.begin(); j != ResIgnoreAuras.end(); ++j)
- {
- if ((*j)->GetMiscValue() & schoolMask)
- *resist= int32(float(*resist) * (float(100-(*j)->GetAmount())/100.0f));
- }
- }
- else
- *resist = 0;
-
- int32 RemainingDamage = damage - *resist;
- int32 TotalAbsorb = RemainingDamage;
- // Get unit state (need for some absorb check)
- uint32 unitflag = pVictim->GetUInt32Value(UNIT_FIELD_FLAGS);
- // Death Prevention Aura
- SpellEntry const* preventDeathSpell = NULL;
- int32 preventDeathAmount = 0;
- // Need remove expired auras after
- bool existExpired = false;
- TriggeredSpellInfoVct triggeredSpells;
- // absorb without mana cost
- AuraEffectList const& vSchoolAbsorb = pVictim->GetAuraEffectsByType(SPELL_AURA_SCHOOL_ABSORB);
- for (AuraEffectList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end() && RemainingDamage > 0; ++i)
- {
- if (!((*i)->GetMiscValue() & schoolMask))
- continue;
-
- SpellEntry const* spellProto = (*i)->GetSpellProto();
-
- // Max Amount can be absorbed by this aura
- int32 currentAbsorb = (*i)->GetAmount();
-
- // Found empty aura (impossible but..)
- if (currentAbsorb <= 0)
- {
- existExpired = true;
- continue;
- }
- // Handle custom absorb auras
- // TODO: try find better way
- switch (spellProto->SpellFamilyName)
- {
- case SPELLFAMILY_GENERIC:
- {
- // Astral Shift
- if (spellProto->SpellIconID == 3066)
- {
- //reduces all damage taken while stun, fear or silence
- if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
- RemainingDamage -= RemainingDamage * currentAbsorb / 100;
- continue;
- }
- // Nerves of Steel
- if (spellProto->SpellIconID == 2115)
- {
- // while affected by Stun and Fear
- if (unitflag&(UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING))
- RemainingDamage -= RemainingDamage * currentAbsorb / 100;
- continue;
- }
- // Spell Deflection
- if (spellProto->SpellIconID == 3006)
- {
- // You have a chance equal to your Parry chance
- if (damagetype == DIRECT_DAMAGE && // Only for direct damage
- roll_chance_f(pVictim->GetUnitParryChance())) // Roll chance
- RemainingDamage -= RemainingDamage * currentAbsorb / 100;
- continue;
- }
- // Reflective Shield (Lady Malande boss)
- if (spellProto->Id == 41475)
- {
- triggeredSpells.push_back(TriggeredSpellInfo(33619, pVictim, this,
- std::min(RemainingDamage, currentAbsorb) / 2, *i));
- break;
- }
- if (spellProto->Id == 39228 || // Argussian Compass
- spellProto->Id == 60218) // Essence of Gossamer
- {
- // Max absorb stored in 1 dummy effect
- if (spellProto->EffectBasePoints[1] < currentAbsorb)
- currentAbsorb = spellProto->EffectBasePoints[1];
- break;
- }
- break;
- }
- case SPELLFAMILY_DRUID:
- {
- // Primal Tenacity
- if (spellProto->SpellIconID == 2253)
- {
- //reduces all damage taken while Stunned
- if (unitflag & UNIT_FLAG_STUNNED)
- RemainingDamage -= RemainingDamage * currentAbsorb / 100;
- continue;
- }
- // Savage Defense (amount store original percent of attack power applied)
- if (spellProto->SpellIconID == 50) // only spell with this aura fit
- {
- RemainingDamage -= int32(currentAbsorb * pVictim->GetTotalAttackPowerValue(BASE_ATTACK) / 100);
- continue;
- }
- // Moonkin Form passive
- if (spellProto->Id == 69366)
- {
- //reduces all damage taken while Stunned
- if (unitflag & UNIT_FLAG_STUNNED)
- RemainingDamage -= RemainingDamage * currentAbsorb / 100;
- continue;
- }
- break;
- }
- case SPELLFAMILY_ROGUE:
- {
- // Cheat Death (make less prio with Guardian Spirit case)
- if (spellProto->SpellIconID == 2109)
- {
- if (!preventDeathSpell &&
- pVictim->GetTypeId() == TYPEID_PLAYER && // Only players
- !((Player*)pVictim)->HasSpellCooldown(31231) && // Only if no cooldown
- roll_chance_i((*i)->GetAmount())) // Only if roll
- {
- preventDeathSpell = (*i)->GetSpellProto();
- }
- continue;
- }
- break;
- }
- case SPELLFAMILY_PRIEST:
- {
- // Guardian Spirit
- if (spellProto->SpellIconID == 2873)
- {
- preventDeathSpell = (*i)->GetSpellProto();
- preventDeathAmount = (*i)->GetAmount();
- continue;
- }
-
- // Power Word: Shield
- if (spellProto->SpellFamilyFlags.IsEqual(0x1, 0, 0x400))
- {
- if (pVictim == this)
- break;
- Unit* caster = (*i)->GetCaster();
- if (!caster)
- break;
- // Reflective Shield
- if (AuraEffect const * aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_PRIEST, 566, 0))
- {
- switch(aurEff->GetMiscValue())
- {
- case 5065: // Rank 1
- case 5064: // Rank 2
- triggeredSpells.push_back(TriggeredSpellInfo(33619, pVictim, this,
- std::min(RemainingDamage, currentAbsorb) * aurEff->GetAmount() / 100, *i));
- break;
- default:
- sLog.outError("Unit::CalcAbsorbResist: unknown Reflective Shield spell %d", aurEff->GetId());
- break;
- }
- }
- }
- break;
- }
- case SPELLFAMILY_PALADIN:
- {
- // Ardent Defender
- if (spellProto->SpellIconID == 2135 && pVictim->GetTypeId() == TYPEID_PLAYER)
- {
- int32 remainingHealth = pVictim->GetHealth() - RemainingDamage;
- uint32 allowedHealth = pVictim->GetMaxHealth() * 0.35f;
- // If damage kills us
- if (remainingHealth <= 0 && !((Player*)pVictim)->HasSpellCooldown(66235))
- {
- // Cast healing spell, completely avoid damage
- RemainingDamage = 0;
-
- uint32 defenseSkillValue = pVictim->GetDefenseSkillValue();
- // Max heal when defense skill denies critical hits from raid bosses
- // Formula: max defense at level + 140 (raiting from gear)
- uint32 reqDefForMaxHeal = pVictim->getLevel() * 5 + 140;
- float pctFromDefense = (defenseSkillValue >= reqDefForMaxHeal)
- ? 1.0f
- : float(defenseSkillValue) / float(reqDefForMaxHeal);
-
- int32 healAmount = pVictim->GetMaxHealth() * (*i)->GetAmount() / 100.0f * pctFromDefense;
- pVictim->CastCustomSpell(pVictim, 66235, &healAmount, NULL, NULL, true);
- ((Player*)pVictim)->AddSpellCooldown(66235,0,time(NULL) + 120);
- }
- else if (remainingHealth < allowedHealth)
- {
- // Reduce damage that brings us under 35% (or full damage if we are already under 35%) by x%
- uint32 damageToReduce = (pVictim->GetHealth() < allowedHealth)
- ? RemainingDamage
- : allowedHealth - remainingHealth;
- RemainingDamage -= damageToReduce * currentAbsorb / 100;
- }
- continue;
-
- }
- break;
- }
- case SPELLFAMILY_SHAMAN:
- {
- // Astral Shift
- if (spellProto->SpellIconID == 3066)
- {
- //reduces all damage taken while stun, fear or silence
- if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
- RemainingDamage -= RemainingDamage * currentAbsorb / 100;
- continue;
- }
- break;
- }
- case SPELLFAMILY_DEATHKNIGHT:
- {
- switch (spellProto->Id)
- {
- case 51271: // Unbreakable Armor
- if (Unit *caster = (*i)->GetCaster())
- {
- uint32 absorbed = uint32( currentAbsorb * caster->GetArmor() * 0.01f );
-
- // Glyph of Unbreakable Armor
- if (AuraEffect *aurEff = caster->GetAuraEffect(58635, 0))
- absorbed += uint32(absorbed * aurEff->GetAmount() / 100);
-
- RemainingDamage -= absorbed;
- }
- continue;
- case 48707: // Anti-Magic Shell (on self)
- {
- // damage absorbed by Anti-Magic Shell energizes the DK with additional runic power.
- // This, if I'm not mistaken, shows that we get back ~2% of the absorbed damage as runic power.
- int32 absorbed = RemainingDamage * currentAbsorb / 100;
- RemainingDamage -= absorbed;
- triggeredSpells.push_back(TriggeredSpellInfo(49088, pVictim, pVictim, absorbed * 2 / 10, *i));
- continue;
- }
- case 50462: // Anti-Magic Shell (on single party/raid member)
- RemainingDamage -= RemainingDamage * currentAbsorb / 100;
- continue;
- case 50461: // Anti-Magic Zone
- if (Unit *caster = (*i)->GetCaster())
- {
- int32 absorbed = RemainingDamage * currentAbsorb / 100;
- int32 canabsorb = caster->GetHealth();
- if (canabsorb < absorbed)
- absorbed = canabsorb;
-
- RemainingDamage -= absorbed;
- }
- continue;
- default:
- break;
- }
- break;
- }
- default:
- break;
- }
-
- // currentAbsorb - damage can be absorbed by shield
- // If need absorb less damage
- if (RemainingDamage < currentAbsorb)
- currentAbsorb = RemainingDamage;
-
- RemainingDamage -= currentAbsorb;
-
- // Reduce shield amount
- (*i)->SetAmount((*i)->GetAmount() -currentAbsorb);
- // Need remove it later
- if ((*i)->GetAmount() <= 0)
- existExpired = true;
- }
-
- for (TriggeredSpellInfoVct::const_iterator itr = triggeredSpells.begin(); itr != triggeredSpells.end(); ++itr)
- {
- if (itr->spell)
- itr->source->CastCustomSpell(itr->spell, SPELLVALUE_BASE_POINT0, itr->amount, itr->target, true, NULL, itr->auraEff);
- else if (itr->amount > 0)
- {
- uint32 damage = uint32(itr->amount);
- itr->source->DealDamageMods(itr->target, damage, NULL);
- itr->source->DealDamage(itr->target, damage, NULL, damagetype, schoolMask, 0, false);
- }
- }
-
- // Remove all expired absorb auras
- if (existExpired)
- {
- for (AuraEffectList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end();)
- {
- AuraEffect * auraEff =(*i);
- ++i;
- if (auraEff->GetAmount()<=0)
- {
- uint32 removedAuras = pVictim->m_removedAurasCount;
- auraEff->GetBase()->Remove(AURA_REMOVE_BY_ENEMY_SPELL);
- if (removedAuras+1<pVictim->m_removedAurasCount)
- i=vSchoolAbsorb.begin();
- }
- }
- }
-
- // absorb by mana cost
- AuraEffectList const& vManaShield = pVictim->GetAuraEffectsByType(SPELL_AURA_MANA_SHIELD);
- for (AuraEffectList::const_iterator i = vManaShield.begin(), next; i != vManaShield.end() && RemainingDamage > 0; i = next)
- {
- next = i; ++next;
-
- // check damage school mask
- if (((*i)->GetMiscValue() & schoolMask)==0)
- continue;
-
- int32 currentAbsorb;
- if (RemainingDamage >= (*i)->GetAmount())
- currentAbsorb = (*i)->GetAmount();
- else
- currentAbsorb = RemainingDamage;
-
- if (float manaMultiplier = (*i)->GetSpellProto()->EffectMultipleValue[(*i)->GetEffIndex()])
- {
- if(Player *modOwner = pVictim->GetSpellModOwner())
- modOwner->ApplySpellMod((*i)->GetId(), SPELLMOD_MULTIPLE_VALUE, manaMultiplier);
-
- int32 maxAbsorb = int32(pVictim->GetPower(POWER_MANA) / manaMultiplier);
- if (currentAbsorb > maxAbsorb)
- currentAbsorb = maxAbsorb;
-
- int32 manaReduction = int32(currentAbsorb * manaMultiplier);
- pVictim->ApplyPowerMod(POWER_MANA, manaReduction, false);
- }
-
- (*i)->SetAmount((*i)->GetAmount()-currentAbsorb);
- if ((*i)->GetAmount() <= 0)
- {
- (*i)->GetBase()->Remove(AURA_REMOVE_BY_ENEMY_SPELL);
- next = vManaShield.begin();
- }
-
- RemainingDamage -= currentAbsorb;
- }
-
- // only split damage if not damaging yourself
- if (pVictim != this)
- {
- AuraEffectList const& vSplitDamageFlat = pVictim->GetAuraEffectsByType(SPELL_AURA_SPLIT_DAMAGE_FLAT);
- for (AuraEffectList::const_iterator i = vSplitDamageFlat.begin(), next; i != vSplitDamageFlat.end() && RemainingDamage >= 0; i = next)
- {
- next = i; ++next;
-
- // check damage school mask
- if (((*i)->GetMiscValue() & schoolMask) == 0)
- continue;
-
- // Damage can be splitted only if aura has an alive caster
- Unit *caster = (*i)->GetCaster();
- if (!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
- continue;
-
- int32 currentAbsorb;
- if (RemainingDamage >= (*i)->GetAmount())
- currentAbsorb = (*i)->GetAmount();
- else
- currentAbsorb = RemainingDamage;
-
- RemainingDamage -= currentAbsorb;
-
- uint32 splitted = currentAbsorb;
- uint32 splitted_absorb = 0;
- DealDamageMods(caster,splitted,&splitted_absorb);
-
- SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, splitted_absorb, 0, false, 0, false);
-
- CleanDamage cleanDamage = CleanDamage(splitted, 0, BASE_ATTACK, MELEE_HIT_NORMAL);
- DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
- }
-
- AuraEffectList const& vSplitDamagePct = pVictim->GetAuraEffectsByType(SPELL_AURA_SPLIT_DAMAGE_PCT);
- for (AuraEffectList::const_iterator i = vSplitDamagePct.begin(), next; i != vSplitDamagePct.end() && RemainingDamage >= 0; i = next)
- {
- next = i; ++next;
-
- // check damage school mask
- if (((*i)->GetMiscValue() & schoolMask)==0)
- continue;
-
- // Damage can be splitted only if aura has an alive caster
- Unit *caster = (*i)->GetCaster();
- if (!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
- continue;
-
- uint32 splitted = uint32(RemainingDamage * (*i)->GetAmount() / 100.0f);
-
- RemainingDamage -= int32(splitted);
-
- uint32 split_absorb = 0;
- DealDamageMods(caster,splitted,&split_absorb);
-
- SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, split_absorb, 0, false, 0, false);
-
- CleanDamage cleanDamage = CleanDamage(splitted, 0, BASE_ATTACK, MELEE_HIT_NORMAL);
- DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
- }
- }
-
- TotalAbsorb = (TotalAbsorb - RemainingDamage > 0) ? TotalAbsorb - RemainingDamage : 0;
- // TODO: School should be checked for absorbing auras or for attacks?
- int32 auraAbsorbMod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_TARGET_ABSORB_SCHOOL);
- AuraEffectList const& AbsIgnoreAurasAb = GetAuraEffectsByType(SPELL_AURA_MOD_TARGET_ABILITY_ABSORB_SCHOOL);
- for (AuraEffectList::const_iterator i = AbsIgnoreAurasAb.begin(); i != AbsIgnoreAurasAb.end(); ++i)
- {
- if ((*i)->GetAmount() > auraAbsorbMod
- && (*i)->IsAffectedOnSpell(spellInfo))
- auraAbsorbMod = (*i)->GetAmount();
- }
-
- // Ignore absorb - add reduced amount again to damage
- RemainingDamage += auraAbsorbMod * TotalAbsorb / 100;
-
- // Apply death prevention spells effects
- if (preventDeathSpell && RemainingDamage >= pVictim->GetHealth())
- {
- switch(preventDeathSpell->SpellFamilyName)
- {
- case SPELLFAMILY_ROGUE:
- {
- // Cheat Death
- if (preventDeathSpell->SpellIconID == 2109)
- {
- pVictim->CastSpell(pVictim,31231,true);
- ((Player*)pVictim)->AddSpellCooldown(31231,0,time(NULL)+60);
- // with health > 10% lost health until health==10%, in other case no losses
- uint32 health10 = pVictim->GetMaxHealth()/10;
- RemainingDamage = pVictim->GetHealth() > health10 ? pVictim->GetHealth() - health10 : 0;
- }
- break;
- }
- case SPELLFAMILY_PRIEST:
- {
- // Guardian Spirit
- if (preventDeathSpell->SpellIconID == 2873)
- {
- int32 healAmount = pVictim->GetMaxHealth() * preventDeathAmount / 100;
- pVictim->CastCustomSpell(pVictim, 48153, &healAmount, NULL, NULL, true);
- pVictim->RemoveAurasDueToSpell(preventDeathSpell->Id);
- RemainingDamage = 0;
- }
- break;
- }
- }
- }
-
- *absorb = RemainingDamage > 0 ? (damage - RemainingDamage - *resist) : (damage - *resist);
-
- if (*absorb)
- {
- // Incanter's Absorption
- // TODO: move this code to procflag
- if (AuraEffect const * aurEff = pVictim->GetDummyAuraEffect(SPELLFAMILY_GENERIC, 2941, 0))
- {
- // Get total damage bonus from auras
- int32 current_dmg = 0;
- std::pair<AuraApplicationMap::const_iterator, AuraApplicationMap::const_iterator> range = pVictim->GetAppliedAuras().equal_range(44413);
- for (AuraApplicationMap::const_iterator iter = range.first; iter != range.second; ++iter)
- if (AuraEffect const * bonusEff = iter->second->GetBase()->GetEffect(0))
- current_dmg += bonusEff->GetAmount();
-
- int32 new_dmg = (int32)*absorb * aurEff->GetAmount() / 100;
- int32 max_dmg = (int32)pVictim->GetMaxHealth() * 5 / 100;
- // Do not apply more auras if more than 5% hp
- if (current_dmg + new_dmg > max_dmg)
- new_dmg = max_dmg - current_dmg;
- if (new_dmg > 0)
- pVictim->CastCustomSpell(pVictim, 44413, &new_dmg, NULL, NULL, true);
- }
- }
-}
-
-void Unit::AttackerStateUpdate (Unit *pVictim, WeaponAttackType attType, bool extra )
-{
- if (hasUnitState(UNIT_STAT_CANNOT_AUTOATTACK) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) )
- return;
-
- if (!pVictim->isAlive())
- return;
-
- CombatStart(pVictim);
- RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MELEE_ATTACK);
-
- uint32 hitInfo;
- if (attType == BASE_ATTACK)
- hitInfo = HITINFO_NORMALSWING2;
- else if (attType == OFF_ATTACK)
- hitInfo = HITINFO_LEFTSWING;
- else
- return; // ignore ranged case
-
- // melee attack spell casted at main hand attack only
- if (attType == BASE_ATTACK && m_currentSpells[CURRENT_MELEE_SPELL])
- {
- m_currentSpells[CURRENT_MELEE_SPELL]->cast();
- return;
- }
-
- // attack can be redirected to another target
- pVictim = SelectMagnetTarget(pVictim);
-
- CalcDamageInfo damageInfo;
- CalculateMeleeDamage(pVictim, 0, &damageInfo, attType);
- // Send log damage message to client
- DealDamageMods(pVictim, damageInfo.damage, &damageInfo.absorb);
- SendAttackStateUpdate(&damageInfo);
-
- ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.damage, damageInfo.attackType);
- DealMeleeDamage(&damageInfo,true);
-
- if (GetTypeId() == TYPEID_PLAYER)
- DEBUG_LOG("AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
- GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
- else
- DEBUG_LOG("AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
- GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
-
- // if damage pVictim call AI reaction
- //if (pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->AI())
- // ((Creature*)pVictim)->AI()->AttackedBy(this);
-
-}
-
-MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType) const
-{
- // This is only wrapper
-
- // Miss chance based on melee
- //float miss_chance = MeleeMissChanceCalc(pVictim, attType);
- float miss_chance = MeleeSpellMissChance(pVictim, attType, int32(GetWeaponSkillValue(attType,pVictim)) - int32(pVictim->GetDefenseSkillValue(this)), 0);
-
- // Critical hit chance
- float crit_chance = GetUnitCriticalChance(attType, pVictim);
-
- // stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case)
- float dodge_chance = pVictim->GetUnitDodgeChance();
- float block_chance = pVictim->GetUnitBlockChance();
- float parry_chance = pVictim->GetUnitParryChance();
-
- // Useful if want to specify crit & miss chances for melee, else it could be removed
- DEBUG_LOG("MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance,crit_chance,dodge_chance,parry_chance,block_chance);
-
- return RollMeleeOutcomeAgainst(pVictim, attType, int32(crit_chance*100), int32(miss_chance*100), int32(dodge_chance*100),int32(parry_chance*100),int32(block_chance*100));
-}
-
-MeleeHitOutcome Unit::RollMeleeOutcomeAgainst (const Unit *pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const
-{
- if (pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
- return MELEE_HIT_EVADE;
-
- int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(pVictim);
- int32 victimMaxSkillValueForLevel = pVictim->GetMaxSkillValueForLevel(this);
-
- int32 attackerWeaponSkill = GetWeaponSkillValue(attType,pVictim);
- int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this);
-
- // bonus from skills is 0.04%
- int32 skillBonus = 4 * ( attackerWeaponSkill - victimMaxSkillValueForLevel );
- int32 sum = 0, tmp = 0;
- int32 roll = urand (0, 10000);
-
- DEBUG_LOG ("RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus);
- DEBUG_LOG ("RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d",
- roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance);
-
- tmp = miss_chance;
-
- if (tmp > 0 && roll < (sum += tmp ))
- {
- DEBUG_LOG ("RollMeleeOutcomeAgainst: MISS");
- return MELEE_HIT_MISS;
- }
-
- // always crit against a sitting target (except 0 crit chance)
- if (pVictim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !pVictim->IsStandState() )
- {
- DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT (sitting victim)");
- return MELEE_HIT_CRIT;
- }
-
- // Dodge chance
-
- // only players can't dodge if attacker is behind
- if (pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->HasInArc(M_PI,this) && !pVictim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
- {
- DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind and victim was a player.");
- }
- else
- {
- // Reduce dodge chance by attacker expertise rating
- if (GetTypeId() == TYPEID_PLAYER)
- dodge_chance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
- else
- dodge_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
-
- // Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
- dodge_chance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE)*100;
- dodge_chance = int32 (float (dodge_chance) * GetTotalAuraMultiplier(SPELL_AURA_MOD_ENEMY_DODGE));
-
- tmp = dodge_chance;
- if ( (tmp > 0) // check if unit _can_ dodge
- && ((tmp -= skillBonus) > 0)
- && roll < (sum += tmp))
- {
- DEBUG_LOG ("RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum-tmp, sum);
- return MELEE_HIT_DODGE;
- }
- }
-
- // parry & block chances
-
- // check if attack comes from behind, nobody can parry or block if attacker is behind
- if (!pVictim->HasInArc(M_PI,this) && !pVictim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
- {
- DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind.");
- }
- else
- {
- // Reduce parry chance by attacker expertise rating
- if (GetTypeId() == TYPEID_PLAYER)
- parry_chance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
- else
- parry_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
-
- if (pVictim->GetTypeId() == TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY) )
- {
- int32 tmp2 = int32(parry_chance);
- if (tmp2 > 0 // check if unit _can_ parry
- && (tmp2 -= skillBonus) > 0
- && roll < (sum += tmp2))
- {
- DEBUG_LOG ("RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum-tmp2, sum);
- return MELEE_HIT_PARRY;
- }
- }
-
- if (pVictim->GetTypeId() == TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) )
- {
- tmp = block_chance;
- if (tmp > 0 // check if unit _can_ block
- && (tmp -= skillBonus) > 0
- && roll < (sum += tmp))
- {
- DEBUG_LOG ("RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum-tmp, sum);
- return MELEE_HIT_BLOCK;
- }
- }
- }
-
- // Critical chance
- tmp = crit_chance;
-
- if (tmp > 0 && roll < (sum += tmp))
- {
- DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum-tmp, sum);
- if (GetTypeId() == TYPEID_UNIT && (((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRIT))
- DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT DISABLED)");
- else
- return MELEE_HIT_CRIT;
- }
-
- // Max 40% chance to score a glancing blow against mobs that are higher level (can do only players and pets and not with ranged weapon)
- if (attType != RANGED_ATTACK &&
- (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet()) &&
- pVictim->GetTypeId() != TYPEID_PLAYER && !((Creature*)pVictim)->isPet() &&
- getLevel() < pVictim->getLevelForTarget(this))
- {
- // cap possible value (with bonuses > max skill)
- int32 skill = attackerWeaponSkill;
- int32 maxskill = attackerMaxSkillValueForLevel;
- skill = (skill > maxskill) ? maxskill : skill;
-
- tmp = (10 + (victimDefenseSkill - skill)) * 100;
- tmp = tmp > 4000 ? 4000 : tmp;
- if (roll < (sum += tmp))
- {
- DEBUG_LOG ("RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum-4000, sum);
- return MELEE_HIT_GLANCING;
- }
- }
-
- // mobs can score crushing blows if they're 4 or more levels above victim
- if (getLevelForTarget(pVictim) >= pVictim->getLevelForTarget(this) + 4 &&
- // can be from by creature (if can) or from controlled player that considered as creature
- !IsControlledByPlayer() &&
- !(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH))
- {
- // when their weapon skill is 15 or more above victim's defense skill
- tmp = victimDefenseSkill;
- int32 tmpmax = victimMaxSkillValueForLevel;
- // having defense above your maximum (from items, talents etc.) has no effect
- tmp = tmp > tmpmax ? tmpmax : tmp;
- // tmp = mob's level * 5 - player's current defense skill
- tmp = attackerMaxSkillValueForLevel - tmp;
- if (tmp >= 15)
- {
- // add 2% chance per lacking skill point, min. is 15%
- tmp = tmp * 200 - 1500;
- if (roll < (sum += tmp))
- {
- DEBUG_LOG ("RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum-tmp, sum);
- return MELEE_HIT_CRUSHING;
- }
- }
- }
-
- DEBUG_LOG ("RollMeleeOutcomeAgainst: NORMAL");
- return MELEE_HIT_NORMAL;
-}
-
-uint32 Unit::CalculateDamage(WeaponAttackType attType, bool normalized, bool addTotalPct)
-{
- float min_damage, max_damage;
-
- if (GetTypeId() == TYPEID_PLAYER && (normalized || !addTotalPct))
- ((Player*)this)->CalculateMinMaxDamage(attType,normalized,addTotalPct,min_damage, max_damage);
- else
- {
- switch (attType)
- {
- case RANGED_ATTACK:
- min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE);
- max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE);
- break;
- case BASE_ATTACK:
- min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE);
- max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE);
- break;
- case OFF_ATTACK:
- min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE);
- max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE);
- break;
- // Just for good manner
- default:
- min_damage = 0.0f;
- max_damage = 0.0f;
- break;
- }
- }
-
- if (min_damage > max_damage)
- {
- std::swap(min_damage,max_damage);
- }
-
- if (max_damage == 0.0f)
- max_damage = 5.0f;
-
- return urand((uint32)min_damage, (uint32)max_damage);
-}
-
-float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const
-{
- if (spellProto->spellLevel <= 0)
- return 1.0f;
-
- float LvlPenalty = 0.0f;
-
- if (spellProto->spellLevel < 20)
- LvlPenalty = 20.0f - spellProto->spellLevel * 3.75f;
- float LvlFactor = (float(spellProto->spellLevel) + 6.0f) / float(getLevel());
- if (LvlFactor > 1.0f)
- LvlFactor = 1.0f;
-
- return (100.0f - LvlPenalty) * LvlFactor / 100.0f;
-}
-
-void Unit::SendMeleeAttackStart(Unit* pVictim)
-{
- WorldPacket data( SMSG_ATTACKSTART, 8 + 8 );
- data << uint64(GetGUID());
- data << uint64(pVictim->GetGUID());
-
- SendMessageToSet(&data, true);
- DEBUG_LOG( "WORLD: Sent SMSG_ATTACKSTART" );
-}
-
-void Unit::SendMeleeAttackStop(Unit* victim)
-{
- if (!victim)
- return;
-
- WorldPacket data( SMSG_ATTACKSTOP, (4+16) ); // we guess size
- data.append(GetPackGUID());
- data.append(victim->GetPackGUID()); // can be 0x00...
- data << uint32(0); // can be 0x1
- SendMessageToSet(&data, true);
- sLog.outDetail("%s %u stopped attacking %s %u", (GetTypeId() == TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), (victim->GetTypeId() == TYPEID_PLAYER ? "player" : "creature"),victim->GetGUIDLow());
-
- /*if (victim->GetTypeId() == TYPEID_UNIT)
- ((Creature*)victim)->AI().EnterEvadeMode(this);*/
-}
-
-bool Unit::isSpellBlocked(Unit *pVictim, SpellEntry const * /*spellProto*/, WeaponAttackType attackType)
-{
- if (pVictim->HasInArc(M_PI,this) || pVictim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
- {
- /* Currently not exist spells with ignore block
- // Ignore combat result aura (parry/dodge check on prepare)
- AuraList const& ignore = GetAuraEffectsByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
- for (AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
- {
- if (!(*i)->IsAffectedOnSpell(spellProto))
- continue;
- if ((*i)->GetMiscValue() == )
- return false;
- }
- */
-
- // Check creatures flags_extra for disable block
- if (pVictim->GetTypeId() == TYPEID_UNIT &&
- ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK )
- return false;
-
- float blockChance = pVictim->GetUnitBlockChance();
- blockChance += (int32(GetWeaponSkillValue(attackType)) - int32(pVictim->GetMaxSkillValueForLevel()))*0.04f;
- if (roll_chance_f(blockChance))
- return true;
- }
- return false;
-}
-
-bool Unit::isBlockCritical()
-{
- if (roll_chance_i(GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_CRIT_CHANCE)))
- return true;
- return false;
-}
-
-// Melee based spells can be miss, parry or dodge on this step
-// Crit or block - determined on damage calculation phase! (and can be both in some time)
-/*float Unit::MeleeSpellMissChance(Unit *pVictim, WeaponAttackType attType, int32 skillDiff, SpellEntry const *spell)
-{
- // Calculate hit chance (more correct for chance mod)
- int32 HitChance;
-
- // PvP - PvE melee chances
- int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
- int32 leveldif = pVictim->getLevelForTarget(this) - getLevelForTarget(pVictim);
- if (leveldif < 3)
- HitChance = 95 - leveldif;
- else
- HitChance = 93 - (leveldif - 2) * lchance;
-
- // Hit chance depends from victim auras
- if (attType == RANGED_ATTACK)
- HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
- else
- HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
-
- // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
- if (Player *modOwner = GetSpellModOwner())
- modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, HitChance);
-
- // Miss = 100 - hit
- float miss_chance= 100.0f - HitChance;
-
- // Bonuses from attacker aura and ratings
- if (attType == RANGED_ATTACK)
- miss_chance -= m_modRangedHitChance;
- else
- miss_chance -= m_modMeleeHitChance;
-
- // bonus from skills is 0.04%
- miss_chance -= skillDiff * 0.04f;
-
- // Limit miss chance from 0 to 60%
- if (miss_chance < 0.0f)
- return 0.0f;
- if (miss_chance > 60.0f)
- return 60.0f;
- return miss_chance;
-}*/
-
-int32 Unit::GetMechanicResistChance(const SpellEntry *spell)
-{
- if (!spell)
- return 0;
- int32 resist_mech = 0;
- for (uint8 eff = 0; eff < MAX_SPELL_EFFECTS; ++eff)
- {
- if (spell->Effect[eff] == 0)
- break;
- int32 effect_mech = GetEffectMechanic(spell, eff);
- if (effect_mech)
- {
- int32 temp = GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
- if (resist_mech < temp)
- resist_mech = temp;
- }
- }
- return resist_mech;
-}
-
-// Melee based spells hit result calculations
-SpellMissInfo Unit::MeleeSpellHitResult(Unit *pVictim, SpellEntry const *spell)
-{
- WeaponAttackType attType = BASE_ATTACK;
-
- // Check damage class instead of attack type to correctly handle judgements
- // - they are meele, but can't be dodged/parried/deflected because of ranged dmg class
- if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED)
- attType = RANGED_ATTACK;
-
- int32 attackerWeaponSkill;
- // skill value for these spells (for example judgements) is 5* level
- if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED && !IsRangedWeaponSpell(spell))
- attackerWeaponSkill = getLevel() * 5;
- // bonus from skills is 0.04% per skill Diff
- else
- attackerWeaponSkill = int32(GetWeaponSkillValue(attType,pVictim));
-
- int32 skillDiff = attackerWeaponSkill - int32(pVictim->GetMaxSkillValueForLevel(this));
- int32 fullSkillDiff = attackerWeaponSkill - int32(pVictim->GetDefenseSkillValue(this));
-
- uint32 roll = urand (0, 10000);
-
- uint32 missChance = uint32(MeleeSpellMissChance(pVictim, attType, fullSkillDiff, spell->Id)*100.0f);
- // Roll miss
- uint32 tmp = missChance;
- if (roll < tmp)
- return SPELL_MISS_MISS;
-
- // Chance resist mechanic (select max value from every mechanic spell effect)
- int32 resist_mech = 0;
- // Get effects mechanic and chance
- for (uint8 eff = 0; eff < MAX_SPELL_EFFECTS; ++eff)
- {
- int32 effect_mech = GetEffectMechanic(spell, eff);
- if (effect_mech)
- {
- int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
- if (resist_mech < temp*100)
- resist_mech = temp*100;
- }
- }
- // Roll chance
- tmp += resist_mech;
- if (roll < tmp)
- return SPELL_MISS_RESIST;
-
- bool canDodge = true;
- bool canParry = true;
- bool canBlock = spell->AttributesEx3 & SPELL_ATTR_EX3_BLOCKABLE_SPELL;
-
- // Same spells cannot be parry/dodge
- if (spell->Attributes & SPELL_ATTR_IMPOSSIBLE_DODGE_PARRY_BLOCK)
- return SPELL_MISS_NONE;
-
- // Chance resist mechanic
- int32 resist_chance = pVictim->GetMechanicResistChance(spell)*100;
- tmp += resist_chance;
- if (roll < tmp)
- return SPELL_MISS_RESIST;
-
- // Ranged attacks can only miss, resist and deflect
- if (attType == RANGED_ATTACK)
- {
- // only if in front
- if (pVictim->HasInArc(M_PI,this) || pVictim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
- {
- int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
- tmp+=deflect_chance;
- if (roll < tmp)
- return SPELL_MISS_DEFLECT;
- }
- return SPELL_MISS_NONE;
- }
-
- // Check for attack from behind
- if (!pVictim->HasInArc(M_PI,this) && !pVictim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
- {
- // Can`t dodge from behind in PvP (but its possible in PvE)
- if (pVictim->GetTypeId() == TYPEID_PLAYER)
- canDodge = false;
- // Can`t parry or block
- canParry = false;
- canBlock = false;
- }
- // Check creatures flags_extra for disable parry
- if (pVictim->GetTypeId() == TYPEID_UNIT)
- {
- uint32 flagEx = ((Creature*)pVictim)->GetCreatureInfo()->flags_extra;
- if (flagEx & CREATURE_FLAG_EXTRA_NO_PARRY)
- canParry = false;
- // Check creatures flags_extra for disable block
- if (flagEx & CREATURE_FLAG_EXTRA_NO_BLOCK)
- canBlock = false;
- }
- // Ignore combat result aura
- AuraEffectList const &ignore = GetAuraEffectsByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
- for (AuraEffectList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
- {
- if (!(*i)->IsAffectedOnSpell(spell))
- continue;
- switch ((*i)->GetMiscValue())
- {
- case MELEE_HIT_DODGE: canDodge = false; break;
- case MELEE_HIT_BLOCK: canBlock = false; break;
- case MELEE_HIT_PARRY: canParry = false; break;
- default:
- DEBUG_LOG("Spell %u SPELL_AURA_IGNORE_COMBAT_RESULT have unhandled state %d", (*i)->GetId(), (*i)->GetMiscValue());
- break;
- }
- }
-
- if (canDodge)
- {
- // Roll dodge
- int32 dodgeChance = int32(pVictim->GetUnitDodgeChance()*100.0f) - skillDiff * 4;
- // Reduce enemy dodge chance by SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
- dodgeChance += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE)*100;
- dodgeChance = int32(float(dodgeChance) * GetTotalAuraMultiplier(SPELL_AURA_MOD_ENEMY_DODGE));
- // Reduce dodge chance by attacker expertise rating
- if (GetTypeId() == TYPEID_PLAYER)
- dodgeChance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
- else
- dodgeChance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
- if (dodgeChance < 0)
- dodgeChance = 0;
-
- if (roll < (tmp += dodgeChance))
- return SPELL_MISS_DODGE;
- }
-
- if (canParry)
- {
- // Roll parry
- int32 parryChance = int32(pVictim->GetUnitParryChance()*100.0f) - skillDiff * 4;
- // Reduce parry chance by attacker expertise rating
- if (GetTypeId() == TYPEID_PLAYER)
- parryChance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
- else
- parryChance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
- if (parryChance < 0)
- parryChance = 0;
-
- tmp += parryChance;
- if (roll < tmp)
- return SPELL_MISS_PARRY;
- }
-
- if (canBlock)
- {
- int32 blockChance = int32(pVictim->GetUnitBlockChance()*100.0f) - skillDiff * 4;
- if (blockChance < 0)
- blockChance = 0;
- tmp += blockChance;
-
- if (roll < tmp)
- return SPELL_MISS_BLOCK;
- }
-
- return SPELL_MISS_NONE;
-}
-
-// TODO need use unit spell resistances in calculations
-SpellMissInfo Unit::MagicSpellHitResult(Unit *pVictim, SpellEntry const *spell)
-{
- // Can`t miss on dead target (on skinning for example)
- if (!pVictim->isAlive() && pVictim->GetTypeId() != TYPEID_PLAYER)
- return SPELL_MISS_NONE;
-
- SpellSchoolMask schoolMask = GetSpellSchoolMask(spell);
- // PvP - PvE spell misschances per leveldif > 2
- int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 7 : 11;
- int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
-
- // Base hit chance from attacker and victim levels
- int32 modHitChance;
- if (leveldif < 3)
- modHitChance = 96 - leveldif;
- else
- modHitChance = 94 - (leveldif - 2) * lchance;
-
- // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
- if (Player *modOwner = GetSpellModOwner())
- modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance);
- // Increase from attacker SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT auras
- modHitChance+=GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT, schoolMask);
- // Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras
- modHitChance+= pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask);
- // Reduce spell hit chance for Area of effect spells from victim SPELL_AURA_MOD_AOE_AVOIDANCE aura
- if (IsAreaOfEffectSpell(spell))
- modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE);
- // Reduce spell hit chance for dispel mechanic spells from victim SPELL_AURA_MOD_DISPEL_RESIST
- if (IsDispelSpell(spell))
- modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_DISPEL_RESIST);
-
- int32 HitChance = modHitChance * 100;
- // Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings
- HitChance += int32(m_modSpellHitChance*100.0f);
-
- // Decrease hit chance from victim rating bonus
- if (pVictim->GetTypeId() == TYPEID_PLAYER)
- HitChance -= int32(((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_SPELL)*100.0f);
-
- if (HitChance < 100)
- HitChance = 100;
- else if (HitChance > 10000)
- HitChance = 10000;
-
- int32 tmp = 10000 - HitChance;
-
- uint32 rand = urand(0,10000);
-
- if (rand < tmp)
- return SPELL_MISS_MISS;
-
- // Chance resist mechanic (select max value from every mechanic spell effect)
- int32 resist_chance = pVictim->GetMechanicResistChance(spell);
- tmp += resist_chance;
-
- // Chance resist debuff
- tmp -= pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel));
-
- // Roll chance
- if (rand < tmp)
- return SPELL_MISS_RESIST;
-
- // cast by caster in front of victim
- if (pVictim->HasInArc(M_PI,this) || pVictim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
- {
- int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
- tmp+=deflect_chance;
- if (rand < tmp)
- return SPELL_MISS_DEFLECT;
- }
-
- return SPELL_MISS_NONE;
-}
-
-// Calculate spell hit result can be:
-// Every spell can: Evade/Immune/Reflect/Sucesful hit
-// For melee based spells:
-// Miss
-// Dodge
-// Parry
-// For spells
-// Resist
-SpellMissInfo Unit::SpellHitResult(Unit *pVictim, SpellEntry const *spell, bool CanReflect)
-{
- // Return evade for units in evade mode
- if (pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode() && this != pVictim)
- return SPELL_MISS_EVADE;
-
- // Check for immune
- if (pVictim->IsImmunedToSpell(spell))
- return SPELL_MISS_IMMUNE;
-
- // All positive spells can`t miss
- // TODO: client not show miss log for this spells - so need find info for this in dbc and use it!
- if (IsPositiveSpell(spell->Id)
- &&(!IsHostileTo(pVictim))) //prevent from affecting enemy by "positive" spell
- return SPELL_MISS_NONE;
- // Check for immune
- if (pVictim->IsImmunedToDamage(spell))
- return SPELL_MISS_IMMUNE;
-
- if(this == pVictim)
- return SPELL_MISS_NONE;
-
- // Try victim reflect spell
- if (CanReflect)
- {
- int32 reflectchance = pVictim->GetTotalAuraModifier(SPELL_AURA_REFLECT_SPELLS);
- Unit::AuraEffectList const& mReflectSpellsSchool = pVictim->GetAuraEffectsByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL);
- for (Unit::AuraEffectList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i)
- if((*i)->GetMiscValue() & GetSpellSchoolMask(spell))
- reflectchance += (*i)->GetAmount();
- if (reflectchance > 0 && roll_chance_i(reflectchance))
- {
- // Start triggers for remove charges if need (trigger only for victim, and mark as active spell)
- ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_TAKEN_NEGATIVE_MAGIC_SPELL, PROC_EX_REFLECT, 1, BASE_ATTACK, spell);
- return SPELL_MISS_REFLECT;
- }
- }
-
- switch (spell->DmgClass)
- {
- case SPELL_DAMAGE_CLASS_RANGED:
- case SPELL_DAMAGE_CLASS_MELEE:
- return MeleeSpellHitResult(pVictim, spell);
- case SPELL_DAMAGE_CLASS_NONE:
- return SPELL_MISS_NONE;
- case SPELL_DAMAGE_CLASS_MAGIC:
- return MagicSpellHitResult(pVictim, spell);
- }
- return SPELL_MISS_NONE;
-}
-
-/*float Unit::MeleeMissChanceCalc(const Unit *pVictim, WeaponAttackType attType) const
-{
- if(!pVictim)
- return 0.0f;
-
- // Base misschance 5%
- float misschance = 5.0f;
-
- // DualWield - Melee spells and physical dmg spells - 5% , white damage 24%
- if (haveOffhandWeapon() && attType != RANGED_ATTACK)
- {
- bool isNormal = false;
- for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
- {
- if( m_currentSpells[i] && (GetSpellSchoolMask(m_currentSpells[i]->m_spellInfo) & SPELL_SCHOOL_MASK_NORMAL) )
- {
- isNormal = true;
- break;
- }
- }
- if (isNormal || m_currentSpells[CURRENT_MELEE_SPELL])
- misschance = 5.0f;
- else
- misschance = 24.0f;
- }
-
- // PvP : PvE melee misschances per leveldif > 2
- int32 chance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
-
- int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
- if(leveldif < 0)
- leveldif = 0;
-
- // Hit chance from attacker based on ratings and auras
- float m_modHitChance;
- if (attType == RANGED_ATTACK)
- m_modHitChance = m_modRangedHitChance;
- else
- m_modHitChance = m_modMeleeHitChance;
-
- if(leveldif < 3)
- misschance += (leveldif - m_modHitChance);
- else
- misschance += ((leveldif - 2) * chance - m_modHitChance);
-
- // Hit chance for victim based on ratings
- if (pVictim->GetTypeId() == TYPEID_PLAYER)
- {
- if (attType == RANGED_ATTACK)
- misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_RANGED);
- else
- misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_MELEE);
- }
-
- // Modify miss chance by victim auras
- if(attType == RANGED_ATTACK)
- misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
- else
- misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
-
- // Modify miss chance from skill difference ( bonus from skills is 0.04% )
- int32 skillBonus = int32(GetWeaponSkillValue(attType,pVictim)) - int32(pVictim->GetDefenseSkillValue(this));
- misschance -= skillBonus * 0.04f;
-
- // Limit miss chance from 0 to 60%
- if ( misschance < 0.0f)
- return 0.0f;
- if ( misschance > 60.0f)
- return 60.0f;
-
- return misschance;
-}*/
-
-uint32 Unit::GetDefenseSkillValue(Unit const* target) const
-{
- if(GetTypeId() == TYPEID_PLAYER)
- {
- // in PvP use full skill instead current skill value
- uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER)
- ? ((Player*)this)->GetMaxSkillValue(SKILL_DEFENSE)
- : ((Player*)this)->GetSkillValue(SKILL_DEFENSE);
- value += uint32(((Player*)this)->GetRatingBonusValue(CR_DEFENSE_SKILL));
- return value;
- }
- else
- return GetUnitMeleeSkill(target);
-}
-
-float Unit::GetUnitDodgeChance() const
-{
- if(hasUnitState(UNIT_STAT_STUNNED))
- return 0.0f;
- if( GetTypeId() == TYPEID_PLAYER )
- return GetFloatValue(PLAYER_DODGE_PERCENTAGE);
- else
- {
- if(((Creature const*)this)->isTotem())
- return 0.0f;
- else
- {
- float dodge = 5.0f;
- dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT);
- return dodge > 0.0f ? dodge : 0.0f;
- }
- }
-}
-
-float Unit::GetUnitParryChance() const
-{
- if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
- return 0.0f;
-
- float chance = 0.0f;
-
- if(GetTypeId() == TYPEID_PLAYER)
- {
- Player const* player = (Player const*)this;
- if(player->CanParry() )
- {
- Item *tmpitem = player->GetWeaponForAttack(BASE_ATTACK,true);
- if(!tmpitem)
- tmpitem = player->GetWeaponForAttack(OFF_ATTACK,true);
-
- if(tmpitem)
- chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE);
- }
- }
- else if(GetTypeId() == TYPEID_UNIT)
- {
- if(GetCreatureType() == CREATURE_TYPE_HUMANOID)
- {
- chance = 5.0f;
- chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT);
- }
- }
-
- return chance > 0.0f ? chance : 0.0f;
-}
-
-float Unit::GetUnitBlockChance() const
-{
- if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
- return 0.0f;
-
- if(GetTypeId() == TYPEID_PLAYER)
- {
- Player const* player = (Player const*)this;
- if(player->CanBlock() )
- {
- Item *tmpitem = player->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
- if(tmpitem && !tmpitem->IsBroken() && tmpitem->GetProto()->Block)
- return GetFloatValue(PLAYER_BLOCK_PERCENTAGE);
- }
- // is player but has no block ability or no not broken shield equipped
- return 0.0f;
- }
- else
- {
- if(((Creature const*)this)->isTotem())
- return 0.0f;
- else
- {
- float block = 5.0f;
- block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT);
- return block > 0.0f ? block : 0.0f;
- }
- }
-}
-
-float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit *pVictim) const
-{
- float crit;
-
- if(GetTypeId() == TYPEID_PLAYER)
- {
- switch(attackType)
- {
- case BASE_ATTACK:
- crit = GetFloatValue( PLAYER_CRIT_PERCENTAGE );
- break;
- case OFF_ATTACK:
- crit = GetFloatValue( PLAYER_OFFHAND_CRIT_PERCENTAGE );
- break;
- case RANGED_ATTACK:
- crit = GetFloatValue( PLAYER_RANGED_CRIT_PERCENTAGE );
- break;
- // Just for good manner
- default:
- crit = 0.0f;
- break;
- }
- }
- else
- {
- crit = 5.0f;
- crit += GetTotalAuraModifier(SPELL_AURA_MOD_WEAPON_CRIT_PERCENT);
- crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PCT);
- }
-
- // flat aura mods
- if(attackType == RANGED_ATTACK)
- crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE);
- else
- crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE);
-
- crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
-
- // reduce crit chance from Rating for players
- if (attackType != RANGED_ATTACK)
- {
- crit -= pVictim->GetMeleeCritChanceReduction();
- // Glyph of barkskin
- if (pVictim->HasAura(63057) && pVictim->HasAura(22812))
- crit-=25.0f;
- }
- else
- crit -= pVictim->GetRangedCritChanceReduction();
-
- // Apply crit chance from defence skill
- crit += (int32(GetMaxSkillValueForLevel(pVictim)) - int32(pVictim->GetDefenseSkillValue(this))) * 0.04f;
-
- if (crit < 0.0f)
- crit = 0.0f;
- return crit;
-}
-
-uint32 Unit::GetWeaponSkillValue (WeaponAttackType attType, Unit const* target) const
-{
- uint32 value = 0;
- if(GetTypeId() == TYPEID_PLAYER)
- {
- Item* item = ((Player*)this)->GetWeaponForAttack(attType,true);
-
- // feral or unarmed skill only for base attack
- if (attType != BASE_ATTACK && !item)
- return 0;
-
- if (IsInFeralForm())
- return GetMaxSkillValueForLevel(); // always maximized SKILL_FERAL_COMBAT in fact
-
- // weapon skill or (unarmed for base attack and fist weapons)
- uint32 skill = item && item->GetSkill() != SKILL_FIST_WEAPONS ? item->GetSkill() : SKILL_UNARMED;
-
- // in PvP use full skill instead current skill value
- value = (target && target->IsControlledByPlayer())
- ? ((Player*)this)->GetMaxSkillValue(skill)
- : ((Player*)this)->GetSkillValue(skill);
- // Modify value from ratings
- value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL));
- switch (attType)
- {
- case BASE_ATTACK: value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_MAINHAND)); break;
- case OFF_ATTACK: value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_OFFHAND)); break;
- case RANGED_ATTACK: value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_RANGED)); break;
- }
- }
- else
- value = GetUnitMeleeSkill(target);
- return value;
-}
-
-void Unit::_DeleteRemovedAuras()
-{
- while(!m_removedAuras.empty())
- {
- delete m_removedAuras.front();
- m_removedAuras.pop_front();
- }
-}
-
-void Unit::_UpdateSpells( uint32 time )
-{
- if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
- _UpdateAutoRepeatSpell();
-
- // remove finished spells from current pointers
- for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
- {
- if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED)
- {
- m_currentSpells[i]->SetReferencedFromCurrent(false);
- m_currentSpells[i] = NULL; // remove pointer
- }
- }
-
- // m_auraUpdateIterator can be updated in indirect called code at aura remove to skip next planned to update but removed auras
- for (m_auraUpdateIterator = m_ownedAuras.begin(); m_auraUpdateIterator != m_ownedAuras.end();)
- {
- Aura * i_aura = m_auraUpdateIterator->second;
- ++m_auraUpdateIterator; // need shift to next for allow update if need into aura update
- i_aura->UpdateOwner(time, this);
- }
-
- // remove expired auras - do that after updates(used in scripts?)
- for (AuraMap::iterator i = m_ownedAuras.begin(); i != m_ownedAuras.end();)
- {
- if(i->second->IsExpired())
- RemoveOwnedAura(i, AURA_REMOVE_BY_EXPIRE);
- else
- ++i;
- }
-
- for (VisibleAuraMap::iterator itr = m_visibleAuras.begin(); itr != m_visibleAuras.end(); ++itr)
- if (itr->second->IsNeedClientUpdate())
- itr->second->ClientUpdate();
-
- _DeleteRemovedAuras();
-
- if(!m_gameObj.empty())
- {
- GameObjectList::iterator itr;
- for (itr = m_gameObj.begin(); itr != m_gameObj.end();)
- {
- if( !(*itr)->isSpawned() )
- {
- (*itr)->SetOwnerGUID(0);
- (*itr)->SetRespawnTime(0);
- (*itr)->Delete();
- m_gameObj.erase(itr++);
- }
- else
- ++itr;
- }
- }
-}
-
-void Unit::_UpdateAutoRepeatSpell()
-{
- //check "realtime" interrupts
- if ( (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->isMoving()) || IsNonMeleeSpellCasted(false,false,true,m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id == 75) )
- {
- // cancel wand shoot
- if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75)
- InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
- m_AutoRepeatFirstCast = true;
- return;
- }
-
- //apply delay
- if ( m_AutoRepeatFirstCast && getAttackTimer(RANGED_ATTACK) < 500 )
- setAttackTimer(RANGED_ATTACK,500);
- m_AutoRepeatFirstCast = false;
-
- //castroutine
- if (isAttackReady(RANGED_ATTACK))
- {
- // Check if able to cast
- if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->CheckCast(true) != SPELL_CAST_OK)
- {
- InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
- return;
- }
-
- // we want to shoot
- Spell* spell = new Spell(this, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, true, 0);
- spell->prepare(&(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_targets));
-
- // all went good, reset attack
- resetAttackTimer(RANGED_ATTACK);
- }
-}
-
-void Unit::SetCurrentCastedSpell( Spell * pSpell )
-{
- assert(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells
-
- CurrentSpellTypes CSpellType = pSpell->GetCurrentContainer();
-
- if (pSpell == m_currentSpells[CSpellType]) return; // avoid breaking self
-
- // break same type spell if it is not delayed
- InterruptSpell(CSpellType,false);
-
- // special breakage effects:
- switch (CSpellType)
- {
- case CURRENT_GENERIC_SPELL:
- {
- // generic spells always break channeled not delayed spells
- InterruptSpell(CURRENT_CHANNELED_SPELL,false);
-
- // autorepeat breaking
- if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
- {
- // break autorepeat if not Auto Shot
- if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75)
- InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
- m_AutoRepeatFirstCast = true;
- }
- addUnitState(UNIT_STAT_CASTING);
- } break;
-
- case CURRENT_CHANNELED_SPELL:
- {
- // channel spells always break generic non-delayed and any channeled spells
- InterruptSpell(CURRENT_GENERIC_SPELL,false);
- InterruptSpell(CURRENT_CHANNELED_SPELL);
-
- // it also does break autorepeat if not Auto Shot
- if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] &&
- m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75 )
- InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
- addUnitState(UNIT_STAT_CASTING);
- } break;
-
- case CURRENT_AUTOREPEAT_SPELL:
- {
- // only Auto Shoot does not break anything
- if (pSpell->m_spellInfo->Id != 75)
- {
- // generic autorepeats break generic non-delayed and channeled non-delayed spells
- InterruptSpell(CURRENT_GENERIC_SPELL,false);
- InterruptSpell(CURRENT_CHANNELED_SPELL,false);
- }
- // special action: set first cast flag
- m_AutoRepeatFirstCast = true;
- } break;
-
- default:
- {
- // other spell types don't break anything now
- } break;
- }
-
- // current spell (if it is still here) may be safely deleted now
- if (m_currentSpells[CSpellType])
- m_currentSpells[CSpellType]->SetReferencedFromCurrent(false);
-
- // set new current spell
- m_currentSpells[CSpellType] = pSpell;
- pSpell->SetReferencedFromCurrent(true);
-
- pSpell->m_selfContainer = &(m_currentSpells[pSpell->GetCurrentContainer()]);
-}
-
-void Unit::InterruptSpell(CurrentSpellTypes spellType, bool withDelayed, bool withInstant)
-{
- assert(spellType < CURRENT_MAX_SPELL);
-
- //sLog.outDebug("Interrupt spell for unit %u.", GetEntry());
- Spell *spell = m_currentSpells[spellType];
- if(spell
- && (withDelayed || spell->getState() != SPELL_STATE_DELAYED)
- && (withInstant || spell->GetCastTime() > 0))
- {
- // for example, do not let self-stun aura interrupt itself
- if(!spell->IsInterruptable())
- return;
-
- m_currentSpells[spellType] = NULL;
-
- // send autorepeat cancel message for autorepeat spells
- if (spellType == CURRENT_AUTOREPEAT_SPELL)
- {
- if(GetTypeId() == TYPEID_PLAYER)
- ((Player*)this)->SendAutoRepeatCancel(this);
- }
-
- if (spell->getState() != SPELL_STATE_FINISHED)
- spell->cancel();
- spell->SetReferencedFromCurrent(false);
- }
-}
-
-void Unit::FinishSpell(CurrentSpellTypes spellType, bool ok /*= true*/)
-{
- Spell* spell = m_currentSpells[spellType];
- if (!spell)
- return;
-
- if (spellType == CURRENT_CHANNELED_SPELL)
- spell->SendChannelUpdate(0);
-
- spell->finish(ok);
-}
-
-bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat, bool isAutoshoot) const
-{
- // We don't do loop here to explicitly show that melee spell is excluded.
- // Maybe later some special spells will be excluded too.
-
- // generic spells are casted when they are not finished and not delayed
- if ( m_currentSpells[CURRENT_GENERIC_SPELL] &&
- (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
- (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
- {
- if (!isAutoshoot || !(m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_NOT_RESET_AUTOSHOT))
- return(true);
- }
- // channeled spells may be delayed, but they are still considered casted
- else if ( !skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] &&
- (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED) )
- {
- if (!isAutoshoot || !(m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_NOT_RESET_AUTOSHOT))
- return(true);
- }
- // autorepeat spells may be finished or delayed, but they are still considered casted
- else if ( !skipAutorepeat && m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
- return(true);
-
- return(false);
-}
-
-void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id, bool withInstant)
-{
- // generic spells are interrupted if they are not finished or delayed
- if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id==spell_id))
- InterruptSpell(CURRENT_GENERIC_SPELL,withDelayed,withInstant);
-
- // autorepeat spells are interrupted if they are not finished or delayed
- if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id==spell_id))
- InterruptSpell(CURRENT_AUTOREPEAT_SPELL,withDelayed,withInstant);
-
- // channeled spells are interrupted if they are not finished, even if they are delayed
- if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id==spell_id))
- InterruptSpell(CURRENT_CHANNELED_SPELL,true,true);
-}
-
-Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const
-{
- for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
- if(m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id==spell_id)
- return m_currentSpells[i];
- return NULL;
-}
-
-int32 Unit::GetCurrentSpellCastTime(uint32 spell_id) const
-{
- if (Spell const * spell = FindCurrentSpellBySpellId(spell_id))
- return spell->GetCastTime();
- return 0;
-}
-
-bool Unit::isInFrontInMap(Unit const* target, float distance, float arc) const
-{
- return IsWithinDistInMap(target, distance) && HasInArc( arc, target );
-}
-
-bool Unit::isInBackInMap(Unit const* target, float distance, float arc) const
-{
- return IsWithinDistInMap(target, distance) && !HasInArc( 2 * M_PI - arc, target );
-}
-
-void Unit::SetFacingToObject(WorldObject* pObject)
-{
- // update orientation at server
- SetOrientation(GetAngle(pObject));
-
- // and client
- WorldPacket data;
- BuildHeartBeatMsg(&data);
- SendMessageToSet(&data, false);
-}
-
-bool Unit::isInAccessiblePlaceFor(Creature const* c) const
-{
- if(IsInWater())
- return c->canSwim();
- else
- return c->canWalk() || c->canFly();
-}
-
-bool Unit::IsInWater() const
-{
- return GetBaseMap()->IsInWater(GetPositionX(),GetPositionY(), GetPositionZ());
-}
-
-bool Unit::IsUnderWater() const
-{
- return GetBaseMap()->IsUnderWater(GetPositionX(),GetPositionY(),GetPositionZ());
-}
-
-void Unit::DeMorph()
-{
- SetDisplayId(GetNativeDisplayId());
-}
-
-void Unit::_AddAura(UnitAura * aura, Unit * caster)
-{
- assert(!m_cleanupDone);
- m_ownedAuras.insert(AuraMap::value_type(aura->GetId(), aura));
-
- // passive and Incanter's Absorption and auras with different type can stack with themselves any number of times
- if (!aura->IsPassive() && aura->GetId() != 44413)
- {
- // find current aura from spell and change it's stackamount
- if (Aura * foundAura = GetOwnedAura(aura->GetId(), aura->GetCasterGUID(), 0, aura))
- {
- if(aura->GetSpellProto()->StackAmount)
- aura->ModStackAmount(foundAura->GetStackAmount());
-
- // Use the new one to replace the old one
- // This is the only place where AURA_REMOVE_BY_STACK should be used
- RemoveOwnedAura(foundAura, AURA_REMOVE_BY_STACK);
- }
- }
- _RemoveNoStackAurasDueToAura(aura);
-
- if (aura->IsRemoved())
- return;
-
- aura->SetIsSingleTarget(caster && IsSingleTargetSpell(aura->GetSpellProto()));
- if (aura->IsSingleTarget())
- {
- // register single target aura
- caster->GetSingleCastAuras().push_back(aura);
- // remove other single target auras
- for (;;)
- {
- bool restart = false;
- Unit::AuraList& scAuras = caster->GetSingleCastAuras();
- for (Unit::AuraList::iterator itr = scAuras.begin(); itr != scAuras.end(); ++itr)
- {
- if( (*itr) != aura &&
- IsSingleTargetSpells((*itr)->GetSpellProto(), aura->GetSpellProto()))
- {
- (*itr)->Remove();
- restart = true;
- break;
- }
- }
-
- if(!restart)
- break;
- }
- }
-}
-
-// creates aura application instance and registers it in lists
-// aura application effects are handled separately to prevent aura list corruption
-AuraApplication * Unit::_CreateAuraApplication(Aura * aura, uint8 effMask)
-{
- // can't apply aura on unit which is going to be deleted - to not create a memory leak
- assert(!m_cleanupDone);
- // aura musn't be removed
- assert(!aura->IsRemoved());
-
- SpellEntry const* aurSpellInfo = aura->GetSpellProto();
- uint32 aurId = aurSpellInfo->Id;
-
- // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load)
- if( !isAlive() && !IsDeathPersistentSpell(aurSpellInfo) &&
- (GetTypeId() != TYPEID_PLAYER || !((Player*)this)->GetSession()->PlayerLoading()) )
- return NULL;
-
- Unit * caster = aura->GetCaster();
-
- AuraApplication * aurApp = new AuraApplication(this, caster, aura, effMask);
- m_appliedAuras.insert(AuraApplicationMap::value_type(aurId, aurApp));
-
- if(aurSpellInfo->AuraInterruptFlags)
- {
- m_interruptableAuras.push_back(aurApp);
- AddInterruptMask(aurSpellInfo->AuraInterruptFlags);
- }
-
- if(AuraState aState = GetSpellAuraState(aura->GetSpellProto()))
- m_auraStateAuras.insert(AuraStateAurasMap::value_type(aState, aurApp));
-
- aura->_ApplyForTarget(this, caster, aurApp);
- return aurApp;
-}
-
-void Unit::_ApplyAuraEffect(Aura * aura, uint8 effIndex)
-{
- assert(aura);
- assert(aura->HasEffect(effIndex));
- AuraApplication * aurApp = aura->GetApplicationOfTarget(GetGUID());
- assert(aurApp);
- if (!aurApp->GetEffectMask())
- _ApplyAura(aurApp, 1<<effIndex);
- else
- aurApp->_HandleEffect(effIndex, true);
-}
-
-// handles effects of aura application
-// should be done after registering aura in lists
-void Unit::_ApplyAura(AuraApplication * aurApp, uint8 effMask)
-{
- Aura * aura = aurApp->GetBase();
-
- _RemoveNoStackAurasDueToAura(aura);
-
- if (aurApp->GetRemoveMode())
- return;
-
- // Update target aura state flag
- if(AuraState aState = GetSpellAuraState(aura->GetSpellProto()))
- ModifyAuraState(aState, true);
-
- if (aurApp->GetRemoveMode())
- return;
-
- // Sitdown on apply aura req seated
- if (aura->GetSpellProto()->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED && !IsSitState())
- SetStandState(UNIT_STAND_STATE_SIT);
-
- Unit * caster = aura->GetCaster();
-
- if (aurApp->GetRemoveMode())
- return;
-
- aura->HandleAuraSpecificMods(aurApp, caster, true);
-
- // apply effects of the aura
- for (uint8 i = 0 ; i < MAX_SPELL_EFFECTS; ++i)
- {
- if (effMask & 1<<i && (!aurApp->GetRemoveMode()))
- aurApp->_HandleEffect(i, true);
- }
-}
-
-// removes aura application from lists and unapplies effects
-void Unit::_UnapplyAura(AuraApplicationMap::iterator &i, AuraRemoveMode removeMode)
-{
- AuraApplication * aurApp = i->second;
- assert(aurApp);
- assert(!aurApp->GetRemoveMode());
- assert(aurApp->GetTarget() == this);
- aurApp->SetRemoveMode(removeMode);
- Aura * aura = aurApp->GetBase();
- sLog.outDebug("Aura %u now is remove mode %d", aura->GetId(), removeMode);
-
- // dead loop is killing the server probably
- assert(m_removedAurasCount < 0xFFFFFFFF);
-
- ++m_removedAurasCount;
-
- Unit * caster = aura->GetCaster();
-
- // Remove all pointers from lists here to prevent possible pointer invalidation on spellcast/auraapply/auraremove
- m_appliedAuras.erase(i);
-
- if (aura->GetSpellProto()->AuraInterruptFlags)
- {
- m_interruptableAuras.remove(aurApp);
- UpdateInterruptMask();
- }
-
- bool auraStateFound = false;
- AuraState auraState;
- if (auraState = GetSpellAuraState(aura->GetSpellProto()))
- {
- bool canBreak = false;
- // Get mask of all aurastates from remaining auras
- for (AuraStateAurasMap::iterator itr = m_auraStateAuras.lower_bound(auraState); itr != m_auraStateAuras.upper_bound(auraState) && !(auraStateFound && canBreak);)
- {
- if (itr->second == aurApp)
- {
- m_auraStateAuras.erase(itr);
- itr = m_auraStateAuras.lower_bound(auraState);
- canBreak = true;
- continue;
- }
- auraStateFound = true;
- ++itr;
- }
- }
-
- aurApp->_Remove();
- aura->_UnapplyForTarget(this, caster, aurApp);
-
- // remove effects of the spell - needs to be done after removing aura from lists
- for (uint8 itr = 0 ; itr < MAX_SPELL_EFFECTS; ++itr)
- {
- if (aurApp->HasEffect(itr))
- aurApp->_HandleEffect(itr, false);
- }
-
- // all effect mustn't be applied
- assert(!aurApp->GetEffectMask());
-
- // Remove totem at next update if totem looses its aura
- if (aurApp->GetRemoveMode() == AURA_REMOVE_BY_EXPIRE && GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isTotem()&& ((TempSummon*)this)->GetSummonerGUID() == aura->GetCasterGUID())
- {
- if (((Totem*)this)->GetSpell() == aura->GetId() && ((Totem*)this)->GetTotemType() == TOTEM_PASSIVE)
- ((Totem*)this)->setDeathState(JUST_DIED);
- }
-
- // Remove aurastates only if were not found
- if (!auraStateFound)
- ModifyAuraState(auraState, false);
-
- aura->HandleAuraSpecificMods(aurApp, caster, false);
-
- // only way correctly remove all auras from list
- //if(removedAuras != m_removedAurasCount) new aura may be added
- i = m_appliedAuras.begin();
-}
-
-void Unit::_UnapplyAura(AuraApplication * aurApp, AuraRemoveMode removeMode)
-{
- // aura can be removed from unit only if it's applied on it, shouldn't happen
- assert(aurApp->GetBase()->GetApplicationOfTarget(GetGUID()) == aurApp);
- uint32 spellId = aurApp->GetBase()->GetId();
- for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound(spellId); iter != m_appliedAuras.upper_bound(spellId);)
- {
- if (iter->second == aurApp)
- {
- _UnapplyAura(iter, removeMode);
- return;
- }
- else
- ++iter;
- }
- assert(false);
-}
-
-void Unit::_RemoveNoStackAuraApplicationsDueToAura(Aura * aura)
-{
- // dynobj auras can stack infinite number of times
- if (aura->GetType() == DYNOBJ_AURA_TYPE)
- return;
-
- SpellEntry const* spellProto = aura->GetSpellProto();
-
- uint32 spellId = spellProto->Id;
-
- // passive spell special case (only non stackable with ranks)
- if(IsPassiveSpell(spellId) && IsPassiveSpellStackableWithRanks(spellProto))
- return;
-
- bool remove = false;
- for (AuraApplicationMap::iterator i = m_appliedAuras.begin(); i != m_appliedAuras.end(); ++i)
- {
- if(remove)
- {
- remove = false;
- i = m_appliedAuras.begin();
- }
-
- if (!_IsNoStackAuraDueToAura(aura, i->second->GetBase()))
- continue;
-
- RemoveAura(i, AURA_REMOVE_BY_DEFAULT);
- if(i == m_appliedAuras.end())
- break;
- remove = true;
- }
-}
-
-void Unit::_RemoveNoStackAurasDueToAura(Aura * aura)
-{
- SpellEntry const* spellProto = aura->GetSpellProto();
-
- uint32 spellId = spellProto->Id;
-
- // passive spell special case (only non stackable with ranks)
- if(IsPassiveSpell(spellId) && IsPassiveSpellStackableWithRanks(spellProto))
- return;
-
- bool remove = false;
- for (AuraMap::iterator i = m_ownedAuras.begin(); i != m_ownedAuras.end(); ++i)
- {
- if(remove)
- {
- remove = false;
- i = m_ownedAuras.begin();
- }
-
- if (!_IsNoStackAuraDueToAura(aura, i->second))
- continue;
-
- RemoveOwnedAura(i, AURA_REMOVE_BY_DEFAULT);
- if(i == m_ownedAuras.end())
- break;
- remove = true;
- }
-}
-
-bool Unit::_IsNoStackAuraDueToAura(Aura * appliedAura, Aura * existingAura) const
-{
- SpellEntry const* spellProto = appliedAura->GetSpellProto();
- // Do not check already applied aura
- if (existingAura == appliedAura)
- return false;
-
- // Do not check dynobj auras for stacking
- if (existingAura->GetType() != UNIT_AURA_TYPE)
- return false;
-
- SpellEntry const* i_spellProto = existingAura->GetSpellProto();
- uint32 i_spellId = i_spellProto->Id;
- bool sameCaster = appliedAura->GetCasterGUID() == existingAura->GetCasterGUID();
-
- if(IsPassiveSpell(i_spellId))
- {
- // passive non-stackable spells not stackable only for same caster
- if(!sameCaster)
- return false;
-
- // passive non-stackable spells not stackable only with another rank of same spell
- if (!spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
- return false;
- }
-
- bool is_triggered_by_spell = false;
- // prevent triggering aura of removing aura that triggered it
- // prevent triggered aura of removing aura that triggering it (triggered effect early some aura of parent spell
- for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j)
- {
- if (i_spellProto->EffectTriggerSpell[j] == spellProto->Id
- || spellProto->EffectTriggerSpell[j] == i_spellProto->Id) // I do not know what is this for
- {
- is_triggered_by_spell = true;
- break;
- }
- }
-
- if (is_triggered_by_spell)
- return false;
-
- if(spellmgr.CanAurasStack(spellProto, i_spellProto, sameCaster))
- return false;
- return true;
-}
-
-void Unit::_HandleAuraEffect(AuraEffect * aurEff, bool apply)
-{
- if (apply)
- m_modAuras[aurEff->GetAuraType()].push_back(aurEff);
- else
- m_modAuras[aurEff->GetAuraType()].remove(aurEff);
-}
-
-// All aura base removes should go threw this function!
-void Unit::RemoveOwnedAura(AuraMap::iterator &i, AuraRemoveMode removeMode)
-{
- Aura * aura = i->second;
- assert(!aura->IsRemoved());
-
- // if unit currently update aura list then make safe update iterator shift to next
- if (m_auraUpdateIterator == i)
- ++m_auraUpdateIterator;
-
- m_ownedAuras.erase(i);
- m_removedAuras.push_back(aura);
-
- // Unregister single target aura
- if (aura->IsSingleTarget())
- aura->UnregisterSingleTarget();
-
- aura->_Remove(removeMode);
-
- i = m_ownedAuras.begin();
-}
-
-void Unit::RemoveOwnedAura(uint32 spellId, uint64 caster, uint8 reqEffMask, AuraRemoveMode removeMode)
-{
- for (AuraMap::iterator itr = m_ownedAuras.lower_bound(spellId); itr != m_ownedAuras.upper_bound(spellId);)
- if(((itr->second->GetEffectMask() & reqEffMask) == reqEffMask) && (!caster || itr->second->GetCasterGUID() == caster))
- {
- RemoveOwnedAura(itr, removeMode);
- itr = m_ownedAuras.lower_bound(spellId);
- }
- else
- ++itr;
-}
-
-void Unit::RemoveOwnedAura(Aura * aura, AuraRemoveMode removeMode)
-{
- if (aura->IsRemoved())
- return;
-
- assert(aura->GetOwner() == this);
-
- uint32 spellId = aura->GetId();
- for (AuraMap::iterator itr = m_ownedAuras.lower_bound(spellId); itr != m_ownedAuras.upper_bound(spellId); ++itr)
- if (itr->second == aura)
- {
- RemoveOwnedAura(itr, removeMode);
- return;
- }
- assert(false);
-}
-
-Aura * Unit::GetOwnedAura(uint32 spellId, uint64 caster, uint8 reqEffMask, Aura * except) const
-{
- for (AuraMap::const_iterator itr = m_ownedAuras.lower_bound(spellId); itr != m_ownedAuras.upper_bound(spellId); ++itr)
- if(((itr->second->GetEffectMask() & reqEffMask) == reqEffMask) && (!caster || itr->second->GetCasterGUID() == caster) && (!except || except != itr->second))
- return itr->second;
- return NULL;
-}
-
-void Unit::RemoveAura(AuraApplicationMap::iterator &i, AuraRemoveMode mode)
-{
- AuraApplication * aurApp = i->second;
- // Do not remove aura which is already being removed
- if (aurApp->GetRemoveMode())
- return;
- Aura * aura = aurApp->GetBase();
- _UnapplyAura(i, mode);
- // Remove aura - for Area and Target auras
- if (aura->GetOwner() == this)
- aura->Remove(mode);
-}
-
-void Unit::RemoveAura(uint32 spellId, uint64 caster, uint8 reqEffMask, AuraRemoveMode removeMode)
-{
- for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound(spellId); iter != m_appliedAuras.upper_bound(spellId);)
- {
- Aura const * aura = iter->second->GetBase();
- if (((aura->GetEffectMask() & reqEffMask) == reqEffMask)
- && (!caster || aura->GetCasterGUID() == caster))
- {
- RemoveAura(iter, removeMode);
- return;
- }
- else
- ++iter;
- }
-}
-
-void Unit::RemoveAura(AuraApplication * aurApp, AuraRemoveMode mode)
-{
- assert(aurApp->GetBase()->GetApplicationOfTarget(GetGUID()) == aurApp);
- // no need to remove
- if (aurApp->GetRemoveMode() || aurApp->GetBase()->IsRemoved())
- return;
- uint32 spellId = aurApp->GetBase()->GetId();
- for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound(spellId); iter != m_appliedAuras.upper_bound(spellId);)
- {
- if (aurApp == iter->second)
- {
- RemoveAura(iter, mode);
- return;
- }
- else
- ++iter;
- }
-}
-
-void Unit::RemoveAura(Aura * aura, AuraRemoveMode mode)
-{
- if (aura->IsRemoved())
- return;
- if (AuraApplication * aurApp = aura->GetApplicationOfTarget(GetGUID()))
- RemoveAura(aurApp, mode);
- else
- assert(false);
-}
-
-void Unit::RemoveAurasDueToSpell(uint32 spellId, uint64 caster, uint8 reqEffMask, AuraRemoveMode removeMode)
-{
- for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound(spellId); iter != m_appliedAuras.upper_bound(spellId);)
- {
- Aura const * aura = iter->second->GetBase();
- if (((aura->GetEffectMask() & reqEffMask) == reqEffMask)
- && (!caster || aura->GetCasterGUID() == caster))
- {
- RemoveAura(iter, removeMode);
- iter = m_appliedAuras.lower_bound(spellId);
- }
- else
- ++iter;
- }
-}
-
-void Unit::RemoveAuraFromStack(uint32 spellId, uint64 caster, AuraRemoveMode removeMode)
-{
- for (AuraMap::iterator iter = m_ownedAuras.lower_bound(spellId); iter != m_ownedAuras.upper_bound(spellId);)
- {
- Aura const * aura = iter->second;
- if ((aura->GetType() == UNIT_AURA_TYPE)
- && (!caster || aura->GetCasterGUID() == caster))
- {
- RemoveAuraFromStack(iter, removeMode);
- return;
- }
- else
- ++iter;
- }
-}
-
-inline void Unit::RemoveAuraFromStack(AuraMap::iterator &iter, AuraRemoveMode removeMode)
-{
- if (iter->second->ModStackAmount(-1))
- RemoveOwnedAura(iter, removeMode);
-}
-
-void Unit::RemoveAurasDueToSpellByDispel(uint32 spellId, uint64 casterGUID, Unit *dispeller)
-{
- for (AuraMap::iterator iter = m_ownedAuras.lower_bound(spellId); iter != m_ownedAuras.upper_bound(spellId);)
- {
- Aura * aura = iter->second;
- if (aura->GetCasterGUID() == casterGUID)
- {
- if (aura->GetSpellProto()->AttributesEx7 & SPELL_ATTR_EX7_DISPEL_CHARGES)
- aura->DropCharge();
- else
- RemoveAuraFromStack(iter, AURA_REMOVE_BY_ENEMY_SPELL);
-
- // Unstable Affliction (crash if before removeaura?)
- if (aura->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && (aura->GetSpellProto()->SpellFamilyFlags[1] & 0x0100))
- {
- if (AuraEffect const * aurEff = aura->GetEffect(0))
- {
- int32 damage = aurEff->GetAmount()*9;
- // backfire damage and silence
- dispeller->CastCustomSpell(dispeller, 31117, &damage, NULL, NULL, true, NULL, NULL, GetGUID());
- }
- }
- // Flame Shock
- if (aura->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN && (aura->GetSpellProto()->SpellFamilyFlags[0] & 0x10000000))
- {
- Unit * caster = aura->GetCaster();
- if (caster)
- {
- uint32 triggeredSpellId = 0;
- // Lava Flows
- if (AuraEffect const * aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_SHAMAN, 3087, 0))
- {
- switch(aurEff->GetId())
- {
- case 51482: // Rank 3
- triggeredSpellId = 65264;
- break;
- case 51481: // Rank 2
- triggeredSpellId = 65263;
- break;
- case 51480: // Rank 1
- triggeredSpellId = 64694;
- break;
- default:
- sLog.outError("Aura::HandleAuraSpecificMods: Unknown rank of Lava Flows (%d) found", aurEff->GetId());
- }
- }
- if (triggeredSpellId)
- caster->CastSpell(caster, triggeredSpellId, true);
- }
- }
- return;
- }
- else
- ++iter;
- }
-}
-
-void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit *stealer)
-{
- for (AuraMap::iterator iter = m_ownedAuras.lower_bound(spellId); iter != m_ownedAuras.upper_bound(spellId);)
- {
- Aura * aura = iter->second;
- if (aura->GetCasterGUID() == casterGUID)
- {
- int32 damage[MAX_SPELL_EFFECTS];
- int32 baseDamage[MAX_SPELL_EFFECTS];
- uint8 effMask = 0;
- uint8 recalculateMask = 0;
- for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
- {
- if (aura->GetEffect(i))
- {
- baseDamage[i] = aura->GetEffect(i)->GetBaseAmount();
- damage[i] = aura->GetEffect(i)->GetAmount();
- effMask |= (1<<i);
- if (aura->GetEffect(i)->CanBeRecalculated())
- recalculateMask |= (1<<i);
- }
- else
- {
- baseDamage[i] = NULL;
- damage[i] = NULL;
- }
- }
-
- bool stealCharge = aura->GetSpellProto()->AttributesEx7 & SPELL_ATTR_EX7_DISPEL_CHARGES;
-
- if (stealCharge)
- aura->DropCharge();
- else
- RemoveAuraFromStack(iter, AURA_REMOVE_BY_ENEMY_SPELL);
-
-
- if (Aura * newAura = stealCharge ? stealer->GetAura(aura->GetId(), aura->GetCasterGUID()) : NULL)
- {
- uint8 newCharges = newAura->GetCharges() + 1;
- uint8 maxCharges = newAura->GetSpellProto()->procCharges;
- // We must be able to steal as much charges as original caster can have
- if (Unit * caster = newAura->GetCaster())
- if (Player* modOwner = caster->GetSpellModOwner())
- modOwner->ApplySpellMod(aura->GetId(), SPELLMOD_CHARGES, maxCharges);
- newAura->SetCharges(maxCharges < newCharges ? maxCharges : newCharges);
- }
- else
- {
- int32 dur = 2*MINUTE*IN_MILISECONDS < aura->GetDuration() ? 2*MINUTE*IN_MILISECONDS : aura->GetDuration();
-
- newAura = Aura::TryCreate(aura->GetSpellProto(), effMask, stealer, NULL, &baseDamage[0], NULL, aura->GetCasterGUID());
- if (!newAura)
- return;
- newAura->SetLoadedState(dur, dur, stealCharge ? 1 : aura->GetCharges(), aura->GetStackAmount(), recalculateMask, &damage[0]);
- // strange but intended behaviour: Stolen single target auras won't be treated as single targeted
- if (newAura->IsSingleTarget())
- newAura->UnregisterSingleTarget();
- newAura->ApplyForTargets();
- }
- return;
- }
- else
- ++iter;
- }
-}
-
-void Unit::RemoveAurasDueToItemSpell(Item* castItem,uint32 spellId)
-{
- for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound(spellId); iter != m_appliedAuras.upper_bound(spellId);)
- {
- if (!castItem || iter->second->GetBase()->GetCastItemGUID() == castItem->GetGUID())
- {
- RemoveAura(iter);
- iter = m_appliedAuras.upper_bound(spellId); // overwrite by more appropriate
- }
- else
- ++iter;
- }
-}
-
-void Unit::RemoveAurasByType(AuraType auraType, uint64 casterGUID, Aura * except, bool negative, bool positive)
-{
- for (AuraEffectList::iterator iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end();)
- {
- Aura * aura = (*iter)->GetBase();
- AuraApplication * aurApp = aura ->GetApplicationOfTarget(GetGUID());
-
- ++iter;
- if (aura != except && (!casterGUID || aura->GetCasterGUID() == casterGUID)
- && ((negative && !aurApp->IsPositive()) || (positive && aurApp->IsPositive())))
- {
- uint32 removedAuras = m_removedAurasCount;
- RemoveAura(aurApp);
- if (m_removedAurasCount > removedAuras + 1)
- iter = m_modAuras[auraType].begin();
- }
- }
-}
-
-void Unit::RemoveNotOwnSingleTargetAuras(uint32 newPhase)
-{
- // single target auras from other casters
- for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
- {
- AuraApplication const * aurApp = iter->second;
- Aura const * aura = aurApp->GetBase();
-
- if (aura->GetCasterGUID() !=GetGUID() && IsSingleTargetSpell(aura->GetSpellProto()))
- {
- if (!newPhase)
- RemoveAura(iter);
- else
- {
- Unit* caster = aura->GetCaster();
- if (!caster || !caster->InSamePhase(newPhase))
- RemoveAura(iter);
- else
- ++iter;
- }
- }
- else
- ++iter;
- }
-
- // single target auras at other targets
- AuraList& scAuras = GetSingleCastAuras();
- for (AuraList::iterator iter = scAuras.begin(); iter != scAuras.end();)
- {
- Aura * aura = *iter;
- ++iter;
- if (aura->GetUnitOwner() != this && !aura->GetUnitOwner()->InSamePhase(newPhase))
- {
- uint32 removedAuras = m_removedAurasCount;
- aura->Remove();
- if (m_removedAurasCount > removedAuras + 1)
- iter = scAuras.begin();
- }
- }
-}
-
-
-void Unit::RemoveAurasWithInterruptFlags(uint32 flag, uint32 except)
-{
- if (!(m_interruptMask & flag))
- return;
-
- // interrupt auras
- for (AuraApplicationList::iterator iter = m_interruptableAuras.begin(); iter != m_interruptableAuras.end();)
- {
- Aura * aura = (*iter)->GetBase();
- ++iter;
- if ((aura->GetSpellProto()->AuraInterruptFlags & flag) && (!except || aura->GetId() != except))
- {
- uint32 removedAuras = m_removedAurasCount;
- RemoveAura(aura);
- if (m_removedAurasCount > removedAuras + 1)
- iter = m_interruptableAuras.begin();
- }
- }
-
- // interrupt channeled spell
- if (Spell* spell = m_currentSpells[CURRENT_CHANNELED_SPELL])
- if (spell->getState() == SPELL_STATE_CASTING
- && (spell->m_spellInfo->ChannelInterruptFlags & flag)
- && spell->m_spellInfo->Id != except)
- InterruptNonMeleeSpells(false);
-
- UpdateInterruptMask();
-}
-
-void Unit::RemoveAurasWithFamily(SpellFamilyNames family, uint32 familyFlag1, uint32 familyFlag2, uint32 familyFlag3, uint64 casterGUID)
-{
- for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
- {
- Aura const * aura = iter->second->GetBase();
- if (!casterGUID || aura->GetCasterGUID() == casterGUID)
- {
- SpellEntry const *spell = aura->GetSpellProto();
- if (spell->SpellFamilyName == family && spell->SpellFamilyFlags.HasFlag(familyFlag1, familyFlag2, familyFlag3))
- {
- RemoveAura(iter);
- continue;
- }
- }
- ++iter;
- }
-}
-
-void Unit::RemoveMovementImpairingAuras()
-{
- RemoveAurasWithMechanic((1<<MECHANIC_SNARE)|(1<<MECHANIC_ROOT));
-}
-
-void Unit::RemoveAurasWithMechanic(uint32 mechanic_mask, AuraRemoveMode removemode, uint32 except)
-{
- for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
- {
- Aura const * aura = iter->second->GetBase();
- if (!except || aura->GetId() != except)
- {
- if (GetAllSpellMechanicMask(aura->GetSpellProto()) & mechanic_mask)
- {
- RemoveAura(iter, removemode);
- continue;
- }
- }
- ++iter;
- }
-}
-
-void Unit::RemoveAreaAurasDueToLeaveWorld()
-{
- bool cleanRun;
- do
- {
- cleanRun = true;
- // make sure that all area auras not applied on self are removed - prevent access to deleted pointer later
- for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();)
- {
- Aura * aura = iter->second;
- ++iter;
- Aura::ApplicationMap const & appMap = aura->GetApplicationMap();
- for(Aura::ApplicationMap::const_iterator itr = appMap.begin(); itr!= appMap.end();)
- {
- AuraApplication * aurApp = itr->second;
- ++itr;
- Unit * target = aurApp->GetTarget();
- if (target == this)
- continue;
- target->RemoveAura(aurApp);
- cleanRun = false;
- // things linked on aura remove may apply new area aura - so start from the beginning
- iter = m_ownedAuras.begin();
- }
- }
-
- // remove area auras owned by others
- for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
- {
- if (iter->second->GetBase()->GetOwner()!=this)
- {
- RemoveAura(iter);
- cleanRun = false;
- }
- else
- ++iter;
- }
- }
- while (!cleanRun);
-}
-
-void Unit::RemoveAllAuras()
-{
- while (!m_appliedAuras.empty() || !m_ownedAuras.empty())
- {
- AuraApplicationMap::iterator aurAppIter = m_appliedAuras.begin();
- while (!m_appliedAuras.empty())
- _UnapplyAura(aurAppIter, AURA_REMOVE_BY_DEFAULT);
-
- AuraMap::iterator aurIter = m_ownedAuras.begin();
- while (!m_ownedAuras.empty())
- RemoveOwnedAura(aurIter);
- }
-}
-
-void Unit::RemoveArenaAuras(bool onleave)
-{
- // in join, remove positive buffs, on end, remove negative
- // used to remove positive visible auras in arenas
- for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
- {
- AuraApplication const * aurApp = iter->second;
- Aura const * aura = aurApp->GetBase();
- if ( !(aura->GetSpellProto()->AttributesEx4 & (1<<21)) // don't remove stances, shadowform, pally/hunter auras
- && !aura->IsPassive() // don't remove passive auras
- && (!(aura->GetSpellProto()->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY) || !(aura->GetSpellProto()->Attributes & SPELL_ATTR_UNK8)) // not unaffected by invulnerability auras or not having that unknown flag (that seemed the most probable)
- && (aurApp->IsPositive() ^ onleave)) // remove positive buffs on enter, negative buffs on leave
- RemoveAura(iter);
- else
- ++iter;
- }
-}
-
-void Unit::RemoveAllAurasOnDeath()
-{
- // used just after dieing to remove all visible auras
- // and disable the mods for the passive ones
- for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
- {
- Aura const * aura = iter->second->GetBase();
- if (!aura->IsPassive() && !aura->IsDeathPersistent())
- _UnapplyAura(iter, AURA_REMOVE_BY_DEATH);
- else
- ++iter;
- }
-
- for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();)
- {
- Aura * aura = iter->second;
- if (!aura->IsPassive() && !aura->IsDeathPersistent())
- RemoveOwnedAura(iter, AURA_REMOVE_BY_DEATH);
- else
- ++iter;
- }
-}
-
-void Unit::DelayOwnedAuras(uint32 spellId, uint64 caster, int32 delaytime)
-{
- for (AuraMap::iterator iter = m_ownedAuras.lower_bound(spellId); iter != m_ownedAuras.upper_bound(spellId);++iter)
- {
- Aura * aura = iter->second;
- if (!caster || aura->GetCasterGUID() == caster)
- {
- if (aura->GetDuration() < delaytime)
- aura->SetDuration(0);
- else
- aura->SetDuration(aura->GetDuration() - delaytime);
-
- // update for out of range group members (on 1 slot use)
- aura->SetNeedClientUpdateForTargets();
- sLog.outDebug("Aura %u partially interrupted on unit %u, new duration: %u ms",aura->GetId() , GetGUIDLow(), aura->GetDuration());
- }
- }
-}
-
-void Unit::_RemoveAllAuraStatMods()
-{
- for (AuraApplicationMap::iterator i = m_appliedAuras.begin(); i != m_appliedAuras.end(); ++i)
- (*i).second->GetBase()->HandleAllEffects(i->second, AURA_EFFECT_HANDLE_STAT, false);
-}
-
-void Unit::_ApplyAllAuraStatMods()
-{
- for (AuraApplicationMap::iterator i = m_appliedAuras.begin(); i != m_appliedAuras.end(); ++i)
- (*i).second->GetBase()->HandleAllEffects(i->second, AURA_EFFECT_HANDLE_STAT, true);
-}
-
-AuraEffect * Unit::GetAuraEffect(uint32 spellId, uint8 effIndex, uint64 caster) const
-{
- for (AuraApplicationMap::const_iterator itr = m_appliedAuras.lower_bound(spellId); itr != m_appliedAuras.upper_bound(spellId); ++itr)
- if(itr->second->HasEffect(effIndex) && (!caster || itr->second->GetBase()->GetCasterGUID() == caster))
- return itr->second->GetBase()->GetEffect(effIndex);
- return NULL;
-}
-
-AuraEffect * Unit::GetAuraEffectOfRankedSpell(uint32 spellId, uint8 effIndex, uint64 caster) const
-{
- uint32 rankSpell = spellmgr.GetFirstSpellInChain(spellId);
- while(true)
- {
- if (AuraEffect * aurEff = GetAuraEffect(rankSpell, effIndex, caster))
- return aurEff;
- SpellChainNode const * chainNode = spellmgr.GetSpellChainNode(rankSpell);
- if (!chainNode)
- break;
- else
- rankSpell = chainNode->next;
- }
- return NULL;
-}
-
-AuraEffect* Unit::GetAuraEffect(AuraType type, SpellFamilyNames name, uint32 iconId, uint8 effIndex) const
-{
- AuraEffectList const& auras = GetAuraEffectsByType(type);
- for (Unit::AuraEffectList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
- {
- if (effIndex != (*itr)->GetEffIndex())
- continue;
- SpellEntry const * spell = (*itr)->GetSpellProto();
- if (spell->SpellIconID == iconId && spell->SpellFamilyName == name && !spell->SpellFamilyFlags)
- return *itr;
- }
- return NULL;
-}
-
-AuraEffect* Unit::GetAuraEffect(AuraType type, SpellFamilyNames family, uint32 familyFlag1, uint32 familyFlag2, uint32 familyFlag3, uint64 casterGUID)
-{
- AuraEffectList const& auras = GetAuraEffectsByType(type);
- for (AuraEffectList::const_iterator i = auras.begin(); i != auras.end(); ++i)
- {
- SpellEntry const *spell = (*i)->GetSpellProto();
- if (spell->SpellFamilyName == family && spell->SpellFamilyFlags.HasFlag(familyFlag1, familyFlag2, familyFlag3))
- {
- if (casterGUID && (*i)->GetCasterGUID()!=casterGUID)
- continue;
- return (*i);
- }
- }
- return NULL;
-}
-
-AuraApplication * Unit::GetAuraApplication(uint32 spellId, uint64 casterGUID, uint8 reqEffMask, AuraApplication * except) const
-{
- for (AuraApplicationMap::const_iterator itr = m_appliedAuras.lower_bound(spellId); itr != m_appliedAuras.upper_bound(spellId); ++itr)
- {
- Aura const * aura = itr->second->GetBase();
- if(((aura->GetEffectMask() & reqEffMask) == reqEffMask) && (!casterGUID || aura->GetCasterGUID() == casterGUID) && (!except || except!=itr->second))
- return itr->second;
- }
- return NULL;
-}
-
-Aura * Unit::GetAura(uint32 spellId, uint64 casterGUID, uint8 reqEffMask) const
-{
- AuraApplication * aurApp = GetAuraApplication(spellId, casterGUID, reqEffMask);
- return aurApp ? aurApp->GetBase():NULL;
-}
-
-AuraApplication * Unit::GetAuraApplicationOfRankedSpel(uint32 spellId, uint64 casterGUID, uint8 reqEffMask, AuraApplication * except) const
-{
- uint32 rankSpell = spellmgr.GetFirstSpellInChain(spellId);
- while(true)
- {
- if (AuraApplication * aurApp = GetAuraApplication(rankSpell, casterGUID, reqEffMask, except))
- return aurApp;
- SpellChainNode const * chainNode = spellmgr.GetSpellChainNode(rankSpell);
- if (!chainNode)
- break;
- else
- rankSpell = chainNode->next;
- }
- return NULL;
-}
-
-Aura * Unit::GetAuraOfRankedSpell(uint32 spellId, uint64 casterGUID, uint8 reqEffMask) const
-{
- AuraApplication * aurApp = GetAuraApplicationOfRankedSpel(spellId, casterGUID, reqEffMask);
- return aurApp ? aurApp->GetBase() : NULL;
-}
-
-bool Unit::HasAuraEffect(uint32 spellId, uint8 effIndex, uint64 caster) const
-{
- for (AuraApplicationMap::const_iterator itr = m_appliedAuras.lower_bound(spellId); itr != m_appliedAuras.upper_bound(spellId); ++itr)
- if(itr->second->HasEffect(effIndex) && (!caster || itr->second->GetBase()->GetCasterGUID() == caster))
- return true;
- return false;
-}
-
-bool Unit::HasAura(uint32 spellId, uint64 caster, uint8 reqEffMask) const
-{
- //Special case for non existing spell
- if (spellId==61988)
- return HasAura(61987, caster, reqEffMask) || HasAura(25771, caster, reqEffMask);
-
- if (GetAuraApplication(spellId, caster, reqEffMask))
- return true;
- return false;
-}
-
-bool Unit::HasAuraType(AuraType auraType) const
-{
- return (!m_modAuras[auraType].empty());
-}
-
-bool Unit::HasAuraTypeWithMiscvalue(AuraType auratype, uint32 miscvalue) const
-{
- AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
- for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
- if (miscvalue == (*i)->GetMiscValue())
- return true;
- return false;
-}
-
-bool Unit::HasAuraTypeWithValue(AuraType auratype, uint32 value) const
-{
- AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
- for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
- if (value == (*i)->GetAmount())
- return true;
- return false;
-}
-
-bool Unit::HasNegativeAuraWithInterruptFlag(uint32 flag)
-{
- if (!(m_interruptMask & flag))
- return false;
- for (AuraApplicationList::iterator iter = m_interruptableAuras.begin(); iter != m_interruptableAuras.end(); ++iter)
- {
- if (!(*iter)->IsPositive() && (*iter)->GetBase()->GetSpellProto()->AuraInterruptFlags & flag)
- return true;
- }
- return false;
-}
-
-AuraEffect * Unit::IsScriptOverriden(SpellEntry const * spell, int32 script) const
-{
- AuraEffectList const& auras = GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
- for (AuraEffectList::const_iterator i = auras.begin(); i != auras.end(); ++i)
- {
- if ((*i)->GetMiscValue() == script)
- if ((*i)->IsAffectedOnSpell(spell))
- return (*i);
- }
- return NULL;
-}
-
-uint32 Unit::GetDiseasesByCaster(uint64 casterGUID, bool remove)
-{
- static const AuraType diseaseAuraTypes[] =
- {
- SPELL_AURA_PERIODIC_DAMAGE, // Frost Fever and Blood Plague
- SPELL_AURA_LINKED, // Crypt Fever and Ebon Plague
- SPELL_AURA_NONE
- };
-
- uint32 diseases=0;
- for (AuraType const* itr = &diseaseAuraTypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
- {
- for (AuraEffectList::iterator i = m_modAuras[*itr].begin(); i != m_modAuras[*itr].end();)
- {
- // Get auras with disease dispel type by caster
- if ((*i)->GetSpellProto()->Dispel == DISPEL_DISEASE
- && (*i)->GetCasterGUID()==casterGUID)
- {
- ++diseases;
-
- if (remove)
- {
- RemoveAura((*i)->GetId(), (*i)->GetCasterGUID());
- i = m_modAuras[*itr].begin();
- continue;
- }
- }
- ++i;
- }
- }
- return diseases;
-}
-
-uint32 Unit::GetDoTsByCaster(uint64 casterGUID) const
-{
- static const AuraType diseaseAuraTypes[] =
- {
- SPELL_AURA_PERIODIC_DAMAGE,
- SPELL_AURA_PERIODIC_DAMAGE_PERCENT,
- SPELL_AURA_NONE
- };
-
- uint32 dots=0;
- for (AuraType const* itr = &diseaseAuraTypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
- {
- Unit::AuraEffectList const& auras = GetAuraEffectsByType(*itr);
- for (AuraEffectList::const_iterator i = auras.begin(); i != auras.end(); ++i)
- {
- // Get auras by caster
- if ((*i)->GetCasterGUID()==casterGUID)
- ++dots;
- }
- }
- return dots;
-}
-
-int32 Unit::GetTotalAuraModifier(AuraType auratype) const
-{
- int32 modifier = 0;
-
- AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
- for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
- modifier += (*i)->GetAmount();
-
- return modifier;
-}
-
-float Unit::GetTotalAuraMultiplier(AuraType auratype) const
-{
- float multiplier = 1.0f;
-
- AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
- for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
- multiplier *= (100.0f + (*i)->GetAmount())/100.0f;
-
- return multiplier;
-}
-
-int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype)
-{
- int32 modifier = 0;
-
- AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
- for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
- {
- if ((*i)->GetAmount() > modifier)
- modifier = (*i)->GetAmount();
- }
-
- return modifier;
-}
-
-int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const
-{
- int32 modifier = 0;
-
- AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
- for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
- if ((*i)->GetAmount() < modifier)
- modifier = (*i)->GetAmount();
-
- return modifier;
-}
-
-int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
-{
- int32 modifier = 0;
-
- AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
- for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
- {
- if ((*i)->GetMiscValue()& misc_mask)
- modifier += (*i)->GetAmount();
- }
- return modifier;
-}
-
-float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const
-{
- float multiplier = 1.0f;
-
- AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
- for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
- {
- if ((*i)->GetMiscValue()& misc_mask)
- multiplier *= (100.0f + (*i)->GetAmount())/100.0f;
- }
- return multiplier;
-}
-
-int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
-{
- int32 modifier = 0;
-
- AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
- for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
- {
- if ((*i)->GetMiscValue()& misc_mask && (*i)->GetAmount() > modifier)
- modifier = (*i)->GetAmount();
- }
-
- return modifier;
-}
-
-int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
-{
- int32 modifier = 0;
-
- AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
- for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
- {
- if ((*i)->GetMiscValue()& misc_mask && (*i)->GetAmount() < modifier)
- modifier = (*i)->GetAmount();
- }
-
- return modifier;
-}
-
-int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
-{
- int32 modifier = 0;
-
- AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
- for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
- {
- if ((*i)->GetMiscValue()== misc_value)
- modifier += (*i)->GetAmount();
- }
- return modifier;
-}
-
-float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const
-{
- float multiplier = 1.0f;
-
- AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
- for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
- {
- if ((*i)->GetMiscValue()== misc_value)
- multiplier *= (100.0f + (*i)->GetAmount())/100.0f;
- }
- return multiplier;
-}
-
-int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
-{
- int32 modifier = 0;
-
- AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
- for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
- {
- if ((*i)->GetMiscValue()== misc_value && (*i)->GetAmount() > modifier)
- modifier = (*i)->GetAmount();
- }
-
- return modifier;
-}
-
-int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
-{
- int32 modifier = 0;
-
- AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
- for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
- {
- if ((*i)->GetMiscValue()== misc_value && (*i)->GetAmount() < modifier)
- modifier = (*i)->GetAmount();
- }
-
- return modifier;
-}
-
-void Unit::AddDynObject(DynamicObject* dynObj)
-{
- m_dynObjGUIDs.push_back(dynObj->GetGUID());
-}
-
-void Unit::RemoveDynObject(uint32 spellid)
-{
- if(m_dynObjGUIDs.empty())
- return;
- for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
- {
- DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
- if(!dynObj) // may happen if a dynobj is removed when grid unload
- {
- i = m_dynObjGUIDs.erase(i);
- }
- else if(spellid == 0 || dynObj->GetSpellId() == spellid)
- {
- dynObj->Delete();
- i = m_dynObjGUIDs.erase(i);
- }
- else
- ++i;
- }
-}
-
-void Unit::RemoveAllDynObjects()
-{
- while(!m_dynObjGUIDs.empty())
- {
- DynamicObject* dynObj = GetMap()->GetDynamicObject(*m_dynObjGUIDs.begin());
- if(dynObj)
- dynObj->Delete();
- m_dynObjGUIDs.erase(m_dynObjGUIDs.begin());
- }
-}
-
-DynamicObject * Unit::GetDynObject(uint32 spellId)
-{
- for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
- {
- DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
- if(!dynObj)
- {
- i = m_dynObjGUIDs.erase(i);
- continue;
- }
-
- if (dynObj->GetSpellId() == spellId)
- return dynObj;
- ++i;
- }
- return NULL;
-}
-
-GameObject* Unit::GetGameObject(uint32 spellId) const
-{
- for (GameObjectList::const_iterator i = m_gameObj.begin(); i != m_gameObj.end(); ++i)
- if ((*i)->GetSpellId() == spellId)
- return *i;
-
- return NULL;
-}
-
-void Unit::AddGameObject(GameObject* gameObj)
-{
- if(!gameObj || !gameObj->GetOwnerGUID()==0) return;
- m_gameObj.push_back(gameObj);
- gameObj->SetOwnerGUID(GetGUID());
-
- if ( GetTypeId() == TYPEID_PLAYER && gameObj->GetSpellId() )
- {
- SpellEntry const* createBySpell = sSpellStore.LookupEntry(gameObj->GetSpellId());
- // Need disable spell use for owner
- if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
- // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
- ((Player*)this)->AddSpellAndCategoryCooldowns(createBySpell,0,NULL,true);
- }
-}
-
-void Unit::RemoveGameObject(GameObject* gameObj, bool del)
-{
- if(!gameObj || !gameObj->GetOwnerGUID()==GetGUID()) return;
-
- gameObj->SetOwnerGUID(0);
-
- for (uint32 i = 0; i < 4; ++i)
- {
- if(m_ObjectSlot[i] == gameObj->GetGUID())
- {
- m_ObjectSlot[i] = 0;
- break;
- }
- }
-
- // GO created by some spell
- if (uint32 spellid = gameObj->GetSpellId())
- {
- RemoveAurasDueToSpell(spellid);
-
- if (GetTypeId() == TYPEID_PLAYER)
- {
- SpellEntry const* createBySpell = sSpellStore.LookupEntry(spellid );
- // Need activate spell use for owner
- if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
- // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
- ((Player*)this)->SendCooldownEvent(createBySpell);
- }
- }
-
- m_gameObj.remove(gameObj);
-
- if(del)
- {
- gameObj->SetRespawnTime(0);
- gameObj->Delete();
- }
-}
-
-void Unit::RemoveGameObject(uint32 spellid, bool del)
-{
- if(m_gameObj.empty())
- return;
- GameObjectList::iterator i, next;
- for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next)
- {
- next = i;
- if(spellid == 0 || (*i)->GetSpellId() == spellid)
- {
- (*i)->SetOwnerGUID(0);
- if(del)
- {
- (*i)->SetRespawnTime(0);
- (*i)->Delete();
- }
-
- next = m_gameObj.erase(i);
- }
- else
- ++next;
- }
-}
-
-void Unit::RemoveAllGameObjects()
-{
- // remove references to unit
- for (GameObjectList::iterator i = m_gameObj.begin(); i != m_gameObj.end();)
- {
- (*i)->SetOwnerGUID(0);
- (*i)->SetRespawnTime(0);
- (*i)->Delete();
- i = m_gameObj.erase(i);
- }
-}
-
-void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage *log)
-{
- WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+4+1+4+4+1+1+4+4+1)); // we guess size
- data.append(log->target->GetPackGUID());
- data.append(log->attacker->GetPackGUID());
- data << uint32(log->SpellID);
- data << uint32(log->damage); // damage amount
- int32 overkill = log->damage - log->target->GetHealth();
- data << uint32(overkill > 0 ? overkill : 0);
- //data << uint32(log->overkill); // overkill
- data << uint8 (log->schoolMask); // damage school
- data << uint32(log->absorb); // AbsorbedDamage
- data << uint32(log->resist); // resist
- data << uint8 (log->physicalLog); // if 1, then client show spell name (example: %s's ranged shot hit %s for %u school or %s suffers %u school damage from %s's spell_name
- data << uint8 (log->unused); // unused
- data << uint32(log->blocked); // blocked
- data << uint32(log->HitInfo);
- data << uint8 (0); // flag to use extend data
- SendMessageToSet( &data, true );
-}
-
-void Unit::SendSpellNonMeleeDamageLog(Unit *target, uint32 SpellID, uint32 Damage, SpellSchoolMask damageSchoolMask, uint32 AbsorbedDamage, uint32 Resist, bool PhysicalDamage, uint32 Blocked, bool CriticalHit)
-{
- SpellNonMeleeDamage log(this, target, SpellID, damageSchoolMask);
- log.damage = Damage - AbsorbedDamage - Resist - Blocked;
- log.absorb = AbsorbedDamage;
- log.resist = Resist;
- log.physicalLog = PhysicalDamage;
- log.blocked = Blocked;
- log.HitInfo = SPELL_HIT_TYPE_UNK1 | SPELL_HIT_TYPE_UNK3 | SPELL_HIT_TYPE_UNK6;
- if(CriticalHit)
- log.HitInfo |= SPELL_HIT_TYPE_CRIT;
- SendSpellNonMeleeDamageLog(&log);
-}
-
-void Unit::ProcDamageAndSpell(Unit *pVictim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellEntry const *procSpell, SpellEntry const * procAura)
-{
- // Not much to do if no flags are set.
- if (procAttacker)
- ProcDamageAndSpellFor(false, pVictim,procAttacker, procExtra,attType, procSpell, amount, procAura);
- // Now go on with a victim's events'n'auras
- // Not much to do if no flags are set or there is no victim
- if(pVictim && pVictim->isAlive() && procVictim)
- pVictim->ProcDamageAndSpellFor(true, this, procVictim, procExtra, attType, procSpell, amount, procAura);
-}
-
-void Unit::SendPeriodicAuraLog(SpellPeriodicAuraLogInfo *pInfo)
-{
- AuraEffect const * aura = pInfo->auraEff;
-
- WorldPacket data(SMSG_PERIODICAURALOG, 30);
- data.append(GetPackGUID());
- data.appendPackGUID(aura->GetCasterGUID());
- data << uint32(aura->GetId()); // spellId
- data << uint32(1); // count
- data << uint32(aura->GetAuraType()); // auraId
- switch(aura->GetAuraType())
- {
- case SPELL_AURA_PERIODIC_DAMAGE:
- case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
- data << uint32(pInfo->damage); // damage
- data << uint32(pInfo->overDamage); // overkill?
- data << uint32(GetSpellSchoolMask(aura->GetSpellProto()));
- data << uint32(pInfo->absorb); // absorb
- data << uint32(pInfo->resist); // resist
- data << uint8(pInfo->critical); // new 3.1.2 critical tick
- break;
- case SPELL_AURA_PERIODIC_HEAL:
- case SPELL_AURA_OBS_MOD_HEALTH:
- data << uint32(pInfo->damage); // damage
- data << uint32(pInfo->overDamage); // overheal?
- data << uint8(pInfo->critical); // new 3.1.2 critical tick
- break;
- case SPELL_AURA_OBS_MOD_POWER:
- case SPELL_AURA_PERIODIC_ENERGIZE:
- data << uint32(aura->GetMiscValue()); // power type
- data << uint32(pInfo->damage); // damage
- break;
- case SPELL_AURA_PERIODIC_MANA_LEECH:
- data << uint32(aura->GetMiscValue()); // power type
- data << uint32(pInfo->damage); // amount
- data << float(pInfo->multiplier); // gain multiplier
- break;
- default:
- sLog.outError("Unit::SendPeriodicAuraLog: unknown aura %u", uint32(aura->GetAuraType()));
- return;
- }
-
- SendMessageToSet(&data, true);
-}
-
-void Unit::SendSpellMiss(Unit *target, uint32 spellID, SpellMissInfo missInfo)
-{
- WorldPacket data(SMSG_SPELLLOGMISS, (4+8+1+4+8+1));
- data << uint32(spellID);
- data << uint64(GetGUID());
- data << uint8(0); // can be 0 or 1
- data << uint32(1); // target count
- // for (i = 0; i < target count; ++i)
- data << uint64(target->GetGUID()); // target GUID
- data << uint8(missInfo);
- // end loop
- SendMessageToSet(&data, true);
-}
-
-void Unit::SendAttackStateUpdate(CalcDamageInfo *damageInfo)
-{
- sLog.outDebug("WORLD: Sending SMSG_ATTACKERSTATEUPDATE");
-
- uint32 count = 1;
- WorldPacket data(SMSG_ATTACKERSTATEUPDATE, 16 + 45); // we guess size
- data << uint32(damageInfo->HitInfo);
- data.append(damageInfo->attacker->GetPackGUID());
- data.append(damageInfo->target->GetPackGUID());
- data << uint32(damageInfo->damage); // Full damage
- int32 overkill = damageInfo->damage - damageInfo->target->GetHealth();
- data << uint32(overkill < 0 ? 0 : overkill); // Overkill
- data << uint8(count); // Sub damage count
-
- for (uint32 i = 0; i < count; ++i)
- {
- data << uint32(damageInfo->damageSchoolMask); // School of sub damage
- data << float(damageInfo->damage); // sub damage
- data << uint32(damageInfo->damage); // Sub Damage
- }
-
- if(damageInfo->HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
- {
- for (uint32 i = 0; i < count; ++i)
- data << uint32(damageInfo->absorb); // Absorb
- }
-
- if(damageInfo->HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
- {
- for (uint32 i = 0; i < count; ++i)
- data << uint32(damageInfo->resist); // Resist
- }
-
- data << uint8(damageInfo->TargetState);
- data << uint32(0);
- data << uint32(0);
-
- if(damageInfo->HitInfo & HITINFO_BLOCK)
- data << uint32(damageInfo->blocked_amount);
-
- if(damageInfo->HitInfo & HITINFO_UNK3)
- data << uint32(0);
-
- if(damageInfo->HitInfo & HITINFO_UNK1)
- {
- data << uint32(0);
- data << float(0);
- data << float(0);
- data << float(0);
- data << float(0);
- data << float(0);
- data << float(0);
- data << float(0);
- data << float(0);
- for (uint8 i = 0; i < 5; ++i)
- {
- data << float(0);
- data << float(0);
- }
- data << uint32(0);
- }
-
- SendMessageToSet( &data, true );
-}
-
-void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit *target, uint8 SwingType, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount)
-{
- CalcDamageInfo dmgInfo;
- dmgInfo.HitInfo = HitInfo;
- dmgInfo.attacker = this;
- dmgInfo.target = target;
- dmgInfo.damage = Damage - AbsorbDamage - Resist - BlockedAmount;
- dmgInfo.damageSchoolMask = damageSchoolMask;
- dmgInfo.absorb = AbsorbDamage;
- dmgInfo.resist = Resist;
- dmgInfo.TargetState = TargetState;
- dmgInfo.blocked_amount = BlockedAmount;
- SendAttackStateUpdate(&dmgInfo);
-}
-
-bool Unit::HandleHasteAuraProc(Unit *pVictim, uint32 damage, AuraEffect* triggeredByAura, SpellEntry const * procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
-{
- SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto();
-
- Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
- ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
-
- uint32 triggered_spell_id = 0;
- Unit* target = pVictim;
- int32 basepoints0 = 0;
-
- switch(hasteSpell->SpellFamilyName)
- {
- case SPELLFAMILY_ROGUE:
- {
- switch(hasteSpell->Id)
- {
- // Blade Flurry
- case 13877:
- case 33735:
- {
- target = SelectNearbyTarget();
- if (!target || target == pVictim)
- return false;
- basepoints0 = damage;
- triggered_spell_id = 22482;
- break;
- }
- }
- break;
- }
- }
-
- // processed charge only counting case
- if (!triggered_spell_id)
- return true;
-
- SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
-
- if (!triggerEntry)
- {
- sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",hasteSpell->Id,triggered_spell_id);
- return false;
- }
-
- // default case
- if ((!target && !spellmgr.IsSrcTargetSpell(triggerEntry)) || (target && target!=this && !target->isAlive()))
- return false;
-
- if (cooldown && GetTypeId() == TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
- return false;
-
- if (basepoints0)
- CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
- else
- CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
-
- if (cooldown && GetTypeId() == TYPEID_PLAYER)
- ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
-
- return true;
-}
-
-bool Unit::HandleSpellCritChanceAuraProc(Unit *pVictim, uint32 /*damage*/, AuraEffect* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
-{
- SpellEntry const *triggeredByAuraSpell = triggeredByAura->GetSpellProto();
-
- Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
- ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
-
- uint32 triggered_spell_id = 0;
- Unit* target = pVictim;
- int32 basepoints0 = 0;
-
- switch(triggeredByAuraSpell->SpellFamilyName)
- {
- case SPELLFAMILY_MAGE:
- {
- switch(triggeredByAuraSpell->Id)
- {
- // Focus Magic
- case 54646:
- {
- Unit* caster = triggeredByAura->GetCaster();
- if(!caster)
- return false;
-
- triggered_spell_id = 54648;
- target = caster;
- break;
- }
- }
- }
- }
-
- // processed charge only counting case
- if(!triggered_spell_id)
- return true;
-
- SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
-
- if(!triggerEntry)
- {
- sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",triggeredByAuraSpell->Id,triggered_spell_id);
- return false;
- }
-
- // default case
- if(!target || target!=this && !target->isAlive())
- return false;
-
- if( cooldown && GetTypeId() == TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
- return false;
-
- if(basepoints0)
- CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
- else
- CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
-
- if( cooldown && GetTypeId() == TYPEID_PLAYER )
- ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
-
- return true;
-}
-
-bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
-{
- SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
- uint32 effIndex = triggeredByAura->GetEffIndex();
- int32 triggerAmount = triggeredByAura->GetAmount();
-
- Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
- ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
-
- uint32 triggered_spell_id = 0;
- Unit* target = pVictim;
- int32 basepoints0 = 0;
- uint64 originalCaster = 0;
-
- switch(dummySpell->SpellFamilyName)
- {
- case SPELLFAMILY_GENERIC:
- {
- switch (dummySpell->Id)
- {
- // Bloodworms Health Leech
- case 50453:
- {
- if (Unit *owner = this->GetOwner())
- {
- basepoints0 = int32(damage*1.50);
- target = owner;
- triggered_spell_id = 50454;
- break;
- }
- return false;
- }
- // Eye for an Eye
- case 9799:
- case 25988:
- {
- // return damage % to attacker but < 50% own total health
- basepoints0 = triggerAmount*int32(damage)/100;
- if(basepoints0 > GetMaxHealth()/2)
- basepoints0 = GetMaxHealth()/2;
-
- triggered_spell_id = 25997;
- break;
- }
- // Sweeping Strikes
- case 18765:
- case 35429:
- {
- target = SelectNearbyTarget();
- if(!target)
- return false;
-
- triggered_spell_id = 26654;
- break;
- }
- // Unstable Power
- case 24658:
- {
- if (!procSpell || procSpell->Id == 24659)
- return false;
- // Need remove one 24659 aura
- RemoveAuraFromStack(24659);
- return true;
- }
- // Restless Strength
- case 24661:
- {
- // Need remove one 24662 aura
- RemoveAuraFromStack(24662);
- return true;
- }
- // Adaptive Warding (Frostfire Regalia set)
- case 28764:
- {
- if(!procSpell)
- return false;
-
- // find Mage Armor
- if (!GetAuraEffect(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT, SPELLFAMILY_MAGE, 0x10000000, 0, 0))
- return false;
-
- switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
- {
- case SPELL_SCHOOL_NORMAL:
- case SPELL_SCHOOL_HOLY:
- return false; // ignored
- case SPELL_SCHOOL_FIRE: triggered_spell_id = 28765; break;
- case SPELL_SCHOOL_NATURE: triggered_spell_id = 28768; break;
- case SPELL_SCHOOL_FROST: triggered_spell_id = 28766; break;
- case SPELL_SCHOOL_SHADOW: triggered_spell_id = 28769; break;
- case SPELL_SCHOOL_ARCANE: triggered_spell_id = 28770; break;
- default:
- return false;
- }
-
- target = this;
- break;
- }
- // Obsidian Armor (Justice Bearer`s Pauldrons shoulder)
- case 27539:
- {
- if(!procSpell)
- return false;
-
- switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
- {
- case SPELL_SCHOOL_NORMAL:
- return false; // ignore
- case SPELL_SCHOOL_HOLY: triggered_spell_id = 27536; break;
- case SPELL_SCHOOL_FIRE: triggered_spell_id = 27533; break;
- case SPELL_SCHOOL_NATURE: triggered_spell_id = 27538; break;
- case SPELL_SCHOOL_FROST: triggered_spell_id = 27534; break;
- case SPELL_SCHOOL_SHADOW: triggered_spell_id = 27535; break;
- case SPELL_SCHOOL_ARCANE: triggered_spell_id = 27540; break;
- default:
- return false;
- }
-
- target = this;
- break;
- }
- // Mana Leech (Passive) (Priest Pet Aura)
- case 28305:
- {
- // Cast on owner
- target = GetOwner();
- if(!target)
- return false;
-
- triggered_spell_id = 34650;
- break;
- }
- // Spirit Walk
- case 58875:
- {
- // Cast on owner
- target = GetOwner();
- if(!target)
- return false;
-
- triggered_spell_id = 58876;
- break;
- }
- // Mark of Malice
- case 33493:
- {
- // Cast finish spell at last charge
- if (triggeredByAura->GetBase()->GetCharges() > 1)
- return false;
-
- target = this;
- triggered_spell_id = 33494;
- break;
- }
- // Twisted Reflection (boss spell)
- case 21063:
- triggered_spell_id = 21064;
- break;
- // Vampiric Aura (boss spell)
- case 38196:
- {
- basepoints0 = 3 * damage; // 300%
- if (basepoints0 < 0)
- return false;
-
- triggered_spell_id = 31285;
- target = this;
- break;
- }
- // Aura of Madness (Darkmoon Card: Madness trinket)
- //=====================================================
- // 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior)
- // 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid)
- // 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid)
- // 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin)
- // 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes)
- // 41005 Manic: +35 haste (spell, melee and ranged) (All classes)
- // 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter)
- // 41011 Martyr Complex: +35 stamina (All classes)
- // 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
- // 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
- case 39446:
- {
- if(GetTypeId() != TYPEID_PLAYER || !this->isAlive())
- return false;
-
- // Select class defined buff
- switch (getClass())
- {
- case CLASS_PALADIN: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
- case CLASS_DRUID: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
- {
- uint32 RandomSpell[]={39511,40997,40998,40999,41002,41005,41009,41011,41409};
- triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
- break;
- }
- case CLASS_ROGUE: // 39511,40997,40998,41002,41005,41011
- case CLASS_WARRIOR: // 39511,40997,40998,41002,41005,41011
- {
- uint32 RandomSpell[]={39511,40997,40998,41002,41005,41011};
- triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
- break;
- }
- case CLASS_PRIEST: // 40999,41002,41005,41009,41011,41406,41409
- case CLASS_SHAMAN: // 40999,41002,41005,41009,41011,41406,41409
- case CLASS_MAGE: // 40999,41002,41005,41009,41011,41406,41409
- case CLASS_WARLOCK: // 40999,41002,41005,41009,41011,41406,41409
- {
- uint32 RandomSpell[]={40999,41002,41005,41009,41011,41406,41409};
- triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
- break;
- }
- case CLASS_HUNTER: // 40997,40999,41002,41005,41009,41011,41406,41409
- {
- uint32 RandomSpell[]={40997,40999,41002,41005,41009,41011,41406,41409};
- triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
- break;
- }
- default:
- return false;
- }
-
- target = this;
- if (roll_chance_i(10))
- ((Player*)this)->Say("This is Madness!", LANG_UNIVERSAL);
- break;
- }
- /*
- // Sunwell Exalted Caster Neck (??? neck)
- // cast ??? Light's Wrath if Exalted by Aldor
- // cast ??? Arcane Bolt if Exalted by Scryers*/
- case 46569:
- return false; // old unused version
- // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck)
- // cast 45479 Light's Wrath if Exalted by Aldor
- // cast 45429 Arcane Bolt if Exalted by Scryers
- case 45481:
- {
- if(GetTypeId() != TYPEID_PLAYER)
- return false;
-
- // Get Aldor reputation rank
- if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
- {
- target = this;
- triggered_spell_id = 45479;
- break;
- }
- // Get Scryers reputation rank
- if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
- {
- // triggered at positive/self casts also, current attack target used then
- if(IsFriendlyTo(target))
- {
- target = getVictim();
- if(!target)
- {
- uint64 selected_guid = ((Player *)this)->GetSelection();
- target = ObjectAccessor::GetUnit(*this,selected_guid);
- if(!target)
- return false;
- }
- if(IsFriendlyTo(target))
- return false;
- }
-
- triggered_spell_id = 45429;
- break;
- }
- return false;
- }
- // Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck)
- // cast 45480 Light's Strength if Exalted by Aldor
- // cast 45428 Arcane Strike if Exalted by Scryers
- case 45482:
- {
- if(GetTypeId() != TYPEID_PLAYER)
- return false;
-
- // Get Aldor reputation rank
- if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
- {
- target = this;
- triggered_spell_id = 45480;
- break;
- }
- // Get Scryers reputation rank
- if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
- {
- triggered_spell_id = 45428;
- break;
- }
- return false;
- }
- // Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck)
- // cast 45431 Arcane Insight if Exalted by Aldor
- // cast 45432 Light's Ward if Exalted by Scryers
- case 45483:
- {
- if(GetTypeId() != TYPEID_PLAYER)
- return false;
-
- // Get Aldor reputation rank
- if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
- {
- target = this;
- triggered_spell_id = 45432;
- break;
- }
- // Get Scryers reputation rank
- if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
- {
- target = this;
- triggered_spell_id = 45431;
- break;
- }
- return false;
- }
- // Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck)
- // cast 45478 Light's Salvation if Exalted by Aldor
- // cast 45430 Arcane Surge if Exalted by Scryers
- case 45484:
- {
- if(GetTypeId() != TYPEID_PLAYER)
- return false;
-
- // Get Aldor reputation rank
- if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
- {
- target = this;
- triggered_spell_id = 45478;
- break;
- }
- // Get Scryers reputation rank
- if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
- {
- triggered_spell_id = 45430;
- break;
- }
- return false;
- }
- // Living Seed
- case 48504:
- {
- triggered_spell_id = 48503;
- basepoints0 = triggerAmount;
- target = this;
- break;
- }
- // Kill command
- case 58914:
- {
- // Remove aura stack from pet
- RemoveAuraFromStack(58914);
- Unit* owner = GetOwner();
- if(!owner)
- return true;
- // reduce the owner's aura stack
- owner->RemoveAuraFromStack(34027);
- return true;
- }
- // Vampiric Touch (generic, used by some boss)
- case 52723:
- case 60501:
- {
- triggered_spell_id = 52724;
- basepoints0 = damage / 2;
- target = this;
- break;
- }
- // Shadowfiend Death (Gain mana if pet dies with Glyph of Shadowfiend)
- case 57989:
- {
- Unit *owner = GetOwner();
- if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
- return false;
- // Glyph of Shadowfiend (need cast as self cast for owner, no hidden cooldown)
- owner->CastSpell(owner,58227,true,castItem,triggeredByAura);
- return true;
- }
- // Divine purpose
- case 31871:
- case 31872:
- {
- // Roll chane
- if (!pVictim || !pVictim->isAlive() || !roll_chance_i(triggerAmount))
- return false;
-
- // Remove any stun effect on target
- pVictim->RemoveAurasWithMechanic(1<<MECHANIC_STUN, AURA_REMOVE_BY_ENEMY_SPELL);
- return true;
- }
- }
- break;
- }
- case SPELLFAMILY_MAGE:
- {
- // Magic Absorption
- if (dummySpell->SpellIconID == 459) // only this spell have SpellIconID == 459 and dummy aura
- {
- if (getPowerType() != POWER_MANA)
- return false;
-
- // mana reward
- basepoints0 = (triggerAmount * GetMaxPower(POWER_MANA) / 100);
- target = this;
- triggered_spell_id = 29442;
- break;
- }
- // Master of Elements
- if (dummySpell->SpellIconID == 1920)
- {
- if(!procSpell)
- return false;
-
- // mana cost save
- int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
- basepoints0 = cost * triggerAmount/100;
- if( basepoints0 <=0 )
- return false;
-
- target = this;
- triggered_spell_id = 29077;
- break;
- }
- // Arcane Potency
- if (dummySpell->SpellIconID == 2120)
- {
- if(!procSpell)
- return false;
-
- target = this;
- switch (dummySpell->Id)
- {
- case 31571: triggered_spell_id = 57529; break;
- case 31572: triggered_spell_id = 57531; break;
- default:
- sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u",dummySpell->Id);
- return false;
- }
- break;
- }
-
- // Hot Streak
- if (dummySpell->SpellIconID == 2999)
- {
- if (effIndex!=0)
- return false;
- AuraEffect *counter = triggeredByAura->GetBase()->GetEffect(1);
- if (!counter)
- return true;
-
- // Count spell criticals in a row in second aura
- if (procEx & PROC_EX_CRITICAL_HIT)
- {
- counter->SetAmount(counter->GetAmount()*2);
- if (counter->GetAmount() < 100) // not enough
- return true;
- // Crititcal counted -> roll chance
- if (roll_chance_i(triggerAmount))
- CastSpell(this, 48108, true, castItem, triggeredByAura);
- }
- counter->SetAmount(25);
- return true;
- }
- // Burnout
- if (dummySpell->SpellIconID == 2998)
- {
- if(!procSpell)
- return false;
-
- int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
- basepoints0 = cost * triggerAmount/100;
- if( basepoints0 <=0 )
- return false;
- triggered_spell_id = 44450;
- target = this;
- break;
- }
- // Incanter's Regalia set (add trigger chance to Mana Shield)
- if (dummySpell->SpellFamilyFlags[0] & 0x8000)
- {
- if(GetTypeId() != TYPEID_PLAYER)
- return false;
-
- target = this;
- triggered_spell_id = 37436;
- break;
- }
- switch(dummySpell->Id)
- {
- // Glyph of Polymorph
- case 56375:
- {
- target->RemoveAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
- target->RemoveAurasByType(SPELL_AURA_PERIODIC_DAMAGE_PERCENT);
- return true;
- }
- // Glyph of Drain Soul
- case 58070:
- {
- triggered_spell_id = 58068;
- break;
- }
- // Glyph of Icy Veins
- case 56374:
- {
- RemoveAurasByType(SPELL_AURA_MOD_HASTE, 0, 0, true, false);
- RemoveAurasByType(SPELL_AURA_MOD_DECREASE_SPEED);
- return true;
- }
- // Ignite
- case 11119:
- case 11120:
- case 12846:
- case 12847:
- case 12848:
- {
- switch (dummySpell->Id)
- {
- case 11119: basepoints0 = int32(0.04f*damage); break;
- case 11120: basepoints0 = int32(0.08f*damage); break;
- case 12846: basepoints0 = int32(0.12f*damage); break;
- case 12847: basepoints0 = int32(0.16f*damage); break;
- case 12848: basepoints0 = int32(0.20f*damage); break;
- default:
- sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (IG)",dummySpell->Id);
- return false;
- }
-
- AuraEffectList const& DoTAuras = target->GetAuraEffectsByType(SPELL_AURA_PERIODIC_DAMAGE);
- for (Unit::AuraEffectList::const_iterator i = DoTAuras.begin(); i != DoTAuras.end(); ++i)
- {
- if ((*i)->GetCasterGUID() != GetGUID() || (*i)->GetId() != 12654 || (*i)->GetEffIndex() != 0)
- continue;
- basepoints0 += ((*i)->GetAmount() * ((*i)->GetTotalTicks() - ((*i)->GetTickNumber()))) / 2;
- break;
- }
-
- triggered_spell_id = 12654;
- break;
- }
- // Glyph of Ice Block
- case 56372:
- {
- if(GetTypeId() != TYPEID_PLAYER)
- return false;
-
- SpellCooldowns const SpellCDs = ((Player*)this)->GetSpellCooldowns();
- // remove cooldowns on all ranks of Frost Nova
- for (SpellCooldowns::const_iterator itr = SpellCDs.begin(); itr != SpellCDs.end(); itr++)
- {
- SpellEntry const* SpellCDs_entry = sSpellStore.LookupEntry(itr->first);
- // Frost Nova
- if(SpellCDs_entry && SpellCDs_entry->SpellFamilyName == SPELLFAMILY_MAGE
- && SpellCDs_entry->SpellFamilyFlags[0] & 0x00000040)
- ((Player*)this)->RemoveSpellCooldown(SpellCDs_entry->Id, true);
- }
- break;
- }
- }
- break;
- }
- case SPELLFAMILY_WARRIOR:
- {
- switch(dummySpell->Id)
- {
- // Sweeping Strikes
- case 12328:
- {
- target = SelectNearbyTarget();
- if(!target)
- return false;
-
- triggered_spell_id = 26654;
- break;
- }
- // Improved Spell Reflection
- case 59088:
- case 59089:
- {
- triggered_spell_id = 59725;
- target = this;
- break;
- }
- }
-
- // Retaliation
- if(dummySpell->SpellFamilyFlags[1] & 0x8)
- {
- // check attack comes not from behind
- if (!HasInArc(M_PI, pVictim))
- return false;
-
- triggered_spell_id = 22858;
- break;
- }
- // Second Wind
- if (dummySpell->SpellIconID == 1697)
- {
- // only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example)
- if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
- return false;
- // Need stun or root mechanic
- if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_STUN))))
- return false;
-
- switch (dummySpell->Id)
- {
- case 29838: triggered_spell_id=29842; break;
- case 29834: triggered_spell_id=29841; break;
- case 42770: triggered_spell_id=42771; break;
- default:
- sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)",dummySpell->Id);
- return false;
- }
-
- target = this;
- break;
- }
- // Damage Shield
- if (dummySpell->SpellIconID == 3214)
- {
- triggered_spell_id = 59653;
- // % of amount blocked
- basepoints0 = GetShieldBlockValue() * triggerAmount / 100;
- break;
- }
- // Glyph of Blocking
- if (dummySpell->Id == 58375)
- {
- triggered_spell_id = 58374;
- break;
- }
- // Glyph of Sunder Armor
- if (dummySpell->Id == 58387)
- {
- if (!pVictim || !pVictim->isAlive() || !procSpell)
- return false;
-
- target = SelectNearbyTarget();
- if (!target || target == pVictim)
- return false;
-
- CastSpell(target, 58567, true);
- return true;
- }
- break;
- }
- case SPELLFAMILY_WARLOCK:
- {
- // Seed of Corruption
- if (dummySpell->SpellFamilyFlags[1] & 0x00000010)
- {
- if(procSpell && procSpell->Id == 27285)
- return false;
- // if damage is more than need or target die from damage deal finish spell
- if( triggeredByAura->GetAmount() <= damage || GetHealth() <= damage )
- {
- // remember guid before aura delete
- uint64 casterGuid = triggeredByAura->GetCasterGUID();
-
- // Remove aura (before cast for prevent infinite loop handlers)
- RemoveAurasDueToSpell(triggeredByAura->GetId());
-
- // Cast finish spell (triggeredByAura already not exist!)
- if(Unit* caster = GetUnit(*this, casterGuid))
- caster->CastSpell(this, 27285, true, castItem);
- return true; // no hidden cooldown
- }
-
- // Damage counting
- triggeredByAura->SetAmount(triggeredByAura->GetAmount() - damage);
- return true;
- }
- // Seed of Corruption (Mobs cast) - no die req
- if (dummySpell->SpellFamilyFlags.IsEqual(0,0,0) && dummySpell->SpellIconID == 1932)
- {
- // if damage is more than need deal finish spell
- if( triggeredByAura->GetAmount() <= damage )
- {
- // remember guid before aura delete
- uint64 casterGuid = triggeredByAura->GetCasterGUID();
-
- // Remove aura (before cast for prevent infinite loop handlers)
- RemoveAurasDueToSpell(triggeredByAura->GetId());
-
- // Cast finish spell (triggeredByAura already not exist!)
- if(Unit* caster = GetUnit(*this, casterGuid))
- caster->CastSpell(this, 32865, true, castItem);
- return true; // no hidden cooldown
- }
- // Damage counting
- triggeredByAura->SetAmount(triggeredByAura->GetAmount() - damage);
- return true;
- }
- // Fel Synergy
- if (dummySpell->SpellIconID == 3222)
- {
- target = GetGuardianPet();
- if (!target)
- return false;
- basepoints0 = damage * triggerAmount / 100;
- triggered_spell_id = 54181;
- break;
- }
- switch (dummySpell->Id)
- {
- // Siphon Life
- case 63108:
- {
- // Glyph of Siphon Life
- if (HasAura(56216))
- triggerAmount += triggerAmount / 4;
- triggered_spell_id = 63106;
- target = this;
- basepoints0 = int32(damage*triggerAmount/100);
- break;
- }
- // Glyph of Shadowflame
- case 63310:
- {
- triggered_spell_id = 63311;
- break;
- }
- // Glyph of Life Tap
- case 63320:
- {
- triggered_spell_id = 63321;
- break;
- }
- // Nightfall
- case 18094:
- case 18095:
- // Glyph of corruption
- case 56218:
- {
- target = this;
- triggered_spell_id = 17941;
- break;
- }
- //Soul Leech
- case 30293:
- case 30295:
- case 30296:
- {
- // Improved Soul Leech
- AuraEffectList const& SoulLeechAuras = GetAuraEffectsByType(SPELL_AURA_DUMMY);
- for (Unit::AuraEffectList::const_iterator i = SoulLeechAuras.begin(); i != SoulLeechAuras.end(); ++i)
- {
- if ((*i)->GetId()==54117 || (*i)->GetId()==54118)
- {
- if ((*i)->GetEffIndex() != 0)
- continue;
- basepoints0 = int32((*i)->GetAmount());
- if (target = GetGuardianPet())
- {
- // regen mana for pet
- CastCustomSpell(target,54607,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
- }
- // regen mana for caster
- CastCustomSpell(this,59117,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
- // Get second aura of spell for replenishment effect on party
- if (AuraEffect const * aurEff = (*i)->GetBase()->GetEffect(1))
- {
- // Replenishment - roll chance
- if (roll_chance_i(aurEff->GetAmount()))
- {
- CastSpell(this,57669,true, castItem, triggeredByAura);
- }
- }
- break;
- }
- }
- // health
- basepoints0 = int32(damage*triggerAmount/100);
- target = this;
- triggered_spell_id = 30294;
- break;
- }
- // Shadowflame (Voidheart Raiment set bonus)
- case 37377:
- {
- triggered_spell_id = 37379;
- break;
- }
- // Pet Healing (Corruptor Raiment or Rift Stalker Armor)
- case 37381:
- {
- target = GetGuardianPet();
- if(!target)
- return false;
-
- // heal amount
- basepoints0 = damage * triggerAmount/100;
- triggered_spell_id = 37382;
- break;
- }
- // Shadowflame Hellfire (Voidheart Raiment set bonus)
- case 39437:
- {
- triggered_spell_id = 37378;
- break;
- }
- }
- break;
- }
- case SPELLFAMILY_PRIEST:
- {
- // Vampiric Touch
- if( dummySpell->SpellFamilyFlags[1] & 0x00000400 )
- {
- if(!pVictim || !pVictim->isAlive())
- return false;
-
- if (effIndex!=0)
- return false;
-
- // pVictim is caster of aura
- if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
- return false;
-
- // Energize 0.25% of max. mana
- pVictim->CastSpell(pVictim,57669,true,castItem,triggeredByAura);
- return true; // no hidden cooldown
- }
- // Divine Aegis
- if (dummySpell->SpellIconID == 2820)
- {
- // Multiple effects stack, so let's try to find this aura.
- int32 bonus = 0;
- if (AuraEffect *aurEff = target->GetAuraEffect(47753, 0))
- bonus = aurEff->GetAmount();
-
- basepoints0 = damage * triggerAmount/100 + bonus;
- if (basepoints0 > target->getLevel() * 125)
- basepoints0 = target->getLevel() * 125;
-
- triggered_spell_id = 47753;
- break;
- }
- // Body and Soul
- if (dummySpell->SpellIconID == 2218)
- {
- // Proc only from Abolish desease on self cast
- if (procSpell->Id != 552 || pVictim != this || !roll_chance_i(triggerAmount))
- return false;
- triggered_spell_id = 64136;
- target = this;
- break;
- }
- switch(dummySpell->Id)
- {
- // Vampiric Embrace
- case 15286:
- {
- if(!pVictim || !pVictim->isAlive())
- return false;
-
- // heal amount
- int32 team = triggerAmount*damage/500;
- int32 self = triggerAmount*damage/100 - team;
- CastCustomSpell(this,15290,&team,&self,NULL,true,castItem,triggeredByAura);
- return true; // no hidden cooldown
- }
- // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen)
- case 40438:
- {
- // Shadow Word: Pain
- if( procSpell->SpellFamilyFlags[0] & 0x8000 )
- triggered_spell_id = 40441;
- // Renew
- else if( procSpell->SpellFamilyFlags[0] & 0x40 )
- triggered_spell_id = 40440;
- else
- return false;
-
- target = this;
- break;
- }
- // Glyph of Prayer of Healing
- case 55680:
- {
- triggered_spell_id = 56161;
-
- SpellEntry const* GoPoH = sSpellStore.LookupEntry(triggered_spell_id);
- if(!GoPoH)
- return false;
-
- int EffIndex = 0;
- for (uint8 i = 0; i < MAX_SPELL_EFFECTS; i++)
- {
- if(GoPoH->Effect[i] == SPELL_EFFECT_APPLY_AURA)
- {
- EffIndex = i;
- break;
- }
- }
- int32 tickcount = GetSpellMaxDuration(GoPoH) / GoPoH->EffectAmplitude[EffIndex];
- if(!tickcount)
- return false;
-
- basepoints0 = damage * triggerAmount / tickcount / 100;
- break;
- }
- // Improved Shadowform
- case 47570:
- case 47569:
- {
- if (!roll_chance_i(triggerAmount))
- return false;
-
- RemoveMovementImpairingAuras();
- break;
- }
- // Glyph of Dispel Magic
- case 55677:
- {
- // Dispel Magic shares spellfamilyflag with abolish disease
- if (procSpell->SpellIconID != 74)
- return false;
- if(!target || !target->IsFriendlyTo(this))
- return false;
-
- basepoints0 = int32(target->GetMaxHealth() * triggerAmount / 100);
- triggered_spell_id = 56131;
- break;
- }
- // Oracle Healing Bonus ("Garments of the Oracle" set)
- case 26169:
- {
- // heal amount
- basepoints0 = int32(damage * 10/100);
- target = this;
- triggered_spell_id = 26170;
- break;
- }
- // Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set
- case 39372:
- {
- if(!procSpell || (GetSpellSchoolMask(procSpell) & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW))==0 )
- return false;
-
- // heal amount
- basepoints0 = damage * triggerAmount/100;
- target = this;
- triggered_spell_id = 39373;
- break;
- }
- // Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus)
- case 28809:
- {
- triggered_spell_id = 28810;
- break;
- }
- }
- break;
- }
- case SPELLFAMILY_DRUID:
- {
- switch(dummySpell->Id)
- {
- // Glyph of Innervate
- case 54832:
- {
- if (procSpell->SpellIconID != 62)
- return false;
-
- int32 mana_perc = triggeredByAura->GetSpellProto()->EffectBasePoints[triggeredByAura->GetEffIndex()]+1;
- basepoints0 = uint32((GetPower(POWER_MANA) * mana_perc / 100) / 10);
- triggered_spell_id = 54833;
- target = this;
- break;
- }
- // Glyph of Starfire
- case 54845:
- {
- triggered_spell_id = 54846;
- break;
- }
- // Glyph of Shred
- case 54815:
- {
- triggered_spell_id = 63974;
- break;
- }
- // Glyph of Rake
- case 54821:
- {
- if (procSpell->SpellVisual[0] == 750 && procSpell->EffectApplyAuraName[1] == 3)
- {
- if (target->GetTypeId() == TYPEID_UNIT)
- {
- triggered_spell_id = 54820;
- break;
- }
- }
- return false;
- }
- // Leader of the Pack
- case 24932:
- {
- if (triggerAmount <= 0)
- return false;
- basepoints0 = triggerAmount * GetMaxHealth() / 100;
- target = this;
- triggered_spell_id = 34299;
- if (triggeredByAura->GetCasterGUID() != GetGUID())
- break;
- int32 basepoints1 = triggerAmount * 2;
- // Improved Leader of the Pack
- // Check cooldown of heal spell cooldown
- if (GetTypeId() == TYPEID_PLAYER && !((Player *)this)->HasSpellCooldown(34299))
- CastCustomSpell(this,60889,&basepoints1,0,0,true,0,triggeredByAura);
- break;
- }
- // Healing Touch (Dreamwalker Raiment set)
- case 28719:
- {
- // mana back
- basepoints0 = int32(procSpell->manaCost * 30 / 100);
- target = this;
- triggered_spell_id = 28742;
- break;
- }
- // Glyph of Rejuvenation
- case 54754:
- {
- if (!pVictim || pVictim->GetHealth() >= triggerAmount * pVictim->GetMaxHealth()/100)
- return false;
- basepoints0 = int32(triggerAmount * damage / 100);
- triggered_spell_id = 54755;
- break;
- }
- // Healing Touch Refund (Idol of Longevity trinket)
- case 28847:
- {
- target = this;
- triggered_spell_id = 28848;
- break;
- }
- // Mana Restore (Malorne Raiment set / Malorne Regalia set)
- case 37288:
- case 37295:
- {
- target = this;
- triggered_spell_id = 37238;
- break;
- }
- // Druid Tier 6 Trinket
- case 40442:
- {
- float chance;
-
- // Starfire
- if( procSpell->SpellFamilyFlags[0] & 0x4 )
- {
- triggered_spell_id = 40445;
- chance = 25.0f;
- }
- // Rejuvenation
- else if( procSpell->SpellFamilyFlags[0] & 0x10 )
- {
- triggered_spell_id = 40446;
- chance = 25.0f;
- }
- // Mangle (Bear) and Mangle (Cat)
- else if( procSpell->SpellFamilyFlags[1] & 0x00000440)
- {
- triggered_spell_id = 40452;
- chance = 40.0f;
- }
- else
- return false;
-
- if (!roll_chance_f(chance))
- return false;
-
- target = this;
- break;
- }
- // Maim Interrupt
- case 44835:
- {
- // Deadly Interrupt Effect
- triggered_spell_id = 32747;
- break;
- }
- }
- // Eclipse
- if (dummySpell->SpellIconID == 2856 && GetTypeId() == TYPEID_PLAYER)
- {
- if (!procSpell || effIndex != 0)
- return false;
-
- bool isWrathSpell = (procSpell->SpellFamilyFlags[0] & 1);
-
- if (!roll_chance_f(dummySpell->procChance * (isWrathSpell ? 0.6f : 1.0f)))
- return false;
-
- target = this;
- if (target->HasAura(isWrathSpell ? 48517 : 48518))
- return false;
-
- triggered_spell_id = isWrathSpell ? 48518 : 48517;
- break;
- }
- // Living Seed
- else if (dummySpell->SpellIconID == 2860)
- {
- triggered_spell_id = 48504;
- basepoints0 = triggerAmount * damage / 100;
- break;
- }
- // King of the Jungle
- else if (dummySpell->SpellIconID == 2850)
- {
- // Effect 0 - mod damage while having Enrage
- if (effIndex==0)
- {
- if (!(procSpell->SpellFamilyFlags[0] & 0x00080000))
- return false;
- triggered_spell_id = 51185;
- basepoints0 = triggerAmount;
- target = this;
- break;
- }
- // Effect 1 - Tiger's Fury restore energy
- else if (effIndex==1)
- {
- if (!(procSpell->SpellFamilyFlags[2] & 0x00000800))
- return false;
- triggered_spell_id = 51178;
- basepoints0 = triggerAmount;
- target = this;
- break;
- }
- }
- break;
- }
- case SPELLFAMILY_ROGUE:
- {
- switch(dummySpell->Id)
- {
- // Glyph of Backstab
- case 56800:
- {
- triggered_spell_id = 63975;
- break;
- }
- // Deadly Throw Interrupt
- case 32748:
- {
- // Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw
- if(this == pVictim)
- return false;
-
- triggered_spell_id = 32747;
- break;
- }
- }
- // Cut to the Chase
- if( dummySpell->SpellIconID == 2909 )
- {
- // "refresh your Slice and Dice duration to its 5 combo point maximum"
- // lookup Slice and Dice
- if (AuraEffect const* aur = GetAuraEffect(SPELL_AURA_MOD_HASTE, SPELLFAMILY_ROGUE,0x40000, 0, 0))
- {
- aur->GetBase()->SetDuration(GetSpellMaxDuration(aur->GetSpellProto()), true);
- return true;
- }
- return false;
- }
- // Deadly Brew
- else if( dummySpell->SpellIconID == 2963 )
- {
- triggered_spell_id = 3409;
- break;
- }
- // Quick Recovery
- else if( dummySpell->SpellIconID == 2116 )
- {
- if(!procSpell)
- return false;
-
- // energy cost save
- basepoints0 = procSpell->manaCost * triggerAmount/100;
- if(basepoints0 <= 0)
- return false;
-
- target = this;
- triggered_spell_id = 31663;
- break;
- }
- break;
- }
- case SPELLFAMILY_HUNTER:
- {
- // Thrill of the Hunt
- if ( dummySpell->SpellIconID == 2236 )
- {
- if(!procSpell)
- return false;
-
- // mana cost save
- int32 mana = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
- basepoints0 = mana * 40/100;
- if(basepoints0 <= 0)
- return false;
-
- target = this;
- triggered_spell_id = 34720;
- break;
- }
- // Hunting Party
- if ( dummySpell->SpellIconID == 3406 )
- {
- triggered_spell_id = 57669;
- target = this;
- break;
- }
- // Improved Mend Pet
- if ( dummySpell->SpellIconID == 267 )
- {
- int32 chance = triggeredByAura->GetSpellProto()->EffectBasePoints[triggeredByAura->GetEffIndex()];
- if(!roll_chance_i(chance))
- return false;
-
- triggered_spell_id = 24406;
- break;
- }
- // Lock and Load
- if ( dummySpell->SpellIconID == 3579 )
- {
- // Proc only from periodic (from trap activation proc another aura of this spell)
- if (!(procFlag & PROC_FLAG_ON_DO_PERIODIC) || !roll_chance_i(triggerAmount))
- return false;
- triggered_spell_id = 56453;
- target = this;
- break;
- }
- // Rapid Recuperation
- if (dummySpell->SpellIconID == 3560)
- {
- // This effect only from Rapid Killing (mana regen)
- if (!(procSpell->SpellFamilyFlags[1] & 0x01000000))
- return false;
- triggered_spell_id = 56654;
-
- target = this;
-
- switch(dummySpell->Id)
- {
- case 53228: // Rank 1
- triggered_spell_id = 56654;
- break;
- case 53232: // Rank 2
- triggered_spell_id = 58882;
- break;
- }
- break;
- }
- break;
- }
- case SPELLFAMILY_PALADIN:
- {
- // Seal of Righteousness - melee proc dummy (addition ${$MWS*(0.022*$AP+0.044*$SPH)} damage)
- if (dummySpell->SpellFamilyFlags[0]&0x8000000)
- {
- if (effIndex!=0)
- return false;
- triggered_spell_id = 25742;
- float ap = GetTotalAttackPowerValue(BASE_ATTACK);
- int32 holy = SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
- SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, pVictim);
- basepoints0 = (int32)GetAttackTime(BASE_ATTACK) * int32(ap*0.022f + 0.044f * holy) / 1000;
- break;
- }
- // Light's Beacon - Beacon of Light
- if (dummySpell->Id == 53651)
- {
- // Get target of beacon of light
- if (Unit * beaconTarget = triggeredByAura->GetBase()->GetCaster())
- {
- // do not proc when target of beacon of light is healed
- if (beaconTarget == this)
- return false;
- // check if it was heal by paladin which casted this beacon of light
- if (Aura const * aura = beaconTarget->GetAura(53563, pVictim->GetGUID()))
- {
- basepoints0 = damage;
- triggered_spell_id = 53654;
- target = beaconTarget;
- break;
- }
- }
- return false;
- }
- // Judgements of the Wise
- if (dummySpell->SpellIconID == 3017)
- {
- target = this;
- triggered_spell_id = 31930;
- // replenishment
- CastSpell(this,57669,true, castItem, triggeredByAura);
- break;
- }
- // Sanctified Wrath
- if (dummySpell->SpellIconID == 3029)
- {
- triggered_spell_id = 57318;
- target = this;
- basepoints0 = triggerAmount;
- CastCustomSpell(target,triggered_spell_id,&basepoints0,&basepoints0,NULL,true,castItem,triggeredByAura);
- return true;
- }
- // Sacred Shield
- if (dummySpell->SpellFamilyFlags[1]&0x00080000)
- {
- if (procFlag & PROC_FLAG_TAKEN_POSITIVE_MAGIC_SPELL)
- {
- if (procSpell->SpellFamilyName == SPELLFAMILY_PALADIN
- && (procSpell->SpellFamilyFlags[0] & 0x40000000))
- {
- basepoints0 = int32(float(damage)/12.0f);
- CastCustomSpell(this,66922,&basepoints0,NULL,NULL,true,0,triggeredByAura, pVictim->GetGUID());
- return true;
- }
- else
- return false;
- }
- else
- triggered_spell_id = 58597;
- target = this;
- break;
- }
- // Righteous Vengeance
- if (dummySpell->SpellIconID == 3025)
- {
- // 4 damage tick
- basepoints0 = triggerAmount*damage/400;
- triggered_spell_id = 61840;
- break;
- }
- // Sheath of Light
- if (dummySpell->SpellIconID == 3030)
- {
- // 4 healing tick
- basepoints0 = triggerAmount*damage/400;
- triggered_spell_id = 54203;
- break;
- }
- switch (dummySpell->Id)
- {
- // Heart of the Crusader
- case 20335: // rank 1
- triggered_spell_id = 21183;
- break;
- case 20336: // rank 2
- triggered_spell_id = 54498;
- break;
- case 20337: // rank 3
- triggered_spell_id = 54499;
- break;
- // Judgement of Light
- case 20185:
- {
- if (pVictim->getPowerType() == POWER_MANA)
- {
- // 2% of base mana
- basepoints0 = int32(pVictim->GetMaxHealth() * 2 / 100);
- pVictim->CastCustomSpell(pVictim, 20267, &basepoints0, 0, 0, true, 0, triggeredByAura);
- }
- return true;
- }
- // Judgement of Wisdom
- case 20186:
- {
- if (pVictim && pVictim->isAlive() && pVictim->getPowerType() == POWER_MANA)
- {
- // 2% of base mana
- basepoints0 = int32(pVictim->GetCreateMana() * 2 / 100);
- pVictim->CastCustomSpell(pVictim, 20268, &basepoints0, NULL, NULL, true, 0, triggeredByAura);
- }
- return true;
- }
- // Holy Power (Redemption Armor set)
- case 28789:
- {
- if(!pVictim)
- return false;
-
- // Set class defined buff
- switch (pVictim->getClass())
- {
- case CLASS_PALADIN:
- case CLASS_PRIEST:
- case CLASS_SHAMAN:
- case CLASS_DRUID:
- triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
- break;
- case CLASS_MAGE:
- case CLASS_WARLOCK:
- triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
- break;
- case CLASS_HUNTER:
- case CLASS_ROGUE:
- triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d.
- break;
- case CLASS_WARRIOR:
- triggered_spell_id = 28790; // Increases the friendly target's armor
- break;
- default:
- return false;
- }
- break;
- }
- case 25899: // Greater Blessing of Sanctuary
- case 20911: // Blessing of Sanctuary
- {
- target = this;
- switch (target->getPowerType())
- {
- case POWER_MANA:
- triggered_spell_id = 57319;
- break;
- default:
- return false;
- }
- break;
- }
- // Seal of Vengeance (damage calc on apply aura)
- case 31801:
- {
- if(effIndex != 0) // effect 1,2 used by seal unleashing code
- return false;
-
- // At melee attack or Hammer of the Righteous spell damage considered as melee attack
- if ((procFlag & PROC_FLAG_SUCCESSFUL_MELEE_HIT) || (procSpell && procSpell->Id == 53595) )
- triggered_spell_id = 31803;
- // On target with 5 stacks of Holy Vengeance direct damage is done
- if (Aura * aur = pVictim->GetAura(triggered_spell_id, GetGUID()))
- {
- if (aur->GetStackAmount() == 5)
- {
- aur->RefreshDuration();
- CastSpell(pVictim, 42463, true);
- return true;
- }
- }
-
- // Only Autoattack can stack debuff
- if (procFlag & PROC_FLAG_SUCCESSFUL_MELEE_SPELL_HIT)
- return false;
- break;
- }
- // Seal of Corruption
- case 53736:
- {
- if(effIndex != 0) // effect 1,2 used by seal unleashing code
- return false;
-
- // At melee attack or Hammer of the Righteous spell damage considered as melee attack
- if ((procFlag & PROC_FLAG_SUCCESSFUL_MELEE_HIT) || (procSpell && procSpell->Id == 53595))
- triggered_spell_id = 53742;
- // On target with 5 stacks of Blood Corruption direct damage is done
- if (Aura * aur = pVictim->GetAura(triggered_spell_id, GetGUID()))
- {
- if (aur->GetStackAmount() == 5)
- {
- aur->RefreshDuration();
- CastSpell(pVictim, 53739, true);
- return true;
- }
- }
-
- // Only Autoattack can stack debuff
- if (procFlag & PROC_FLAG_SUCCESSFUL_MELEE_SPELL_HIT)
- return false;
- break;
- }
- // Spiritual Attunement
- case 31785:
- case 33776:
- {
- // if healed by another unit (pVictim)
- if(this == pVictim)
- return false;
-
- // heal amount
- basepoints0 = triggerAmount*damage/100;
- target = this;
-
- if(basepoints0)
- triggered_spell_id = 31786;
- break;
- }
- // Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal)
- case 40470:
- {
- if( !procSpell )
- return false;
-
- float chance;
-
- // Flash of light/Holy light
- if( procSpell->SpellFamilyFlags[0] & 0xC0000000)
- {
- triggered_spell_id = 40471;
- chance = 15.0f;
- }
- // Judgement (any)
- else if (GetSpellSpecific(procSpell) == SPELL_SPECIFIC_JUDGEMENT)
- {
- triggered_spell_id = 40472;
- chance = 50.0f;
- }
- else
- return false;
-
- if (!roll_chance_f(chance))
- return false;
-
- break;
- }
- // Glyph of Divinity
- case 54939:
- {
- // Lookup base amount mana restore
- for (uint8 i=0; i<MAX_SPELL_EFFECTS; i++)
- if (procSpell->Effect[i] == SPELL_EFFECT_ENERGIZE)
- {
- int32 mana = procSpell->EffectBasePoints[i];
- CastCustomSpell(this, 54986, 0, &mana, 0, true, castItem, triggeredByAura);
- break;
- }
- return true;
- }
- // Glyph of Flash of Light
- case 54936:
- {
- triggered_spell_id = 54957;
- basepoints0 = triggerAmount*damage/100;
- break;
- }
- // Glyph of Holy Light
- case 54937:
- {
- triggered_spell_id = 54968;
- basepoints0 = triggerAmount*damage/100;
- break;
- }
- }
- break;
- }
- case SPELLFAMILY_SHAMAN:
- {
- switch(dummySpell->Id)
- {
- // Earthen Power (Rank 1, 2)
- case 51523:
- case 51524:
- {
- // Totem itself must be a caster of this spell
- Unit* caster = NULL;
- for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr) {
- if ((*itr)->GetEntry() != 2630)
- continue;
-
- caster = (*itr);
- break;
- }
-
- if (!caster)
- return false;
-
- caster->CastSpell(caster, 59566, true, castItem, triggeredByAura, originalCaster);
- return true;
- }
- // Tidal Force
- case 55198:
- {
- // Remove aura stack from caster
- RemoveAuraFromStack(55166);
- // drop charges
- return false;
- }
- // Totemic Power (The Earthshatterer set)
- case 28823:
- {
- if( !pVictim )
- return false;
-
- // Set class defined buff
- switch (pVictim->getClass())
- {
- case CLASS_PALADIN:
- case CLASS_PRIEST:
- case CLASS_SHAMAN:
- case CLASS_DRUID:
- triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
- break;
- case CLASS_MAGE:
- case CLASS_WARLOCK:
- triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
- break;
- case CLASS_HUNTER:
- case CLASS_ROGUE:
- triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d.
- break;
- case CLASS_WARRIOR:
- triggered_spell_id = 28827; // Increases the friendly target's armor
- break;
- default:
- return false;
- }
- break;
- }
- // Lesser Healing Wave (Totem of Flowing Water Relic)
- case 28849:
- {
- target = this;
- triggered_spell_id = 28850;
- break;
- }
- // Windfury Weapon (Passive) 1-5 Ranks
- case 33757:
- {
- if(GetTypeId()!=TYPEID_PLAYER || !castItem || !castItem->IsEquipped() || !pVictim || !pVictim->isAlive())
- return false;
-
- // custom cooldown processing case
- if( cooldown && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
- return false;
-
- if (triggeredByAura->GetBase() && castItem->GetGUID() != triggeredByAura->GetBase()->GetCastItemGUID())
- return false;
-
- WeaponAttackType attType = WeaponAttackType(((Player*)this)->GetAttackBySlot(castItem->GetSlot()));
- if ((attType != BASE_ATTACK && attType != OFF_ATTACK) || !isAttackReady(attType))
- return false;
-
- // Now compute real proc chance...
- uint32 chance = 20;
- ((Player*)this)->ApplySpellMod(dummySpell->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
-
- Item* addWeapon = ((Player*)this)->GetWeaponForAttack(attType == BASE_ATTACK ? OFF_ATTACK : BASE_ATTACK, true);
- uint32 enchant_id_add = addWeapon ? addWeapon->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)) : 0;
- SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id_add);
- if (pEnchant && pEnchant->spellid[0] == dummySpell->Id)
- chance += 14;
-
- if (!roll_chance_i(chance))
- return false;
-
- // Now amount of extra power stored in 1 effect of Enchant spell
- // Get it by item enchant id
- uint32 spellId;
- switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)))
- {
- case 283: spellId = 8232; break; // 1 Rank
- case 284: spellId = 8235; break; // 2 Rank
- case 525: spellId = 10486; break; // 3 Rank
- case 1669:spellId = 16362; break; // 4 Rank
- case 2636:spellId = 25505; break; // 5 Rank
- case 3785:spellId = 58801; break; // 6 Rank
- case 3786:spellId = 58803; break; // 7 Rank
- case 3787:spellId = 58804; break; // 8 Rank
- default:
- {
- sLog.outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)",
- castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)),dummySpell->Id);
- return false;
- }
- }
-
- SpellEntry const* windfurySpellEntry = sSpellStore.LookupEntry(spellId);
- if(!windfurySpellEntry)
- {
- sLog.outError("Unit::HandleDummyAuraProc: non existed spell id: %u (Windfury)",spellId);
- return false;
- }
-
- int32 extra_attack_power = CalculateSpellDamage(windfurySpellEntry, 1, windfurySpellEntry->EffectBasePoints[1], pVictim);
-
- // Value gained from additional AP
- basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(BASE_ATTACK)/1000);
- triggered_spell_id = 25504;
-
- // apply cooldown before cast to prevent processing itself
- if( cooldown )
- ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
-
- // Attack Twice
- for (uint32 i = 0; i<2; ++i )
- CastCustomSpell(pVictim,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
-
- return true;
- }
- // Shaman Tier 6 Trinket
- case 40463:
- {
- if (!procSpell)
- return false;
-
- float chance;
- if (procSpell->SpellFamilyFlags[0] & 0x1)
- {
- triggered_spell_id = 40465; // Lightning Bolt
- chance = 15.0f;
- }
- else if (procSpell->SpellFamilyFlags[0] & 0x80)
- {
- triggered_spell_id = 40465; // Lesser Healing Wave
- chance = 10.0f;
- }
- else if (procSpell->SpellFamilyFlags[1] & 0x00000010)
- {
- triggered_spell_id = 40466; // Stormstrike
- chance = 50.0f;
- }
- else
- return false;
-
- if (!roll_chance_f(chance))
- return false;
-
- target = this;
- break;
- }
- // Glyph of Healing Wave
- case 55440:
- {
- // Not proc from self heals
- if (this == pVictim)
- return false;
- basepoints0 = triggerAmount * damage / 100;
- target = this;
- triggered_spell_id = 55533;
- break;
- }
- // Spirit Hunt
- case 58877:
- {
- // Cast on owner
- target = GetOwner();
- if(!target)
- return false;
- basepoints0 = triggerAmount * damage / 100;
- triggered_spell_id = 58879;
- break;
- }
- // Shaman T8 Elemental 4P Bonus
- case 64928:
- {
- basepoints0 = int32( triggerAmount * damage / 100 );
- triggered_spell_id = 64930; // Electrified
- break;
- }
- }
- // Frozen Power
- if (dummySpell->SpellIconID == 3780)
- {
- if (this->GetDistance(target) < 15.0f)
- return false;
- float chance = triggerAmount;
- if (!roll_chance_f(chance))
- return false;
-
- triggered_spell_id = 63685;
- break;
- }
- // Storm, Earth and Fire
- if (dummySpell->SpellIconID == 3063)
- {
- // Earthbind Totem summon only
- if(procSpell->Id != 2484)
- return false;
-
- float chance = triggerAmount;
- if (!roll_chance_f(chance))
- return false;
-
- triggered_spell_id = 64695;
- break;
- }
- // Ancestral Awakening
- if (dummySpell->SpellIconID == 3065)
- {
- triggered_spell_id = 52759;
- basepoints0 = triggerAmount * damage / 100;
- target = this;
- break;
- }
- // Earth Shield
- if(dummySpell->SpellFamilyFlags[1] & 0x00000400)
- {
- // 3.0.8: Now correctly uses the Shaman's own spell critical strike chance to determine the chance of a critical heal.
- originalCaster = triggeredByAura->GetCasterGUID();
- target = this;
- basepoints0 = triggerAmount;
-
- // Glyph of Earth Shield
- if (AuraEffect* aur = GetAuraEffect(63279,0))
- {
- int32 aur_mod = aur->GetAmount();
- basepoints0 = int32(basepoints0 * (aur_mod + 100.0f) / 100.0f);
- }
- triggered_spell_id = 379;
- break;
- }
- // Flametongue Weapon (Passive)
- if (dummySpell->SpellFamilyFlags[0] & 0x200000)
- {
- if(GetTypeId()!=TYPEID_PLAYER || !pVictim || !pVictim->isAlive() || !castItem || !castItem->IsEquipped())
- return false;
-
- // firehit = dummySpell->EffectBasePoints[0] / ((4*19.25) * 1.3);
- float fire_onhit = dummySpell->EffectBasePoints[0] / 100.0;
-
- float add_spellpower = SpellBaseDamageBonus(SPELL_SCHOOL_MASK_FIRE)
- + SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_FIRE, pVictim);
-
- // 1.3speed = 5%, 2.6speed = 10%, 4.0 speed = 15%, so, 1.0speed = 3.84%
- add_spellpower= add_spellpower / 100.0 * 3.84;
-
- // Enchant on Off-Hand and ready?
- if ( castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND && isAttackReady(OFF_ATTACK))
- {
- float BaseWeaponSpeed = GetAttackTime(OFF_ATTACK)/1000.0;
-
- // Value1: add the tooltip damage by swingspeed + Value2: add spelldmg by swingspeed
- basepoints0 = int32( (fire_onhit * BaseWeaponSpeed) + (add_spellpower * BaseWeaponSpeed) );
- triggered_spell_id = 10444;
- }
-
- // Enchant on Main-Hand and ready?
- else if ( castItem->GetSlot() == EQUIPMENT_SLOT_MAINHAND && isAttackReady(BASE_ATTACK))
- {
- float BaseWeaponSpeed = GetAttackTime(BASE_ATTACK)/1000.0;
-
- // Value1: add the tooltip damage by swingspeed + Value2: add spelldmg by swingspeed
- basepoints0 = int32( (fire_onhit * BaseWeaponSpeed) + (add_spellpower * BaseWeaponSpeed) );
- triggered_spell_id = 10444;
- }
-
- // If not ready, we should return, shouldn't we?!
- else
- return false;
-
- CastCustomSpell(pVictim,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
- return true;
- }
- // Improved Water Shield
- if (dummySpell->SpellIconID == 2287)
- {
- // Default chance for Healing Wave and Riptide
- float chance = triggeredByAura->GetAmount();
-
- if (procSpell->SpellFamilyFlags[0] & 0x80)
- // Lesser Healing Wave - 0.6 of default
- chance *= 0.6f;
- else if (procSpell->SpellFamilyFlags[0] & 0x100)
- // Chain heal - 0.3 of default
- chance *= 0.3f;
-
- if (!roll_chance_f(chance))
- return false;
-
- // Water Shield
- if (AuraEffect const * aurEff = GetAuraEffect(SPELL_AURA_PROC_TRIGGER_SPELL, SPELLFAMILY_SHAMAN, 0, 0x00000020, 0))
- {
- uint32 spell = aurEff->GetSpellProto()->EffectTriggerSpell[aurEff->GetEffIndex()];
- CastSpell(this, spell, true, castItem, triggeredByAura);
- return true;
- }
- return false;
- }
- // Lightning Overload
- if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura
- {
- if(!procSpell || GetTypeId() != TYPEID_PLAYER || !pVictim )
- return false;
-
- // custom cooldown processing case
- if( cooldown && GetTypeId() == TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
- return false;
-
- uint32 spellId = 0;
- // Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost
- switch (procSpell->Id)
- {
- // Lightning Bolt
- case 403: spellId = 45284; break; // Rank 1
- case 529: spellId = 45286; break; // Rank 2
- case 548: spellId = 45287; break; // Rank 3
- case 915: spellId = 45288; break; // Rank 4
- case 943: spellId = 45289; break; // Rank 5
- case 6041: spellId = 45290; break; // Rank 6
- case 10391: spellId = 45291; break; // Rank 7
- case 10392: spellId = 45292; break; // Rank 8
- case 15207: spellId = 45293; break; // Rank 9
- case 15208: spellId = 45294; break; // Rank 10
- case 25448: spellId = 45295; break; // Rank 11
- case 25449: spellId = 45296; break; // Rank 12
- case 49237: spellId = 49239; break; // Rank 13
- case 49238: spellId = 49240; break; // Rank 14
- // Chain Lightning
- case 421: spellId = 45297; break; // Rank 1
- case 930: spellId = 45298; break; // Rank 2
- case 2860: spellId = 45299; break; // Rank 3
- case 10605: spellId = 45300; break; // Rank 4
- case 25439: spellId = 45301; break; // Rank 5
- case 25442: spellId = 45302; break; // Rank 6
- case 49270: spellId = 49268; break; // Rank 7
- case 49271: spellId = 49269; break; // Rank 8
- default:
- sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (LO)", procSpell->Id);
- return false;
- }
- // No thread generated mod
- // TODO: exist special flag in spell attributes for this, need found and use!
- SpellModifier *mod = new SpellModifier;
- mod->op = SPELLMOD_THREAT;
- mod->value = -100;
- mod->type = SPELLMOD_PCT;
- mod->spellId = dummySpell->Id;
- mod->mask[0] = 0x02;
- mod->mask[2] = 0x00;
- ((Player*)this)->AddSpellMod(mod, true);
-
- // Remove cooldown (Chain Lightning - have Category Recovery time)
- if (procSpell->SpellFamilyFlags[0] & 0x2)
- ((Player*)this)->RemoveSpellCooldown(spellId);
-
- CastSpell(pVictim, spellId, true, castItem, triggeredByAura);
-
- ((Player*)this)->AddSpellMod(mod, false);
-
- if( cooldown && GetTypeId() == TYPEID_PLAYER )
- ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
-
- return true;
- }
- // Static Shock
- if(dummySpell->SpellIconID == 3059)
- {
- // Lightning Shield
- if (AuraEffect const * aurEff = GetAuraEffect(SPELL_AURA_PROC_TRIGGER_SPELL, SPELLFAMILY_SHAMAN, 0x400, 0, 0))
- {
- uint32 spell = spellmgr.GetSpellWithRank(26364, spellmgr.GetSpellRank(aurEff->GetId()));
-
- // custom cooldown processing case
- if (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(spell))
- ((Player*)this)->RemoveSpellCooldown(spell);
-
- CastSpell(target, spell, true, castItem, triggeredByAura);
- aurEff->GetBase()->DropCharge();
- return true;
- }
- return false;
- }
- break;
- }
- case SPELLFAMILY_DEATHKNIGHT:
- {
- // Blood-Caked Strike - Blood-Caked Blade
- if (dummySpell->SpellIconID == 138)
- {
- if (!target || !target->isAlive())
- return false;
-
- triggered_spell_id = dummySpell->EffectTriggerSpell[effIndex];
- break;
- }
- // Improved Blood Presence
- if (dummySpell->SpellIconID == 2636)
- {
- if (GetTypeId() != TYPEID_PLAYER)
- return false;
- basepoints0 = triggerAmount * damage / 100;
- break;
- }
- // Butchery
- if (dummySpell->SpellIconID == 2664)
- {
- basepoints0 = triggerAmount;
- triggered_spell_id = 50163;
- target = this;
- break;
- }
- // Dancing Rune Weapon
- if (dummySpell->Id == 49028)
- {
- // 1 dummy aura for dismiss rune blade
- if (effIndex!=2)
- return false;
- uint64 PetGUID = NULL;
- for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr) //Find Rune Weapon
- if ((*itr)->GetEntry() == 27893)
- {
- PetGUID = (*itr)->GetGUID();
- break;
- }
-
- if (PetGUID && pVictim && damage && procSpell)
- {
- int32 procDmg = damage / 2;
- CastCustomSpell(pVictim, procSpell->Id, &procDmg, NULL, NULL, true, NULL, NULL, PetGUID);
- break;
- }
- else
- return false;
- }
- // Mark of Blood
- if (dummySpell->Id == 49005)
- {
- // TODO: need more info (cooldowns/PPM)
- triggered_spell_id = 61607;
- break;
- }
- // Unholy Blight
- if (dummySpell->Id == 49194)
- {
- basepoints0 = triggerAmount * damage / 100;
- // Glyph of Unholy Blight
- if (AuraEffect *glyph=GetAuraEffect(63332,0))
- basepoints0 += basepoints0 * glyph->GetAmount() / 100;
- // Find replaced aura to use it's remaining amount
- AuraEffectList const& DoTAuras = target->GetAuraEffectsByType(SPELL_AURA_PERIODIC_DAMAGE);
- for (Unit::AuraEffectList::const_iterator i = DoTAuras.begin(); i != DoTAuras.end(); ++i)
- {
- if ((*i)->GetCasterGUID() != GetGUID() || (*i)->GetId() != 50536)
- continue;
- basepoints0 += ((*i)->GetAmount() * ((*i)->GetTotalTicks() - ((*i)->GetTickNumber()))) / (*i)->GetTotalTicks();
- break;
- }
-
- triggered_spell_id = 50536;
- break;
- }
- // Vendetta
- if (dummySpell->SpellFamilyFlags[0] & 0x10000)
- {
- basepoints0 = triggerAmount * GetMaxHealth() / 100;
- triggered_spell_id = 50181;
- target = this;
- break;
- }
- // Necrosis
- if (dummySpell->SpellIconID == 2709)
- {
- basepoints0 = triggerAmount * damage / 100;
- triggered_spell_id = 51460;
- break;
- }
- // Threat of Thassarian
- if (dummySpell->SpellIconID == 2023)
- {
- // Must Dual Wield
- if (!procSpell || !haveOffhandWeapon())
- return false;
- // Chance as basepoints for dummy aura
- if (!roll_chance_i(triggerAmount))
- return false;
-
- switch (procSpell->Id)
- {
- // Obliterate
- case 49020: triggered_spell_id = 66198; break; // Rank 1
- case 51423: triggered_spell_id = 66972; break; // Rank 2
- case 51424: triggered_spell_id = 66973; break; // Rank 3
- case 51425: triggered_spell_id = 66974; break; // Rank 4
-
- // Frost Strike
- case 49143: triggered_spell_id = 66196; break; // Rank 1
- case 51416: triggered_spell_id = 66958; break; // Rank 2
- case 51417: triggered_spell_id = 66959; break; // Rank 3
- case 51418: triggered_spell_id = 66960; break; // Rank 4
- case 51419: triggered_spell_id = 66961; break; // Rank 5
- case 51420: triggered_spell_id = 66962; break; // Rank 6
-
- // Plague Strike
- case 45462: triggered_spell_id = 66216; break; // Rank 1
- case 49917: triggered_spell_id = 66988; break; // Rank 2
- case 49918: triggered_spell_id = 66989; break; // Rank 3
- case 49919: triggered_spell_id = 66990; break; // Rank 4
- case 49920: triggered_spell_id = 66991; break; // Rank 5
- case 49921: triggered_spell_id = 66992; break; // Rank 6
-
- // Death Strike
- case 49998: triggered_spell_id = 66188; break; // Rank 1
- case 49999: triggered_spell_id = 66950; break; // Rank 2
- case 45463: triggered_spell_id = 66951; break; // Rank 3
- case 49923: triggered_spell_id = 66952; break; // Rank 4
- case 49924: triggered_spell_id = 66953; break; // Rank 5
-
- // Rune Strike
- case 56815: triggered_spell_id = 66217; break; // Rank 1
-
- // Blood Strike
- case 45902: triggered_spell_id = 66215; break; // Rank 1
- case 49926: triggered_spell_id = 66975; break; // Rank 2
- case 49927: triggered_spell_id = 66976; break; // Rank 3
- case 49928: triggered_spell_id = 66977; break; // Rank 4
- case 49929: triggered_spell_id = 66978; break; // Rank 5
- case 49930: triggered_spell_id = 66979; break; // Rank 6
- default:
- return false;
- }
- break;
- }
- // Runic Power Back on Snare/Root
- if (dummySpell->Id == 61257)
- {
- // only for spells and hit/crit (trigger start always) and not start from self casted spells
- if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
- return false;
- // Need snare or root mechanic
- if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_SNARE))))
- return false;
- triggered_spell_id = 61258;
- target = this;
- break;
- }
- // Wandering Plague
- if (dummySpell->SpellIconID == 1614)
- {
- if (!roll_chance_f(GetUnitCriticalChance(BASE_ATTACK, pVictim)))
- return false;
- basepoints0 = triggerAmount * damage / 100;
- triggered_spell_id = 50526;
- break;
- }
- // Sudden Doom
- if (dummySpell->SpellIconID == 1939 && GetTypeId() == TYPEID_PLAYER)
- {
- SpellChainNode const* chain = NULL;
- // get highest rank of the Death Coil spell
- const PlayerSpellMap& sp_list = ((Player*)this)->GetSpellMap();
- for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
- {
- // check if shown in spell book
- if(!itr->second->active || itr->second->disabled || itr->second->state == PLAYERSPELL_REMOVED)
- continue;
-
- SpellEntry const *spellProto = sSpellStore.LookupEntry(itr->first);
- if (!spellProto)
- continue;
-
- if (spellProto->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT
- && spellProto->SpellFamilyFlags[0] & 0x2000)
- {
- SpellChainNode const* newChain = spellmgr.GetSpellChainNode(itr->first);
-
- // No chain entry or entry lower than found entry
- if (!chain || !newChain || (chain->rank < newChain->rank))
- {
- triggered_spell_id = itr->first;
- chain = newChain;
- }
- else
- continue;
- // Found spell is last in chain - do not need to look more
- // Optimisation for most common case
- if (chain && chain->last == itr->first)
- break;
- }
- }
- }
- break;
- }
- case SPELLFAMILY_POTION:
- {
- // alchemist's stone
- if (dummySpell->Id == 17619)
- {
- if (procSpell->SpellFamilyName == SPELLFAMILY_POTION)
- {
- for (uint8 i=0; i<MAX_SPELL_EFFECTS; i++)
- {
- if (procSpell->Effect[i]==SPELL_EFFECT_HEAL)
- {
- triggered_spell_id = 21399;
- }
- else if (procSpell->Effect[i]==SPELL_EFFECT_ENERGIZE)
- {
- triggered_spell_id = 21400;
- }
- else
- continue;
-
- basepoints0 = CalculateSpellDamage(procSpell,i,procSpell->EffectBasePoints[i],this) * 0.4f;
- CastCustomSpell(this,triggered_spell_id,&basepoints0,NULL,NULL,true,NULL,triggeredByAura);
- }
- return true;
- }
- }
- break;
- }
- case SPELLFAMILY_PET:
- {
- // improved cower
- if (dummySpell->SpellIconID == 958 && procSpell->SpellIconID == 958)
- {
- triggered_spell_id = dummySpell->Id == 53180 ? 54200 : 54201;
- target = this;
- break;
- }
- // guard dog
- if (dummySpell->SpellIconID == 201 && procSpell->SpellIconID == 201)
- {
- triggered_spell_id = 54445;
- target = this;
- pVictim->AddThreat(this,procSpell->EffectBasePoints[0]*triggerAmount/100.0f);
- break;
- }
- break;
- }
- default:
- break;
- }
-
- // processed charge only counting case
- if(!triggered_spell_id)
- return true;
-
- SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
-
- if(!triggerEntry)
- {
- sLog.outError("Unit::HandleDummyAuraProc: Spell %u have not existed triggered spell %u",dummySpell->Id,triggered_spell_id);
- return false;
- }
-
- // default case
- if((!target && !spellmgr.IsSrcTargetSpell(triggerEntry)) || (target && target!=this && !target->isAlive()))
- return false;
-
- if( cooldown && GetTypeId() == TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
- return false;
-
- if(basepoints0)
- CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura, originalCaster);
- else
- CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura, originalCaster);
-
- if( cooldown && GetTypeId() == TYPEID_PLAYER )
- ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
-
- return true;
-}
-bool Unit::HandleObsModEnergyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
-{
- SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
- uint32 effIndex = triggeredByAura->GetEffIndex();
- int32 triggerAmount = triggeredByAura->GetAmount();
-
- Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
- ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
-
- uint32 triggered_spell_id = 0;
- Unit* target = pVictim;
- int32 basepoints0 = 0;
-
- switch(dummySpell->SpellFamilyName)
- {
- case SPELLFAMILY_HUNTER:
- {
- // Aspect of the Viper
- if ( dummySpell->SpellFamilyFlags[1] & 0x40000 )
- {
- uint32 maxmana = GetMaxPower(POWER_MANA);
- basepoints0 = maxmana* GetAttackTime(RANGED_ATTACK)/1000.0f/100.0f;
- target = this;
- triggered_spell_id = 34075;
- break;
- }
- break;
- }
- }
- // processed charge only counting case
- if(!triggered_spell_id)
- return true;
-
- SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
-
- // Try handle unknown trigger spells
- if(!triggerEntry)
- {
- sLog.outError("Unit::HandleObsModEnergyAuraProc: Spell %u have not existed triggered spell %u",dummySpell->Id,triggered_spell_id);
- return false;
- }
-
- // default case
- if((!target && !spellmgr.IsSrcTargetSpell(triggerEntry)) || (target && target!=this && !target->isAlive()))
- return false;
-
- if( cooldown && GetTypeId() == TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
- return false;
- if(basepoints0)
- CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
- else
- CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
-
- if( cooldown && GetTypeId() == TYPEID_PLAYER )
- ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
- return true;
-}
-bool Unit::HandleModDamagePctTakenAuraProc(Unit *pVictim, uint32 damage, AuraEffect* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
-{
- SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
- uint32 effIndex = triggeredByAura->GetEffIndex();
- int32 triggerAmount = triggeredByAura->GetAmount();
-
- Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
- ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
-
- uint32 triggered_spell_id = 0;
- Unit* target = pVictim;
- int32 basepoints0 = 0;
-
- switch(dummySpell->SpellFamilyName)
- {
- case SPELLFAMILY_PALADIN:
- {
- // Blessing of Sanctuary
- if ( dummySpell->SpellFamilyFlags[0] & 0x10000000 )
- {
- switch (getPowerType())
- {
- case POWER_MANA: triggered_spell_id = 57319; break;
- default:
- return false;
- }
- }
- break;
- }
- }
- // processed charge only counting case
- if(!triggered_spell_id)
- return true;
-
- SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
-
- if(!triggerEntry)
- {
- sLog.outError("Unit::HandleModDamagePctTakenAuraProc: Spell %u have not existed triggered spell %u",dummySpell->Id,triggered_spell_id);
- return false;
- }
-
- // default case
- if((!target && !spellmgr.IsSrcTargetSpell(triggerEntry)) || (target && target!=this && !target->isAlive()))
- return false;
-
- if( cooldown && GetTypeId() == TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
- return false;
-
- if(basepoints0)
- CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
- else
- CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
-
- if( cooldown && GetTypeId() == TYPEID_PLAYER )
- ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
-
- return true;
-}
-
-// Used in case when access to whole aura is needed
-// All procs should be handled like this...
-bool Unit::HandleAuraProc(Unit *pVictim, uint32 damage, Aura * triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown, bool * handled)
-{
- SpellEntry const *dummySpell = triggeredByAura->GetSpellProto();
-
- switch(dummySpell->SpellFamilyName)
- {
- case SPELLFAMILY_MAGE:
- {
- // Combustion
- switch (dummySpell->Id)
- {
- case 11129:
- {
- *handled = true;
- Unit *caster = triggeredByAura->GetCaster();
- if (!caster || !damage)
- return false;
-
- //last charge and crit
- if (triggeredByAura->GetCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT) )
- {
- RemoveAurasDueToSpell(28682); //-> remove Combustion auras
- return true; // charge counting (will removed)
- }
-
- this->CastSpell(this, 28682, true);
- return false; // ordinary chrages will be removed during crit chance computations.
- }
- // Empowered Fire
- case 31656:
- case 31657:
- case 31658:
- {
- *handled = true;
-
- SpellEntry const *spInfo = sSpellStore.LookupEntry(67545);
- if (!spInfo)
- return false;
-
- int32 bp0 = this->GetCreateMana() * spInfo->CalculateSimpleValue(0) / 100;
- this->CastCustomSpell(this, 67545, &bp0, NULL, NULL, true, NULL, triggeredByAura->GetEffect(0), this->GetGUID());
- return true;
- }
- }
- break;
- }
- case SPELLFAMILY_DEATHKNIGHT:
- {
- // Blood of the North
- // Reaping
- // Death Rune Mastery
- if (dummySpell->SpellIconID == 3041 || dummySpell->SpellIconID == 22 || dummySpell->SpellIconID == 2622)
- {
- *handled = true;
- // Convert recently used Blood Rune to Death Rune
- if (GetTypeId() == TYPEID_PLAYER)
- {
- if(((Player*)this)->getClass() != CLASS_DEATH_KNIGHT)
- return false;
- RuneType rune = ((Player*)this)->GetLastUsedRune();
- // can't proc from death rune use
- if (rune == RUNE_DEATH)
- return false;
- AuraEffect * aurEff = triggeredByAura->GetEffect(0);
- if (!aurEff)
- return false;
- // Reset amplitude - set death rune remove timer to 30s
- aurEff->ResetPeriodic();
- uint32 runesLeft;
-
- if (dummySpell->SpellIconID == 2622)
- runesLeft = 2;
- else
- runesLeft = 1;
-
- for (uint8 i=0; i < MAX_RUNES && runesLeft; ++i)
- {
- if (dummySpell->SpellIconID == 2622)
- {
- if (((Player*)this)->GetCurrentRune(i) == RUNE_DEATH ||
- ((Player*)this)->GetBaseRune(i) == RUNE_BLOOD )
- continue;
- }
- else
- {
- if (((Player*)this)->GetCurrentRune(i) == RUNE_DEATH ||
- ((Player*)this)->GetBaseRune(i) != RUNE_BLOOD )
- continue;
- }
- if (((Player*)this)->GetRuneCooldown(i) != ((Player*)this)->GetRuneBaseCooldown(i))
- continue;
-
- --runesLeft;
- // Mark aura as used
- ((Player*)this)->AddRuneByAuraEffect(i, RUNE_DEATH, aurEff);
- }
- return true;
- }
- return false;
- }
-
- switch(dummySpell->Id)
- {
- // Hungering Cold aura drop
- case 51209:
- *handled = true;
- // Drop only in not disease case
- if (procSpell && procSpell->Dispel == DISPEL_DISEASE)
- return false;
- return true;
- }
- break;
- }
- }
- return false;
-}
-
-bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, AuraEffect* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown)
-{
- // Get triggered aura spell info
- SpellEntry const* auraSpellInfo = triggeredByAura->GetSpellProto();
-
- // Basepoints of trigger aura
- int32 triggerAmount = triggeredByAura->GetAmount();
-
- // Set trigger spell id, target, custom basepoints
- uint32 trigger_spell_id = auraSpellInfo->EffectTriggerSpell[triggeredByAura->GetEffIndex()];
-
- Unit* target = NULL;
- int32 basepoints0 = 0;
-
- if(triggeredByAura->GetAuraType() == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE)
- basepoints0 = triggerAmount;
-
- Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
- ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
-
- // Try handle unknown trigger spells
- if (sSpellStore.LookupEntry(trigger_spell_id) == NULL)
- {
- switch (auraSpellInfo->SpellFamilyName)
- {
- case SPELLFAMILY_GENERIC:
- switch (auraSpellInfo->Id)
- {
- case 23780: // Aegis of Preservation (Aegis of Preservation trinket)
- trigger_spell_id = 23781;
- break;
- case 33896: // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher)
- trigger_spell_id = 33898;
- break;
- case 43820: // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket)
- // Pct value stored in dummy
- basepoints0 = pVictim->GetCreateHealth() * auraSpellInfo->EffectBasePoints[1] / 100;
- target = pVictim;
- break;
- case 57345: // Darkmoon Card: Greatness
- {
- float stat = 0.0f;
- // strength
- if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); }
- // agility
- if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); }
- // intellect
- if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);}
- // spirit
- if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235; }
- break;
- }
- case 67702: // Death's Choice, Item - Coliseum 25 Normal Melee Trinket
- {
- float stat = 0.0f;
- // strength
- if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67708;stat = GetStat(STAT_STRENGTH); }
- // agility
- if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67703; }
- break;
- }
- case 67771: // Death's Choice (heroic), Item - Coliseum 25 Heroic Melee Trinket
- {
- float stat = 0.0f;
- // strength
- if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67773;stat = GetStat(STAT_STRENGTH); }
- // agility
- if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67772; }
- break;
- }
- // Mana Drain Trigger
- case 27522:
- case 40336:
- {
- // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target.
- if (this && this->isAlive())
- CastSpell(this, 29471, true, castItem, triggeredByAura);
- if (pVictim && pVictim->isAlive())
- CastSpell(pVictim, 27526, true, castItem, triggeredByAura);
- return true;
- }
- }
- break;
- case SPELLFAMILY_MAGE:
- if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed
- {
- switch (auraSpellInfo->Id)
- {
- case 31641: // Rank 1
- case 31642: // Rank 2
- trigger_spell_id = 31643;
- break;
- default:
- sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blazing Speed",auraSpellInfo->Id);
- return false;
- }
- }
- break;
- case SPELLFAMILY_WARRIOR:
- if (auraSpellInfo->Id == 50421) // Scent of Blood
- trigger_spell_id = 50422;
- break;
- case SPELLFAMILY_WARLOCK:
- {
- // Drain Soul
- if (auraSpellInfo->SpellFamilyFlags[0] & 0x4000)
- {
- // Improved Drain Soul
- Unit::AuraEffectList const& mAddFlatModifier = GetAuraEffectsByType(SPELL_AURA_DUMMY);
- for (Unit::AuraEffectList::const_iterator i = mAddFlatModifier.begin(); i != mAddFlatModifier.end(); ++i)
- {
- if ((*i)->GetMiscValue() == SPELLMOD_CHANCE_OF_SUCCESS && (*i)->GetSpellProto()->SpellIconID == 113)
- {
- int32 value2 = CalculateSpellDamage((*i)->GetSpellProto(),2,(*i)->GetSpellProto()->EffectBasePoints[2],this);
- basepoints0 = value2 * GetMaxPower(POWER_MANA) / 100;
- // Drain Soul
- CastCustomSpell(this, 18371, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
- break;
- }
- }
- // Not remove charge (aura removed on death in any cases)
- // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura
- return false;
- }
- // Nether Protection
- else if (auraSpellInfo->SpellIconID == 1985)
- {
- if (!procSpell)
- return false;
- switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
- {
- case SPELL_SCHOOL_NORMAL:
- return false; // ignore
- case SPELL_SCHOOL_HOLY: trigger_spell_id = 54370; break;
- case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break;
- case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break;
- case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break;
- case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break;
- case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
- default:
- return false;
- }
- }
- break;
- }
- case SPELLFAMILY_PRIEST:
- {
- // Greater Heal Refund
- if (auraSpellInfo->Id==37594)
- trigger_spell_id = 37595;
- // Blessed Recovery
- else if (auraSpellInfo->SpellIconID == 1875)
- {
- switch (auraSpellInfo->Id)
- {
- case 27811: trigger_spell_id = 27813; break;
- case 27815: trigger_spell_id = 27817; break;
- case 27816: trigger_spell_id = 27818; break;
- default:
- sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id);
- return false;
- }
- basepoints0 = damage * triggerAmount / 100 / 3;
- target = this;
- }
- break;
- }
- case SPELLFAMILY_DRUID:
- {
- // Druid Forms Trinket
- if (auraSpellInfo->Id==37336)
- {
- switch(m_form)
- {
- case FORM_NONE: trigger_spell_id = 37344;break;
- case FORM_CAT: trigger_spell_id = 37341;break;
- case FORM_BEAR:
- case FORM_DIREBEAR: trigger_spell_id = 37340;break;
- case FORM_TREE: trigger_spell_id = 37342;break;
- case FORM_MOONKIN: trigger_spell_id = 37343;break;
- default:
- return false;
- }
- }
- // Druid T9 Feral Relic (Lacerate, Swipe, Mangle, and Shred)
- else if (auraSpellInfo->Id==67353)
- {
- switch(m_form)
- {
- case FORM_CAT: trigger_spell_id = 67355; break;
- case FORM_BEAR:
- case FORM_DIREBEAR: trigger_spell_id = 67354; break;
- default:
- return false;
- }
- }
- break;
- }
- case SPELLFAMILY_HUNTER:
- {
- if (auraSpellInfo->SpellIconID == 3247) // Piercing Shots
- {
- switch (auraSpellInfo->Id)
- {
- case 53234: // Rank 1
- case 53237: // Rank 2
- case 53238: // Rank 3
- trigger_spell_id = 63468;
- break;
- default:
- sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Piercing Shots",auraSpellInfo->Id);
- return false;
- }
- SpellEntry const *TriggerPS = sSpellStore.LookupEntry(trigger_spell_id);
- if(!TriggerPS)
- return false;
- basepoints0 = int32(damage * triggerAmount / 100 / (GetSpellMaxDuration(TriggerPS) / TriggerPS->EffectAmplitude[0]));
- target = pVictim;
- }
- break;
- }
- case SPELLFAMILY_PALADIN:
- {
- switch (auraSpellInfo->Id)
- {
- // Healing Discount
- case 37705:
- {
- trigger_spell_id = 37706;
- target = this;
- break;
- }
- // Soul Preserver
- case 60510:
- {
- trigger_spell_id = 60515;
- target = this;
- break;
- }
- // Lightning Capacitor
- case 37657:
- {
- if(!pVictim || !pVictim->isAlive())
- return false;
- // stacking
- CastSpell(this, 37658, true, NULL, triggeredByAura);
-
- Aura * dummy = GetAura(37658);
- // release at 3 aura in stack (cont contain in basepoint of trigger aura)
- if(!dummy || dummy->GetStackAmount() < triggerAmount)
- return false;
-
- RemoveAurasDueToSpell(37658);
- trigger_spell_id = 37661;
- target = pVictim;
- break;
- }
- // Thunder Capacitor
- case 54841:
- {
- if(!pVictim || !pVictim->isAlive())
- return false;
- // stacking
- CastSpell(this, 54842, true, NULL, triggeredByAura);
-
- // counting
- Aura * dummy = GetAura(54842);
- // release at 3 aura in stack (cont contain in basepoint of trigger aura)
- if(!dummy || dummy->GetStackAmount() < triggerAmount)
- return false;
-
- RemoveAurasDueToSpell(54842);
- trigger_spell_id = 54843;
- target = pVictim;
- break;
- }
- default:
- // Illumination
- if (auraSpellInfo->SpellIconID==241)
- {
- if(!procSpell)
- return false;
- // procspell is triggered spell but we need mana cost of original casted spell
- uint32 originalSpellId = procSpell->Id;
- // Holy Shock heal
- if(procSpell->SpellFamilyFlags[1] & 0x00010000)
- {
- switch(procSpell->Id)
- {
- case 25914: originalSpellId = 20473; break;
- case 25913: originalSpellId = 20929; break;
- case 25903: originalSpellId = 20930; break;
- case 27175: originalSpellId = 27174; break;
- case 33074: originalSpellId = 33072; break;
- case 48820: originalSpellId = 48824; break;
- case 48821: originalSpellId = 48825; break;
- default:
- sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in HShock",procSpell->Id);
- return false;
- }
- }
- SpellEntry const *originalSpell = sSpellStore.LookupEntry(originalSpellId);
- if(!originalSpell)
- {
- sLog.outError("Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu",originalSpellId);
- return false;
- }
- // percent stored in effect 1 (class scripts) base points
- int32 cost = originalSpell->manaCost + originalSpell->ManaCostPercentage * GetCreateMana() / 100;
- basepoints0 = cost*auraSpellInfo->CalculateSimpleValue(1)/100;
- trigger_spell_id = 20272;
- target = this;
- }
- break;
- }
- break;
- }
- case SPELLFAMILY_SHAMAN:
- {
- switch (auraSpellInfo->Id)
- {
- // Lightning Shield (The Ten Storms set)
- case 23551:
- {
- trigger_spell_id = 23552;
- target = pVictim;
- break;
- }
- // Damage from Lightning Shield (The Ten Storms set)
- case 23552:
- {
- trigger_spell_id = 27635;
- break;
- }
- // Mana Surge (The Earthfury set)
- case 23572:
- {
- if(!procSpell)
- return false;
- basepoints0 = procSpell->manaCost * 35 / 100;
- trigger_spell_id = 23571;
- target = this;
- break;
- }
- default:
- {
- // Lightning Shield (overwrite non existing triggered spell call in spell.dbc
- if(auraSpellInfo->SpellFamilyFlags[0] & 0x400)
- {
- trigger_spell_id = spellmgr.GetSpellWithRank(26364, spellmgr.GetSpellRank(auraSpellInfo->Id));
- }
- // Nature's Guardian
- else if (auraSpellInfo->SpellIconID == 2013)
- {
- // Check health condition - should drop to less 30% (damage deal after this!)
- if (!(10*(int32(GetHealth() - damage)) < 3 * GetMaxHealth()))
- return false;
-
- if(pVictim && pVictim->isAlive())
- pVictim->getThreatManager().modifyThreatPercent(this,-10);
-
- basepoints0 = triggerAmount * GetMaxHealth() / 100;
- trigger_spell_id = 31616;
- target = this;
- }
- }
- }
- break;
- }
- case SPELLFAMILY_DEATHKNIGHT:
- {
- // Acclimation
- if (auraSpellInfo->SpellIconID == 1930)
- {
- if (!procSpell)
- return false;
- switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
- {
- case SPELL_SCHOOL_NORMAL:
- return false; // ignore
- case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break;
- case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break;
- case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break;
- case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break;
- case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break;
- case SPELL_SCHOOL_ARCANE: trigger_spell_id = 50486; break;
- default:
- return false;
- }
- }
- // Blood Presence (Improved)
- else if (auraSpellInfo->Id == 63611)
- {
- if (GetTypeId() != TYPEID_PLAYER)
- return false;
-
- trigger_spell_id = 50475;
- basepoints0 = damage * triggerAmount / 100;
- }
- break;
- }
- default:
- break;
- }
- }
-
- // All ok. Check current trigger spell
- SpellEntry const* triggerEntry = sSpellStore.LookupEntry(trigger_spell_id);
- if ( triggerEntry == NULL )
- {
- // Not cast unknown spell
- // sLog.outError("Unit::HandleProcTriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?",auraSpellInfo->Id,triggeredByAura->GetEffIndex());
- return false;
- }
-
- // not allow proc extra attack spell at extra attack
- if( m_extraAttacks && IsSpellHaveEffect(triggerEntry, SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
- return false;
-
- // Custom requirements (not listed in procEx) Warning! damage dealing after this
- // Custom triggered spells
- switch (auraSpellInfo->Id)
- {
- // Persistent Shield (Scarab Brooch trinket)
- // This spell originally trigger 13567 - Dummy Trigger (vs dummy efect)
- case 26467:
- {
- basepoints0 = damage * 15 / 100;
- target = pVictim;
- trigger_spell_id = 26470;
- break;
- }
- // Unyielding Knights (item exploit 29108\29109)
- case 38164:
- {
- if(pVictim->GetEntry() != 19457) // Proc only if you target is Grillok
- return false;
- break;
- }
- // Deflection
- case 52420:
- {
- if(GetHealth()*100 / GetMaxHealth() >= 35)
- return false;
- break;
- }
-
- // Cheat Death
- case 28845:
- {
- // When your health drops below 20%
- if (GetHealth() - damage > GetMaxHealth() / 5 || GetHealth() < GetMaxHealth() / 5)
- return false;
- break;
- }
- // Deadly Swiftness (Rank 1)
- case 31255:
- {
- // whenever you deal damage to a target who is below 20% health.
- if (!pVictim || !pVictim->isAlive() || (pVictim->GetHealth() > pVictim->GetMaxHealth() / 5))
- return false;
-
- target = this;
- trigger_spell_id = 22588;
- }
- // Greater Heal Refund (Avatar Raiment set)
- case 37594:
- {
- if (!pVictim || !pVictim->isAlive())
- return false;
-
- // Not give if target already have full health
- if (pVictim->GetHealth() == pVictim->GetMaxHealth())
- return false;
- // If your Greater Heal brings the target to full health, you gain $37595s1 mana.
- if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
- return false;
- break;
- }
- // Bonus Healing (Crystal Spire of Karabor mace)
- case 40971:
- {
- // If your target is below $s1% health
- if (!pVictim || !pVictim->isAlive() || (pVictim->GetHealth() > pVictim->GetMaxHealth() * triggerAmount / 100))
- return false;
- break;
- }
- // Evasive Maneuvers (Commendation of Kael`thas trinket)
- case 45057:
- {
- // reduce you below $s1% health
- if (GetHealth() - damage > GetMaxHealth() * triggerAmount / 100)
- return false;
- break;
- }
- // Rapid Recuperation
- case 53228:
- case 53232:
- {
- // This effect only from Rapid Fire (ability cast)
- if (!(procSpell->SpellFamilyFlags[0] & 0x20))
- return false;
- break;
- }
- // Blessing of Ancient Kings (Val'anyr, Hammer of Ancient Kings)
- case 64411:
- {
- basepoints0 = damage * 15 / 100;
- target = pVictim;
- trigger_spell_id = 26470;
- break;
- }
- // Decimation
- case 63156:
- case 63158:
- // Can proc only if target has hp below 35%
- if(!pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, procSpell, this))
- return false;
- break;
- }
-
- // Blade Barrier
- if (auraSpellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && auraSpellInfo->SpellIconID == 85)
- {
- if (this->GetTypeId() != TYPEID_PLAYER || !((Player*)this)->IsBaseRuneSlotsOnCooldown(RUNE_BLOOD))
- return false;
- }
-
- // Rime
- else if (auraSpellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && auraSpellInfo->SpellIconID == 56)
- {
- if (GetTypeId() != TYPEID_PLAYER)
- return false;
-
- // Howling Blast
- ((Player*)this)->RemoveSpellCategoryCooldown(1248, true);
- }
-
- // Custom basepoints/target for exist spell
- // dummy basepoints or other customs
- switch(trigger_spell_id)
- {
- // Auras which should proc on area aura source (caster in this case):
- // Turn the Tables
- case 52914:
- case 52915:
- case 52910:
- // Honor Among Thieves
- case 52916:
- {
- target = triggeredByAura->GetBase()->GetCaster();
- if(!target)
- return false;
-
- if( cooldown && GetTypeId() == TYPEID_PLAYER && ((Player*)target)->HasSpellCooldown(trigger_spell_id))
- return false;
-
- target->CastSpell(target,trigger_spell_id,true,castItem,triggeredByAura);
-
- if( cooldown && GetTypeId() == TYPEID_PLAYER )
- ((Player*)this)->AddSpellCooldown(trigger_spell_id,0,time(NULL) + cooldown);
- return true;
- }
- // Cast positive spell on enemy target
- case 7099: // Curse of Mending
- case 39647: // Curse of Mending
- case 29494: // Temptation
- case 20233: // Improved Lay on Hands (cast on target)
- {
- target = pVictim;
- break;
- }
- // Combo points add triggers (need add combopoint only for main target, and after possible combopoints reset)
- case 15250: // Rogue Setup
- {
- if(!pVictim || pVictim != getVictim()) // applied only for main target
- return false;
- break; // continue normal case
- }
- // Finish movies that add combo
- case 14189: // Seal Fate (Netherblade set)
- case 14157: // Ruthlessness
- {
- if (!pVictim || pVictim == this)
- return false;
- // Need add combopoint AFTER finish movie (or they dropped in finish phase)
- break;
- }
- // Bloodthirst (($m/100)% of max health)
- case 23880:
- {
- basepoints0 = int32(GetMaxHealth() * triggerAmount / 100);
- break;
- }
- // Shamanistic Rage triggered spell
- case 30824:
- {
- basepoints0 = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
- break;
- }
- // Enlightenment (trigger only from mana cost spells)
- case 35095:
- {
- if(!procSpell || procSpell->powerType!=POWER_MANA || procSpell->manaCost==0 && procSpell->ManaCostPercentage==0 && procSpell->manaCostPerlevel==0)
- return false;
- break;
- }
- // Demonic Pact
- case 48090:
- {
- // Get talent aura from owner
- if (isPet())
- if (Unit * owner = GetOwner())
- {
- if (AuraEffect * aurEff = owner->GetDummyAuraEffect(SPELLFAMILY_WARLOCK, 3220, 0))
- {
- basepoints0 = int32((aurEff->GetAmount() * owner->SpellBaseDamageBonus(SpellSchoolMask(SPELL_SCHOOL_MASK_MAGIC)) + 100.0f) / 100.0f);
- CastCustomSpell(this,trigger_spell_id,&basepoints0,&basepoints0,NULL,true,castItem,triggeredByAura);
- return true;
- }
- }
- break;
- }
- // Sword and Board
- case 50227:
- {
- // Remove cooldown on Shield Slam
- if (GetTypeId() == TYPEID_PLAYER)
- ((Player*)this)->RemoveSpellCategoryCooldown(1209, true);
- break;
- }
- // Maelstrom Weapon
- case 53817:
- {
- // have rank dependent proc chance, ignore too often cases
- // PPM = 2.5 * (rank of talent),
- uint32 rank = spellmgr.GetSpellRank(auraSpellInfo->Id);
- // 5 rank -> 100% 4 rank -> 80% and etc from full rate
- if(!roll_chance_i(20*rank))
- return false;
- break;
- }
- // Astral Shift
- case 52179:
- {
- if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
- return false;
-
- // Need stun, fear or silence mechanic
- if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_SILENCE)|(1<<MECHANIC_STUN)|(1<<MECHANIC_FEAR))))
- return false;
- break;
- }
- // Burning Determination
- case 54748:
- {
- if(!procSpell)
- return false;
- // Need Interrupt or Silenced mechanic
- if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_INTERRUPT)|(1<<MECHANIC_SILENCE))))
- return false;
- break;
- }
- // Lock and Load
- case 56453:
- {
- // Proc only from Frost/Freezing trap activation or from Freezing Arrow (the periodic dmg proc handled elsewhere)
- if (!(procFlags & PROC_FLAG_ON_TRAP_ACTIVATION) || !procSpell || !(procSpell->SchoolMask & SPELL_SCHOOL_MASK_FROST) || !roll_chance_i(triggerAmount))
- return false;
- break;
- }
- // Glyph of Death's Embrace
- case 58679:
- {
- // Proc only from healing part of Death Coil. Check is essential as all Death Coil spells have 0x2000 mask in SpellFamilyFlags
- if (!procSpell || !(procSpell->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && procSpell->SpellFamilyFlags[0] == 0x80002000))
- return false;
- break;
- }
- // Glyph of Death Grip
- case 58628:
- {
- // remove cooldown of Death Grip
- if (GetTypeId() == TYPEID_PLAYER)
- ((Player*)this)->RemoveCategoryCooldown(82);
- return true;
- }
- // Savage Defense
- case 62606:
- {
- basepoints0 = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100.0f);
- break;
- }
- // Body and Soul
- case 64128:
- case 65081:
- {
- // Proc only from PW:S cast
- if (!(procSpell->SpellFamilyFlags[0] & 0x00000001))
- return false;
- break;
- }
- }
-
- if( cooldown && GetTypeId() == TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(trigger_spell_id))
- return false;
-
- // try detect target manually if not set
- if ( target == NULL )
- target = !(procFlags & (PROC_FLAG_SUCCESSFUL_POSITIVE_MAGIC_SPELL | PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL_HIT)) && IsPositiveSpell(trigger_spell_id) ? this : pVictim;
-
- // default case
- if((!target && !spellmgr.IsSrcTargetSpell(triggerEntry)) || (target && target!=this && !target->isAlive()))
- return false;
-
- if(basepoints0)
- CastCustomSpell(target,trigger_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
- else
- CastSpell(target,trigger_spell_id,true,castItem,triggeredByAura);
-
- if( cooldown && GetTypeId() == TYPEID_PLAYER )
- ((Player*)this)->AddSpellCooldown(trigger_spell_id,0,time(NULL) + cooldown);
-
- return true;
-}
-
-bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, uint32 damage, AuraEffect *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown)
-{
- int32 scriptId = triggeredByAura->GetMiscValue();
-
- if(!pVictim || !pVictim->isAlive())
- return false;
-
- Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
- ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
-
- uint32 triggered_spell_id = 0;
-
- switch(scriptId)
- {
- case 836: // Improved Blizzard (Rank 1)
- {
- if (!procSpell || procSpell->SpellVisual[0]!=9487)
- return false;
- triggered_spell_id = 12484;
- break;
- }
- case 988: // Improved Blizzard (Rank 2)
- {
- if (!procSpell || procSpell->SpellVisual[0]!=9487)
- return false;
- triggered_spell_id = 12485;
- break;
- }
- case 989: // Improved Blizzard (Rank 3)
- {
- if (!procSpell || procSpell->SpellVisual[0]!=9487)
- return false;
- triggered_spell_id = 12486;
- break;
- }
- case 4533: // Dreamwalker Raiment 2 pieces bonus
- {
- // Chance 50%
- if (!roll_chance_i(50))
- return false;
-
- switch (pVictim->getPowerType())
- {
- case POWER_MANA: triggered_spell_id = 28722; break;
- case POWER_RAGE: triggered_spell_id = 28723; break;
- case POWER_ENERGY: triggered_spell_id = 28724; break;
- default:
- return false;
- }
- break;
- }
- case 4537: // Dreamwalker Raiment 6 pieces bonus
- triggered_spell_id = 28750; // Blessing of the Claw
- break;
- case 5497: // Improved Mana Gems
- triggered_spell_id = 37445; // Mana Surge
- break;
- case 7010: // Revitalize - can proc on full hp target
- case 7011:
- case 7012:
- {
- if (!roll_chance_i(triggeredByAura->GetAmount()))
- return false;
- switch(pVictim->getPowerType())
- {
- case POWER_MANA: triggered_spell_id = 48542; break;
- case POWER_RAGE: triggered_spell_id = 48541; break;
- case POWER_ENERGY: triggered_spell_id = 48540; break;
- case POWER_RUNIC_POWER: triggered_spell_id = 48543; break;
- }
- break;
- }
- }
-
- // not processed
- if(!triggered_spell_id)
- return false;
-
- // standard non-dummy case
- SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
-
- if(!triggerEntry)
- {
- sLog.outError("Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u",triggered_spell_id,scriptId);
- return false;
- }
-
- if( cooldown && GetTypeId() == TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
- return false;
-
- CastSpell(pVictim, triggered_spell_id, true, castItem, triggeredByAura);
-
- if( cooldown && GetTypeId() == TYPEID_PLAYER )
- ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
-
- return true;
-}
-
-void Unit::setPowerType(Powers new_powertype)
-{
- SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype);
-
- if(GetTypeId() == TYPEID_PLAYER)
- {
- if(((Player*)this)->GetGroup())
- ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE);
- }
- else if(((Creature*)this)->isPet())
- {
- Pet *pet = ((Pet*)this);
- if(pet->isControlled())
- {
- Unit *owner = GetOwner();
- if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
- ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE);
- }
- }
-
- switch(new_powertype)
- {
- default:
- case POWER_MANA:
- break;
- case POWER_RAGE:
- SetMaxPower(POWER_RAGE, GetCreatePowers(POWER_RAGE));
- SetPower(POWER_RAGE, 0);
- break;
- case POWER_FOCUS:
- SetMaxPower(POWER_FOCUS, GetCreatePowers(POWER_FOCUS));
- SetPower(POWER_FOCUS, GetCreatePowers(POWER_FOCUS));
- break;
- case POWER_ENERGY:
- SetMaxPower(POWER_ENERGY, GetCreatePowers(POWER_ENERGY));
- break;
- case POWER_HAPPINESS:
- SetMaxPower(POWER_HAPPINESS, GetCreatePowers(POWER_HAPPINESS));
- SetPower(POWER_HAPPINESS, GetCreatePowers(POWER_HAPPINESS));
- break;
- }
-}
-
-FactionTemplateEntry const* Unit::getFactionTemplateEntry() const
-{
- FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry(getFaction());
- if(!entry)
- {
- static uint64 guid = 0; // prevent repeating spam same faction problem
-
- if(GetGUID() != guid)
- {
- if(GetTypeId() == TYPEID_PLAYER)
- sLog.outError("Player %s have invalid faction (faction template id) #%u", ((Player*)this)->GetName(), getFaction());
- else
- sLog.outError("Creature (template id: %u) have invalid faction (faction template id) #%u", ((Creature*)this)->GetCreatureInfo()->Entry, getFaction());
- guid = GetGUID();
- }
- }
- return entry;
-}
-
-bool Unit::IsHostileTo(Unit const* unit) const
-{
- if(!unit)
- return false;
- // always non-hostile to self
- if(unit==this)
- return false;
-
- // always non-hostile to GM in GM mode
- if(unit->GetTypeId() == TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
- return false;
-
- // always hostile to enemy
- if(getVictim()==unit || unit->getVictim()==this)
- return true;
-
- // test pet/charm masters instead pers/charmeds
- Unit const* testerOwner = GetCharmerOrOwner();
- Unit const* targetOwner = unit->GetCharmerOrOwner();
-
- // always hostile to owner's enemy
- if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
- return true;
-
- // always hostile to enemy owner
- if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
- return true;
-
- // always hostile to owner of owner's enemy
- if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
- return true;
-
- Unit const* tester = testerOwner ? testerOwner : this;
- Unit const* target = targetOwner ? targetOwner : unit;
-
- // always non-hostile to target with common owner, or to owner/pet
- if(tester==target)
- return false;
-
- // special cases (Duel, etc)
- if(tester->GetTypeId() == TYPEID_PLAYER && target->GetTypeId() == TYPEID_PLAYER)
- {
- Player const* pTester = (Player const*)tester;
- Player const* pTarget = (Player const*)target;
-
- // Duel
- if(pTester->duel && pTester->duel->opponent == pTarget && pTester->duel->startTime != 0)
- return true;
-
- // Group
- if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
- return false;
-
- // Sanctuary
- if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
- return false;
-
- // PvP FFA state
- if(pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
- return true;
-
- //= PvP states
- // Green/Blue (can't attack)
- if (!pTester->HasAuraType(SPELL_AURA_MOD_FACTION) && !pTarget->HasAuraType(SPELL_AURA_MOD_FACTION))
- {
- if(pTester->GetTeam()==pTarget->GetTeam())
- return false;
-
- // Red (can attack) if true, Blue/Yellow (can't attack) in another case
- return pTester->IsPvP() && pTarget->IsPvP();
- }
- }
-
- // faction base cases
- FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
- FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
- if(!tester_faction || !target_faction)
- return false;
-
- if(target->isAttackingPlayer() && tester->IsContestedGuard())
- return true;
-
- // PvC forced reaction and reputation case
- if(tester->GetTypeId() == TYPEID_PLAYER && !tester->HasAuraType(SPELL_AURA_MOD_FACTION))
- {
- // forced reaction
- if(target_faction->faction)
- {
- if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
- return *force <= REP_HOSTILE;
-
- // if faction have reputation then hostile state for tester at 100% dependent from at_war state
- if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
- if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
- return (factionState->Flags & FACTION_FLAG_AT_WAR);
- }
- }
- // CvP forced reaction and reputation case
- else if(target->GetTypeId() == TYPEID_PLAYER && !target->HasAuraType(SPELL_AURA_MOD_FACTION))
- {
- // forced reaction
- if(tester_faction->faction)
- {
- if(ReputationRank const* force = ((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
- return *force <= REP_HOSTILE;
-
- // apply reputation state
- FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction);
- if(raw_tester_faction && raw_tester_faction->reputationListID >=0 )
- return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) <= REP_HOSTILE;
- }
- }
-
- // common faction based case (CvC,PvC,CvP)
- return tester_faction->IsHostileTo(*target_faction);
-}
-
-bool Unit::IsFriendlyTo(Unit const* unit) const
-{
- // always friendly to self
- if(unit==this)
- return true;
-
- // always friendly to GM in GM mode
- if(unit->GetTypeId() == TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
- return true;
-
- // always non-friendly to enemy
- if(getVictim()==unit || unit->getVictim()==this)
- return false;
-
- // test pet/charm masters instead pers/charmeds
- Unit const* testerOwner = GetCharmerOrOwner();
- Unit const* targetOwner = unit->GetCharmerOrOwner();
-
- // always non-friendly to owner's enemy
- if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
- return false;
-
- // always non-friendly to enemy owner
- if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
- return false;
-
- // always non-friendly to owner of owner's enemy
- if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
- return false;
-
- Unit const* tester = testerOwner ? testerOwner : this;
- Unit const* target = targetOwner ? targetOwner : unit;
-
- // always friendly to target with common owner, or to owner/pet
- if(tester==target)
- return true;
-
- // special cases (Duel)
- if(tester->GetTypeId() == TYPEID_PLAYER && target->GetTypeId() == TYPEID_PLAYER)
- {
- Player const* pTester = (Player const*)tester;
- Player const* pTarget = (Player const*)target;
-
- // Duel
- if(pTester->duel && pTester->duel->opponent == target && pTester->duel->startTime != 0)
- return false;
-
- // Group
- if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
- return true;
-
- // Sanctuary
- if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
- return true;
-
- // PvP FFA state
- if(pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
- return false;
-
- //= PvP states
- // Green/Blue (non-attackable)
- if (!pTester->HasAuraType(SPELL_AURA_MOD_FACTION) && !pTarget->HasAuraType(SPELL_AURA_MOD_FACTION))
- {
- if(pTester->GetTeam()==pTarget->GetTeam())
- return true;
-
- // Blue (friendly/non-attackable) if not PVP, or Yellow/Red in another case (attackable)
- return !pTarget->IsPvP();
- }
- }
-
- // faction base cases
- FactionTemplateEntry const *tester_faction = tester->getFactionTemplateEntry();
- FactionTemplateEntry const *target_faction = target->getFactionTemplateEntry();
- if (!tester_faction || !target_faction)
- return false;
-
- if (target->isAttackingPlayer() && tester->IsContestedGuard())
- return false;
-
- // PvC forced reaction and reputation case
- if (tester->GetTypeId() == TYPEID_PLAYER && !tester->HasAuraType(SPELL_AURA_MOD_FACTION))
- {
- // forced reaction
- if (target_faction->faction)
- {
- if (ReputationRank const *force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
- return *force >= REP_FRIENDLY;
-
- // if faction have reputation then friendly state for tester at 100% dependent from at_war state
- if (FactionEntry const *raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
- if (FactionState const *factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
- return !(factionState->Flags & FACTION_FLAG_AT_WAR);
- }
- }
- // CvP forced reaction and reputation case
- else if (target->GetTypeId() == TYPEID_PLAYER && !target->HasAuraType(SPELL_AURA_MOD_FACTION))
- {
- // forced reaction
- if (tester_faction->faction)
- {
- if (ReputationRank const *force =((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
- return *force >= REP_FRIENDLY;
-
- // apply reputation state
- if (FactionEntry const *raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction))
- if (raw_tester_faction->reputationListID >= 0)
- return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) >= REP_FRIENDLY;
- }
- }
-
- // common faction based case (CvC,PvC,CvP)
- return tester_faction->IsFriendlyTo(*target_faction);
-}
-
-bool Unit::IsHostileToPlayers() const
-{
- FactionTemplateEntry const *my_faction = getFactionTemplateEntry();
- if (!my_faction || !my_faction->faction)
- return false;
-
- FactionEntry const *raw_faction = sFactionStore.LookupEntry(my_faction->faction);
- if (raw_faction && raw_faction->reputationListID >= 0)
- return false;
-
- return my_faction->IsHostileToPlayers();
-}
-
-bool Unit::IsNeutralToAll() const
-{
- FactionTemplateEntry const *my_faction = getFactionTemplateEntry();
- if (!my_faction || !my_faction->faction)
- return true;
-
- FactionEntry const *raw_faction = sFactionStore.LookupEntry(my_faction->faction);
- if (raw_faction && raw_faction->reputationListID >= 0)
- return false;
-
- return my_faction->IsNeutralToAll();
-}
-
-bool Unit::Attack(Unit *victim, bool meleeAttack)
-{
- if(!victim || victim == this)
- return false;
-
- // dead units can neither attack nor be attacked
- if(!isAlive() || !victim->IsInWorld() || !victim->isAlive())
- return false;
-
- // player cannot attack in mount state
- if(GetTypeId() == TYPEID_PLAYER && IsMounted())
- return false;
-
- // nobody can attack GM in GM-mode
- if(victim->GetTypeId() == TYPEID_PLAYER)
- {
- if(((Player*)victim)->isGameMaster())
- return false;
- }
- else
- {
- if(((Creature*)victim)->IsInEvadeMode())
- return false;
- }
-
- // remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack)
- if(HasAuraType(SPELL_AURA_MOD_UNATTACKABLE))
- RemoveAurasByType(SPELL_AURA_MOD_UNATTACKABLE);
-
- if (m_attacking)
- {
- if (m_attacking == victim)
- {
- // switch to melee attack from ranged/magic
- if (meleeAttack)
- {
- if (!hasUnitState(UNIT_STAT_MELEE_ATTACKING))
- {
- addUnitState(UNIT_STAT_MELEE_ATTACKING);
- SendMeleeAttackStart(victim);
- return true;
- }
- }
- else if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
- {
- clearUnitState(UNIT_STAT_MELEE_ATTACKING);
- SendMeleeAttackStop(victim);
- return true;
- }
- return false;
- }
-
- //switch target
- InterruptSpell(CURRENT_MELEE_SPELL);
- if (!meleeAttack)
- clearUnitState(UNIT_STAT_MELEE_ATTACKING);
- }
-
- if (m_attacking)
- m_attacking->_removeAttacker(this);
-
- m_attacking = victim;
- m_attacking->_addAttacker(this);
-
- // Set our target
- SetUInt64Value(UNIT_FIELD_TARGET, victim->GetGUID());
-
- if (meleeAttack)
- addUnitState(UNIT_STAT_MELEE_ATTACKING);
-
- // set position before any AI calls/assistance
- //if(GetTypeId() == TYPEID_UNIT)
- // ((Creature*)this)->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ());
-
- if (GetTypeId() == TYPEID_UNIT)
- {
- // should not let player enter combat by right clicking target
- SetInCombatWith(victim);
- if (victim->GetTypeId() == TYPEID_PLAYER)
- victim->SetInCombatWith(this);
- AddThreat(victim, 0.0f);
-
- ((Creature*)this)->SendAIReaction(AI_REACTION_AGGRO);
- ((Creature*)this)->CallAssistance();
- }
-
- // delay offhand weapon attack to next attack time
- if(haveOffhandWeapon())
- resetAttackTimer(OFF_ATTACK);
-
- if (meleeAttack)
- SendMeleeAttackStart(victim);
-
- return true;
-}
-
-bool Unit::AttackStop()
-{
- if (!m_attacking)
- return false;
-
- Unit* victim = m_attacking;
-
- m_attacking->_removeAttacker(this);
- m_attacking = NULL;
-
- // Clear our target
- SetUInt64Value(UNIT_FIELD_TARGET, 0);
-
- clearUnitState(UNIT_STAT_MELEE_ATTACKING);
-
- InterruptSpell(CURRENT_MELEE_SPELL);
-
- // reset only at real combat stop
- if (GetTypeId() == TYPEID_UNIT)
- {
- ((Creature*)this)->SetNoCallAssistance(false);
-
- if (((Creature*)this)->HasSearchedAssistance())
- {
- ((Creature*)this)->SetNoSearchAssistance(false);
- UpdateSpeed(MOVE_RUN, false);
- }
- }
-
- SendMeleeAttackStop(victim);
-
- return true;
-}
-
-void Unit::CombatStop(bool includingCast)
-{
- if (includingCast && IsNonMeleeSpellCasted(false))
- InterruptNonMeleeSpells(false);
-
- AttackStop();
- RemoveAllAttackers();
- if (GetTypeId() == TYPEID_PLAYER)
- ((Player*)this)->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel
- ClearInCombat();
-}
-
-void Unit::CombatStopWithPets(bool includingCast)
-{
- CombatStop(includingCast);
-
- for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
- (*itr)->CombatStop(includingCast);
-}
-
-bool Unit::isAttackingPlayer() const
-{
- if (hasUnitState(UNIT_STAT_ATTACK_PLAYER))
- return true;
-
- for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
- if ((*itr)->isAttackingPlayer())
- return true;
-
- for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i)
- if (m_SummonSlot[i])
- if (Creature *summon = GetMap()->GetCreature(m_SummonSlot[i]))
- if (summon->isAttackingPlayer())
- return true;
-
- return false;
-}
-
-void Unit::RemoveAllAttackers()
-{
- while (!m_attackers.empty())
- {
- AttackerSet::iterator iter = m_attackers.begin();
- if (!(*iter)->AttackStop())
- {
- sLog.outError("WORLD: Unit has an attacker that isn't attacking it!");
- m_attackers.erase(iter);
- }
- }
-}
-
-void Unit::ModifyAuraState(AuraState flag, bool apply)
-{
- if (apply)
- {
- if (!HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)))
- {
- SetFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
- if (GetTypeId() == TYPEID_PLAYER)
- {
- PlayerSpellMap const& sp_list = ((Player*)this)->GetSpellMap();
- for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
- {
- if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled) continue;
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first);
- if (!spellInfo || !IsPassiveSpell(itr->first)) continue;
- if (spellInfo->CasterAuraState == flag)
- CastSpell(this, itr->first, true, NULL);
- }
- }
- else if (((Creature*)this)->isPet())
- {
- Pet *pet = ((Pet*)this);
- for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
- {
- if (itr->second.state == PETSPELL_REMOVED) continue;
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first);
- if (!spellInfo || !IsPassiveSpell(itr->first)) continue;
- if (spellInfo->CasterAuraState == flag)
- CastSpell(this, itr->first, true, NULL);
- }
- }
- }
- }
- else
- {
- if (HasFlag(UNIT_FIELD_AURASTATE,1<<(flag-1)))
- {
- RemoveFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
-
- if (flag != AURA_STATE_ENRAGE) // enrage aura state triggering continues auras
- {
- Unit::AuraApplicationMap& tAuras = GetAppliedAuras();
- for (Unit::AuraApplicationMap::iterator itr = tAuras.begin(); itr != tAuras.end();)
- {
- SpellEntry const* spellProto = (*itr).second->GetBase()->GetSpellProto();
- if (spellProto->CasterAuraState == flag)
- RemoveAura(itr);
- else
- ++itr;
- }
- }
- }
- }
-}
-
-uint32 Unit::BuildAuraStateUpdateForTarget(Unit * target) const
-{
- uint32 auraStates = GetUInt32Value(UNIT_FIELD_AURASTATE) &~(PER_CASTER_AURA_STATE_MASK);
- for (AuraStateAurasMap::const_iterator itr = m_auraStateAuras.begin(); itr != m_auraStateAuras.end(); ++itr)
- if ((1<<(itr->first-1)) & PER_CASTER_AURA_STATE_MASK)
- if (itr->second->GetBase()->GetCasterGUID() == target->GetGUID())
- auraStates |= (1<<(itr->first-1));
-
- return auraStates;
-}
-
-bool Unit::HasAuraState(AuraState flag, SpellEntry const *spellProto, Unit const * Caster) const
-{
- if (Caster)
- {
- if (spellProto)
- {
- AuraEffectList const& stateAuras = Caster->GetAuraEffectsByType(SPELL_AURA_ABILITY_IGNORE_AURASTATE);
- for (AuraEffectList::const_iterator j = stateAuras.begin(); j != stateAuras.end(); ++j)
- if ((*j)->IsAffectedOnSpell(spellProto))
- return true;
- }
- // Check per caster aura state
- // If aura with aurastate by caster not found return false
- if ((1<<(flag-1)) & PER_CASTER_AURA_STATE_MASK)
- {
- for (AuraStateAurasMap::const_iterator itr = m_auraStateAuras.lower_bound(flag); itr != m_auraStateAuras.upper_bound(flag); ++itr)
- if (itr->second->GetBase()->GetCasterGUID() == Caster->GetGUID())
- return true;
- return false;
- }
- }
-
- return HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
-}
-
-Unit *Unit::GetOwner(bool inWorld) const
-{
- if (uint64 ownerid = GetOwnerGUID())
- {
- if (inWorld)
- return ObjectAccessor::GetUnit(*this, ownerid);
- return ObjectAccessor::GetUnitInOrOutOfWorld(*this, ownerid);
- }
- return NULL;
-}
-
-Unit *Unit::GetCharmer() const
-{
- if (uint64 charmerid = GetCharmerGUID())
- return ObjectAccessor::GetUnit(*this, charmerid);
- return NULL;
-}
-
-Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself() const
-{
- uint64 guid = GetCharmerOrOwnerGUID();
- if (IS_PLAYER_GUID(guid))
- return ObjectAccessor::GetPlayer(*this, guid);
-
- return GetTypeId() == TYPEID_PLAYER ? (Player*)this : NULL;
-}
-
-Minion *Unit::GetFirstMinion() const
-{
- if (uint64 pet_guid = GetMinionGUID())
- {
- if (Creature* pet = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, pet_guid))
- if (pet->HasUnitTypeMask(UNIT_MASK_MINION))
- return (Minion*)pet;
-
- sLog.outError("Unit::GetFirstMinion: Minion %u not exist.",GUID_LOPART(pet_guid));
- const_cast<Unit*>(this)->SetMinionGUID(0);
- }
-
- return NULL;
-}
-
-Guardian* Unit::GetGuardianPet() const
-{
- if (uint64 pet_guid = GetPetGUID())
- {
- if (Creature* pet = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, pet_guid))
- if (pet->HasUnitTypeMask(UNIT_MASK_GUARDIAN))
- return (Guardian*)pet;
-
- sLog.outCrash("Unit::GetGuardianPet: Guardian " I64FMT " not exist.", pet_guid);
- const_cast<Unit*>(this)->SetPetGUID(0);
- }
-
- return NULL;
-}
-
-Unit* Unit::GetCharm() const
-{
- if (uint64 charm_guid = GetCharmGUID())
- {
- if (Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid))
- return pet;
-
- sLog.outError("Unit::GetCharm: Charmed creature %u not exist.",GUID_LOPART(charm_guid));
- const_cast<Unit*>(this)->SetUInt64Value(UNIT_FIELD_CHARM, 0);
- }
-
- return NULL;
-}
-
-void Unit::SetMinion(Minion *minion, bool apply)
-{
- sLog.outDebug("SetMinion %u for %u, apply %u", minion->GetEntry(), GetEntry(), apply);
-
- if (apply)
- {
- if (!minion->AddUInt64Value(UNIT_FIELD_SUMMONEDBY, GetGUID()))
- {
- sLog.outCrash("SetMinion: Minion %u is not the minion of owner %u", minion->GetEntry(), GetEntry());
- return;
- }
-
- m_Controlled.insert(minion);
-
- if (GetTypeId() == TYPEID_PLAYER)
- {
- minion->m_ControlledByPlayer = true;
- minion->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
- }
-
- // Can only have one pet. If a new one is summoned, dismiss the old one.
- if (minion->IsGuardianPet())
- {
- if (Guardian* oldPet = GetGuardianPet())
- {
- if (oldPet != minion && (oldPet->isPet() || minion->isPet() || oldPet->GetEntry() != minion->GetEntry()))
- {
- // remove existing minion pet
- if (oldPet->isPet())
- ((Pet*)oldPet)->Remove(PET_SAVE_AS_CURRENT);
- else
- oldPet->UnSummon();
- SetPetGUID(minion->GetGUID());
- SetMinionGUID(0);
- }
- }
- else
- {
- SetPetGUID(minion->GetGUID());
- SetMinionGUID(0);
- }
- }
-
- if (minion->HasUnitTypeMask(UNIT_MASK_CONTROLABLE_GUARDIAN))
- {
- if (AddUInt64Value(UNIT_FIELD_SUMMON, minion->GetGUID()))
- {
- }
- }
- //else if(minion->m_Properties && minion->m_Properties->Type == SUMMON_TYPE_MINIPET)
- // AddUInt64Value(UNIT_FIELD_CRITTER, minion->GetGUID());
-
- // PvP, FFAPvP
- minion->SetByteValue(UNIT_FIELD_BYTES_2, 1, GetByteValue(UNIT_FIELD_BYTES_2, 1));
-
- // FIXME: hack, speed must be set only at follow
- if (GetTypeId() == TYPEID_PLAYER && minion->isPet())
- for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i)
- minion->SetSpeed(UnitMoveType(i), m_speed_rate[i], true);
-
- // Ghoul pets have energy instead of mana (is anywhere better place for this code?)
- if (minion->IsPetGhoul())
- minion->setPowerType(POWER_ENERGY);
-
- if (GetTypeId() == TYPEID_PLAYER)
- {
- // Send infinity cooldown - client does that automatically but after relog cooldown needs to be set again
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(minion->GetUInt32Value(UNIT_CREATED_BY_SPELL));
- if (spellInfo && (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE))
- ((Player*)this)->AddSpellAndCategoryCooldowns(spellInfo, 0, NULL ,true);
- }
- }
- else
- {
- if (minion->GetOwnerGUID() != GetGUID())
- {
- sLog.outCrash("SetMinion: Minion %u is not the minion of owner %u", minion->GetEntry(), GetEntry());
- return;
- }
-
- m_Controlled.erase(minion);
-
- if (minion->IsGuardianPet())
- {
- if (GetPetGUID() == minion->GetGUID())
- SetPetGUID(0);
- }
- else if (minion->isTotem())
- {
- // All summoned by totem minions must disappear when it is removed.
- if (const SpellEntry* spInfo = sSpellStore.LookupEntry(((Totem*)minion)->GetSpell()))
- for (int i = 0; i < MAX_SPELL_EFFECTS; ++i)
- {
- if (spInfo->Effect[i] != SPELL_EFFECT_SUMMON)
- continue;
-
- this->RemoveAllMinionsByEntry(spInfo->EffectMiscValue[i]);
- }
- }
-
- if (GetTypeId() == TYPEID_PLAYER)
- {
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(minion->GetUInt32Value(UNIT_CREATED_BY_SPELL));
- // Remove infinity cooldown
- if (spellInfo && (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE))
- ((Player*)this)->SendCooldownEvent(spellInfo);
- }
-
- //if(minion->HasUnitTypeMask(UNIT_MASK_GUARDIAN))
- {
- if (RemoveUInt64Value(UNIT_FIELD_SUMMON, minion->GetGUID()))
- {
- //Check if there is another minion
- for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
- {
- // do not use this check, creature do not have charm guid
- //if(GetCharmGUID() == (*itr)->GetGUID())
- if (GetGUID() == (*itr)->GetCharmerGUID())
- continue;
-
- //assert((*itr)->GetOwnerGUID() == GetGUID());
- if ((*itr)->GetOwnerGUID() != GetGUID())
- {
- OutDebugInfo();
- (*itr)->OutDebugInfo();
- assert(false);
- }
- assert((*itr)->GetTypeId() == TYPEID_UNIT);
-
- if (!(*itr)->HasUnitTypeMask(UNIT_MASK_CONTROLABLE_GUARDIAN))
- continue;
-
- if (AddUInt64Value(UNIT_FIELD_SUMMON, (*itr)->GetGUID()))
- {
- //show another pet bar if there is no charm bar
- if (GetTypeId() == TYPEID_PLAYER && !GetCharmGUID())
- {
- if ((*itr)->isPet())
- ((Player*)this)->PetSpellInitialize();
- else
- ((Player*)this)->CharmSpellInitialize();
- }
- }
- break;
- }
- }
- }
- //else if(minion->m_Properties && minion->m_Properties->Type == SUMMON_TYPE_MINIPET)
- // RemoveUInt64Value(UNIT_FIELD_CRITTER, minion->GetGUID());
- }
-}
-
-void Unit::GetAllMinionsByEntry(std::list<Creature*>& Minions, uint32 entry)
-{
- for (Unit::ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end();)
- {
- Unit *unit = *itr;
- ++itr;
- if (unit->GetEntry() == entry && unit->GetTypeId() == TYPEID_UNIT
- && ((Creature*)unit)->isSummon()) // minion, actually
- Minions.push_back((Creature*)unit);
- }
-}
-
-void Unit::RemoveAllMinionsByEntry(uint32 entry)
-{
- for (Unit::ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end();)
- {
- Unit *unit = *itr;
- ++itr;
- if (unit->GetEntry() == entry && unit->GetTypeId() == TYPEID_UNIT
- && ((Creature*)unit)->isSummon()) // minion, actually
- ((TempSummon*)unit)->UnSummon();
- // i think this is safe because i have never heard that a despawned minion will trigger a same minion
- }
-}
-
-void Unit::SetCharm(Unit* charm, bool apply)
-{
- if (apply)
- {
- if (GetTypeId() == TYPEID_PLAYER)
- {
- if (!AddUInt64Value(UNIT_FIELD_CHARM, charm->GetGUID()))
- sLog.outCrash("Player %s is trying to charm unit %u, but it already has a charmed unit %u", GetName(), charm->GetEntry(), GetCharmGUID());
-
- charm->m_ControlledByPlayer = true;
- // TODO: maybe we can use this flag to check if controlled by player
- charm->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
- }
- else
- charm->m_ControlledByPlayer = false;
-
- // PvP, FFAPvP
- charm->SetByteValue(UNIT_FIELD_BYTES_2, 1, GetByteValue(UNIT_FIELD_BYTES_2, 1));
-
- if (!charm->AddUInt64Value(UNIT_FIELD_CHARMEDBY, GetGUID()))
- sLog.outCrash("Unit %u is being charmed, but it already has a charmer %u", charm->GetEntry(), charm->GetCharmerGUID());
-
- if (charm->HasUnitMovementFlag(MOVEMENTFLAG_WALK_MODE))
- {
- charm->RemoveUnitMovementFlag(MOVEMENTFLAG_WALK_MODE);
- charm->SendMovementFlagUpdate();
- }
-
- m_Controlled.insert(charm);
- }
- else
- {
- if (GetTypeId() == TYPEID_PLAYER)
- {
- if (!RemoveUInt64Value(UNIT_FIELD_CHARM, charm->GetGUID()))
- sLog.outCrash("Player %s is trying to uncharm unit %u, but it has another charmed unit %u", GetName(), charm->GetEntry(), GetCharmGUID());
- }
-
- if (!charm->RemoveUInt64Value(UNIT_FIELD_CHARMEDBY, GetGUID()))
- sLog.outCrash("Unit %u is being uncharmed, but it has another charmer %u", charm->GetEntry(), charm->GetCharmerGUID());
-
- if (charm->GetTypeId() == TYPEID_PLAYER)
- {
- charm->m_ControlledByPlayer = true;
- charm->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
- ((Player*)charm)->UpdatePvPState();
- }
- else if(Player *player = charm->GetCharmerOrOwnerPlayerOrPlayerItself())
- {
- charm->m_ControlledByPlayer = true;
- charm->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
- charm->SetByteValue(UNIT_FIELD_BYTES_2, 1, player->GetByteValue(UNIT_FIELD_BYTES_2, 1));
- }
- else
- {
- charm->m_ControlledByPlayer = false;
- charm->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
- charm->SetByteValue(UNIT_FIELD_BYTES_2, 1, 0);
- }
-
- if (charm->GetTypeId() == TYPEID_PLAYER
- || !((Creature*)charm)->HasUnitTypeMask(UNIT_MASK_MINION)
- || charm->GetOwnerGUID() != GetGUID())
- m_Controlled.erase(charm);
- }
-}
-
-int32 Unit::DealHeal(Unit *pVictim, uint32 addhealth, SpellEntry const *spellProto, bool critical)
-{
- int32 gain = pVictim->ModifyHealth(int32(addhealth));
-
- Unit* unit = this;
-
- if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isTotem())
- unit = GetOwner();
-
- if (unit->GetTypeId() == TYPEID_PLAYER)
- {
- // overheal = addhealth - gain
- unit->SendHealSpellLog(pVictim, spellProto->Id, addhealth, addhealth - gain, critical);
-
- if (BattleGround *bg = ((Player*)unit)->GetBattleGround())
- bg->UpdatePlayerScore((Player*)unit, SCORE_HEALING_DONE, gain);
-
- // use the actual gain, as the overheal shall not be counted, skip gain 0 (it ignored anyway in to criteria)
- if (gain)
- ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE, gain, 0, pVictim);
-
- ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED, addhealth);
- }
-
- if (pVictim->GetTypeId() == TYPEID_PLAYER)
- {
- ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED, gain);
- ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED, addhealth);
- }
-
- return gain;
-}
-
-Unit* Unit::SelectMagnetTarget(Unit *victim, SpellEntry const *spellInfo)
-{
- if (!victim)
- return NULL;
-
- // Magic case
- if (spellInfo && (spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC))
- {
- //I am not sure if this should be redirected.
- if (spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE)
- return victim;
-
- Unit::AuraEffectList const& magnetAuras = victim->GetAuraEffectsByType(SPELL_AURA_SPELL_MAGNET);
- for (Unit::AuraEffectList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
- if (Unit* magnet = (*itr)->GetBase()->GetUnitOwner())
- if (magnet->isAlive())
- {
- (*itr)->GetBase()->DropCharge();
- return magnet;
- }
- }
- // Melee && ranged case
- else
- {
- AuraEffectList const& hitTriggerAuras = victim->GetAuraEffectsByType(SPELL_AURA_ADD_CASTER_HIT_TRIGGER);
- for (AuraEffectList::const_iterator i = hitTriggerAuras.begin(); i != hitTriggerAuras.end(); ++i)
- if (Unit* magnet = (*i)->GetBase()->GetUnitOwner())
- if (magnet->isAlive() && magnet->IsWithinLOSInMap(this))
- if (roll_chance_i((*i)->GetAmount()))
- {
- (*i)->GetBase()->DropCharge();
- return magnet;
- }
- }
-
- return victim;
-}
-
-Unit* Unit::GetFirstControlled() const
-{
- //Sequence: charmed, pet, other guardians
- Unit *unit = GetCharm();
- if (!unit)
- if (uint64 guid = GetUInt64Value(UNIT_FIELD_SUMMON))
- unit = ObjectAccessor::GetUnit(*this, guid);
-
- return unit;
-}
-
-void Unit::RemoveAllControlled()
-{
- //possessed pet and vehicle
- if (GetTypeId() == TYPEID_PLAYER)
- ((Player*)this)->StopCastingCharm();
-
- while (!m_Controlled.empty())
- {
- Unit *target = *m_Controlled.begin();
- m_Controlled.erase(m_Controlled.begin());
- if (target->GetCharmerGUID() == GetGUID())
- target->RemoveCharmAuras();
- else if (target->GetOwnerGUID() == GetGUID() && target->isSummon())
- ((TempSummon*)target)->UnSummon();
- else
- sLog.outError("Unit %u is trying to release unit %u which is neither charmed nor owned by it", GetEntry(), target->GetEntry());
- }
- if (GetPetGUID())
- sLog.outCrash("Unit %u is not able to release its pet " I64FMT, GetEntry(), GetPetGUID());
- if (GetMinionGUID())
- sLog.outCrash("Unit %u is not able to release its minion " I64FMT, GetEntry(), GetMinionGUID());
- if (GetCharmGUID())
- sLog.outCrash("Unit %u is not able to release its charm " I64FMT, GetEntry(), GetCharmGUID());
-}
-
-Unit* Unit::GetNextRandomRaidMemberOrPet(float radius)
-{
- Player* player = NULL;
- if (GetTypeId() == TYPEID_PLAYER)
- player = (Player*)this;
- // Should we enable this also for charmed units?
- else if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
- player = (Player*)GetOwner();
-
- if (!player)
- return NULL;
- Group *pGroup = player->GetGroup();
- //When there is no group check pet presence
- if (!pGroup)
- {
- // We are pet now, return owner
- if (player!=this)
- return IsWithinDistInMap(player, radius) ? player : NULL;
- Unit * pet = GetGuardianPet();
- //No pet, no group, nothing to return
- if (!pet)
- return NULL;
- // We are owner now, return pet
- return IsWithinDistInMap(pet, radius) ? pet : NULL;
- }
-
- std::vector<Unit*> nearMembers;
- //reserve place for players and pets because resizing vector every unit push is unefficient (vector is reallocated then)
- nearMembers.reserve(pGroup->GetMembersCount()*2);
-
- for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
- if (Player *Target = itr->getSource())
- {
- // IsHostileTo check duel and controlled by enemy
- if (Target !=this && Target->isAlive() && IsWithinDistInMap(Target, radius) && !IsHostileTo(Target))
- nearMembers.push_back(Target);
-
- // Push player's pet to vector
- if (Unit *pet = Target->GetGuardianPet())
- if (pet != this && pet->isAlive() && IsWithinDistInMap(pet, radius) && !IsHostileTo(pet))
- nearMembers.push_back(pet);
- }
-
- if (nearMembers.empty())
- return NULL;
-
- uint32 randTarget = urand(0,nearMembers.size()-1);
- return nearMembers[randTarget];
-}
-
-/*
-Player * Unit::GetMoverSource() const
-{
- if (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->m_mover == this)
- return (Player*)this;
- if (Unit *charmer = GetCharmer())
- if (charmer->GetTypeId() == TYPEID_PLAYER && ((Player*)charmer)->m_mover == this)
- return (Player*)charmer;
- return NULL;
-}
-*/
-
-//only called in Player::SetSeer
-void Unit::AddPlayerToVision(Player* plr)
-{
- if (m_sharedVision.empty())
- {
- setActive(true);
- SetWorldObject(true);
- }
- m_sharedVision.push_back(plr);
-}
-
-//only called in Player::SetSeer
-void Unit::RemovePlayerFromVision(Player* plr)
-{
- m_sharedVision.remove(plr);
- if (m_sharedVision.empty())
- {
- setActive(false);
- SetWorldObject(false);
- }
-}
-
-void Unit::RemoveBindSightAuras()
-{
- RemoveAurasByType(SPELL_AURA_BIND_SIGHT);
-}
-
-void Unit::RemoveCharmAuras()
-{
- RemoveAurasByType(SPELL_AURA_MOD_CHARM);
- RemoveAurasByType(SPELL_AURA_MOD_POSSESS_PET);
- RemoveAurasByType(SPELL_AURA_MOD_POSSESS);
- RemoveAurasByType(SPELL_AURA_AOE_CHARM);
-}
-
-void Unit::UnsummonAllTotems()
-{
- for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i)
- {
- if (!m_SummonSlot[i])
- continue;
-
- if (Creature *OldTotem = GetMap()->GetCreature(m_SummonSlot[i]))
- if (OldTotem->isSummon())
- ((TempSummon*)OldTotem)->UnSummon();
- }
-}
-
-void Unit::SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, uint32 OverHeal, bool critical)
-{
- // we guess size
- WorldPacket data(SMSG_SPELLHEALLOG, (8+8+4+4+4+4+1));
- data.append(pVictim->GetPackGUID());
- data.append(GetPackGUID());
- data << uint32(SpellID);
- data << uint32(Damage);
- data << uint32(OverHeal);
- data << uint32(0); // Absorb amount
- data << uint8(critical ? 1 : 0);
- SendMessageToSet(&data, true);
-}
-
-void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
-{
- WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1));
- data.append(pVictim->GetPackGUID());
- data.append(GetPackGUID());
- data << uint32(SpellID);
- data << uint32(powertype);
- data << uint32(Damage);
- SendMessageToSet(&data, true);
-}
-
-void Unit::EnergizeBySpell(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
-{
- SendEnergizeSpellLog(pVictim, SpellID, Damage, powertype);
- // needs to be called after sending spell log
- pVictim->ModifyPower(powertype, Damage);
-}
-
-uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack)
-{
- if (!spellProto || !pVictim || damagetype == DIRECT_DAMAGE)
- return pdamage;
-
- // For totems get damage bonus from owner
- if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isTotem())
- if (Unit *owner = GetOwner())
- return owner->SpellDamageBonus(pVictim, spellProto, pdamage, damagetype);
-
- // Taken/Done total percent damage auras
- float DoneTotalMod = 1.0f;
- float TakenTotalMod = 1.0f;
- float ApCoeffMod = 1.0f;
- int32 DoneTotal = 0;
- int32 TakenTotal = 0;
-
- // ..done
- // Pet damage
- if (GetTypeId() == TYPEID_UNIT && !((Creature*)this)->isPet())
- DoneTotalMod *= ((Creature*)this)->GetSpellDamageMod(((Creature*)this)->GetCreatureInfo()->rank);
-
- AuraEffectList const &mModDamagePercentDone = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
- for (AuraEffectList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
- if (((*i)->GetMiscValue() & GetSpellSchoolMask(spellProto)) &&
- (*i)->GetSpellProto()->EquippedItemClass == -1 && // -1 == any item class (not wand)
- (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0) // 0 == any inventory type (not wand)
- DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
-
- uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
- // Add flat bonus from spell damage versus
- DoneTotal += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask);
- AuraEffectList const &mDamageDoneVersus = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
- for (AuraEffectList::const_iterator i = mDamageDoneVersus.begin(); i != mDamageDoneVersus.end(); ++i)
- if (creatureTypeMask & uint32((*i)->GetMiscValue()))
- DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
-
- // done scripted mod (take it from owner)
- Unit *owner = GetOwner() ? GetOwner() : this;
- AuraEffectList const &mOverrideClassScript= owner->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
- for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
- {
- if (!(*i)->IsAffectedOnSpell(spellProto))
- continue;
- switch ((*i)->GetMiscValue())
- {
- case 4920: // Molten Fury
- case 4919:
- case 6917: // Death's Embrace
- case 6926:
- case 6928:
- {
- if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this))
- DoneTotalMod *= (100.0f+(*i)->GetAmount())/100.0f;
- break;
- }
- // Soul Siphon
- case 4992:
- case 4993:
- {
- // effect 1 m_amount
- int32 maxPercent = (*i)->GetAmount();
- // effect 0 m_amount
- int32 stepPercent = CalculateSpellDamage((*i)->GetSpellProto(), 0, (*i)->GetSpellProto()->EffectBasePoints[0], this);
- // count affliction effects and calc additional damage in percentage
- int32 modPercent = 0;
- AuraApplicationMap const &victimAuras = pVictim->GetAppliedAuras();
- for (AuraApplicationMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
- {
- Aura const * aura = itr->second->GetBase();
- SpellEntry const *m_spell = aura->GetSpellProto();
- if (m_spell->SpellFamilyName != SPELLFAMILY_WARLOCK || !(m_spell->SpellFamilyFlags[1] & 0x0004071B || m_spell->SpellFamilyFlags[0] & 0x8044C402))
- continue;
- modPercent += stepPercent * aura->GetStackAmount();
- if (modPercent >= maxPercent)
- {
- modPercent = maxPercent;
- break;
- }
- }
- DoneTotalMod *= (modPercent+100.0f)/100.0f;
- break;
- }
- case 6916: // Death's Embrace
- case 6925:
- case 6927:
- if (HasAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, spellProto, this))
- DoneTotalMod *= (100.0f+(*i)->GetAmount())/100.0f;
- break;
- case 5481: // Starfire Bonus
- {
- if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x200002, 0, 0))
- DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
- break;
- }
- case 4418: // Increased Shock Damage
- case 4554: // Increased Lightning Damage
- case 4555: // Improved Moonfire
- case 5142: // Increased Lightning Damage
- case 5147: // Improved Consecration / Libram of Resurgence
- case 5148: // Idol of the Shooting Star
- case 6008: // Increased Lightning Damage / Totem of Hex
- {
- DoneTotal += (*i)->GetAmount();
- break;
- }
- // Tundra Stalker
- // Merciless Combat
- case 7277:
- {
- // Merciless Combat
- if ((*i)->GetSpellProto()->SpellIconID == 2656)
- {
- if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this))
- DoneTotalMod *= (100.0f+(*i)->GetAmount())/100.0f;
- }
- // Tundra Stalker
- else
- {
- // Frost Fever (target debuff)
- if (pVictim->HasAura(55095))
- DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
- break;
- }
- break;
- }
- // Rage of Rivendare
- case 7293:
- {
- if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0,0x02000000,0))
- {
- if (SpellChainNode const *chain = spellmgr.GetSpellChainNode((*i)->GetId()))
- DoneTotalMod *= (chain->rank * 2.0f + 100.0f)/100.0f;
- }
- break;
- }
- // Twisted Faith
- case 7377:
- {
- if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x8000, 0,0, GetGUID()))
- DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
- break;
- }
- // Marked for Death
- case 7598:
- case 7599:
- case 7600:
- case 7601:
- case 7602:
- {
- if (pVictim->GetAuraEffect(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, 0x400, 0, 0))
- DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
- break;
- }
- }
- }
-
- // Custom scripted damage
- switch(spellProto->SpellFamilyName)
- {
- case SPELLFAMILY_MAGE:
- // Ice Lance
- if (spellProto->SpellIconID == 186)
- {
- if (pVictim->HasAuraState(AURA_STATE_FROZEN, spellProto, this))
- {
- // Glyph of Ice Lance
- if (owner->HasAura(56377) && pVictim->getLevel() > owner->getLevel())
- DoneTotalMod *= 4.0f;
- else
- DoneTotalMod *= 3.0f;
- }
- }
-
- // Torment the weak
- if (spellProto->SpellFamilyFlags[0]&0x20200021 || spellProto->SpellFamilyFlags[1]& 0x9000)
- if (pVictim->HasAuraType(SPELL_AURA_MOD_DECREASE_SPEED))
- {
- AuraEffectList const& mDumyAuras = GetAuraEffectsByType(SPELL_AURA_DUMMY);
- for (AuraEffectList::const_iterator i = mDumyAuras.begin(); i != mDumyAuras.end(); ++i)
- if ((*i)->GetSpellProto()->SpellIconID == 3263)
- {
- DoneTotalMod *= float((*i)->GetAmount() + 100.f) / 100.f;
- break;
- }
- }
- break;
- // Glyph of Shadow Word: Pain
- case SPELLFAMILY_PRIEST:
- if (spellProto->SpellFamilyFlags[0] & 0x800000)
- {
- // Increase Mind Flay damage
- if (AuraEffect * aurEff = GetAuraEffect(55687, 0))
- // if Shadow Word: Pain present
- if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x8000, 0,0, GetGUID()))
- DoneTotalMod *= (aurEff->GetAmount() + 100.0f) / 100.f;
- }
- break;
-
- case SPELLFAMILY_PALADIN:
- // Judgement of Vengeance/Judgement of Corruption
- if ((spellProto->SpellFamilyFlags[1] & 0x400000) && spellProto->SpellIconID==2292)
- {
- // Get stack of Holy Vengeance/Blood Corruption on the target added by caster
- uint32 stacks = 0;
- Unit::AuraEffectList const& auras = pVictim->GetAuraEffectsByType(SPELL_AURA_PERIODIC_DAMAGE);
- for (Unit::AuraEffectList::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr)
- if (((*itr)->GetId() == 31803 || (*itr)->GetId() == 53742) && (*itr)->GetCasterGUID()==GetGUID())
- {
- stacks = (*itr)->GetBase()->GetStackAmount();
- break;
- }
- // + 10% for each application of Holy Vengeance/Blood Corruption on the target
- if (stacks)
- DoneTotalMod *= (10.0f + float(stacks)) / 10.0f;
- }
- break;
- case SPELLFAMILY_WARLOCK:
- //Fire and Brimstone
- if (spellProto->SpellFamilyFlags[1] & 0x00020040)
- if (pVictim->HasAuraState(AURA_STATE_CONFLAGRATE))
- {
- AuraEffectList const& mDumyAuras = GetAuraEffectsByType(SPELL_AURA_DUMMY);
- for (AuraEffectList::const_iterator i = mDumyAuras.begin(); i != mDumyAuras.end(); ++i)
- if ((*i)->GetSpellProto()->SpellIconID == 3173)
- {
- DoneTotalMod *= float((*i)->GetAmount() + 100.f) / 100.f;
- break;
- }
- }
- break;
- case SPELLFAMILY_DEATHKNIGHT:
- // Improved Icy Touch
- if (spellProto->SpellFamilyFlags[0] & 0x2)
- if (AuraEffect * aurEff = GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 2721, 0))
- DoneTotalMod *= (100.0f + aurEff->GetAmount()) / 100.0f;
-
- // Glacier Rot
- if (spellProto->SpellFamilyFlags[0] & 0x2 || spellProto->SpellFamilyFlags[1] & 0x6)
- if (AuraEffect * aurEff = GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 196, 0))
- if (pVictim->GetDiseasesByCaster(owner->GetGUID()) > 0)
- DoneTotalMod *= (100.0f + aurEff->GetAmount()) / 100.0f;
-
- // Impurity (dummy effect)
- if (GetTypeId() == TYPEID_PLAYER)
- {
- PlayerSpellMap playerSpells = ((Player*)this)->GetSpellMap();
- for (PlayerSpellMap::const_iterator itr = playerSpells.begin(); itr != playerSpells.end(); ++itr)
- {
- if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
- continue;
- switch (itr->first)
- {
- case 49220:
- case 49633:
- case 49635:
- case 49636:
- case 49638:
- {
- if (const SpellEntry *proto=sSpellStore.LookupEntry(itr->first))
- ApCoeffMod *= (100.0f + proto->CalculateSimpleValue(0)) / 100.0f;
- }
- break;
- }
- }
- }
- break;
- }
-
- // ..taken
- AuraEffectList const& mModDamagePercentTaken = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
- for (AuraEffectList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
- if ((*i)->GetMiscValue() & GetSpellSchoolMask(spellProto) )
- TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
-
- // .. taken pct: dummy auras
- AuraEffectList const& mDummyAuras = pVictim->GetAuraEffectsByType(SPELL_AURA_DUMMY);
- for (AuraEffectList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
- {
- switch((*i)->GetSpellProto()->SpellIconID)
- {
- // Cheat Death
- case 2109:
- if ((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL)
- {
- if (pVictim->GetTypeId() != TYPEID_PLAYER)
- continue;
- float mod = ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f);
- if (mod < (*i)->GetAmount())
- mod = (*i)->GetAmount();
- TakenTotalMod *= (mod+100.0f)/100.0f;
- }
- break;
- // Ebon Plague
- case 1933:
- if ((*i)->GetMiscValue() & (spellProto ? GetSpellSchoolMask(spellProto) : 0))
- TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
- break;
- }
- }
-
- // From caster spells
- AuraEffectList const& mOwnerTaken = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_FROM_CASTER);
- for (AuraEffectList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i)
- if ((*i)->GetCasterGUID() == GetGUID() && (*i)->IsAffectedOnSpell(spellProto))
- TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
-
- // Mod damage from spell mechanic
- if (uint32 mechanicMask = GetAllSpellMechanicMask(spellProto))
- {
- AuraEffectList const& mDamageDoneMechanic = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT);
- for (AuraEffectList::const_iterator i = mDamageDoneMechanic.begin(); i != mDamageDoneMechanic.end(); ++i)
- if (mechanicMask & uint32(1<<((*i)->GetMiscValue())))
- TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
- }
-
- // Taken/Done fixed damage bonus auras
- int32 DoneAdvertisedBenefit = SpellBaseDamageBonus(GetSpellSchoolMask(spellProto));
- int32 TakenAdvertisedBenefit = SpellBaseDamageBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
- // Pets just add their bonus damage to their spell damage
- // note that their spell damage is just gain of their own auras
- if (HasUnitTypeMask(UNIT_MASK_GUARDIAN))
- DoneAdvertisedBenefit += ((Guardian*)this)->GetBonusDamage();
-
- // Check for table values
- float coeff = 0;
- SpellBonusEntry const *bonus = spellmgr.GetSpellBonusData(spellProto->Id);
- if (bonus)
- {
- if (damagetype == DOT)
- {
- coeff = bonus->dot_damage;
- if (bonus->ap_dot_bonus > 0)
- DoneTotal += bonus->ap_dot_bonus * stack * ApCoeffMod * GetTotalAttackPowerValue(
- (IsRangedWeaponSpell(spellProto) && spellProto->DmgClass !=SPELL_DAMAGE_CLASS_MELEE) ? RANGED_ATTACK : BASE_ATTACK);
- }
- else
- {
- coeff = bonus->direct_damage;
- if (bonus->ap_bonus > 0)
- DoneTotal += bonus->ap_bonus * stack * ApCoeffMod * GetTotalAttackPowerValue(
- (IsRangedWeaponSpell(spellProto) && spellProto->DmgClass !=SPELL_DAMAGE_CLASS_MELEE)? RANGED_ATTACK : BASE_ATTACK);
- }
- }
- // Default calculation
- if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
- {
- if (!bonus || coeff < 0)
- {
- // Damage Done from spell damage bonus
- int32 CastingTime = IsChanneledSpell(spellProto) ? GetSpellDuration(spellProto) : GetSpellCastTime(spellProto);
- // Damage over Time spells bonus calculation
- float DotFactor = 1.0f;
- if (damagetype == DOT)
- {
- int32 DotDuration = GetSpellDuration(spellProto);
- // 200% limit
- if (DotDuration > 0)
- {
- if (DotDuration > 30000)
- DotDuration = 30000;
- if (!IsChanneledSpell(spellProto))
- DotFactor = DotDuration / 15000.0f;
- uint8 x = 0;
- for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j)
- {
- if (spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
- spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
- spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH))
- {
- x = j;
- break;
- }
- }
- int32 DotTicks = 6;
- if (spellProto->EffectAmplitude[x] != 0)
- DotTicks = DotDuration / spellProto->EffectAmplitude[x];
- if (DotTicks)
- {
- DoneAdvertisedBenefit /= DotTicks;
- TakenAdvertisedBenefit /= DotTicks;
- }
- }
- }
- // Distribute Damage over multiple effects, reduce by AoE
- CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
-
- // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
- for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j)
- {
- if (spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
- spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH)
- {
- CastingTime /= 2;
- break;
- }
- }
- if (spellProto->SchoolMask != SPELL_SCHOOL_MASK_NORMAL)
- coeff = (CastingTime / 3500.0f) * DotFactor;
- else
- coeff = DotFactor;
- }
-
- float coeff2 = CalculateLevelPenalty(spellProto) * stack;
- if (spellProto->SpellFamilyName) //TODO: fix this
- TakenTotal+= TakenAdvertisedBenefit * coeff * coeff2;
- if (Player* modOwner = GetSpellModOwner())
- {
- coeff *= 100.0f;
- modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_SPELL_BONUS_DAMAGE, coeff);
- coeff /= 100.0f;
- }
- DoneTotal += DoneAdvertisedBenefit * coeff * coeff2;
- }
-
- float tmpDamage = (int32(pdamage) + DoneTotal) * DoneTotalMod;
- // apply spellmod to Done damage (flat and pct)
- if (Player* modOwner = GetSpellModOwner())
- modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
-
- tmpDamage = (tmpDamage + TakenTotal) * TakenTotalMod;
-
- return uint32(std::max(tmpDamage, 0.0f));
-}
-
-int32 Unit::SpellBaseDamageBonus(SpellSchoolMask schoolMask)
-{
- int32 DoneAdvertisedBenefit = 0;
-
- // ..done
- AuraEffectList const& mDamageDone = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE);
- for (AuraEffectList::const_iterator i = mDamageDone.begin(); i != mDamageDone.end(); ++i)
- if (((*i)->GetMiscValue() & schoolMask) != 0 &&
- (*i)->GetSpellProto()->EquippedItemClass == -1 &&
- // -1 == any item class (not wand then)
- (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
- // 0 == any inventory type (not wand then)
- DoneAdvertisedBenefit += (*i)->GetAmount();
-
- if (GetTypeId() == TYPEID_PLAYER)
- {
- // Base value
- DoneAdvertisedBenefit +=((Player*)this)->GetBaseSpellPowerBonus();
-
- // Damage bonus from stats
- AuraEffectList const& mDamageDoneOfStatPercent = GetAuraEffectsByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT);
- for (AuraEffectList::const_iterator i = mDamageDoneOfStatPercent.begin(); i != mDamageDoneOfStatPercent.end(); ++i)
- {
- if ((*i)->GetMiscValue() & schoolMask)
- {
- // stat used stored in miscValueB for this aura
- Stats usedStat = Stats((*i)->GetMiscValueB());
- DoneAdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetAmount() / 100.0f);
- }
- }
- // ... and attack power
- AuraEffectList const& mDamageDonebyAP = GetAuraEffectsByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER);
- for (AuraEffectList::const_iterator i =mDamageDonebyAP.begin(); i != mDamageDonebyAP.end(); ++i)
- if ((*i)->GetMiscValue() & schoolMask)
- DoneAdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetAmount() / 100.0f);
-
- }
- return DoneAdvertisedBenefit > 0 ? DoneAdvertisedBenefit : 0;
-}
-
-int32 Unit::SpellBaseDamageBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
-{
- uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
-
- int32 TakenAdvertisedBenefit = 0;
- // ..done (for creature type by mask) in taken
- AuraEffectList const& mDamageDoneCreature = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
- for (AuraEffectList::const_iterator i = mDamageDoneCreature.begin(); i != mDamageDoneCreature.end(); ++i)
- if (creatureTypeMask & uint32((*i)->GetMiscValue()))
- TakenAdvertisedBenefit += (*i)->GetAmount();
-
- // ..taken
- AuraEffectList const& mDamageTaken = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
- for (AuraEffectList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i)
- if (((*i)->GetMiscValue() & schoolMask) != 0)
- TakenAdvertisedBenefit += (*i)->GetAmount();
-
- return TakenAdvertisedBenefit > 0 ? TakenAdvertisedBenefit : 0;
-}
-
-bool Unit::isSpellCrit(Unit *pVictim, SpellEntry const *spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType) const
-{
- // not critting spell
- if ((spellProto->AttributesEx2 & SPELL_ATTR_EX2_CANT_CRIT))
- return false;
-
- float crit_chance = 0.0f;
- switch(spellProto->DmgClass)
- {
- case SPELL_DAMAGE_CLASS_NONE: // Exception for Earth Shield and Lifebloom Final Bloom
- if (spellProto->Id != 379 && spellProto->Id != 33778) // We need more spells to find a general way (if there is any)
- return false;
- case SPELL_DAMAGE_CLASS_MAGIC:
- {
- if (schoolMask & SPELL_SCHOOL_MASK_NORMAL)
- crit_chance = 0.0f;
- // For other schools
- else if (GetTypeId() == TYPEID_PLAYER)
- crit_chance = GetFloatValue( PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask));
- else
- {
- crit_chance = m_baseSpellCritChance;
- crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
- }
- // taken
- if (pVictim)
- {
- if (!IsPositiveSpell(spellProto->Id))
- {
- // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE
- crit_chance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask);
- // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE
- crit_chance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
- // Modify by player victim resilience
- crit_chance -= pVictim->GetSpellCritChanceReduction();
- }
- // scripted (increase crit chance ... against ... target by x%
- AuraEffectList const& mOverrideClassScript = GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
- for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
- {
- if (!((*i)->IsAffectedOnSpell(spellProto)))
- continue;
- int32 modChance=0;
- switch((*i)->GetMiscValue())
- {
- // Shatter
- case 911: modChance+= 16.0f;
- case 910: modChance+= 17.0f;
- case 849: modChance+= 17.0f;
- if (!pVictim->HasAuraState(AURA_STATE_FROZEN, spellProto, this))
- break;
- crit_chance+=modChance;
- break;
- case 7917: // Glyph of Shadowburn
- if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this))
- crit_chance+=(*i)->GetAmount();
- break;
- case 7997: // Renewed Hope
- case 7998:
- if (pVictim->HasAura(6788))
- crit_chance+=(*i)->GetAmount();
- break;
- case 21: // Test of Faith
- case 6935:
- case 6918:
- if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
- crit_chance+=(*i)->GetAmount();
- break;
- default:
- break;
- }
- }
- // Custom crit by class
- switch(spellProto->SpellFamilyName)
- {
- case SPELLFAMILY_DRUID:
- // Starfire
- if (spellProto->SpellFamilyFlags[0] & 0x4 && spellProto->SpellIconID == 1485)
- {
- // Improved Insect Swarm
- if (AuraEffect const * aurEff = GetDummyAuraEffect(SPELLFAMILY_DRUID, 1771, 0))
- if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x00000002, 0, 0))
- crit_chance+=aurEff->GetAmount();
- break;
- }
- break;
- case SPELLFAMILY_PALADIN:
- // Flash of light
- if (spellProto->SpellFamilyFlags[0] & 0x40000000)
- {
- // Sacred Shield
- AuraEffect const* aura = pVictim->GetAuraEffect(58597,1);
- if (aura && aura->GetCasterGUID() == GetGUID())
- crit_chance+=aura->GetAmount();
- break;
- }
- // Exorcism
- else if (spellProto->Category == 19)
- {
- if (pVictim->GetCreatureTypeMask() & CREATURE_TYPEMASK_DEMON_OR_UNDEAD)
- return true;
- break;
- }
- break;
- case SPELLFAMILY_SHAMAN:
- // Lava Burst
- if (spellProto->SpellFamilyFlags[1] & 0x00001000)
- {
- if (AuraEffect const* flameShock = pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, 0x10000000, 0,0, GetGUID()))
- return true;
- break;
- }
- break;
- }
- }
- break;
- }
- case SPELL_DAMAGE_CLASS_MELEE:
- if (pVictim)
- {
- // Custom crit by class
- switch(spellProto->SpellFamilyName)
- {
- case SPELLFAMILY_DRUID:
- // Rend and Tear - bonus crit chance for Ferocious Bite on bleeding targets
- if (spellProto->SpellFamilyFlags[0] & 0x00800000
- && spellProto->SpellIconID == 1680
- && pVictim->HasAuraState(AURA_STATE_BLEEDING))
- {
- if (AuraEffect const *rendAndTear = GetDummyAuraEffect(SPELLFAMILY_DRUID, 2859, 1))
- crit_chance += rendAndTear->GetAmount();
- break;
- }
- break;
- case SPELLFAMILY_PALADIN:
- // Judgement of Command proc always crits on stunned target
- if (spellProto->SpellFamilyName == SPELLFAMILY_PALADIN)
- if (spellProto->SpellFamilyFlags[0] & 0x0000000000800000LL && spellProto->SpellIconID == 561)
- if (pVictim->hasUnitState(UNIT_STAT_STUNNED))
- return true;
- }
- }
- case SPELL_DAMAGE_CLASS_RANGED:
- {
- if (pVictim)
- {
- crit_chance += GetUnitCriticalChance(attackType, pVictim);
- crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
- }
- break;
- }
- default:
- return false;
- }
- // percent done
- // only players use intelligence for critical chance computations
- if (Player* modOwner = GetSpellModOwner())
- modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance);
-
- crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f;
- if (roll_chance_f(crit_chance))
- return true;
- return false;
-}
-
-uint32 Unit::SpellCriticalDamageBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
-{
- // Calculate critical bonus
- int32 crit_bonus;
- switch(spellProto->DmgClass)
- {
- case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
- case SPELL_DAMAGE_CLASS_RANGED:
- // TODO: write here full calculation for melee/ranged spells
- crit_bonus = damage;
- break;
- default:
- crit_bonus = damage / 2; // for spells is 50%
- break;
- }
-
- // adds additional damage to crit_bonus (from talents)
- if (Player* modOwner = GetSpellModOwner())
- modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
-
- if (pVictim)
- {
- uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
- crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
- }
-
- if (crit_bonus > 0)
- damage += crit_bonus;
-
- return damage;
-}
-
-uint32 Unit::SpellCriticalHealingBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
-{
- // Calculate critical bonus
- int32 crit_bonus;
- switch(spellProto->DmgClass)
- {
- case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
- case SPELL_DAMAGE_CLASS_RANGED:
- // TODO: write here full calculation for melee/ranged spells
- crit_bonus = damage;
- break;
- default:
- crit_bonus = damage / 2; // for spells is 50%
- break;
- }
-
- if (pVictim)
- {
- uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
- crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
- }
-
- if (crit_bonus > 0)
- damage += crit_bonus;
-
- damage = int32(float(damage) * GetTotalAuraMultiplier(SPELL_AURA_MOD_CRITICAL_HEALING_AMOUNT));
-
- return damage;
-}
-
-uint32 Unit::SpellHealingBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 healamount, DamageEffectType damagetype, uint32 stack)
-{
- // For totems get healing bonus from owner (statue isn't totem in fact)
- if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isTotem())
- if (Unit* owner = GetOwner())
- return owner->SpellHealingBonus(pVictim, spellProto, healamount, damagetype, stack);
-
- // Healing Done
- // Taken/Done total percent damage auras
- float DoneTotalMod = 1.0f;
- float TakenTotalMod = 1.0f;
- int32 DoneTotal = 0;
- int32 TakenTotal = 0;
-
- // Healing done percent
- AuraEffectList const& mHealingDonePct = GetAuraEffectsByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT);
- for (AuraEffectList::const_iterator i = mHealingDonePct.begin(); i != mHealingDonePct.end(); ++i)
- DoneTotalMod *= (100.0f + (*i)->GetAmount()) / 100.0f;
-
- // done scripted mod (take it from owner)
- Unit *owner = GetOwner() ? GetOwner() : this;
- AuraEffectList const &mOverrideClassScript= owner->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
- for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
- {
- if (!(*i)->IsAffectedOnSpell(spellProto))
- continue;
- switch((*i)->GetMiscValue())
- {
- case 4415: // Increased Rejuvenation Healing
- case 4953:
- case 3736: // Hateful Totem of the Third Wind / Increased Lesser Healing Wave / LK Arena (4/5/6) Totem of the Third Wind / Savage Totem of the Third Wind
- DoneTotal+=(*i)->GetAmount();
- break;
- case 7997: // Renewed Hope
- case 7998:
- if (pVictim->HasAura(6788))
- DoneTotalMod *=((*i)->GetAmount() + 100.0f)/100.0f;
- break;
- case 21: // Test of Faith
- case 6935:
- case 6918:
- if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
- DoneTotalMod *=((*i)->GetAmount() + 100.0f)/100.0f;
- break;
- case 7798: // Glyph of Regrowth
- {
- if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, 0x40, 0, 0))
- DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
- break;
- }
- case 8477: // Nourish Heal Boost
- {
- int32 stepPercent = (*i)->GetAmount();
- int32 modPercent = 0;
- AuraApplicationMap const& victimAuras = pVictim->GetAppliedAuras();
- for (AuraApplicationMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
- {
- Aura const * aura = itr->second->GetBase();
- if (aura->GetCasterGUID()!=GetGUID())
- continue;
- SpellEntry const* m_spell = aura->GetSpellProto();
- if ( m_spell->SpellFamilyName != SPELLFAMILY_DRUID ||
- !(m_spell->SpellFamilyFlags[1] & 0x00000010 || m_spell->SpellFamilyFlags[0] & 0x50))
- continue;
- modPercent += stepPercent * aura->GetStackAmount();
- }
- DoneTotalMod *= (modPercent+100.0f)/100.0f;
- break;
- }
- case 7871: // Glyph of Lesser Healing Wave
- {
- if (pVictim->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, 0 , 0x00000400, 0, GetGUID()))
- DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
- break;
- }
- default:
- break;
- }
- }
-
- // Taken/Done fixed damage bonus auras
- int32 DoneAdvertisedBenefit = SpellBaseHealingBonus(GetSpellSchoolMask(spellProto));
- int32 TakenAdvertisedBenefit = SpellBaseHealingBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
-
- bool scripted = false;
-
- for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
- {
- switch (spellProto->EffectApplyAuraName[i])
- {
- // These auras do not use healing coeff
- case SPELL_AURA_PERIODIC_LEECH:
- case SPELL_AURA_PERIODIC_HEALTH_FUNNEL:
- scripted = true;
- break;
- }
- }
-
- // Check for table values
- SpellBonusEntry const* bonus = !scripted ? spellmgr.GetSpellBonusData(spellProto->Id) : NULL;
- float coeff = 0;
- float factorMod = 1.0f;
- if (bonus)
- {
- if (damagetype == DOT)
- {
- coeff = bonus->dot_damage;
- if (bonus->ap_dot_bonus > 0)
- DoneTotal+=bonus->ap_dot_bonus * stack * GetTotalAttackPowerValue(
- (IsRangedWeaponSpell(spellProto) && spellProto->DmgClass !=SPELL_DAMAGE_CLASS_MELEE)? RANGED_ATTACK : BASE_ATTACK);
- }
- else
- {
- coeff = bonus->direct_damage;
- if (bonus->ap_bonus > 0)
- DoneTotal+=bonus->ap_bonus * stack * GetTotalAttackPowerValue(
- (IsRangedWeaponSpell(spellProto) && spellProto->DmgClass !=SPELL_DAMAGE_CLASS_MELEE)? RANGED_ATTACK : BASE_ATTACK);
- }
- }
- else // scripted bonus
- {
- // Gift of the Naaru
- if (spellProto->SpellFamilyFlags[2] & 0x80000000 && spellProto->SpellIconID == 329)
- {
- scripted = true;
- int32 apBonus = std::max(GetTotalAttackPowerValue(BASE_ATTACK), GetTotalAttackPowerValue(RANGED_ATTACK));
- if (apBonus > DoneAdvertisedBenefit)
- {
- DoneTotal += apBonus * 0.2f;
- coeff = 0.0f;
- }
- else
- coeff = 1.0f;
- }
- // Earthliving - 0.45% of normal hot coeff
- else if (spellProto->SpellFamilyName==SPELLFAMILY_SHAMAN && spellProto->SpellFamilyFlags[1] & 0x80000)
- factorMod *= 0.45f;
- // Already set to scripted? so not uses healing bonus coefficient
- // No heal coeff for SPELL_DAMAGE_CLASS_NONE class spells by default
- else if (scripted || spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE)
- {
- scripted = true;
- coeff = 0.0f;
- }
- }
-
- // Default calculation
- if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
- {
- if ((!bonus && !scripted) || coeff < 0)
- {
- // Damage Done from spell damage bonus
- int32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
- // Damage over Time spells bonus calculation
- float DotFactor = 1.0f;
- if (damagetype == DOT)
- {
- int32 DotDuration = GetSpellDuration(spellProto);
- // 200% limit
- if (DotDuration > 0)
- {
- if (DotDuration > 30000) DotDuration = 30000;
- if (!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
- uint32 x = 0;
- for (uint8 j = 0; j < MAX_SPELL_EFFECTS; j++)
- {
- if (spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
- spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
- spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH))
- {
- x = j;
- break;
- }
- }
- int32 DotTicks = 6;
- if (spellProto->EffectAmplitude[x] != 0)
- DotTicks = DotDuration / spellProto->EffectAmplitude[x];
- if (DotTicks)
- {
- DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
- TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
- }
- }
- }
- // Distribute Damage over multiple effects, reduce by AoE
- CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
- // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
- for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j)
- {
- if (spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
- spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
- {
- CastingTime /= 2;
- break;
- }
- }
- // As wowwiki says: C = (Cast Time / 3.5) * 1.88 (for healing spells)
- coeff = (CastingTime / 3500.0f) * DotFactor * 1.88f;
- }
-
- factorMod *= CalculateLevelPenalty(spellProto)* stack;
- TakenTotal += TakenAdvertisedBenefit * coeff * factorMod;
- if (Player* modOwner = GetSpellModOwner())
- {
- coeff *= 100.0f;
- modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_SPELL_BONUS_DAMAGE, coeff);
- coeff /= 100.0f;
- }
- DoneTotal += DoneAdvertisedBenefit * coeff * factorMod;
- }
-
- // use float as more appropriate for negative values and percent applying
- float heal = (int32(healamount) + DoneTotal) * DoneTotalMod;
- // apply spellmod to Done amount
- if (Player* modOwner = GetSpellModOwner())
- modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal);
-
- // Nourish cast
- if (spellProto->SpellFamilyName == SPELLFAMILY_DRUID && spellProto->SpellFamilyFlags[1] & 0x2000000)
- {
- // Rejuvenation, Regrowth, Lifebloom, or Wild Growth
- if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, 0x50, 0x4000010, 0))
- //increase healing by 20%
- TakenTotalMod *= 1.2f;
- }
-
- // Taken mods
-
- // Healing Wave
- if (spellProto->SpellFamilyName == SPELLFAMILY_SHAMAN && spellProto->SpellFamilyFlags[0] & 0x40)
- {
- // Search for Healing Way on Victim
- if (AuraEffect const* HealingWay = pVictim->GetAuraEffect(29203, 0))
- TakenTotalMod *= (HealingWay->GetAmount() + 100.0f) / 100.0f;
- }
-
- // Tenacity increase healing % taken
- if (AuraEffect const* Tenacity = pVictim->GetAuraEffect(58549, 0))
- TakenTotalMod *= (Tenacity->GetAmount() + 100.0f) / 100.0f;
-
-
- // Healing taken percent
- float minval = pVictim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
- if (minval)
- TakenTotalMod *= (100.0f + minval) / 100.0f;
-
- float maxval = pVictim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
- if (maxval)
- TakenTotalMod *= (100.0f + maxval) / 100.0f;
-
- if (damagetype == DOT)
- {
- // Healing over time taken percent
- float minval_hot = pVictim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HOT_PCT);
- if (minval_hot)
- TakenTotalMod *= (100.0f + minval_hot) / 100.0f;
-
- float maxval_hot = pVictim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HOT_PCT);
- if (maxval_hot)
- TakenTotalMod *= (100.0f + maxval_hot) / 100.0f;
- }
-
- AuraEffectList const& mHealingGet= pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_HEALING_RECEIVED);
- for (AuraEffectList::const_iterator i = mHealingGet.begin(); i != mHealingGet.end(); ++i)
- if (GetGUID()==(*i)->GetCasterGUID() && (*i)->IsAffectedOnSpell(spellProto) )
- TakenTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f;
-
- heal = (int32(heal) + TakenTotal) * TakenTotalMod;
-
- return uint32(std::max(heal, 0.0f));
-}
-
-int32 Unit::SpellBaseHealingBonus(SpellSchoolMask schoolMask)
-{
- int32 AdvertisedBenefit = 0;
-
- AuraEffectList const& mHealingDone = GetAuraEffectsByType(SPELL_AURA_MOD_HEALING_DONE);
- for (AuraEffectList::const_iterator i = mHealingDone.begin(); i != mHealingDone.end(); ++i)
- if (((*i)->GetMiscValue() & schoolMask) != 0)
- AdvertisedBenefit += (*i)->GetAmount();
-
- // Healing bonus of spirit, intellect and strength
- if (GetTypeId() == TYPEID_PLAYER)
- {
- // Base value
- AdvertisedBenefit +=((Player*)this)->GetBaseSpellPowerBonus();
-
- // Healing bonus from stats
- AuraEffectList const& mHealingDoneOfStatPercent = GetAuraEffectsByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT);
- for (AuraEffectList::const_iterator i = mHealingDoneOfStatPercent.begin(); i != mHealingDoneOfStatPercent.end(); ++i)
- {
- // stat used dependent from misc value (stat index)
- Stats usedStat = Stats((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()]);
- AdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetAmount() / 100.0f);
- }
-
- // ... and attack power
- AuraEffectList const& mHealingDonebyAP = GetAuraEffectsByType(SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER);
- for (AuraEffectList::const_iterator i = mHealingDonebyAP.begin(); i != mHealingDonebyAP.end(); ++i)
- if ((*i)->GetMiscValue() & schoolMask)
- AdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetAmount() / 100.0f);
- }
- return AdvertisedBenefit;
-}
-
-int32 Unit::SpellBaseHealingBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
-{
- int32 AdvertisedBenefit = 0;
- AuraEffectList const& mDamageTaken = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_HEALING);
- for (AuraEffectList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i)
- if (((*i)->GetMiscValue() & schoolMask) != 0)
- AdvertisedBenefit += (*i)->GetAmount();
- return AdvertisedBenefit;
-}
-
-bool Unit::IsImmunedToDamage(SpellSchoolMask shoolMask)
-{
- //If m_immuneToSchool type contain this school type, IMMUNE damage.
- SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
- for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
- if (itr->type & shoolMask)
- return true;
-
- //If m_immuneToDamage type contain magic, IMMUNE damage.
- SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
- for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
- if (itr->type & shoolMask)
- return true;
-
- return false;
-}
-
-bool Unit::IsImmunedToDamage(SpellEntry const* spellInfo)
-{
- if (spellInfo->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY)
- return false;
-
- uint32 shoolMask = GetSpellSchoolMask(spellInfo);
- if (spellInfo->Id != 42292 && spellInfo->Id !=59752)
- {
- //If m_immuneToSchool type contain this school type, IMMUNE damage.
- SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
- for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
- if (itr->type & shoolMask &&!IsDispelableBySpell(spellInfo, itr->spellId))
- return true;
- }
-
- //If m_immuneToDamage type contain magic, IMMUNE damage.
- SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
- for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
- if (itr->type & shoolMask)
- return true;
-
- return false;
-}
-
-bool Unit::IsImmunedToSpell(SpellEntry const* spellInfo)
-{
- if (!spellInfo)
- return false;
-
- // Single spell immunity.
- SpellImmuneList const& idList = m_spellImmune[IMMUNITY_ID];
- for (SpellImmuneList::const_iterator itr = idList.begin(); itr != idList.end(); ++itr)
- if (itr->type == spellInfo->Id)
- return true;
-
- if (spellInfo->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY)
- return false;
-
- if (spellInfo->Dispel)
- {
- SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_DISPEL];
- for (SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr)
- if (itr->type == spellInfo->Dispel)
- return true;
- }
-
- if (spellInfo->Mechanic)
- {
- SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
- for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
- if (itr->type == spellInfo->Mechanic)
- return true;
- }
-
- for (int i=0;i<3;++i)
- {
- // State/effect immunities applied by aura expect full spell immunity
- // Ignore effects with mechanic, they are supposed to be checked separately
- if (!spellInfo->EffectMechanic[i])
- if (IsImmunedToSpellEffect(spellInfo, i))
- return true;
- }
-
- if (spellInfo->Id != 42292 && spellInfo->Id !=59752)
- {
- SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
- for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
- if ((itr->type & GetSpellSchoolMask(spellInfo))
- && !(IsPositiveSpell(itr->spellId) && IsPositiveSpell(spellInfo->Id))
- && !IsDispelableBySpell(spellInfo, itr->spellId))
- return true;
- }
-
- return false;
-}
-
-bool Unit::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
-{
- if (!spellInfo)
- return false;
- //If m_immuneToEffect type contain this effect type, IMMUNE effect.
- uint32 effect = spellInfo->Effect[index];
- SpellImmuneList const& effectList = m_spellImmune[IMMUNITY_EFFECT];
- for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr)
- if (itr->type == effect)
- return true;
-
- if (uint32 mechanic = spellInfo->EffectMechanic[index])
- {
- SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
- for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
- if (itr->type == spellInfo->EffectMechanic[index])
- return true;
- }
-
- if (uint32 aura = spellInfo->EffectApplyAuraName[index])
- {
- SpellImmuneList const& list = m_spellImmune[IMMUNITY_STATE];
- for (SpellImmuneList::const_iterator itr = list.begin(); itr != list.end(); ++itr)
- if (itr->type == aura)
- return true;
- // Check for immune to application of harmful magical effects
- AuraEffectList const& immuneAuraApply = GetAuraEffectsByType(SPELL_AURA_MOD_IMMUNE_AURA_APPLY_SCHOOL);
- for (AuraEffectList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
- if (spellInfo->Dispel == DISPEL_MAGIC && // Magic debuff
- ((*iter)->GetMiscValue() & GetSpellSchoolMask(spellInfo)) && // Check school
- !IsPositiveEffect(spellInfo->Id, index)) // Harmful
- return true;
- }
-
- return false;
-}
-
-bool Unit::IsDamageToThreatSpell(SpellEntry const * spellInfo) const
-{
- if (!spellInfo)
- return false;
-
- switch(spellInfo->SpellFamilyName)
- {
- case SPELLFAMILY_WARLOCK:
- if (spellInfo->SpellFamilyFlags[0] == 0x100) // Searing Pain
- return true;
- break;
- case SPELLFAMILY_SHAMAN:
- if (spellInfo->SpellFamilyFlags[0] == SPELLFAMILYFLAG_SHAMAN_FROST_SHOCK)
- return true;
- break;
- case SPELLFAMILY_DEATHKNIGHT:
- if (spellInfo->SpellFamilyFlags[1] == 0x20000000) // Rune Strike
- return true;
- break;
- }
-
- return false;
-}
-
-void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage, WeaponAttackType attType, SpellEntry const *spellProto)
-{
- if (!pVictim)
- return;
-
- if (*pdamage == 0)
- return;
-
- uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
-
- // Taken/Done fixed damage bonus auras
- int32 DoneFlatBenefit = 0;
- int32 TakenFlatBenefit = 0;
-
- // ..done (for creature type by mask) in taken
- AuraEffectList const& mDamageDoneCreature = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
- for (AuraEffectList::const_iterator i = mDamageDoneCreature.begin(); i != mDamageDoneCreature.end(); ++i)
- if (creatureTypeMask & uint32((*i)->GetMiscValue()))
- DoneFlatBenefit += (*i)->GetAmount();
-
- // ..done
- // SPELL_AURA_MOD_DAMAGE_DONE included in weapon damage
-
- // ..done (base at attack power for marked target and base at attack power for creature type)
- int32 APbonus = 0;
-
- if (attType == RANGED_ATTACK && pVictim->GetTypeId() == TYPEID_UNIT)
- {
- APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_RANGED_AP_ATTACKER_CREATURES_BONUS);
-
- // ..done (base at attack power and creature type)
- AuraEffectList const& mCreatureAttackPower = GetAuraEffectsByType(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS);
- for (AuraEffectList::const_iterator i = mCreatureAttackPower.begin(); i != mCreatureAttackPower.end(); ++i)
- if (creatureTypeMask & uint32((*i)->GetMiscValue()))
- APbonus += (*i)->GetAmount();
- }
- else if (attType == RANGED_ATTACK)
- {
- APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS);
-
- // ..done (base at attack power and creature type)
- AuraEffectList const& mCreatureAttackPower = GetAuraEffectsByType(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS);
- for (AuraEffectList::const_iterator i = mCreatureAttackPower.begin(); i != mCreatureAttackPower.end(); ++i)
- if (creatureTypeMask & uint32((*i)->GetMiscValue()))
- APbonus += (*i)->GetAmount();
- }
- else
- {
- APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS);
-
- // ..done (base at attack power and creature type)
- AuraEffectList const& mCreatureAttackPower = GetAuraEffectsByType(SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS);
- for (AuraEffectList::const_iterator i = mCreatureAttackPower.begin(); i != mCreatureAttackPower.end(); ++i)
- if (creatureTypeMask & uint32((*i)->GetMiscValue()))
- APbonus += (*i)->GetAmount();
- }
-
- if (APbonus != 0) // Can be negative
- {
- bool normalized = false;
- if (spellProto)
- for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
- if (spellProto->Effect[i] == SPELL_EFFECT_NORMALIZED_WEAPON_DMG)
- {
- normalized = true;
- break;
- }
- DoneFlatBenefit += int32(APbonus/14.0f * GetAPMultiplier(attType,normalized));
- }
-
- // ..taken
- AuraEffectList const& mDamageTaken = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
- for (AuraEffectList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i)
- if ((*i)->GetMiscValue() & GetMeleeDamageSchoolMask())
- TakenFlatBenefit += (*i)->GetAmount();
-
- if (attType!=RANGED_ATTACK)
- TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN);
- else
- TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN);
-
- // Done/Taken total percent damage auras
- float DoneTotalMod = 1.0f;
- float TakenTotalMod = 1.0f;
-
- // ..done
- // SPELL_AURA_MOD_DAMAGE_PERCENT_DONE included in weapon damage
- // SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT included in weapon damage
-
- // SPELL_AURA_MOD_DAMAGE_PERCENT_DONE for non-physical spells like Scourge Strike, Frost Strike, this is NOT included in weapon damage
- if (spellProto)
- if (GetSpellSchoolMask(spellProto) != SPELL_SCHOOL_MASK_NORMAL)
- {
- AuraEffectList const &mModDamagePercentDone = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
- for (AuraEffectList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
- if (((*i)->GetMiscValue() & GetSpellSchoolMask(spellProto)) && !((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL))
- DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
- }
-
- AuraEffectList const &mDamageDoneVersus = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
- for (AuraEffectList::const_iterator i = mDamageDoneVersus.begin(); i != mDamageDoneVersus.end(); ++i)
- if (creatureTypeMask & uint32((*i)->GetMiscValue()))
- DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
-
- // done scripted mod (take it from owner)
- Unit *owner = GetOwner() ? GetOwner() : this;
- AuraEffectList const &mOverrideClassScript= owner->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
- for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
- {
- if (!(*i)->IsAffectedOnSpell(spellProto))
- continue;
- switch ((*i)->GetMiscValue())
- {
- // Tundra Stalker
- // Merciless Combat
- case 7277:
- {
- // Merciless Combat
- if ((*i)->GetSpellProto()->SpellIconID == 2656)
- {
- if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this))
- DoneTotalMod *= (100.0f+(*i)->GetAmount())/100.0f;
- }
- // Tundra Stalker
- else
- {
- // Frost Fever (target debuff)
- if (pVictim->HasAura(55095))
- DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
- }
- break;
- }
- // Rage of Rivendare
- case 7293:
- {
- if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0,0x02000000,0))
- if (SpellChainNode const *chain = spellmgr.GetSpellChainNode((*i)->GetId()))
- DoneTotalMod *= (chain->rank * 2.0f + 100.0f)/100.0f;
- break;
- }
- }
- }
-
- // Custom scripted damage
- if (spellProto)
- switch(spellProto->SpellFamilyName)
- {
- case SPELLFAMILY_DEATHKNIGHT:
- // Glacier Rot
- if (spellProto->SpellFamilyFlags[0] & 0x2 || spellProto->SpellFamilyFlags[1] & 0x6)
- if (AuraEffect * aurEff = GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 196, 0))
- if (pVictim->GetDiseasesByCaster(owner->GetGUID()) > 0)
- DoneTotalMod *= (100.0f + aurEff->GetAmount()) / 100.0f;
- break;
- }
-
- // ..taken
- AuraEffectList const& mModDamagePercentTaken = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
- for (AuraEffectList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
- if ((*i)->GetMiscValue() & GetMeleeDamageSchoolMask())
- TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
-
- // .. taken pct (special attacks)
- if (spellProto)
- {
- // Mod damage from spell mechanic
- uint32 mechanicMask = GetAllSpellMechanicMask(spellProto);
-
- // Shred, Maul - "Effects which increase Bleed damage also increase Shred damage"
- if (spellProto->SpellFamilyName == SPELLFAMILY_DRUID && spellProto->SpellFamilyFlags[0] & 0x00008800)
- mechanicMask |= (1<<MECHANIC_BLEED);
-
- if (mechanicMask)
- {
- AuraEffectList const& mDamageDoneMechanic = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT);
- for (AuraEffectList::const_iterator i = mDamageDoneMechanic.begin(); i != mDamageDoneMechanic.end(); ++i)
- if (mechanicMask & uint32(1<<((*i)->GetMiscValue())))
- TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
- }
- }
-
- // .. taken pct: dummy auras
- AuraEffectList const& mDummyAuras = pVictim->GetAuraEffectsByType(SPELL_AURA_DUMMY);
- for (AuraEffectList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
- {
- switch((*i)->GetSpellProto()->SpellIconID)
- {
- //Cheat Death
- case 2109:
- if ((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL)
- {
- if (pVictim->GetTypeId() != TYPEID_PLAYER)
- continue;
- float mod = ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f);
- if (mod < (*i)->GetAmount())
- mod = (*i)->GetAmount();
- TakenTotalMod *= (mod+100.0f)/100.0f;
- }
- break;
- // Blessing of Sanctuary
- // Greater Blessing of Sanctuary
- case 19:
- case 1804:
- {
- if ((*i)->GetSpellProto()->SpellFamilyName != SPELLFAMILY_PALADIN)
- continue;
-
- if ((*i)->GetMiscValue() & (spellProto ? GetSpellSchoolMask(spellProto) : 0))
- TakenTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f;
- break;
- }
- // Ebon Plague
- case 1933:
- if ((*i)->GetMiscValue() & (spellProto ? GetSpellSchoolMask(spellProto) : 0))
- TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
- break;
- }
- }
-
- // .. taken pct: class scripts
- AuraEffectList const& mclassScritAuras = GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
- for (AuraEffectList::const_iterator i = mclassScritAuras.begin(); i != mclassScritAuras.end(); ++i)
- {
- switch((*i)->GetMiscValue())
- {
- case 6427: case 6428: // Dirty Deeds
- if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this))
- {
- AuraEffect* eff0 = (*i)->GetBase()->GetEffect(0);
- if (!eff0 || (*i)->GetEffIndex()!=1)
- {
- sLog.outError("Spell structure of DD (%u) changed.",(*i)->GetId());
- continue;
- }
-
- // effect 0 have expected value but in negative state
- TakenTotalMod *= (-eff0->GetAmount()+100.0f)/100.0f;
- }
- break;
- }
- }
-
- if (attType != RANGED_ATTACK)
- {
- AuraEffectList const& mModMeleeDamageTakenPercent = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT);
- for (AuraEffectList::const_iterator i = mModMeleeDamageTakenPercent.begin(); i != mModMeleeDamageTakenPercent.end(); ++i)
- TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
- }
- else
- {
- AuraEffectList const& mModRangedDamageTakenPercent = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT);
- for (AuraEffectList::const_iterator i = mModRangedDamageTakenPercent.begin(); i != mModRangedDamageTakenPercent.end(); ++i)
- TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
- }
-
- float tmpDamage = float(int32(*pdamage) + DoneFlatBenefit) * DoneTotalMod;
-
- // apply spellmod to Done damage
- if (spellProto)
- if (Player* modOwner = GetSpellModOwner())
- modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, tmpDamage);
-
- tmpDamage = (tmpDamage + TakenFlatBenefit)*TakenTotalMod;
-
- // bonus result can be negative
- *pdamage = uint32(std::max(tmpDamage, 0.0f));
-}
-
-void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply)
-{
- if (apply)
- {
- for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(), next; itr != m_spellImmune[op].end(); itr = next)
- {
- next = itr; ++next;
- if (itr->type == type)
- {
- m_spellImmune[op].erase(itr);
- next = m_spellImmune[op].begin();
- }
- }
- SpellImmune Immune;
- Immune.spellId = spellId;
- Immune.type = type;
- m_spellImmune[op].push_back(Immune);
- }
- else
- {
- for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(); itr != m_spellImmune[op].end(); ++itr)
- {
- if (itr->spellId == spellId)
- {
- m_spellImmune[op].erase(itr);
- break;
- }
- }
- }
-
-}
-
-void Unit::ApplySpellDispelImmunity(const SpellEntry * spellProto, DispelType type, bool apply)
-{
- ApplySpellImmune(spellProto->Id,IMMUNITY_DISPEL, type, apply);
-
- if (apply && spellProto->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)
- {
- // Create dispel mask by dispel type
- uint32 dispelMask = GetDispellMask(type);
- // Dispel all existing auras vs current dispel type
- AuraApplicationMap& auras = GetAppliedAuras();
- for (AuraApplicationMap::iterator itr = auras.begin(); itr != auras.end();)
- {
- SpellEntry const* spell = itr->second->GetBase()->GetSpellProto();
- if ((1<<spell->Dispel) & dispelMask )
- {
- // Dispel aura
- RemoveAura(itr);
- }
- else
- ++itr;
- }
- }
-}
-
-float Unit::GetWeaponProcChance() const
-{
- // normalized proc chance for weapon attack speed
- // (odd formula...)
- if (isAttackReady(BASE_ATTACK))
- return (GetAttackTime(BASE_ATTACK) * 1.8f / 1000.0f);
- else if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
- return (GetAttackTime(OFF_ATTACK) * 1.6f / 1000.0f);
- return 0;
-}
-
-float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM, const SpellEntry * spellProto) const
-{
- // proc per minute chance calculation
- if (PPM <= 0) return 0.0f;
- // Apply chance modifer aura
- if (spellProto)
- if (Player* modOwner = GetSpellModOwner())
- modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_PROC_PER_MINUTE,PPM);
-
- return uint32((WeaponSpeed * PPM) / 600.0f); // result is chance in percents (probability = Speed_in_sec * (PPM / 60))
-}
-
-void Unit::Mount(uint32 mount, uint32 VehicleId)
-{
- RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNT);
-
- if (mount)
- SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount);
-
- SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
-
- // unsummon pet
- if (GetTypeId() == TYPEID_PLAYER)
- {
- Pet* pet = ((Player*)this)->GetPet();
- if (pet)
- {
- BattleGround *bg = ((Player *)this)->GetBattleGround();
- // don't unsummon pet in arena but SetFlag UNIT_FLAG_STUNNED to disable pet's interface
- if (bg && bg->isArena())
- pet->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
- else
- ((Player*)this)->UnsummonPetTemporaryIfAny();
- }
-
- if(VehicleId !=0)
- {
- if(VehicleEntry const *ve = sVehicleStore.LookupEntry(VehicleId))
- {
-
- if (CreateVehicleKit(VehicleId))
- {
- GetVehicleKit()->Reset();
-
- // Send others that we now have a vehicle
- WorldPacket data( SMSG_PLAYER_VEHICLE_DATA, GetPackGUID().size()+4);
- data.appendPackGUID(GetGUID());
- data << uint32(VehicleId);
- SendMessageToSet( &data,true );
-
- data.Initialize(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
- ((Player*)this)->GetSession()->SendPacket( &data );
- }
- }
- }
- }
-
-}
-
-void Unit::Unmount()
-{
- if (!IsMounted())
- return;
-
- RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED);
-
- SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
- RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
-
- // only resummon old pet if the player is already added to a map
- // this prevents adding a pet to a not created map which would otherwise cause a crash
- // (it could probably happen when logging in after a previous crash)
- if (GetTypeId() == TYPEID_PLAYER)
- {
- if (Pet *pPet = ((Player*)this)->GetPet())
- {
- if (pPet && pPet->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED) && !pPet->hasUnitState(UNIT_STAT_STUNNED))
- pPet->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
- }
- else
- ((Player*)this)->ResummonPetTemporaryUnSummonedIfAny();
- }
- if(GetTypeId()==TYPEID_PLAYER && GetVehicleKit())
- {
- // Send other players that we are no longer a vehicle
- WorldPacket data( SMSG_PLAYER_VEHICLE_DATA, 8+4 );
- data.appendPackGUID(GetGUID());
- data << uint32(0);
- ((Player*)this)->SendMessageToSet(&data, true);
- // Remove vehicle class from player
- RemoveVehicleKit();
- }
-}
-
-void Unit::SetInCombatWith(Unit* enemy)
-{
- Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf();
- if (eOwner->IsPvP())
- {
- SetInCombatState(true,enemy);
- return;
- }
-
- //check for duel
- if (eOwner->GetTypeId() == TYPEID_PLAYER && ((Player*)eOwner)->duel)
- {
- Unit const* myOwner = GetCharmerOrOwnerOrSelf();
- if (((Player const*)eOwner)->duel->opponent == myOwner)
- {
- SetInCombatState(true,enemy);
- return;
- }
- }
- SetInCombatState(false,enemy);
-}
-
-void Unit::CombatStart(Unit* target, bool initialAggro)
-{
- if (initialAggro)
- {
- if (!target->IsStandState()/* && !target->hasUnitState(UNIT_STAT_STUNNED)*/)
- target->SetStandState(UNIT_STAND_STATE_STAND);
-
- if (!target->isInCombat() && target->GetTypeId() != TYPEID_PLAYER
- && !((Creature*)target)->HasReactState(REACT_PASSIVE) && ((Creature*)target)->IsAIEnabled)
- {
- ((Creature*)target)->AI()->AttackStart(this);
- }
-
- SetInCombatWith(target);
- target->SetInCombatWith(this);
- }
- Unit *who = target->GetCharmerOrOwnerOrSelf();
- if (who->GetTypeId() == TYPEID_PLAYER)
- SetContestedPvP((Player*)who);
-
- Player *me = GetCharmerOrOwnerPlayerOrPlayerItself();
- if (me && who->IsPvP()
- && (who->GetTypeId() != TYPEID_PLAYER
- || !me->duel || me->duel->opponent != who))
- {
- me->UpdatePvP(true);
- me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
- }
-}
-
-void Unit::SetInCombatState(bool PvP, Unit* enemy)
-{
- // only alive units can be in combat
- if (!isAlive())
- return;
-
- if (PvP)
- m_CombatTimer = 5000;
-
- if (isInCombat() || hasUnitState(UNIT_STAT_EVADE))
- return;
-
- SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
-
- if (GetTypeId() != TYPEID_PLAYER)
- {
- // Set home position at place of engaging combat for escorted creatures
- if (( IsAIEnabled && ((Creature*)this)->AI()->IsEscorted() ) ||
- GetMotionMaster()->GetCurrentMovementGeneratorType() == WAYPOINT_MOTION_TYPE ||
- GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE)
- ((Creature*)this)->SetHomePosition(GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
-
- if (enemy)
- {
- if (IsAIEnabled)
- ((Creature*)this)->AI()->EnterCombat(enemy);
- if (((Creature*)this)->GetFormation())
- ((Creature*)this)->GetFormation()->MemberAttackStart((Creature*)this, enemy);
- }
-
- if (isPet())
- {
- UpdateSpeed(MOVE_RUN, true);
- UpdateSpeed(MOVE_SWIM, true);
- UpdateSpeed(MOVE_FLIGHT, true);
- }
- }
-
- for (Unit::ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
- {
- (*itr)->SetInCombatState(PvP, enemy);
- (*itr)->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
- }
-}
-
-void Unit::ClearInCombat()
-{
- m_CombatTimer = 0;
- RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
-
- // Player's state will be cleared in Player::UpdateContestedPvP
- if (GetTypeId() != TYPEID_PLAYER)
- {
- clearUnitState(UNIT_STAT_ATTACK_PLAYER);
- if (HasFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TAPPED))
- SetUInt32Value(UNIT_DYNAMIC_FLAGS, ((Creature*)this)->GetCreatureInfo()->dynamicflags);
- }
- else
- ((Player*)this)->UpdatePotionCooldown();
-
- if (GetTypeId() != TYPEID_PLAYER && ((Creature*)this)->isPet())
- {
- if (Unit *owner = GetOwner())
- for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i)
- if (owner->GetSpeedRate(UnitMoveType(i)) > GetSpeedRate(UnitMoveType(i)))
- SetSpeed(UnitMoveType(i), owner->GetSpeedRate(UnitMoveType(i)), true);
- }
- else if (!isCharmed())
- return;
-
- RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
-}
-
-//TODO: remove this function
-bool Unit::isTargetableForAttack() const
-{
- return isAttackableByAOE() && !hasUnitState(UNIT_STAT_DIED);
-}
-
-bool Unit::canAttack(Unit const* target, bool force) const
-{
- assert(target);
-
- if (force)
- {
- if (IsFriendlyTo(target))
- return false;
- }
- else if (!IsHostileTo(target))
- return false;
-
- //if(m_Vehicle && m_Vehicle == target->m_Vehicle)
- // return true;
-
- if (!target->isAttackableByAOE() || target->hasUnitState(UNIT_STAT_DIED))
- return false;
-
- // shaman totem quests: spell 8898, shaman can detect elementals but elementals cannot see shaman
- if (m_invisibilityMask || target->m_invisibilityMask)
- if (!canDetectInvisibilityOf(target) && !target->canDetectInvisibilityOf(this))
- return false;
-
- if (target->GetVisibility() == VISIBILITY_GROUP_STEALTH && !canDetectStealthOf(target, GetDistance(target)))
- return false;
-
- if (m_vehicle)
- if (IsOnVehicle(target) || m_vehicle->GetBase()->IsOnVehicle(target))
- return false;
-
- return true;
-}
-
-bool Unit::isAttackableByAOE() const
-{
- if (!isAlive())
- return false;
-
- if (HasFlag(UNIT_FIELD_FLAGS,
- UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_OOC_NOT_ATTACKABLE))
- return false;
-
- if (GetTypeId() == TYPEID_PLAYER && ((Player *)this)->isGameMaster())
- return false;
-
- return !hasUnitState(UNIT_STAT_UNATTACKABLE);
-}
-
-int32 Unit::ModifyHealth(int32 dVal)
-{
- int32 gain = 0;
-
- if (dVal==0)
- return 0;
-
- int32 curHealth = (int32)GetHealth();
-
- int32 val = dVal + curHealth;
- if (val <= 0)
- {
- SetHealth(0);
- return -curHealth;
- }
-
- int32 maxHealth = (int32)GetMaxHealth();
-
- if (val < maxHealth)
- {
- SetHealth(val);
- gain = val - curHealth;
- }
- else if (curHealth != maxHealth)
- {
- SetHealth(maxHealth);
- gain = maxHealth - curHealth;
- }
-
- return gain;
-}
-
-int32 Unit::GetHealthGain(int32 dVal)
-{
- int32 gain = 0;
-
- if (dVal==0)
- return 0;
-
- int32 curHealth = (int32)GetHealth();
-
- int32 val = dVal + curHealth;
- if (val <= 0)
- {
- return -curHealth;
- }
-
- int32 maxHealth = (int32)GetMaxHealth();
-
- if (val < maxHealth)
- gain = dVal;
- else if (curHealth != maxHealth)
- gain = maxHealth - curHealth;
-
- return gain;
-}
-
-int32 Unit::ModifyPower(Powers power, int32 dVal)
-{
- int32 gain = 0;
-
- if (dVal==0)
- return 0;
-
- int32 curPower = (int32)GetPower(power);
-
- int32 val = dVal + curPower;
- if (val <= 0)
- {
- SetPower(power,0);
- return -curPower;
- }
-
- int32 maxPower = (int32)GetMaxPower(power);
-
- if (val < maxPower)
- {
- SetPower(power,val);
- gain = val - curPower;
- }
- else if (curPower != maxPower)
- {
- SetPower(power,maxPower);
- gain = maxPower - curPower;
- }
-
- return gain;
-}
-
-bool Unit::isVisibleForOrDetect(Unit const* u, bool detect, bool inVisibleList, bool is3dDistance) const
-{
- if (!u || !IsInMap(u))
- return false;
-
- return u->canSeeOrDetect(this, detect, inVisibleList, is3dDistance);
-}
-
-bool Unit::canSeeOrDetect(Unit const* u, bool detect, bool inVisibleList, bool is3dDistance) const
-{
- return true;
-}
-
-bool Unit::canDetectInvisibilityOf(Unit const* u) const
-{
- if (m_invisibilityMask & u->m_invisibilityMask) // same group
- return true;
- AuraEffectList const& auras = u->GetAuraEffectsByType(SPELL_AURA_MOD_STALKED); // Hunter mark
- for (AuraEffectList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
- if ((*iter)->GetCasterGUID()==GetGUID())
- return true;
-
- if (uint32 mask = (m_detectInvisibilityMask & u->m_invisibilityMask))
- {
- for (uint32 i = 0; i < 10; ++i)
- {
- if (((1 << i) & mask)==0)
- continue;
-
- // find invisibility level
- uint32 invLevel = 0;
- Unit::AuraEffectList const& iAuras = u->GetAuraEffectsByType(SPELL_AURA_MOD_INVISIBILITY);
- for (Unit::AuraEffectList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr)
- if (((*itr)->GetMiscValue())==i && invLevel < (*itr)->GetAmount())
- invLevel = (*itr)->GetAmount();
-
- // find invisibility detect level
- uint32 detectLevel = 0;
- if (i==6 && GetTypeId() == TYPEID_PLAYER) // special drunk detection case
- {
- detectLevel = ((Player*)this)->GetDrunkValue();
- }
- else
- {
- Unit::AuraEffectList const& dAuras = GetAuraEffectsByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION);
- for (Unit::AuraEffectList::const_iterator itr = dAuras.begin(); itr != dAuras.end(); ++itr)
- if (((*itr)->GetMiscValue())==i && detectLevel < (*itr)->GetAmount())
- detectLevel = (*itr)->GetAmount();
- }
-
- if (invLevel <= detectLevel)
- return true;
- }
- }
-
- return false;
-}
-
-bool Unit::canDetectStealthOf(Unit const* target, float distance) const
-{
- if (hasUnitState(UNIT_STAT_STUNNED))
- return false;
- if (distance < 0.24f) //collision
- return true;
- if (!HasInArc(M_PI, target)) //behind
- return false;
- if (HasAuraType(SPELL_AURA_DETECT_STEALTH))
- return true;
-
- AuraEffectList const &auras = target->GetAuraEffectsByType(SPELL_AURA_MOD_STALKED); // Hunter mark
- for (AuraEffectList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
- if ((*iter)->GetCasterGUID() == GetGUID())
- return true;
-
- //Visible distance based on stealth value (stealth rank 4 300MOD, 10.5 - 3 = 7.5)
- float visibleDistance = 7.5f;
- //Visible distance is modified by -Level Diff (every level diff = 1.0f in visible distance)
- visibleDistance += float(getLevelForTarget(target)) - target->GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH)/5.0f;
- //-Stealth Mod(positive like Master of Deception) and Stealth Detection(negative like paranoia)
- //based on wowwiki every 5 mod we have 1 more level diff in calculation
- visibleDistance += (float)(GetTotalAuraModifier(SPELL_AURA_MOD_DETECT) - target->GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_LEVEL)) / 5.0f;
- visibleDistance = visibleDistance > MAX_PLAYER_STEALTH_DETECT_RANGE ? MAX_PLAYER_STEALTH_DETECT_RANGE : visibleDistance;
-
- return distance < visibleDistance;
-}
-
-void Unit::SetVisibility(UnitVisibility x)
-{
- m_Visibility = x;
-
- if(IsInWorld())
- {
- Map *m = GetMap();
- CellPair p(Trinity::ComputeCellPair(GetPositionX(), GetPositionY()));
- Cell cell(p);
-
- if(GetTypeId() == TYPEID_PLAYER)
- {
- m->UpdatePlayerVisibility((Player*)this, cell, p);
- m->UpdateObjectsVisibilityFor((Player*)this, cell, p);
- }
- else
- m->UpdateObjectVisibility(this, cell, p);
-
- AddToNotify(NOTIFY_AI_RELOCATION);
- }
-
- if (x == VISIBILITY_GROUP_STEALTH)
- DestroyForNearbyPlayers();
-}
-
-void Unit::UpdateSpeed(UnitMoveType mtype, bool forced)
-{
- int32 main_speed_mod = 0;
- float stack_bonus = 1.0f;
- float non_stack_bonus = 1.0f;
-
- switch(mtype)
- {
- // Only apply debuffs
- case MOVE_FLIGHT_BACK:
- case MOVE_RUN_BACK:
- case MOVE_SWIM_BACK:
- break;
- case MOVE_WALK:
- return;
- case MOVE_RUN:
- {
- if (IsMounted()) // Use on mount auras
- {
- main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED);
- stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS);
- non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK))/100.0f;
- }
- else
- {
- main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED);
- stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS);
- non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK))/100.0f;
- }
- break;
- }
- case MOVE_SWIM:
- {
- main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SWIM_SPEED);
- break;
- }
- case MOVE_FLIGHT:
- {
- if (GetTypeId() == TYPEID_UNIT && IsControlledByPlayer()) // not sure if good for pet
- {
- main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED);
- stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_VEHICLE_SPEED_ALWAYS);
-
- // for some spells this mod is applied on vehicle owner
- uint32 owner_speed_mod = 0;
-
- if (Unit * owner = GetCharmer())
- uint32 owner_speed_mod = owner->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED);
-
- main_speed_mod = main_speed_mod>owner_speed_mod ? main_speed_mod : owner_speed_mod;
- }
- else if (IsMounted())
- {
- main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED);
- stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_FLIGHT_SPEED_ALWAYS);
- }
- else // Use not mount (shapeshift for example) auras (should stack)
- main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) + GetTotalAuraModifier(SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED);
-
- non_stack_bonus = (100.0 + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK))/100.0f;
-
- // Update speed for vehicle if available
- if (GetTypeId() == TYPEID_PLAYER && GetVehicle())
- GetVehicleBase()->UpdateSpeed(MOVE_FLIGHT, true);
- break;
- }
- default:
- sLog.outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype);
- return;
- }
-
- float bonus = non_stack_bonus > stack_bonus ? non_stack_bonus : stack_bonus;
-
- // now we ready for speed calculation
- float speed = main_speed_mod ? bonus*(100.0f + main_speed_mod)/100.0f : bonus;
-
- switch(mtype)
- {
- case MOVE_RUN:
- case MOVE_SWIM:
- case MOVE_FLIGHT:
- {
- // Set creature speed rate from CreatureInfo
- if (GetTypeId() == TYPEID_UNIT)
- speed *= ((Creature*)this)->GetCreatureInfo()->speed;
-
- // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need
- // TODO: possible affect only on MOVE_RUN
- if (int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED))
- {
- // Use speed from aura
- float max_speed = normalization / (IsControlledByPlayer() ? playerBaseMoveSpeed[mtype] : baseMoveSpeed[mtype]);
- if (speed > max_speed)
- speed = max_speed;
- }
- break;
- }
- default:
- break;
- }
-
- // for creature case, we check explicit if mob searched for assistance
- if (GetTypeId() == TYPEID_UNIT)
- {
- if (((Creature*)this)->HasSearchedAssistance())
- speed *= 0.66f; // best guessed value, so this will be 33% reduction. Based off initial speed, mob can then "run", "walk fast" or "walk".
- }
-
- // Apply strongest slow aura mod to speed
- int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED);
- if (slow)
- {
- speed *=(100.0f + slow)/100.0f;
- float min_speed = (float)GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MINIMUM_SPEED) / 100.0f;
- if (speed < min_speed)
- speed = min_speed;
- }
- SetSpeed(mtype, speed, forced);
-}
-
-float Unit::GetSpeed( UnitMoveType mtype ) const
-{
- return m_speed_rate[mtype]*(IsControlledByPlayer() ? playerBaseMoveSpeed[mtype] : baseMoveSpeed[mtype]);
-}
-
-void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced)
-{
- if (rate < 0)
- rate = 0.0f;
-
- // Update speed only on change
- if (m_speed_rate[mtype] == rate)
- return;
-
- m_speed_rate[mtype] = rate;
-
- propagateSpeedChange();
-
- WorldPacket data;
- if (!forced)
- {
- switch(mtype)
- {
- case MOVE_WALK:
- data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8+4+2+4+4+4+4+4+4+4);
- break;
- case MOVE_RUN:
- data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8+4+2+4+4+4+4+4+4+4);
- break;
- case MOVE_RUN_BACK:
- data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
- break;
- case MOVE_SWIM:
- data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8+4+2+4+4+4+4+4+4+4);
- break;
- case MOVE_SWIM_BACK:
- data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
- break;
- case MOVE_TURN_RATE:
- data.Initialize(MSG_MOVE_SET_TURN_RATE, 8+4+2+4+4+4+4+4+4+4);
- break;
- case MOVE_FLIGHT:
- data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8+4+2+4+4+4+4+4+4+4);
- break;
- case MOVE_FLIGHT_BACK:
- data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
- break;
- case MOVE_PITCH_RATE:
- data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8+4+2+4+4+4+4+4+4+4);
- break;
- default:
- sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
- return;
- }
-
- data.append(GetPackGUID());
- data << uint32(0); // movement flags
- data << uint16(0); // unk flags
- data << uint32(getMSTime());
- data << float(GetPositionX());
- data << float(GetPositionY());
- data << float(GetPositionZ());
- data << float(GetOrientation());
- data << uint32(0); // fall time
- data << float(GetSpeed(mtype));
- SendMessageToSet( &data, true );
- }
- else
- {
- if (GetTypeId() == TYPEID_PLAYER)
- {
- // register forced speed changes for WorldSession::HandleForceSpeedChangeAck
- // and do it only for real sent packets and use run for run/mounted as client expected
- ++((Player*)this)->m_forced_speed_changes[mtype];
-
- if (!isInCombat())
- if (Pet* pet = ((Player*)this)->GetPet())
- pet->SetSpeed(mtype, m_speed_rate[mtype], forced);
- }
-
- switch(mtype)
- {
- case MOVE_WALK:
- data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE, 16);
- break;
- case MOVE_RUN:
- data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE, 17);
- break;
- case MOVE_RUN_BACK:
- data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE, 16);
- break;
- case MOVE_SWIM:
- data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE, 16);
- break;
- case MOVE_SWIM_BACK:
- data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, 16);
- break;
- case MOVE_TURN_RATE:
- data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE, 16);
- break;
- case MOVE_FLIGHT:
- data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE, 16);
- break;
- case MOVE_FLIGHT_BACK:
- data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, 16);
- break;
- case MOVE_PITCH_RATE:
- data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE, 16);
- break;
- default:
- sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
- return;
- }
- data.append(GetPackGUID());
- data << (uint32)0; // moveEvent, NUM_PMOVE_EVTS = 0x39
- if (mtype == MOVE_RUN)
- data << uint8(0); // new 2.1.0
- data << float(GetSpeed(mtype));
- SendMessageToSet( &data, true );
- }
-}
-
-void Unit::SetHover(bool on)
-{
- if (on)
- CastSpell(this, 11010, true);
- else
- RemoveAurasDueToSpell(11010);
-}
-
-void Unit::setDeathState(DeathState s)
-{
- if (s != ALIVE && s != JUST_ALIVED)
- {
- CombatStop();
- DeleteThreatList();
- getHostilRefManager().deleteReferences();
- ClearComboPointHolders(); // any combo points pointed to unit lost at it death
-
- if (IsNonMeleeSpellCasted(false))
- InterruptNonMeleeSpells(false);
-
- UnsummonAllTotems();
- RemoveAllControlled();
- RemoveAllAurasOnDeath();
- ExitVehicle();
- }
-
- if (s == JUST_DIED)
- {
- ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false);
- ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, false);
- // remove aurastates allowing special moves
- ClearAllReactives();
- ClearDiminishings();
- GetMotionMaster()->Clear(false);
- GetMotionMaster()->MoveIdle();
- if (m_vehicleKit)
- m_vehicleKit->Die();
- StopMoving();
- //without this when removing IncreaseMaxHealth aura player may stuck with 1 hp
- //do not why since in IncreaseMaxHealth currenthealth is checked
- SetHealth(0);
- }
- else if (s == JUST_ALIVED)
- RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground)
-
- if (m_deathState != ALIVE && s == ALIVE)
- {
- //_ApplyAllAuraMods();
- // Reset display id on resurection - needed by corpse explosion to cleanup after display change
- SetDisplayId(GetNativeDisplayId());
- }
- m_deathState = s;
-}
-
-/*########################################
-######## ########
-######## AGGRO SYSTEM ########
-######## ########
-########################################*/
-bool Unit::CanHaveThreatList() const
-{
- // only creatures can have threat list
- if (GetTypeId() != TYPEID_UNIT)
- return false;
-
- // only alive units can have threat list
- if (!isAlive())
- return false;
-
- // totems can not have threat list
- if (((Creature*)this)->isTotem())
- return false;
-
- // vehicles can not have threat list
- //if (((Creature*)this)->IsVehicle())
- // return false;
-
- // summons can not have a threat list, unless they are controlled by a creature
- if (HasUnitTypeMask(UNIT_MASK_MINION | UNIT_MASK_GUARDIAN | UNIT_MASK_CONTROLABLE_GUARDIAN) && IS_PLAYER_GUID(((Pet*)this)->GetOwnerGUID()))
- return false;
-
- return true;
-}
-
-//======================================================================
-
-float Unit::ApplyTotalThreatModifier(float fThreat, SpellSchoolMask schoolMask)
-{
- if (!HasAuraType(SPELL_AURA_MOD_THREAT) || fThreat < 0)
- return fThreat;
-
- SpellSchools school = GetFirstSchoolInMask(schoolMask);
-
- return fThreat * m_threatModifier[school];
-}
-
-//======================================================================
-
-void Unit::AddThreat(Unit* pVictim, float fThreat, SpellSchoolMask schoolMask, SpellEntry const *threatSpell)
-{
- // Only mobs can manage threat lists
- if (CanHaveThreatList())
- m_ThreatManager.addThreat(pVictim, fThreat, schoolMask, threatSpell);
-}
-
-//======================================================================
-
-void Unit::DeleteThreatList()
-{
- if (CanHaveThreatList() && !m_ThreatManager.isThreatListEmpty())
- SendClearThreatListOpcode();
- m_ThreatManager.clearReferences();
-}
-
-//======================================================================
-
-void Unit::TauntApply(Unit* taunter)
-{
- assert(GetTypeId() == TYPEID_UNIT);
-
- if (!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
- return;
-
- if (!CanHaveThreatList())
- return;
-
- if (((Creature*)this)->HasReactState(REACT_PASSIVE))
- return;
-
- Unit *target = getVictim();
- if (target && target == taunter)
- return;
-
- SetInFront(taunter);
- if (((Creature*)this)->IsAIEnabled)
- ((Creature*)this)->AI()->AttackStart(taunter);
-
- //m_ThreatManager.tauntApply(taunter);
-}
-
-//======================================================================
-
-void Unit::TauntFadeOut(Unit *taunter)
-{
- assert(GetTypeId() == TYPEID_UNIT);
-
- if (!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
- return;
-
- if (!CanHaveThreatList())
- return;
-
- if (((Creature*)this)->HasReactState(REACT_PASSIVE))
- return;
-
- Unit *target = getVictim();
- if (!target || target != taunter)
- return;
-
- if (m_ThreatManager.isThreatListEmpty())
- {
- if (((Creature*)this)->IsAIEnabled)
- ((Creature*)this)->AI()->EnterEvadeMode();
- return;
- }
-
- //m_ThreatManager.tauntFadeOut(taunter);
- target = m_ThreatManager.getHostilTarget();
-
- if (target && target != taunter)
- {
- SetInFront(target);
- if (((Creature*)this)->IsAIEnabled)
- ((Creature*)this)->AI()->AttackStart(target);
- }
-}
-
-//======================================================================
-
-Unit* Creature::SelectVictim()
-{
- //function provides main threat functionality
- //next-victim-selection algorithm and evade mode are called
- //threat list sorting etc.
-
- Unit* target = NULL;
- // First checking if we have some taunt on us
- const AuraEffectList& tauntAuras = GetAuraEffectsByType(SPELL_AURA_MOD_TAUNT);
- if (!tauntAuras.empty())
- {
- Unit* caster;
-
- // The last taunt aura caster is alive an we are happy to attack him
- if ((caster = tauntAuras.back()->GetCaster()) && caster->isAlive())
- return getVictim();
- else if (tauntAuras.size() > 1)
- {
- // We do not have last taunt aura caster but we have more taunt auras,
- // so find first available target
-
- // Auras are pushed_back, last caster will be on the end
- AuraEffectList::const_iterator aura = --tauntAuras.end();
- do
- {
- --aura;
- if ((caster = (*aura)->GetCaster()) &&
- caster->IsInMap(this) && canAttack(caster) && caster->isInAccessiblePlaceFor((Creature*)this))
- {
- target = caster;
- break;
- }
- } while (aura != tauntAuras.begin());
- }
- else
- target = getVictim();
- }
-
- if (CanHaveThreatList())
- {
- if (!target && !m_ThreatManager.isThreatListEmpty())
- // No taunt aura or taunt aura caster is dead standard target selection
- target = m_ThreatManager.getHostilTarget();
- }
- else if (!HasReactState(REACT_PASSIVE))
- {
- // We have player pet probably
- target = getAttackerForHelper();
- if (!target && isSummon())
- {
- if (Unit * owner = ((TempSummon*)this)->GetOwner())
- {
- if (owner->isInCombat())
- target = owner->getAttackerForHelper();
- if (!target)
- {
- for (ControlList::const_iterator itr = owner->m_Controlled.begin(); itr != owner->m_Controlled.end(); ++itr)
- {
- if ((*itr)->isInCombat())
- {
- target = (*itr)->getAttackerForHelper();
- if (target) break;
- }
- }
- }
- }
- }
- }
- else
- return NULL;
-
- if (target && _IsTargetAcceptable(target))
- {
- SetInFront(target);
- return target;
- }
-
- // last case when creature don't must go to evade mode:
- // it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list
- // for example at owner command to pet attack some far away creature
- // Note: creature not have targeted movement generator but have attacker in this case
- for (AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr)
- {
- if ((*itr) && !canCreatureAttack(*itr) && (*itr)->GetTypeId() != TYPEID_PLAYER
- && !((Creature*)(*itr))->HasUnitTypeMask(UNIT_MASK_CONTROLABLE_GUARDIAN))
- return NULL;
- }
-
- // TODO: a vehicle may eat some mob, so mob should not evade
- if (GetVehicle())
- return NULL;
-
- // search nearby enemy before enter evade mode
- if (HasReactState(REACT_AGGRESSIVE))
- if (target = SelectNearestTarget())
- if (_IsTargetAcceptable(target))
- return target;
-
- if (m_invisibilityMask)
- {
- Unit::AuraEffectList const& iAuras = GetAuraEffectsByType(SPELL_AURA_MOD_INVISIBILITY);
- for (Unit::AuraEffectList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr)
- if ((*itr)->GetBase()->IsPermanent())
- {
- AI()->EnterEvadeMode();
- break;
- }
- return NULL;
- }
-
- // enter in evade mode in other case
- AI()->EnterEvadeMode();
-
- return NULL;
-}
-
-//======================================================================
-//======================================================================
-//======================================================================
-
-int32 Unit::CalculateSpellDamage(SpellEntry const* spellProto, uint8 effect_index, int32 effBasePoints, Unit const* /*target*/)
-{
- int32 level = int32(getLevel());
- if (level > int32(spellProto->maxLevel) && spellProto->maxLevel > 0)
- level = int32(spellProto->maxLevel);
- else if (level < int32(spellProto->baseLevel))
- level = int32(spellProto->baseLevel);
- level -= int32(spellProto->spellLevel);
-
- float basePointsPerLevel = spellProto->EffectRealPointsPerLevel[effect_index];
- float randomPointsPerLevel = spellProto->EffectDicePerLevel[effect_index];
- int32 basePoints = int32(effBasePoints + level * basePointsPerLevel);
- int32 randomPoints = int32(spellProto->EffectDieSides[effect_index] + level * randomPointsPerLevel);
-
- // range can have possitive and negative values, so order its for irand
- int32 randvalue = int32(spellProto->EffectBaseDice[effect_index]) >= randomPoints
- ? irand(randomPoints, int32(spellProto->EffectBaseDice[effect_index]))
- : irand(int32(spellProto->EffectBaseDice[effect_index]), randomPoints);
-
- int32 value = basePoints + randvalue;
- //random damage
- //if (comboDamage != 0 && unitPlayer /*&& target && (target->GetGUID() == unitPlayer->GetComboTarget())*/)
- if (m_movedPlayer)
- if (uint8 comboPoints = m_movedPlayer->GetComboPoints())
- if (float comboDamage = spellProto->EffectPointsPerComboPoint[effect_index])
- value += int32(comboDamage * comboPoints);
-
- if (Player* modOwner = GetSpellModOwner())
- {
- modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_ALL_EFFECTS, value);
- switch (effect_index)
- {
- case 0:
- modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT1, value);
- break;
- case 1:
- modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT2, value);
- break;
- case 2:
- modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT3, value);
- break;
- }
- }
-
- if (!basePointsPerLevel && (spellProto->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION && spellProto->spellLevel) &&
- spellProto->Effect[effect_index] != SPELL_EFFECT_WEAPON_PERCENT_DAMAGE &&
- spellProto->Effect[effect_index] != SPELL_EFFECT_KNOCK_BACK &&
- spellProto->EffectApplyAuraName[effect_index] != SPELL_AURA_MOD_SPEED_ALWAYS &&
- spellProto->EffectApplyAuraName[effect_index] != SPELL_AURA_MOD_SPEED_NOT_STACK &&
- spellProto->EffectApplyAuraName[effect_index] != SPELL_AURA_MOD_INCREASE_SPEED &&
- spellProto->EffectApplyAuraName[effect_index] != SPELL_AURA_MOD_DECREASE_SPEED)
- //there are many more: slow speed, -healing pct
- value = int32(value*0.25f*exp(getLevel()*(70-spellProto->spellLevel)/1000.0f));
- //value = int32(value * (int32)getLevel() / (int32)(spellProto->spellLevel ? spellProto->spellLevel : 1));
-
- return value;
-}
-
-int32 Unit::CalcSpellDuration(SpellEntry const* spellProto)
-{
- uint8 comboPoints = m_movedPlayer ? m_movedPlayer->GetComboPoints() : 0;
-
- int32 minduration = GetSpellDuration(spellProto);
- int32 maxduration = GetSpellMaxDuration(spellProto);
-
- int32 duration;
-
- if (comboPoints && minduration != -1 && minduration != maxduration)
- duration = minduration + int32((maxduration - minduration) * comboPoints / 5);
- else
- duration = minduration;
-
- return duration;
-}
-
-int32 Unit::ModSpellDuration(SpellEntry const* spellProto, Unit const* target, int32 duration, bool positive)
-{
- //don't mod permament auras duration
- if (duration < 0)
- return duration;
-
- //cut duration only of negative effects
- if (!positive)
- {
- int32 mechanic = GetAllSpellMechanicMask(spellProto);
-
- int32 durationMod;
- int32 durationMod_always = 0;
- int32 durationMod_not_stack = 0;
-
- for (uint8 i = 1; i <= MECHANIC_ENRAGED; ++i)
- {
- if (!(mechanic & 1<<i))
- continue;
- // Find total mod value (negative bonus)
- int32 new_durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD, i);
- // Find max mod (negative bonus)
- int32 new_durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK, i);
- // Check if mods applied before were weaker
- if (new_durationMod_always < durationMod_always)
- durationMod_always = new_durationMod_always;
- if (new_durationMod_not_stack < durationMod_not_stack)
- durationMod_not_stack = new_durationMod_not_stack;
- }
-
- // Select strongest negative mod
- if (durationMod_always > durationMod_not_stack)
- durationMod = durationMod_not_stack;
- else
- durationMod = durationMod_always;
-
- if (durationMod != 0)
- duration = int32(float(duration) * float(100.0f+durationMod) / 100.0f);
-
- // there are only negative mods currently
- durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_AURA_DURATION_BY_DISPEL, spellProto->Dispel);
- durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MOD_AURA_DURATION_BY_DISPEL_NOT_STACK, spellProto->Dispel);
-
- durationMod = 0;
- if (durationMod_always > durationMod_not_stack)
- durationMod += durationMod_not_stack;
- else
- durationMod += durationMod_always;
-
- if (durationMod != 0)
- duration = int32(float(duration) * float(100.0f+durationMod) / 100.0f);
- }
- //else positive mods here, there are no currently
- //when there will be, change GetTotalAuraModifierByMiscValue to GetTotalPositiveAuraModifierByMiscValue
-
- // Glyphs which increase duration of selfcasted buffs
- if (target == this)
- {
- switch (spellProto->SpellFamilyName)
- {
- case SPELLFAMILY_DRUID:
- if (spellProto->SpellFamilyFlags[0] & 0x100)
- {
- // Glyph of Thorns
- if (AuraEffect * aurEff = GetAuraEffect(57862, 0))
- duration += aurEff->GetAmount() * MINUTE * IN_MILISECONDS;
- }
- break;
- case SPELLFAMILY_PALADIN:
- if (spellProto->SpellFamilyFlags[0] & 0x00000002)
- {
- // Glyph of Blessing of Might
- if (AuraEffect * aurEff = GetAuraEffect(57958, 0))
- duration += aurEff->GetAmount() * MINUTE * IN_MILISECONDS;
- }
- else if (spellProto->SpellFamilyFlags[0] & 0x00010000)
- {
- // Glyph of Blessing of Wisdom
- if (AuraEffect * aurEff = GetAuraEffect(57979, 0))
- duration += aurEff->GetAmount() * MINUTE * IN_MILISECONDS;
- }
- break;
- }
- }
- return duration > 0 ? duration : 0;
-}
-
-void Unit::ModSpellCastTime(SpellEntry const* spellProto, int32 & castTime, Spell * spell)
-{
- if (!spellProto || castTime < 0)
- return;
- //called from caster
- if (Player* modOwner = GetSpellModOwner())
- modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CASTING_TIME, castTime, spell);
-
- if (!(spellProto->Attributes & (SPELL_ATTR_UNK4|SPELL_ATTR_TRADESPELL)) && spellProto->SpellFamilyName)
- castTime = int32(float(castTime) * GetFloatValue(UNIT_MOD_CAST_SPEED));
- else
- {
- if (spellProto->Attributes & SPELL_ATTR_REQ_AMMO && !(spellProto->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG))
- castTime = int32(float(castTime) * m_modAttackSpeedPct[RANGED_ATTACK]);
- }
-}
-
-DiminishingLevels Unit::GetDiminishing(DiminishingGroup group)
-{
- for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
- {
- if (i->DRGroup != group)
- continue;
-
- if (!i->hitCount)
- return DIMINISHING_LEVEL_1;
-
- if (!i->hitTime)
- return DIMINISHING_LEVEL_1;
-
- // If last spell was casted more than 15 seconds ago - reset the count.
- if (i->stack==0 && getMSTimeDiff(i->hitTime,getMSTime()) > 15000)
- {
- i->hitCount = DIMINISHING_LEVEL_1;
- return DIMINISHING_LEVEL_1;
- }
- // or else increase the count.
- else
- return DiminishingLevels(i->hitCount);
- }
- return DIMINISHING_LEVEL_1;
-}
-
-void Unit::IncrDiminishing(DiminishingGroup group)
-{
- // Checking for existing in the table
- for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
- {
- if (i->DRGroup != group)
- continue;
- if (i->hitCount < GetDiminishingReturnsMaxLevel(group))
- i->hitCount += 1;
- return;
- }
- m_Diminishing.push_back(DiminishingReturn(group,getMSTime(),DIMINISHING_LEVEL_2));
-}
-
-void Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration,Unit* caster,DiminishingLevels Level, int32 limitduration)
-{
- if (duration == -1 || group == DIMINISHING_NONE || caster->IsFriendlyTo(this))
- return;
-
- // test pet/charm masters instead pets/charmeds
- Unit const* targetOwner = GetCharmerOrOwner();
- Unit const* casterOwner = caster->GetCharmerOrOwner();
-
- // Duration of crowd control abilities on pvp target is limited by 10 sec. (2.2.0)
- if (limitduration > 0 && duration > limitduration)
- {
- Unit const* target = targetOwner ? targetOwner : this;
- Unit const* source = casterOwner ? casterOwner : caster;
-
- if ((target->GetTypeId() == TYPEID_PLAYER
- || ((Creature*)target)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_ALL_DIMINISH)
- && source->GetTypeId() == TYPEID_PLAYER)
- duration = limitduration;
- }
-
- float mod = 1.0f;
-
- if (group == DIMINISHING_TAUNT)
- {
- if(GetTypeId() == TYPEID_UNIT && (((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_TAUNT_DIMINISH))
- {
- DiminishingLevels diminish = Level;
- switch(diminish)
- {
- case DIMINISHING_LEVEL_1: break;
- case DIMINISHING_LEVEL_2: mod = 0.65f; break;
- case DIMINISHING_LEVEL_3: mod = 0.4225f; break;
- case DIMINISHING_LEVEL_4: mod = 0.274625f; break;
- case DIMINISHING_LEVEL_TAUNT_IMMUNE: mod = 0.0f; break;
- default: break;
- }
- }
- }
- // Some diminishings applies to mobs too (for example, Stun)
- else if ((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER
- && ((targetOwner ? (targetOwner->GetTypeId() == TYPEID_PLAYER) : (GetTypeId() == TYPEID_PLAYER))
- || (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_ALL_DIMINISH)))
- || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL)
- {
- DiminishingLevels diminish = Level;
- switch(diminish)
- {
- case DIMINISHING_LEVEL_1: break;
- case DIMINISHING_LEVEL_2: mod = 0.5f; break;
- case DIMINISHING_LEVEL_3: mod = 0.25f; break;
- case DIMINISHING_LEVEL_IMMUNE: mod = 0.0f; break;
- default: break;
- }
- }
-
- duration = int32(duration * mod);
-}
-
-void Unit::ApplyDiminishingAura( DiminishingGroup group, bool apply )
-{
- // Checking for existing in the table
- for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
- {
- if (i->DRGroup != group)
- continue;
-
- if (apply)
- i->stack += 1;
- else if (i->stack)
- {
- i->stack -= 1;
- // Remember time after last aura from group removed
- if (i->stack == 0)
- i->hitTime = getMSTime();
- }
- break;
- }
-}
-
-uint32 Unit::GetSpellMaxRangeForTarget(Unit* target,const SpellRangeEntry * rangeEntry)
-{
- if (!rangeEntry)
- return 0;
- if (rangeEntry->maxRangeHostile == rangeEntry->maxRangeFriend)
- return rangeEntry->maxRangeFriend;
- if (IsHostileTo(target))
- return rangeEntry->maxRangeHostile;
- return rangeEntry->maxRangeFriend;
-};
-uint32 Unit::GetSpellMinRangeForTarget(Unit* target,const SpellRangeEntry * rangeEntry)
-{
- if (!rangeEntry)
- return 0;
- if (rangeEntry->minRangeHostile == rangeEntry->minRangeFriend)
- return rangeEntry->minRangeFriend;
- if (IsHostileTo(target))
- return rangeEntry->minRangeHostile;
- return rangeEntry->minRangeFriend;
-};
-uint32 Unit::GetSpellRadiusForTarget(Unit* target,const SpellRadiusEntry * radiusEntry)
-{
- if (!radiusEntry)
- return 0;
- if (radiusEntry->radiusHostile == radiusEntry->radiusFriend)
- return radiusEntry->radiusFriend;
- if (IsHostileTo(target))
- return radiusEntry->radiusHostile;
- return radiusEntry->radiusFriend;
-};
-
-Unit* Unit::GetUnit(WorldObject& object, uint64 guid)
-{
- return ObjectAccessor::GetUnit(object,guid);
-}
-
-Player* Unit::GetPlayer(uint64 guid)
-{
- return ObjectAccessor::FindPlayer(guid);
-}
-
-Creature* Unit::GetCreature(WorldObject& object, uint64 guid)
-{
- return object.GetMap()->GetCreature(guid);
-}
-
-bool Unit::isVisibleForInState( Player const* u, bool inVisibleList ) const
-{
- return u->canSeeOrDetect(this, false, inVisibleList, false);
-}
-
-uint32 Unit::GetCreatureType() const
-{
- if (GetTypeId() == TYPEID_PLAYER)
- {
- SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
- if (ssEntry && ssEntry->creatureType > 0)
- return ssEntry->creatureType;
- else
- return CREATURE_TYPE_HUMANOID;
- }
- else
- return ((Creature*)this)->GetCreatureInfo()->type;
-}
-
-/*#######################################
-######## ########
-######## STAT SYSTEM ########
-######## ########
-#######################################*/
-
-bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply)
-{
- if (unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
- {
- sLog.outError("ERROR in HandleStatModifier(): non existed UnitMods or wrong UnitModifierType!");
- return false;
- }
-
- float val = 1.0f;
-
- switch (modifierType)
- {
- case BASE_VALUE:
- case TOTAL_VALUE:
- m_auraModifiersGroup[unitMod][modifierType] += apply ? amount : -amount;
- break;
- case BASE_PCT:
- case TOTAL_PCT:
- if (amount <= -100.0f) //small hack-fix for -100% modifiers
- amount = -200.0f;
-
- val = (100.0f + amount) / 100.0f;
- m_auraModifiersGroup[unitMod][modifierType] *= apply ? val : (1.0f/val);
- break;
-
- default:
- break;
- }
-
- if (!CanModifyStats())
- return false;
-
- switch(unitMod)
- {
- case UNIT_MOD_STAT_STRENGTH:
- case UNIT_MOD_STAT_AGILITY:
- case UNIT_MOD_STAT_STAMINA:
- case UNIT_MOD_STAT_INTELLECT:
- case UNIT_MOD_STAT_SPIRIT: UpdateStats(GetStatByAuraGroup(unitMod)); break;
-
- case UNIT_MOD_ARMOR: UpdateArmor(); break;
- case UNIT_MOD_HEALTH: UpdateMaxHealth(); break;
-
- case UNIT_MOD_MANA:
- case UNIT_MOD_RAGE:
- case UNIT_MOD_FOCUS:
- case UNIT_MOD_ENERGY:
- case UNIT_MOD_HAPPINESS:
- case UNIT_MOD_RUNE:
- case UNIT_MOD_RUNIC_POWER: UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); break;
-
- case UNIT_MOD_RESISTANCE_HOLY:
- case UNIT_MOD_RESISTANCE_FIRE:
- case UNIT_MOD_RESISTANCE_NATURE:
- case UNIT_MOD_RESISTANCE_FROST:
- case UNIT_MOD_RESISTANCE_SHADOW:
- case UNIT_MOD_RESISTANCE_ARCANE: UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); break;
-
- case UNIT_MOD_ATTACK_POWER: UpdateAttackPowerAndDamage(); break;
- case UNIT_MOD_ATTACK_POWER_RANGED: UpdateAttackPowerAndDamage(true); break;
-
- case UNIT_MOD_DAMAGE_MAINHAND: UpdateDamagePhysical(BASE_ATTACK); break;
- case UNIT_MOD_DAMAGE_OFFHAND: UpdateDamagePhysical(OFF_ATTACK); break;
- case UNIT_MOD_DAMAGE_RANGED: UpdateDamagePhysical(RANGED_ATTACK); break;
-
- default:
- break;
- }
-
- return true;
-}
-
-float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const
-{
- if (unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
- {
- sLog.outError("trial to access non existed modifier value from UnitMods!");
- return 0.0f;
- }
-
- if (modifierType == TOTAL_PCT && m_auraModifiersGroup[unitMod][modifierType] <= 0.0f)
- return 0.0f;
-
- return m_auraModifiersGroup[unitMod][modifierType];
-}
-
-float Unit::GetTotalStatValue(Stats stat) const
-{
- UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat);
-
- if (m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
- return 0.0f;
-
- // value = ((base_value * base_pct) + total_value) * total_pct
- float value = m_auraModifiersGroup[unitMod][BASE_VALUE] + GetCreateStat(stat);
- value *= m_auraModifiersGroup[unitMod][BASE_PCT];
- value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
- value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
-
- return value;
-}
-
-float Unit::GetTotalAuraModValue(UnitMods unitMod) const
-{
- if (unitMod >= UNIT_MOD_END)
- {
- sLog.outError("trial to access non existed UnitMods in GetTotalAuraModValue()!");
- return 0.0f;
- }
-
- if (m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
- return 0.0f;
-
- float value = m_auraModifiersGroup[unitMod][BASE_VALUE];
- value *= m_auraModifiersGroup[unitMod][BASE_PCT];
- value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
- value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
-
- return value;
-}
-
-SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const
-{
- SpellSchools school = SPELL_SCHOOL_NORMAL;
-
- switch(unitMod)
- {
- case UNIT_MOD_RESISTANCE_HOLY: school = SPELL_SCHOOL_HOLY; break;
- case UNIT_MOD_RESISTANCE_FIRE: school = SPELL_SCHOOL_FIRE; break;
- case UNIT_MOD_RESISTANCE_NATURE: school = SPELL_SCHOOL_NATURE; break;
- case UNIT_MOD_RESISTANCE_FROST: school = SPELL_SCHOOL_FROST; break;
- case UNIT_MOD_RESISTANCE_SHADOW: school = SPELL_SCHOOL_SHADOW; break;
- case UNIT_MOD_RESISTANCE_ARCANE: school = SPELL_SCHOOL_ARCANE; break;
-
- default:
- break;
- }
-
- return school;
-}
-
-Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const
-{
- Stats stat = STAT_STRENGTH;
-
- switch(unitMod)
- {
- case UNIT_MOD_STAT_STRENGTH: stat = STAT_STRENGTH; break;
- case UNIT_MOD_STAT_AGILITY: stat = STAT_AGILITY; break;
- case UNIT_MOD_STAT_STAMINA: stat = STAT_STAMINA; break;
- case UNIT_MOD_STAT_INTELLECT: stat = STAT_INTELLECT; break;
- case UNIT_MOD_STAT_SPIRIT: stat = STAT_SPIRIT; break;
-
- default:
- break;
- }
-
- return stat;
-}
-
-Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const
-{
- switch (unitMod)
- {
- case UNIT_MOD_RAGE: return POWER_RAGE;
- case UNIT_MOD_FOCUS: return POWER_FOCUS;
- case UNIT_MOD_ENERGY: return POWER_ENERGY;
- case UNIT_MOD_HAPPINESS: return POWER_HAPPINESS;
- case UNIT_MOD_RUNE: return POWER_RUNE;
- case UNIT_MOD_RUNIC_POWER: return POWER_RUNIC_POWER;
- default:
- case UNIT_MOD_MANA: return POWER_MANA;
- }
-}
-
-float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const
-{
- if (attType == RANGED_ATTACK)
- {
- int32 ap = GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS);
- if (ap < 0)
- return 0.0f;
- return ap * (1.0f + GetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER));
- }
- else
- {
- int32 ap = GetInt32Value(UNIT_FIELD_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS);
- if (ap < 0)
- return 0.0f;
- return ap * (1.0f + GetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER));
- }
-}
-
-float Unit::GetWeaponDamageRange(WeaponAttackType attType ,WeaponDamageRange type) const
-{
- if (attType == OFF_ATTACK && !haveOffhandWeapon())
- return 0.0f;
-
- return m_weaponDamage[attType][type];
-}
-
-void Unit::SetLevel(uint8 lvl)
-{
- SetUInt32Value(UNIT_FIELD_LEVEL, lvl);
-
- // group update
- if (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->GetGroup())
- ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL);
-}
-
-void Unit::SetHealth(uint32 val)
-{
- if (getDeathState() == JUST_DIED)
- val = 0;
- else if (GetTypeId() == TYPEID_PLAYER && (getDeathState() == DEAD || getDeathState() == DEAD_FALLING))
- val = 1;
- else
- {
- uint32 maxHealth = GetMaxHealth();
- if (maxHealth < val)
- val = maxHealth;
- }
-
- SetUInt32Value(UNIT_FIELD_HEALTH, val);
-
- // group update
- if (GetTypeId() == TYPEID_PLAYER)
- {
- if (((Player*)this)->GetGroup())
- ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP);
- }
- else if (((Creature*)this)->isPet())
- {
- Pet *pet = ((Pet*)this);
- if (pet->isControlled())
- {
- Unit *owner = GetOwner();
- if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
- ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP);
- }
- }
-}
-
-void Unit::SetMaxHealth(uint32 val)
-{
- if (!val)
- val = 1;
-
- uint32 health = GetHealth();
- SetUInt32Value(UNIT_FIELD_MAXHEALTH, val);
-
- // group update
- if (GetTypeId() == TYPEID_PLAYER)
- {
- if (((Player*)this)->GetGroup())
- ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP);
- }
- else if (((Creature*)this)->isPet())
- {
- Pet *pet = ((Pet*)this);
- if (pet->isControlled())
- {
- Unit *owner = GetOwner();
- if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
- ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP);
- }
- }
-
- if (val < health)
- SetHealth(val);
-}
-
-void Unit::SetPower(Powers power, uint32 val)
-{
- if (GetPower(power) == val)
- return;
-
- uint32 maxPower = GetMaxPower(power);
- if (maxPower < val)
- val = maxPower;
-
- SetStatInt32Value(UNIT_FIELD_POWER1 + power, val);
-
- WorldPacket data(SMSG_POWER_UPDATE);
- data.append(GetPackGUID());
- data << uint8(power);
- data << uint32(val);
- SendMessageToSet(&data, GetTypeId() == TYPEID_PLAYER ? true : false);
-
- // group update
- if (GetTypeId() == TYPEID_PLAYER)
- {
- if (((Player*)this)->GetGroup())
- ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
- }
- else if (((Creature*)this)->isPet())
- {
- Pet *pet = ((Pet*)this);
- if (pet->isControlled())
- {
- Unit *owner = GetOwner();
- if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
- ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
- }
-
- // Update the pet's character sheet with happiness damage bonus
- if (pet->getPetType() == HUNTER_PET && power == POWER_HAPPINESS)
- pet->UpdateDamagePhysical(BASE_ATTACK);
- }
-}
-
-void Unit::SetMaxPower(Powers power, uint32 val)
-{
- uint32 cur_power = GetPower(power);
- SetStatInt32Value(UNIT_FIELD_MAXPOWER1 + power, val);
-
- // group update
- if (GetTypeId() == TYPEID_PLAYER)
- {
- if (((Player*)this)->GetGroup())
- ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
- }
- else if (((Creature*)this)->isPet())
- {
- Pet *pet = ((Pet*)this);
- if (pet->isControlled())
- {
- Unit *owner = GetOwner();
- if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
- ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
- }
- }
-
- if (val < cur_power)
- SetPower(power, val);
-}
-
-void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply)
-{
- ApplyModUInt32Value(UNIT_FIELD_POWER1+power, val, apply);
-
- // group update
- if (GetTypeId() == TYPEID_PLAYER)
- {
- if (((Player*)this)->GetGroup())
- ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
- }
- else if (((Creature*)this)->isPet())
- {
- Pet *pet = ((Pet*)this);
- if (pet->isControlled())
- {
- Unit *owner = GetOwner();
- if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
- ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
- }
- }
-}
-
-void Unit::ApplyMaxPowerMod(Powers power, uint32 val, bool apply)
-{
- ApplyModUInt32Value(UNIT_FIELD_MAXPOWER1+power, val, apply);
-
- // group update
- if (GetTypeId() == TYPEID_PLAYER)
- {
- if (((Player*)this)->GetGroup())
- ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
- }
- else if (((Creature*)this)->isPet())
- {
- Pet *pet = ((Pet*)this);
- if (pet->isControlled())
- {
- Unit *owner = GetOwner();
- if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
- ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
- }
- }
-}
-
-uint32 Unit::GetCreatePowers( Powers power ) const
-{
- // POWER_FOCUS and POWER_HAPPINESS only have hunter pet
- switch (power)
- {
- case POWER_MANA: return GetCreateMana();
- case POWER_RAGE: return 1000;
- case POWER_FOCUS: return (GetTypeId() == TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 100);
- case POWER_ENERGY: return 100;
- case POWER_HAPPINESS: return (GetTypeId() == TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 1050000);
- case POWER_RUNIC_POWER: return 1000;
- case POWER_RUNE: return 0;
- case POWER_HEALTH: return 0;
- }
-
- return 0;
-}
-
-void Unit::AddToWorld()
-{
- if (!IsInWorld())
- {
- WorldObject::AddToWorld();
- SetToNotify();
- }
-}
-
-void Unit::RemoveFromWorld()
-{
- // cleanup
- assert(GetGUID());
-
- if (IsInWorld())
- {
- if (IsVehicle())
- GetVehicleKit()->Uninstall();
-
- RemoveCharmAuras();
- RemoveBindSightAuras();
- RemoveNotOwnSingleTargetAuras();
-
- RemoveAllGameObjects();
- RemoveAllDynObjects();
-
- ExitVehicle();
- UnsummonAllTotems();
- RemoveAllControlled();
-
- RemoveAreaAurasDueToLeaveWorld();
-
- if (GetCharmerGUID())
- {
- sLog.outCrash("Unit %u has charmer guid when removed from world", GetEntry());
- assert(false);
- }
-
- if (Unit *owner = GetOwner())
- {
- if (owner->m_Controlled.find(this) != owner->m_Controlled.end())
- {
- sLog.outCrash("Unit %u is in controlled list of %u when removed from world", GetEntry(), owner->GetEntry());
- assert(false);
- }
- }
-
- WorldObject::RemoveFromWorld();
- }
-}
-
-void Unit::CleanupsBeforeDelete(bool finalCleanup)
-{
- if (IsInWorld())
- RemoveFromWorld();
-
- assert(GetGUID());
-
- //A unit may be in removelist and not in world, but it is still in grid
- //and may have some references during delete
- RemoveAllAuras();
-
- if (finalCleanup)
- m_cleanupDone = true;
-
- InterruptNonMeleeSpells(true);
- m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList
- CombatStop();
- ClearComboPointHolders();
- DeleteThreatList();
- getHostilRefManager().setOnlineOfflineState(false);
- GetMotionMaster()->Clear(false); // remove different non-standard movement generators.
-}
-
-void Unit::UpdateCharmAI()
-{
- if (GetTypeId() == TYPEID_PLAYER)
- return;
-
- if (i_disabledAI) // disabled AI must be primary AI
- {
- if (!isCharmed())
- {
- if (i_AI)
- delete i_AI;
- i_AI = i_disabledAI;
- i_disabledAI = NULL;
- }
- }
- else
- {
- if (isCharmed())
- {
- i_disabledAI = i_AI;
- if (isPossessed() || IsVehicle())
- i_AI = new PossessedAI((Creature*)this);
- else
- i_AI = new PetAI((Creature*)this);
- }
- }
-}
-
-CharmInfo* Unit::InitCharmInfo()
-{
- if (!m_charmInfo)
- m_charmInfo = new CharmInfo(this);
-
- return m_charmInfo;
-}
-
-void Unit::DeleteCharmInfo()
-{
- if (!m_charmInfo)
- return;
-
- delete m_charmInfo;
- m_charmInfo = NULL;
-}
-
-CharmInfo::CharmInfo(Unit* unit)
-: m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_petnumber(0), m_barInit(false)
-{
- for (uint8 i = 0; i < MAX_SPELL_CHARM; ++i)
- m_charmspells[i].SetActionAndType(0,ACT_DISABLED);
-
- if (m_unit->GetTypeId() == TYPEID_UNIT)
- {
- m_oldReactState = ((Creature*)m_unit)->GetReactState();
- ((Creature*)m_unit)->SetReactState(REACT_PASSIVE);
- }
-
-}
-
-CharmInfo::~CharmInfo()
-{
- if (m_unit->GetTypeId() == TYPEID_UNIT)
- {
- ((Creature*)m_unit)->SetReactState(m_oldReactState);
- }
-}
-
-void CharmInfo::InitPetActionBar()
-{
- // the first 3 SpellOrActions are attack, follow and stay
- for (uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_START - ACTION_BAR_INDEX_START; ++i)
- SetActionBar(ACTION_BAR_INDEX_START + i,COMMAND_ATTACK - i,ACT_COMMAND);
-
- // middle 4 SpellOrActions are spells/special attacks/abilities
- for (uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_END-ACTION_BAR_INDEX_PET_SPELL_START; ++i)
- SetActionBar(ACTION_BAR_INDEX_PET_SPELL_START + i,0,ACT_PASSIVE);
-
- // last 3 SpellOrActions are reactions
- for (uint32 i = 0; i < ACTION_BAR_INDEX_END - ACTION_BAR_INDEX_PET_SPELL_END; ++i)
- SetActionBar(ACTION_BAR_INDEX_PET_SPELL_END + i,COMMAND_ATTACK - i,ACT_REACTION);
-}
-
-void CharmInfo::InitEmptyActionBar(bool withAttack)
-{
- if (withAttack)
- SetActionBar(ACTION_BAR_INDEX_START,COMMAND_ATTACK,ACT_COMMAND);
- else
- SetActionBar(ACTION_BAR_INDEX_START,0,ACT_PASSIVE);
- for (uint32 x = ACTION_BAR_INDEX_START+1; x < ACTION_BAR_INDEX_END; ++x)
- SetActionBar(x,0,ACT_PASSIVE);
-}
-
-void CharmInfo::InitPossessCreateSpells()
-{
- InitEmptyActionBar();
- if (m_unit->GetTypeId() == TYPEID_UNIT)
- {
- for (uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
- {
- uint32 spellId = ((Creature*)m_unit)->m_spells[i];
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
- if (spellInfo && spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_DEAD)
- spellId = 0;
- if (IsPassiveSpell(spellId))
- m_unit->CastSpell(m_unit, spellId, true);
- else
- AddSpellToActionBar(((Creature*)m_unit)->m_spells[i], ACT_PASSIVE);
- }
- }
-}
-
-void CharmInfo::InitCharmCreateSpells()
-{
- if (m_unit->GetTypeId() == TYPEID_PLAYER) //charmed players don't have spells
- {
- InitEmptyActionBar();
- return;
- }
-
- InitPetActionBar();
-
- for (uint32 x = 0; x < MAX_SPELL_CHARM; ++x)
- {
- uint32 spellId = ((Creature*)m_unit)->m_spells[x];
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
- if (spellInfo && spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_DEAD)
- spellId = 0;
-
- if (!spellId)
- {
- m_charmspells[x].SetActionAndType(spellId,ACT_DISABLED);
- continue;
- }
-
- if (IsPassiveSpell(spellId))
- {
- m_unit->CastSpell(m_unit, spellId, true);
- m_charmspells[x].SetActionAndType(spellId,ACT_PASSIVE);
- }
- else
- {
- m_charmspells[x].SetActionAndType(spellId,ACT_DISABLED);
-
- ActiveStates newstate;
- if (spellInfo)
- {
- if (!IsAutocastableSpell(spellId))
- newstate = ACT_PASSIVE;
- else
- {
- bool autocast = false;
- for (uint32 i = 0; i < MAX_SPELL_EFFECTS && !autocast; ++i)
- if (SpellTargetType[spellInfo->EffectImplicitTargetA[i]] == TARGET_TYPE_UNIT_TARGET)
- autocast = true;
-
- if (autocast)
- {
- newstate = ACT_ENABLED;
- ToggleCreatureAutocast(spellId, true);
- }
- else
- newstate = ACT_DISABLED;
- }
- }
-
- AddSpellToActionBar(spellId, newstate);
- }
- }
-}
-
-bool CharmInfo::AddSpellToActionBar(uint32 spell_id, ActiveStates newstate)
-{
- uint32 first_id = spellmgr.GetFirstSpellInChain(spell_id);
-
- // new spell rank can be already listed
- for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
- {
- if (uint32 action = PetActionBar[i].GetAction())
- {
- if (PetActionBar[i].IsActionBarForSpell() && spellmgr.GetFirstSpellInChain(action) == first_id)
- {
- PetActionBar[i].SetAction(spell_id);
- return true;
- }
- }
- }
-
- // or use empty slot in other case
- for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
- {
- if (!PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell())
- {
- SetActionBar(i,spell_id,newstate == ACT_DECIDE ? IsAutocastableSpell(spell_id) ? ACT_DISABLED : ACT_PASSIVE : newstate);
- return true;
- }
- }
- return false;
-}
-
-bool CharmInfo::RemoveSpellFromActionBar(uint32 spell_id)
-{
- uint32 first_id = spellmgr.GetFirstSpellInChain(spell_id);
-
- for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
- {
- if (uint32 action = PetActionBar[i].GetAction())
- {
- if (PetActionBar[i].IsActionBarForSpell() && spellmgr.GetFirstSpellInChain(action) == first_id)
- {
- SetActionBar(i,0,ACT_PASSIVE);
- return true;
- }
- }
- }
-
- return false;
-}
-
-void CharmInfo::ToggleCreatureAutocast(uint32 spellid, bool apply)
-{
- if (IsPassiveSpell(spellid))
- return;
-
- for (uint32 x = 0; x < MAX_SPELL_CHARM; ++x)
- if (spellid == m_charmspells[x].GetAction())
- m_charmspells[x].SetType(apply ? ACT_ENABLED : ACT_DISABLED);
-}
-
-void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow)
-{
- m_petnumber = petnumber;
- if (statwindow)
- m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber);
- else
- m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0);
-}
-
-void CharmInfo::LoadPetActionBar(const std::string& data )
-{
- InitPetActionBar();
-
- Tokens tokens = StrSplit(data, " ");
-
- if (tokens.size() != (ACTION_BAR_INDEX_END-ACTION_BAR_INDEX_START)*2)
- return; // non critical, will reset to default
-
- uint8 index;
- Tokens::iterator iter;
- for (iter = tokens.begin(), index = ACTION_BAR_INDEX_START; index < ACTION_BAR_INDEX_END; ++iter, ++index)
- {
- // use unsigned cast to avoid sign negative format use at long-> ActiveStates (int) conversion
- uint8 type = atol((*iter).c_str());
- ++iter;
- uint32 action = atol((*iter).c_str());
-
- PetActionBar[index].SetActionAndType(action,ActiveStates(type));
-
- // check correctness
- if (PetActionBar[index].IsActionBarForSpell())
- {
- if (!sSpellStore.LookupEntry(PetActionBar[index].GetAction()))
- SetActionBar(index,0,ACT_PASSIVE);
- else if (!IsAutocastableSpell(PetActionBar[index].GetAction()))
- SetActionBar(index,PetActionBar[index].GetAction(),ACT_PASSIVE);
- }
- }
-}
-
-void CharmInfo::BuildActionBar( WorldPacket* data )
-{
- for (uint32 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
- *data << uint32(PetActionBar[i].packedData);
-}
-
-void CharmInfo::SetSpellAutocast( uint32 spell_id, bool state )
-{
- for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
- {
- if (spell_id == PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell())
- {
- PetActionBar[i].SetType(state ? ACT_ENABLED : ACT_DISABLED);
- break;
- }
- }
-}
-
-bool Unit::isFrozen() const
-{
- return HasAuraState(AURA_STATE_FROZEN);
-}
-
-struct ProcTriggeredData
-{
- ProcTriggeredData(Aura* _aura)
- : aura(_aura)
- {
- effMask = 0;
- spellProcEvent = NULL;
- }
- SpellProcEventEntry const *spellProcEvent;
- Aura * aura;
- uint32 effMask;
-};
-
-typedef std::list< ProcTriggeredData > ProcTriggeredList;
-
-// List of auras that CAN be trigger but may not exist in spell_proc_event
-// in most case need for drop charges
-// in some types of aura need do additional check
-// for example SPELL_AURA_MECHANIC_IMMUNITY - need check for mechanic
-bool InitTriggerAuraData()
-{
- for (uint16 i = 0; i < TOTAL_AURAS; ++i)
- {
- isTriggerAura[i]=false;
- isNonTriggerAura[i] = false;
- }
- isTriggerAura[SPELL_AURA_DUMMY] = true;
- isTriggerAura[SPELL_AURA_MOD_CONFUSE] = true;
- isTriggerAura[SPELL_AURA_MOD_THREAT] = true;
- isTriggerAura[SPELL_AURA_MOD_STUN] = true; // Aura not have charges but need remove him on trigger
- isTriggerAura[SPELL_AURA_MOD_DAMAGE_DONE] = true;
- isTriggerAura[SPELL_AURA_MOD_DAMAGE_TAKEN] = true;
- isTriggerAura[SPELL_AURA_MOD_RESISTANCE] = true;
- isTriggerAura[SPELL_AURA_MOD_STEALTH] = true;
- isTriggerAura[SPELL_AURA_MOD_FEAR] = true; // Aura not have charges but need remove him on trigger
- isTriggerAura[SPELL_AURA_MOD_ROOT] = true;
- isTriggerAura[SPELL_AURA_TRANSFORM] = true;
- isTriggerAura[SPELL_AURA_REFLECT_SPELLS] = true;
- isTriggerAura[SPELL_AURA_DAMAGE_IMMUNITY] = true;
- isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL] = true;
- isTriggerAura[SPELL_AURA_PROC_TRIGGER_DAMAGE] = true;
- isTriggerAura[SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK] = true;
- isTriggerAura[SPELL_AURA_SCHOOL_ABSORB] = true; // Savage Defense untested
- isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT] = true;
- isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL] = true;
- isTriggerAura[SPELL_AURA_REFLECT_SPELLS_SCHOOL] = true;
- isTriggerAura[SPELL_AURA_MECHANIC_IMMUNITY] = true;
- isTriggerAura[SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN] = true;
- isTriggerAura[SPELL_AURA_SPELL_MAGNET] = true;
- isTriggerAura[SPELL_AURA_MOD_ATTACK_POWER] = true;
- isTriggerAura[SPELL_AURA_ADD_CASTER_HIT_TRIGGER] = true;
- isTriggerAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true;
- isTriggerAura[SPELL_AURA_MOD_MECHANIC_RESISTANCE] = true;
- isTriggerAura[SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS] = true;
- isTriggerAura[SPELL_AURA_MOD_HASTE] = true;
- isTriggerAura[SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE]=true;
- isTriggerAura[SPELL_AURA_RAID_PROC_FROM_CHARGE] = true;
- isTriggerAura[SPELL_AURA_RAID_PROC_FROM_CHARGE_WITH_VALUE] = true;
- isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE] = true;
- isTriggerAura[SPELL_AURA_MOD_DAMAGE_FROM_CASTER] = true;
- isTriggerAura[SPELL_AURA_MOD_SPELL_CRIT_CHANCE] = true;
-
- isNonTriggerAura[SPELL_AURA_MOD_POWER_REGEN]=true;
- isNonTriggerAura[SPELL_AURA_REDUCE_PUSHBACK]=true;
- isTriggerAura[SPELL_AURA_RANGED_AP_ATTACKER_CREATURES_BONUS] = true;
-
- return true;
-}
-
-uint32 createProcExtendMask(SpellNonMeleeDamage *damageInfo, SpellMissInfo missCondition)
-{
- uint32 procEx = PROC_EX_NONE;
- // Check victim state
- if (missCondition != SPELL_MISS_NONE)
- switch (missCondition)
- {
- case SPELL_MISS_MISS: procEx|=PROC_EX_MISS; break;
- case SPELL_MISS_RESIST: procEx|=PROC_EX_RESIST; break;
- case SPELL_MISS_DODGE: procEx|=PROC_EX_DODGE; break;
- case SPELL_MISS_PARRY: procEx|=PROC_EX_PARRY; break;
- case SPELL_MISS_BLOCK: procEx|=PROC_EX_BLOCK; break;
- case SPELL_MISS_EVADE: procEx|=PROC_EX_EVADE; break;
- case SPELL_MISS_IMMUNE: procEx|=PROC_EX_IMMUNE; break;
- case SPELL_MISS_IMMUNE2: procEx|=PROC_EX_IMMUNE; break;
- case SPELL_MISS_DEFLECT: procEx|=PROC_EX_DEFLECT;break;
- case SPELL_MISS_ABSORB: procEx|=PROC_EX_ABSORB; break;
- case SPELL_MISS_REFLECT: procEx|=PROC_EX_REFLECT;break;
- default:
- break;
- }
- else
- {
- // On block
- if (damageInfo->blocked)
- procEx|=PROC_EX_BLOCK;
- // On absorb
- if (damageInfo->absorb)
- procEx|=PROC_EX_ABSORB;
- // On crit
- if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT)
- procEx|=PROC_EX_CRITICAL_HIT;
- else
- procEx|=PROC_EX_NORMAL_HIT;
- }
- return procEx;
-}
-
-void Unit::ProcDamageAndSpellFor(bool isVictim, Unit * pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const * procSpell, uint32 damage, SpellEntry const * procAura)
-{
- // Player is loaded now - do not allow passive spell casts to proc
- if (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->GetSession()->PlayerLoading())
- return;
- // For melee/ranged based attack need update skills and set some Aura states if victim present
- if (procFlag & MELEE_BASED_TRIGGER_MASK && pTarget)
- {
- // Update skills here for players
- if (GetTypeId() == TYPEID_PLAYER)
- {
- // On melee based hit/miss/resist need update skill (for victim and attacker)
- if (procExtra&(PROC_EX_NORMAL_HIT|PROC_EX_MISS|PROC_EX_RESIST))
- {
- if (pTarget->GetTypeId() != TYPEID_PLAYER && pTarget->GetCreatureType() != CREATURE_TYPE_CRITTER)
- ((Player*)this)->UpdateCombatSkills(pTarget, attType, isVictim);
- }
- // Update defence if player is victim and parry/dodge/block
- else if (isVictim && procExtra&(PROC_EX_DODGE|PROC_EX_PARRY|PROC_EX_BLOCK))
- ((Player*)this)->UpdateCombatSkills(pTarget, attType, MELEE_HIT_DODGE);
- }
- // If exist crit/parry/dodge/block need update aura state (for victim and attacker)
- if (procExtra & (PROC_EX_CRITICAL_HIT|PROC_EX_PARRY|PROC_EX_DODGE|PROC_EX_BLOCK))
- {
- // for victim
- if (isVictim)
- {
- // if victim and dodge attack
- if (procExtra&PROC_EX_DODGE)
- {
- //Update AURA_STATE on dodge
- if (getClass() != CLASS_ROGUE) // skip Rogue Riposte
- {
- ModifyAuraState(AURA_STATE_DEFENSE, true);
- StartReactiveTimer( REACTIVE_DEFENSE );
- }
- }
- // if victim and parry attack
- if (procExtra & PROC_EX_PARRY)
- {
- // For Hunters only Counterattack (skip Mongoose bite)
- if (getClass() == CLASS_HUNTER)
- {
- ModifyAuraState(AURA_STATE_HUNTER_PARRY, true);
- StartReactiveTimer( REACTIVE_HUNTER_PARRY );
- }
- else
- {
- ModifyAuraState(AURA_STATE_DEFENSE, true);
- StartReactiveTimer( REACTIVE_DEFENSE );
- }
- }
- // if and victim block attack
- if (procExtra & PROC_EX_BLOCK)
- {
- ModifyAuraState(AURA_STATE_DEFENSE,true);
- StartReactiveTimer( REACTIVE_DEFENSE );
- }
- }
- else //For attacker
- {
- // Overpower on victim dodge
- if (procExtra&PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR)
- {
- ((Player*)this)->AddComboPoints(pTarget, 1);
- StartReactiveTimer( REACTIVE_OVERPOWER );
- }
- }
- }
- }
-
- ProcTriggeredList procTriggered;
- // Fill procTriggered list
- for (AuraApplicationMap::const_iterator itr = GetAppliedAuras().begin(); itr!= GetAppliedAuras().end(); ++itr)
- {
- // Do not allow auras to proc from effect triggered by itself
- if (procAura && procAura->Id == itr->first)
- continue;
- ProcTriggeredData triggerData(itr->second->GetBase());
- // Defensive procs are active on absorbs (so absorption effects are not a hindrance)
- bool active = (damage > 0) || ((procExtra & PROC_EX_ABSORB) && isVictim);
- if (!IsTriggeredAtSpellProcEvent(pTarget, triggerData.aura, procSpell, procFlag, procExtra, attType, isVictim, active, triggerData.spellProcEvent))
- continue;
-
- for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
- {
- if (itr->second->HasEffect(i))
- {
- AuraEffect * aurEff = itr->second->GetBase()->GetEffect(i);
- // Skip this auras
- if (isNonTriggerAura[aurEff->GetAuraType()])
- continue;
- // If not trigger by default and spellProcEvent==NULL - skip
- if (!isTriggerAura[aurEff->GetAuraType()] && triggerData.spellProcEvent==NULL)
- continue;
- uint32 triggered_spell_id = aurEff->GetSpellProto()->EffectTriggerSpell[i];
- // check for positive auras that proc with charge drop
- bool positive = (!triggered_spell_id && IsPositiveSpell(aurEff->GetId()) && aurEff->GetBase()->GetCharges()) ||
- // check for positive auras that triggers unknown spells (Blessing Recovery, etc...)
- (!sSpellStore.LookupEntry(triggered_spell_id) && IsPositiveSpell(aurEff->GetId())) ||
- // final check for positive triggered spell
- IsPositiveSpell(triggered_spell_id);
- if (!damage && (procExtra & PROC_EX_ABSORB) && isVictim && positive)
- continue;
- triggerData.effMask |= 1<<i;
- }
- }
- if (triggerData.effMask)
- procTriggered.push_front(triggerData);
- }
-
- // Nothing found
- if (procTriggered.empty())
- return;
-
- if (procExtra & (PROC_EX_INTERNAL_TRIGGERED | PROC_EX_INTERNAL_CANT_PROC))
- SetCantProc(true);
-
- // Handle effects proceed this time
- for (ProcTriggeredList::const_iterator i = procTriggered.begin(); i != procTriggered.end(); ++i)
- {
- // look for aura in auras list, it may be removed while proc event processing
- if (i->aura->IsRemoved())
- continue;
-
- bool useCharges= i->aura->GetCharges()>0;
- bool takeCharges = false;
- SpellEntry const *spellInfo = i->aura->GetSpellProto();
- uint32 Id = i->aura->GetId();
-
- // For players set spell cooldown if need
- uint32 cooldown = 0;
- if (GetTypeId() == TYPEID_PLAYER && i->spellProcEvent && i->spellProcEvent->cooldown)
- cooldown = i->spellProcEvent->cooldown;
-
- if (spellInfo->AttributesEx3 & SPELL_ATTR_EX3_DISABLE_PROC)
- SetCantProc(true);
-
- // This bool is needed till separate aura effect procs are still here
- bool handled = false;
- if (HandleAuraProc(pTarget, damage, i->aura, procSpell, procFlag, procExtra, cooldown, &handled))
- {
- sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), Id);
- takeCharges = true;
- }
-
- if (!handled)
- for (uint8 effIndex = 0; effIndex<MAX_SPELL_EFFECTS; ++effIndex)
- {
- if (!(i->effMask & (1<<effIndex)))
- continue;
-
- AuraEffect *triggeredByAura = i->aura->GetEffect(effIndex);
- assert(triggeredByAura);
-
- switch(triggeredByAura->GetAuraType())
- {
- case SPELL_AURA_PROC_TRIGGER_SPELL:
- {
- sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
- // Don`t drop charge or add cooldown for not started trigger
- if (HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
- takeCharges = true;
- break;
- }
- case SPELL_AURA_PROC_TRIGGER_DAMAGE:
- {
- sLog.outDebug("ProcDamageAndSpell: doing %u damage from spell id %u (triggered by %s aura of spell %u)", triggeredByAura->GetAmount() , spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
- SpellNonMeleeDamage damageInfo(this, pTarget, spellInfo->Id, spellInfo->SchoolMask);
- uint32 damage = SpellDamageBonus(pTarget, spellInfo, triggeredByAura->GetAmount(), SPELL_DIRECT_DAMAGE);
- CalculateSpellDamageTaken(&damageInfo, damage, spellInfo);
- DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb);
- SendSpellNonMeleeDamageLog(&damageInfo);
- DealSpellDamage(&damageInfo, true);
- takeCharges = true;
- break;
- }
- case SPELL_AURA_MANA_SHIELD:
- case SPELL_AURA_DUMMY:
- {
- sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s dummy aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
- if (HandleDummyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
- takeCharges = true;
- break;
- }
- case SPELL_AURA_OBS_MOD_POWER:
- sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
- if (HandleObsModEnergyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
- takeCharges = true;
- break;
- case SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN:
- sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
- if (HandleModDamagePctTakenAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
- takeCharges = true;
- break;
- case SPELL_AURA_MOD_HASTE:
- {
- sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s haste aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
- if (HandleHasteAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
- takeCharges = true;
- break;
- }
- case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
- {
- sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
- if (HandleOverrideClassScriptAuraProc(pTarget, damage, triggeredByAura, procSpell, cooldown))
- takeCharges = true;
- break;
- }
- case SPELL_AURA_RAID_PROC_FROM_CHARGE_WITH_VALUE:
- {
- sLog.outDebug("ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
- (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
-
- HandleAuraRaidProcFromChargeWithValue(triggeredByAura);
- takeCharges = true;
- break;
- }
- case SPELL_AURA_RAID_PROC_FROM_CHARGE:
- {
- sLog.outDebug("ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
- (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
-
- HandleAuraRaidProcFromCharge(triggeredByAura);
- takeCharges = true;
- break;
- }
- case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE:
- {
- sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
-
- if (HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
- takeCharges = true;
- break;
- }
- case SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK:
- // Skip melee hits or instant cast spells
- if (procSpell && GetSpellCastTime(procSpell) != 0)
- takeCharges = true;
- break;
- case SPELL_AURA_REFLECT_SPELLS_SCHOOL:
- // Skip Melee hits and spells ws wrong school
- if (procSpell && (triggeredByAura->GetMiscValue() & procSpell->SchoolMask)) // School check
- takeCharges = true;
- break;
- case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT:
- case SPELL_AURA_MOD_POWER_COST_SCHOOL:
- // Skip melee hits and spells ws wrong school or zero cost
- if (procSpell &&
- (procSpell->manaCost != 0 || procSpell->ManaCostPercentage != 0) && // Cost check
- (triggeredByAura->GetMiscValue() & procSpell->SchoolMask) == 0) // School check
- takeCharges = true;
- break;
- case SPELL_AURA_MECHANIC_IMMUNITY:
- // Compare mechanic
- if (procSpell && procSpell->Mechanic == triggeredByAura->GetMiscValue())
- takeCharges = true;
- break;
- case SPELL_AURA_MOD_MECHANIC_RESISTANCE:
- // Compare mechanic
- if (procSpell && procSpell->Mechanic == triggeredByAura->GetMiscValue())
- takeCharges = true;
- break;
- case SPELL_AURA_MOD_DAMAGE_FROM_CASTER:
- // Compare casters
- if (triggeredByAura->GetCasterGUID() == pTarget->GetGUID())
- takeCharges = true;
- break;
- case SPELL_AURA_MOD_SPELL_CRIT_CHANCE:
- sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s spell crit chance aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
- if (procSpell && HandleSpellCritChanceAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
- takeCharges = true;
- break;
- // CC Auras which use their amount amount to drop
- // Are there any more auras which need this?
- case SPELL_AURA_MOD_CONFUSE:
- case SPELL_AURA_MOD_FEAR:
- case SPELL_AURA_MOD_STUN:
- case SPELL_AURA_MOD_ROOT:
- case SPELL_AURA_TRANSFORM:
- if (isVictim && damage)
- {
- // Damage is dealt after proc system - lets ignore auras which wasn't updated yet
- // to make spell not remove its own aura
- if (i->aura->GetDuration() == i->aura->GetMaxDuration())
- break;
- int32 damageLeft = triggeredByAura->GetAmount();
- // No damage left
- if (damageLeft < damage )
- i->aura->Remove();
- else
- triggeredByAura->SetAmount(damageLeft-damage);
- }
- break;
- //case SPELL_AURA_ADD_FLAT_MODIFIER:
- //case SPELL_AURA_ADD_PCT_MODIFIER:
- // HandleSpellModAuraProc
- //break;
- default:
- // nothing do, just charges counter
- takeCharges = true;
- break;
- }
- }
- // Remove charge (aura can be removed by triggers)
- if (useCharges && takeCharges)
- i->aura->DropCharge();
-
- if (spellInfo->AttributesEx3 & SPELL_ATTR_EX3_DISABLE_PROC)
- SetCantProc(false);
- }
-
- // Cleanup proc requirements
- if (procExtra & (PROC_EX_INTERNAL_TRIGGERED | PROC_EX_INTERNAL_CANT_PROC))
- SetCantProc(false);
-}
-
-SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const
-{
- return SPELL_SCHOOL_MASK_NORMAL;
-}
-
-Player* Unit::GetSpellModOwner() const
-{
- if (GetTypeId() == TYPEID_PLAYER)
- return (Player*)this;
- if (((Creature*)this)->isPet() || ((Creature*)this)->isTotem())
- {
- Unit* owner = GetOwner();
- if (owner && owner->GetTypeId() == TYPEID_PLAYER)
- return (Player*)owner;
- }
- return NULL;
-}
-
-///----------Pet responses methods-----------------
-void Unit::SendPetCastFail(uint32 spellid, SpellCastResult msg)
-{
- if (msg == SPELL_CAST_OK)
- return;
-
- Unit *owner = GetCharmerOrOwner();
- if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
- return;
-
- WorldPacket data(SMSG_PET_CAST_FAILED, 1 + 4 + 1);
- data << uint8(0); // cast count?
- data << uint32(spellid);
- data << uint8(msg);
- // uint32 for some reason
- // uint32 for some reason
- ((Player*)owner)->GetSession()->SendPacket(&data);
-}
-
-void Unit::SendPetActionFeedback (uint8 msg)
-{
- Unit* owner = GetOwner();
- if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
- return;
-
- WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1);
- data << uint8(msg);
- ((Player*)owner)->GetSession()->SendPacket(&data);
-}
-
-void Unit::SendPetTalk (uint32 pettalk)
-{
- Unit* owner = GetOwner();
- if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
- return;
-
- WorldPacket data(SMSG_PET_ACTION_SOUND, 8 + 4);
- data << uint64(GetGUID());
- data << uint32(pettalk);
- ((Player*)owner)->GetSession()->SendPacket(&data);
-}
-
-void Unit::SendPetAIReaction(uint64 guid)
-{
- Unit* owner = GetOwner();
- if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
- return;
-
- WorldPacket data(SMSG_AI_REACTION, 8 + 4);
- data << uint64(guid);
- data << uint32(AI_REACTION_AGGRO);
- ((Player*)owner)->GetSession()->SendPacket(&data);
-}
-
-///----------End of Pet responses methods----------
-
-void Unit::StopMoving()
-{
- clearUnitState(UNIT_STAT_MOVING);
-
- // send explicit stop packet
- // rely on vmaps here because for example stormwind is in air
- //float z = MapManager::Instance().GetBaseMap(GetMapId())->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), true);
- //if (fabs(GetPositionZ() - z) < 2.0f)
- // Relocate(GetPositionX(), GetPositionY(), z);
- //Relocate(GetPositionX(), GetPositionY(),GetPositionZ());
-
- SendMonsterStop();
-
- // update position and orientation;
- WorldPacket data;
- BuildHeartBeatMsg(&data);
- SendMessageToSet(&data,false);
-}
-
-void Unit::SendMovementFlagUpdate()
-{
- WorldPacket data;
- BuildHeartBeatMsg(&data);
- SendMessageToSet(&data, false);
-}
-
-bool Unit::IsSitState() const
-{
- uint8 s = getStandState();
- return
- s == UNIT_STAND_STATE_SIT_CHAIR || s == UNIT_STAND_STATE_SIT_LOW_CHAIR ||
- s == UNIT_STAND_STATE_SIT_MEDIUM_CHAIR || s == UNIT_STAND_STATE_SIT_HIGH_CHAIR ||
- s == UNIT_STAND_STATE_SIT;
-}
-
-bool Unit::IsStandState() const
-{
- uint8 s = getStandState();
- return !IsSitState() && s != UNIT_STAND_STATE_SLEEP && s != UNIT_STAND_STATE_KNEEL;
-}
-
-void Unit::SetStandState(uint8 state)
-{
- SetByteValue(UNIT_FIELD_BYTES_1, 0, state);
-
- if (IsStandState())
- RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED);
-
- if (GetTypeId() == TYPEID_PLAYER)
- {
- WorldPacket data(SMSG_STANDSTATE_UPDATE, 1);
- data << (uint8)state;
- ((Player*)this)->GetSession()->SendPacket(&data);
- }
-}
-
-bool Unit::IsPolymorphed() const
-{
- uint32 transformId = getTransForm();
- if (!transformId)
- return false;
-
- const SpellEntry *spellInfo=sSpellStore.LookupEntry(transformId);
- if (!spellInfo)
- return false;
-
- return GetSpellSpecific(spellInfo)==SPELL_SPECIFIC_MAGE_POLYMORPH;
-}
-
-void Unit::SetDisplayId(uint32 modelId)
-{
- SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId);
-
- if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
- {
- Pet *pet = ((Pet*)this);
- if (!pet->isControlled())
- return;
- Unit *owner = GetOwner();
- if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
- ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID);
- }
-}
-
-void Unit::ClearComboPointHolders()
-{
- while(!m_ComboPointHolders.empty())
- {
- uint32 lowguid = *m_ComboPointHolders.begin();
-
- Player* plr = objmgr.GetPlayer(MAKE_NEW_GUID(lowguid, 0, HIGHGUID_PLAYER));
- if (plr && plr->GetComboTarget()==GetGUID()) // recheck for safe
- plr->ClearComboPoints(); // remove also guid from m_ComboPointHolders;
- else
- m_ComboPointHolders.erase(lowguid); // or remove manually
- }
-}
-
-void Unit::ClearAllReactives()
-{
- for (uint8 i=0; i < MAX_REACTIVE; ++i)
- m_reactiveTimer[i] = 0;
-
- if (HasAuraState(AURA_STATE_DEFENSE))
- ModifyAuraState(AURA_STATE_DEFENSE, false);
- if (getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
- ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
- if (getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
- ((Player*)this)->ClearComboPoints();
-}
-
-void Unit::UpdateReactives( uint32 p_time )
-{
- for (uint8 i = 0; i < MAX_REACTIVE; ++i)
- {
- ReactiveType reactive = ReactiveType(i);
-
- if (!m_reactiveTimer[reactive])
- continue;
-
- if ( m_reactiveTimer[reactive] <= p_time)
- {
- m_reactiveTimer[reactive] = 0;
-
- switch ( reactive )
- {
- case REACTIVE_DEFENSE:
- if (HasAuraState(AURA_STATE_DEFENSE))
- ModifyAuraState(AURA_STATE_DEFENSE, false);
- break;
- case REACTIVE_HUNTER_PARRY:
- if ( getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
- ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
- break;
- case REACTIVE_OVERPOWER:
- if (getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
- ((Player*)this)->ClearComboPoints();
- break;
- default:
- break;
- }
- }
- else
- {
- m_reactiveTimer[reactive] -= p_time;
- }
- }
-}
-
-Unit* Unit::SelectNearbyTarget(float dist) const
-{
- std::list<Unit *> targets;
- Trinity::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, dist);
- Trinity::UnitListSearcher<Trinity::AnyUnfriendlyUnitInObjectRangeCheck> searcher(this, targets, u_check);
- VisitNearbyObject(dist, searcher);
-
- // remove current target
- if (getVictim())
- targets.remove(getVictim());
-
- // remove not LoS targets
- for (std::list<Unit *>::iterator tIter = targets.begin(); tIter != targets.end();)
- {
- if (!IsWithinLOSInMap(*tIter))
- {
- std::list<Unit *>::iterator tIter2 = tIter;
- ++tIter;
- targets.erase(tIter2);
- }
- else
- ++tIter;
- }
-
- // no appropriate targets
- if (targets.empty())
- return NULL;
-
- // select random
- uint32 rIdx = urand(0,targets.size()-1);
- std::list<Unit *>::const_iterator tcIter = targets.begin();
- for (uint32 i = 0; i < rIdx; ++i)
- ++tcIter;
-
- return *tcIter;
-}
-
-void Unit::ApplyAttackTimePercentMod( WeaponAttackType att,float val, bool apply )
-{
- float remainingTimePct = (float)m_attackTimer[att] / (GetAttackTime(att) * m_modAttackSpeedPct[att]);
- if (val > 0)
- {
- ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply);
- ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,val,!apply);
- }
- else
- {
- ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply);
- ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,-val,apply);
- }
- m_attackTimer[att] = uint32(GetAttackTime(att) * m_modAttackSpeedPct[att] * remainingTimePct);
-}
-
-void Unit::ApplyCastTimePercentMod(float val, bool apply )
-{
- if (val > 0)
- ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,val,!apply);
- else
- ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,-val,apply);
-}
-
-uint32 Unit::GetCastingTimeForBonus( SpellEntry const *spellProto, DamageEffectType damagetype, uint32 CastingTime )
-{
- // Not apply this to creature casted spells with casttime==0
- if (CastingTime==0 && GetTypeId() == TYPEID_UNIT && !((Creature*)this)->isPet())
- return 3500;
-
- if (CastingTime > 7000) CastingTime = 7000;
- if (CastingTime < 1500) CastingTime = 1500;
-
- if (damagetype == DOT && !IsChanneledSpell(spellProto))
- CastingTime = 3500;
-
- int32 overTime = 0;
- uint8 effects = 0;
- bool DirectDamage = false;
- bool AreaEffect = false;
-
- for (uint32 i=0; i<MAX_SPELL_EFFECTS; i++)
- {
- switch ( spellProto->Effect[i] )
- {
- case SPELL_EFFECT_SCHOOL_DAMAGE:
- case SPELL_EFFECT_POWER_DRAIN:
- case SPELL_EFFECT_HEALTH_LEECH:
- case SPELL_EFFECT_ENVIRONMENTAL_DAMAGE:
- case SPELL_EFFECT_POWER_BURN:
- case SPELL_EFFECT_HEAL:
- DirectDamage = true;
- break;
- case SPELL_EFFECT_APPLY_AURA:
- switch ( spellProto->EffectApplyAuraName[i] )
- {
- case SPELL_AURA_PERIODIC_DAMAGE:
- case SPELL_AURA_PERIODIC_HEAL:
- case SPELL_AURA_PERIODIC_LEECH:
- if ( GetSpellDuration(spellProto) )
- overTime = GetSpellDuration(spellProto);
- break;
- default:
- // -5% per additional effect
- ++effects;
- break;
- }
- default:
- break;
- }
-
- if (IsAreaEffectTarget[spellProto->EffectImplicitTargetA[i]] || IsAreaEffectTarget[spellProto->EffectImplicitTargetB[i]])
- AreaEffect = true;
- }
-
- // Combined Spells with Both Over Time and Direct Damage
- if ( overTime > 0 && CastingTime > 0 && DirectDamage )
- {
- // mainly for DoTs which are 3500 here otherwise
- uint32 OriginalCastTime = GetSpellCastTime(spellProto);
- if (OriginalCastTime > 7000) OriginalCastTime = 7000;
- if (OriginalCastTime < 1500) OriginalCastTime = 1500;
- // Portion to Over Time
- float PtOT = (overTime / 15000.0f) / ((overTime / 15000.0f) + (OriginalCastTime / 3500.0f));
-
- if ( damagetype == DOT )
- CastingTime = uint32(CastingTime * PtOT);
- else if ( PtOT < 1.0f )
- CastingTime = uint32(CastingTime * (1 - PtOT));
- else
- CastingTime = 0;
- }
-
- // Area Effect Spells receive only half of bonus
- if ( AreaEffect )
- CastingTime /= 2;
-
- // -5% of total per any additional effect
- for (uint8 i=0; i<effects; ++i)
- {
- if ( CastingTime > 175 )
- {
- CastingTime -= 175;
- }
- else
- {
- CastingTime = 0;
- break;
- }
- }
-
- return CastingTime;
-}
-
-void Unit::UpdateAuraForGroup(uint8 slot)
-{
- if (slot >= MAX_AURAS) // slot not found, return
- return;
- if (GetTypeId() == TYPEID_PLAYER)
- {
- Player* player = (Player*)this;
- if (player->GetGroup())
- {
- player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_AURAS);
- player->SetAuraUpdateMaskForRaid(slot);
- }
- }
- else if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
- {
- Pet *pet = ((Pet*)this);
- if (pet->isControlled())
- {
- Unit *owner = GetOwner();
- if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
- {
- ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_AURAS);
- pet->SetAuraUpdateMaskForRaid(slot);
- }
- }
- }
-}
-
-float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized)
-{
- if (!normalized || GetTypeId() != TYPEID_PLAYER)
- return float(GetAttackTime(attType))/1000.0f;
-
- Item *Weapon = ((Player*)this)->GetWeaponForAttack(attType);
- if (!Weapon)
- return 2.4; // fist attack
-
- switch (Weapon->GetProto()->InventoryType)
- {
- case INVTYPE_2HWEAPON:
- return 3.3;
- case INVTYPE_RANGED:
- case INVTYPE_RANGEDRIGHT:
- case INVTYPE_THROWN:
- return 2.8;
- case INVTYPE_WEAPON:
- case INVTYPE_WEAPONMAINHAND:
- case INVTYPE_WEAPONOFFHAND:
- default:
- return Weapon->GetProto()->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7 : 2.4;
- }
-}
-
-bool Unit::IsUnderLastManaUseEffect() const
-{
- return getMSTimeDiff(m_lastManaUse,getMSTime()) < 5000;
-}
-
-void Unit::SetContestedPvP(Player *attackedPlayer)
-{
- Player* player = GetCharmerOrOwnerPlayerOrPlayerItself();
-
- if (!player || attackedPlayer && (attackedPlayer == player || player->duel && player->duel->opponent == attackedPlayer))
- return;
-
- player->SetContestedPvPTimer(30000);
- if (!player->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
- {
- player->addUnitState(UNIT_STAT_ATTACK_PLAYER);
- player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
- // call MoveInLineOfSight for nearby contested guards
- player->SetVisibility(player->GetVisibility());
- }
- if (!hasUnitState(UNIT_STAT_ATTACK_PLAYER))
- {
- addUnitState(UNIT_STAT_ATTACK_PLAYER);
- // call MoveInLineOfSight for nearby contested guards
- SetVisibility(GetVisibility());
- }
-}
-
-void Unit::AddPetAura(PetAura const* petSpell)
-{
- if (GetTypeId() != TYPEID_PLAYER)
- return;
-
- m_petAuras.insert(petSpell);
- if (Pet* pet = ((Player*)this)->GetPet())
- pet->CastPetAura(petSpell);
-}
-
-void Unit::RemovePetAura(PetAura const* petSpell)
-{
- if (GetTypeId() != TYPEID_PLAYER)
- return;
-
- m_petAuras.erase(petSpell);
- if (Pet* pet = ((Player*)this)->GetPet())
- pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry()));
-}
-
-Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget,uint32 spell_id)
-{
- if (GetTypeId() != TYPEID_PLAYER)
- return NULL;
-
- Pet* pet = new Pet((Player*)this, HUNTER_PET);
-
- if (!pet->CreateBaseAtCreature(creatureTarget))
- {
- delete pet;
- return NULL;
- }
-
- pet->SetCreatorGUID(GetGUID());
- pet->setFaction(getFaction());
- pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id);
-
- if (GetTypeId() == TYPEID_PLAYER)
- pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
-
- uint8 level = (creatureTarget->getLevel() < (getLevel() - 5)) ? (getLevel() - 5) : creatureTarget->getLevel();
-
- if (!pet->InitStatsForLevel(level))
- {
- sLog.outError("Pet::InitStatsForLevel() failed for creature (Entry: %u)!",creatureTarget->GetEntry());
- delete pet;
- return NULL;
- }
-
- pet->GetCharmInfo()->SetPetNumber(objmgr.GeneratePetNumber(), true);
- // this enables pet details window (Shift+P)
- pet->InitPetCreateSpells();
- //pet->InitLevelupSpellsForLevel();
- pet->SetHealth(pet->GetMaxHealth());
-
- return pet;
-}
-
-bool Unit::IsTriggeredAtSpellProcEvent(Unit *pVictim, Aura * aura, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const *& spellProcEvent )
-{
- SpellEntry const *spellProto = aura->GetSpellProto();
-
- // Get proc Event Entry
- spellProcEvent = spellmgr.GetSpellProcEvent(spellProto->Id);
-
- // Get EventProcFlag
- uint32 EventProcFlag;
- if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags
- EventProcFlag = spellProcEvent->procFlags;
- else
- EventProcFlag = spellProto->procFlags; // else get from spell proto
- // Continue if no trigger exist
- if (!EventProcFlag)
- return false;
-
- // Additional checks for triggered spells (ignore trap casts)
- if (procExtra & PROC_EX_INTERNAL_TRIGGERED && !(procFlag & PROC_FLAG_ON_TRAP_ACTIVATION))
- {
- if (!(spellProto->AttributesEx3 & SPELL_ATTR_EX3_CAN_PROC_TRIGGERED))
- return false;
- }
-
- // Check spellProcEvent data requirements
- if (!spellmgr.IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active))
- return false;
- // In most cases req get honor or XP from kill
- if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER)
- {
- bool allow = ((Player*)this)->isHonorOrXPTarget(pVictim);
- // Shadow Word: Death - can trigger from every kill
- if (aura->GetId() == 32409)
- allow = true;
- if (!allow)
- return false;
- }
- // Aura added by spell can`t trigger from self (prevent drop charges/do triggers)
- // But except periodic and kill triggers (can triggered from self)
- if (procSpell && procSpell->Id == spellProto->Id
- && !(spellProto->procFlags&(PROC_FLAG_ON_TAKE_PERIODIC | PROC_FLAG_KILL)))
- return false;
-
- // Check if current equipment allows aura to proc
- if (!isVictim && GetTypeId() == TYPEID_PLAYER)
- {
- if (spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
- {
- Item *item = NULL;
- if (attType == BASE_ATTACK)
- item = ((Player*)this)->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
- else if (attType == OFF_ATTACK)
- item = ((Player*)this)->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
- else
- item = ((Player*)this)->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
-
- if (((Player*)this)->IsInFeralForm())
- return false;
-
- if (!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
- return false;
- }
- else if (spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
- {
- // Check if player is wearing shield
- Item *item = ((Player*)this)->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
- if (!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
- return false;
- }
- }
- // Get chance from spell
- float chance = float(spellProto->procChance);
- // If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance;
- if (spellProcEvent && spellProcEvent->customChance)
- chance = spellProcEvent->customChance;
- // If PPM exist calculate chance from PPM
- if (spellProcEvent && spellProcEvent->ppmRate != 0)
- {
- if (!isVictim)
- {
- uint32 WeaponSpeed = GetAttackTime(attType);
- chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate, spellProto);
- }
- else
- {
- uint32 WeaponSpeed = pVictim->GetAttackTime(attType);
- chance = pVictim->GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate, spellProto);
- }
- }
- // Apply chance modifer aura
- if (Player* modOwner = GetSpellModOwner())
- {
- modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
- }
- return roll_chance_f(chance);
-}
-
-bool Unit::HandleAuraRaidProcFromChargeWithValue(AuraEffect *triggeredByAura)
-{
- // aura can be deleted at casts
- SpellEntry const *spellProto = triggeredByAura->GetSpellProto();
- uint32 effIdx = triggeredByAura->GetEffIndex();
- int32 heal = triggeredByAura->GetAmount();
- uint64 caster_guid = triggeredByAura->GetCasterGUID();
-
- //Currently only Prayer of Mending
- if (!(spellProto->SpellFamilyName == SPELLFAMILY_PRIEST && spellProto->SpellFamilyFlags[1] & 0x20))
- {
- sLog.outDebug("Unit::HandleAuraRaidProcFromChargeWithValue, received not handled spell: %u", spellProto->Id);
- return false;
- }
-
- // jumps
- int32 jumps = triggeredByAura->GetBase()->GetCharges()-1;
-
- // current aura expire
- triggeredByAura->GetBase()->SetCharges(1); // will removed at next charges decrease
-
- // next target selection
- if (jumps > 0)
- {
- float radius;
- if (spellProto->EffectRadiusIndex[effIdx])
- radius = GetSpellRadiusForTarget(triggeredByAura->GetCaster(), sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
- else
- radius = GetSpellMaxRangeForTarget(triggeredByAura->GetCaster(), sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
-
- if (Unit * caster = triggeredByAura->GetCaster())
- {
- if (Player * modOwner = caster->GetSpellModOwner())
- modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius, NULL);
-
- if (Unit *target = GetNextRandomRaidMemberOrPet(radius))
- {
- CastCustomSpell(target, spellProto->Id, &heal, NULL, NULL, true, NULL, triggeredByAura, caster_guid);
- if (Aura * aura = target->GetAura(spellProto->Id, caster->GetGUID()))
- aura->SetCharges(jumps);
- heal = caster->SpellHealingBonus(this, spellProto, heal, HEAL);
- }
- }
- }
-
- // heal
- CastCustomSpell(this, 33110, &heal, NULL, NULL, true, NULL, NULL, caster_guid);
- return true;
-
-}
-bool Unit::HandleAuraRaidProcFromCharge(AuraEffect* triggeredByAura)
-{
- // aura can be deleted at casts
- SpellEntry const* spellProto = triggeredByAura->GetSpellProto();
-
- uint32 damageSpellId;
- switch (spellProto->Id)
- {
- case 57949: //shiver
- damageSpellId = 57952;
- //animationSpellId = 57951; dummy effects for jump spell have unknown use (see also 41637)
- break;
- case 59978: //shiver
- damageSpellId = 59979;
- break;
- case 43593: //Cold Stare
- damageSpellId = 43594;
- break;
- default:
- sLog.outError("Unit::HandleAuraRaidProcFromCharge, received not handled spell: %u", spellProto->Id);
- return false;
- }
-
- uint64 caster_guid = triggeredByAura->GetCasterGUID();
- uint32 effIdx = triggeredByAura->GetEffIndex();
-
- // jumps
- int32 jumps = triggeredByAura->GetBase()->GetCharges()-1;
-
- // current aura expire
- triggeredByAura->GetBase()->SetCharges(1); // will removed at next charges decrease
-
- // next target selection
- if (jumps > 0)
- {
- float radius;
- if (spellProto->EffectRadiusIndex[effIdx])
- radius = GetSpellRadiusForTarget(triggeredByAura->GetCaster(), sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
- else
- radius = GetSpellMaxRangeForTarget(triggeredByAura->GetCaster() ,sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
-
- if (Unit * caster = triggeredByAura->GetCaster())
- {
- if (Player * modOwner = caster->GetSpellModOwner())
- modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius, NULL);
-
- if (Unit* target= GetNextRandomRaidMemberOrPet(radius))
- {
- CastSpell(target, spellProto, true,NULL,triggeredByAura,caster_guid);
- if (Aura * aura = target->GetAura(spellProto->Id, caster->GetGUID()))
- aura->SetCharges(jumps);
- }
- }
- }
-
- CastSpell(this, damageSpellId, true,NULL,triggeredByAura,caster_guid);
-
- return true;
-}
-/*-----------------------TRINITY-----------------------------*/
-
-void Unit::SetToNotify()
-{
- if (GetTypeId() == TYPEID_PLAYER)
- AddToNotify(NOTIFY_VISIBILITY_CHANGED | NOTIFY_AI_RELOCATION | NOTIFY_PLAYER_VISIBILITY);
- else
- AddToNotify(NOTIFY_VISIBILITY_CHANGED | NOTIFY_AI_RELOCATION);
-}
-
-void Unit::Kill(Unit *pVictim, bool durabilityLoss)
-{
- // Prevent killing unit twice (and giving reward from kill twice)
- if (!pVictim->GetHealth())
- return;
-
- // Inform pets (if any) when player kills target)
- if (this->GetTypeId() == TYPEID_PLAYER && ((Player*)this)->GetPet())
- {
- Pet *pPet = ((Player*)this)->GetPet();
-
- if (pPet && pPet->isAlive() && pPet->isControlled())
- pPet->AI()->KilledUnit(pVictim);
- }
-
- //sLog.outError("%u kill %u", GetEntry(), pVictim->GetEntry());
-
- pVictim->SetHealth(0);
-
- // find player: owner of controlled `this` or `this` itself maybe
- Player *player = GetCharmerOrOwnerPlayerOrPlayerItself();
-
- bool bRewardIsAllowed = true;
- if (pVictim->GetTypeId() == TYPEID_UNIT)
- {
- bRewardIsAllowed = ((Creature*)pVictim)->IsDamageEnoughForLootingAndReward();
- if (!bRewardIsAllowed)
- ((Creature*)pVictim)->SetLootRecipient(NULL);
- }
-
- if (bRewardIsAllowed && pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->GetLootRecipient())
- player = ((Creature*)pVictim)->GetLootRecipient();
- // Reward player, his pets, and group/raid members
- // call kill spell proc event (before real die and combat stop to triggering auras removed at death/combat stop)
- if (bRewardIsAllowed && player && player!=pVictim)
- {
- WorldPacket data(SMSG_PARTYKILLLOG, (8+8)); //send event PARTY_KILL
- data << uint64(player->GetGUID()); //player with killing blow
- data << uint64(pVictim->GetGUID()); //victim
- if (Group *group = player->GetGroup())
- group->BroadcastPacket(&data, group->GetMemberGroup(player->GetGUID()));
- else
- player->SendDirectMessage(&data);
-
- if (player->RewardPlayerAndGroupAtKill(pVictim))
- player->ProcDamageAndSpell(pVictim, PROC_FLAG_KILL, PROC_FLAG_KILLED, PROC_EX_NONE, 0);
- else
- player->ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_KILLED, PROC_EX_NONE, 0);
- }
-
- // Proc auras on death - must be before aura/combat remove
- pVictim->ProcDamageAndSpell(NULL, PROC_FLAG_DEATH, PROC_FLAG_NONE, PROC_EX_NONE, 0, BASE_ATTACK, 0);
-
- // if talent known but not triggered (check priest class for speedup check)
- bool SpiritOfRedemption = false;
- if (pVictim->GetTypeId() == TYPEID_PLAYER && pVictim->getClass() == CLASS_PRIEST)
- {
- AuraEffectList const& vDummyAuras = pVictim->GetAuraEffectsByType(SPELL_AURA_DUMMY);
- for (AuraEffectList::const_iterator itr = vDummyAuras.begin(); itr != vDummyAuras.end(); ++itr)
- {
- if ((*itr)->GetSpellProto()->SpellIconID==1654)
- {
- // save value before aura remove
- uint32 ressSpellId = pVictim->GetUInt32Value(PLAYER_SELF_RES_SPELL);
- if (!ressSpellId)
- ressSpellId = ((Player*)pVictim)->GetResurrectionSpellId();
- //Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers)
- pVictim->RemoveAllAurasOnDeath();
- // restore for use at real death
- pVictim->SetUInt32Value(PLAYER_SELF_RES_SPELL,ressSpellId);
-
- // FORM_SPIRITOFREDEMPTION and related auras
- pVictim->CastSpell(pVictim,27827,true,NULL,*itr);
- SpiritOfRedemption = true;
- break;
- }
- }
- }
-
- if (!SpiritOfRedemption)
- {
- DEBUG_LOG("SET JUST_DIED");
- pVictim->setDeathState(JUST_DIED);
- }
-
- // 10% durability loss on death
- // clean InHateListOf
- if (pVictim->GetTypeId() == TYPEID_PLAYER)
- {
- // remember victim PvP death for corpse type and corpse reclaim delay
- // at original death (not at SpiritOfRedemtionTalent timeout)
- ((Player*)pVictim)->SetPvPDeath(player != NULL);
-
- // only if not player and not controlled by player pet. And not at BG
- if ((durabilityLoss && !player && !((Player*)pVictim)->InBattleGround()) || (player && sWorld.getConfig(CONFIG_DURABILITY_LOSS_IN_PVP)))
- {
- DEBUG_LOG("We are dead, losing %u percent durability", sWorld.getRate(RATE_DURABILITY_LOSS_ON_DEATH));
- ((Player*)pVictim)->DurabilityLossAll(sWorld.getRate(RATE_DURABILITY_LOSS_ON_DEATH),false);
- // durability lost message
- WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
- ((Player*)pVictim)->GetSession()->SendPacket(&data);
- }
- // Call KilledUnit for creatures
- if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsAIEnabled)
- ((Creature*)this)->AI()->KilledUnit(pVictim);
-
- // last damage from non duel opponent or opponent controlled creature
- if (((Player*)pVictim)->duel)
- {
- ((Player*)pVictim)->duel->opponent->CombatStopWithPets(true);
- ((Player*)pVictim)->CombatStopWithPets(true);
- ((Player*)pVictim)->DuelComplete(DUEL_INTERUPTED);
- }
- }
- else // creature died
- {
- DEBUG_LOG("DealDamageNotPlayer");
- Creature *cVictim = (Creature*)pVictim;
-
- if (!cVictim->isPet())
- {
- cVictim->DeleteThreatList();
- CreatureInfo const* cInfo = cVictim->GetCreatureInfo();
- if (cInfo && (cInfo->lootid || cInfo->maxgold > 0))
- cVictim->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
- }
-
- // Call KilledUnit for creatures, this needs to be called after the lootable flag is set
- if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsAIEnabled)
- ((Creature*)this)->AI()->KilledUnit(pVictim);
-
- // Call creature just died function
- if (cVictim->IsAIEnabled)
- cVictim->AI()->JustDied(this);
-
- // Dungeon specific stuff, only applies to players killing creatures
- if (cVictim->GetInstanceId())
- {
- Map *m = cVictim->GetMap();
- Player *creditedPlayer = GetCharmerOrOwnerPlayerOrPlayerItself();
- // TODO: do instance binding anyway if the charmer/owner is offline
-
- if (m->IsDungeon() && creditedPlayer)
- {
- if (m->IsRaidOrHeroicDungeon())
- {
- if (cVictim->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
- ((InstanceMap *)m)->PermBindAllPlayers(creditedPlayer);
- }
- else
- {
- // the reset time is set but not added to the scheduler
- // until the players leave the instance
- time_t resettime = cVictim->GetRespawnTimeEx() + 2 * HOUR;
- if (InstanceSave *save = sInstanceSaveManager.GetInstanceSave(cVictim->GetInstanceId()))
- if (save->GetResetTime() < resettime) save->SetResetTime(resettime);
- }
- }
- }
- }
-
- // outdoor pvp things, do these after setting the death state, else the player activity notify won't work... doh...
- // handle player kill only if not suicide (spirit of redemption for example)
- if (player && this != pVictim)
- if (OutdoorPvP * pvp = player->GetOutdoorPvP())
- pvp->HandleKill(player, pVictim);
-
- //if (pVictim->GetTypeId() == TYPEID_PLAYER)
- // if (OutdoorPvP * pvp = ((Player*)pVictim)->GetOutdoorPvP())
- // pvp->HandlePlayerActivityChanged((Player*)pVictim);
-
- // battleground things (do this at the end, so the death state flag will be properly set to handle in the bg->handlekill)
- if (player && player->InBattleGround())
- {
- if (BattleGround *bg = player->GetBattleGround())
- {
- if (pVictim->GetTypeId() == TYPEID_PLAYER)
- bg->HandleKillPlayer((Player*)pVictim, player);
- else
- bg->HandleKillUnit((Creature*)pVictim, player);
- }
- }
-
- // achievement stuff
- if (pVictim->GetTypeId() == TYPEID_PLAYER)
- {
- if (GetTypeId() == TYPEID_UNIT)
- ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE, GetEntry());
- else if (GetTypeId() == TYPEID_PLAYER && pVictim != this)
- ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER, 1, ((Player*)this)->GetTeam());
- }
-}
-
-void Unit::SetControlled(bool apply, UnitState state)
-{
- if (apply)
- {
- if (hasUnitState(state))
- return;
-
- addUnitState(state);
-
- switch(state)
- {
- case UNIT_STAT_STUNNED:
- SetStunned(true);
- break;
- case UNIT_STAT_ROOT:
- if (!hasUnitState(UNIT_STAT_STUNNED))
- SetRooted(true);
- break;
- case UNIT_STAT_CONFUSED:
- if (!hasUnitState(UNIT_STAT_STUNNED))
- SetConfused(true);
- break;
- case UNIT_STAT_FLEEING:
- if (!hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_CONFUSED))
- SetFeared(true);
- break;
- default:
- break;
- }
- }
- else
- {
- switch(state)
- {
- case UNIT_STAT_STUNNED: if (HasAuraType(SPELL_AURA_MOD_STUN)) return;
- else SetStunned(false); break;
- case UNIT_STAT_ROOT: if (HasAuraType(SPELL_AURA_MOD_ROOT) || GetVehicle()) return;
- else SetRooted(false); break;
- case UNIT_STAT_CONFUSED:if (HasAuraType(SPELL_AURA_MOD_CONFUSE)) return;
- else SetConfused(false); break;
- case UNIT_STAT_FLEEING: if (HasAuraType(SPELL_AURA_MOD_FEAR)) return;
- else SetFeared(false); break;
- default: return;
- }
-
- clearUnitState(state);
-
- if (hasUnitState(UNIT_STAT_STUNNED))
- SetStunned(true);
- else
- {
- if (hasUnitState(UNIT_STAT_ROOT))
- SetRooted(true);
-
- if (hasUnitState(UNIT_STAT_CONFUSED))
- SetConfused(true);
- else if (hasUnitState(UNIT_STAT_FLEEING))
- SetFeared(true);
- }
- }
-}
-
-void Unit::SetStunned(bool apply)
-{
- if (apply)
- {
- SetUInt64Value(UNIT_FIELD_TARGET, 0);
- SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
- CastStop();
- AddUnitMovementFlag(MOVEMENTFLAG_ROOT);
-
- // Creature specific
- if (GetTypeId() != TYPEID_PLAYER)
- ((Creature*)this)->StopMoving();
- else
- SetStandState(UNIT_STAND_STATE_STAND);
-
- WorldPacket data(SMSG_FORCE_MOVE_ROOT, 8);
- data.append(GetPackGUID());
- data << uint32(0);
- SendMessageToSet(&data,true);
- }
- else
- {
- if (isAlive() && getVictim())
- SetUInt64Value(UNIT_FIELD_TARGET, getVictim()->GetGUID());
-
- // don't remove UNIT_FLAG_STUNNED for pet when owner is mounted (disabled pet's interface)
- Unit *pOwner = GetOwner();
- if (!pOwner || (pOwner->GetTypeId() == TYPEID_PLAYER && !((Player *)pOwner)->IsMounted()))
- RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
-
- if (!hasUnitState(UNIT_STAT_ROOT)) // prevent allow move if have also root effect
- {
- WorldPacket data(SMSG_FORCE_MOVE_UNROOT, 8+4);
- data.append(GetPackGUID());
- data << uint32(0);
- SendMessageToSet(&data,true);
-
- RemoveUnitMovementFlag(MOVEMENTFLAG_ROOT);
- }
- }
-}
-
-void Unit::SetRooted(bool apply)
-{
- if (apply)
- {
- AddUnitMovementFlag(MOVEMENTFLAG_ROOT);
-
- WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
- data.append(GetPackGUID());
- data << (uint32)2;
- SendMessageToSet(&data,true);
-
- if (GetTypeId() != TYPEID_PLAYER)
- ((Creature *)this)->StopMoving();
- }
- else
- {
- if (!hasUnitState(UNIT_STAT_STUNNED)) // prevent allow move if have also stun effect
- {
- WorldPacket data(SMSG_FORCE_MOVE_UNROOT, 10);
- data.append(GetPackGUID());
- data << (uint32)2;
- SendMessageToSet(&data,true);
-
- RemoveUnitMovementFlag(MOVEMENTFLAG_ROOT);
- }
- }
-}
-
-void Unit::SetFeared(bool apply)
-{
- if (apply)
- {
- SetUInt64Value(UNIT_FIELD_TARGET, 0);
-
- Unit *caster = NULL;
- Unit::AuraEffectList const& fearAuras = GetAuraEffectsByType(SPELL_AURA_MOD_FEAR);
- if (!fearAuras.empty())
- caster = ObjectAccessor::GetUnit(*this, fearAuras.front()->GetCasterGUID());
- if (!caster)
- caster = getAttackerForHelper();
- GetMotionMaster()->MoveFleeing(caster, fearAuras.empty() ? sWorld.getConfig(CONFIG_CREATURE_FAMILY_FLEE_DELAY) : 0); // caster==NULL processed in MoveFleeing
- }
- else
- {
- if (isAlive())
- {
- if (GetMotionMaster()->GetCurrentMovementGeneratorType() == FLEEING_MOTION_TYPE)
- GetMotionMaster()->MovementExpired();
- if (getVictim())
- SetUInt64Value(UNIT_FIELD_TARGET, getVictim()->GetGUID());
- }
- }
-
- if (GetTypeId() == TYPEID_PLAYER)
- ((Player*)this)->SetClientControl(this, !apply);
-}
-
-void Unit::SetConfused(bool apply)
-{
- if (apply)
- {
- SetUInt64Value(UNIT_FIELD_TARGET, 0);
- GetMotionMaster()->MoveConfused();
- }
- else
- {
- if (isAlive())
- {
- if (GetMotionMaster()->GetCurrentMovementGeneratorType() == CONFUSED_MOTION_TYPE)
- GetMotionMaster()->MovementExpired();
- if (getVictim())
- SetUInt64Value(UNIT_FIELD_TARGET, getVictim()->GetGUID());
- }
- }
-
- if (GetTypeId() == TYPEID_PLAYER)
- ((Player*)this)->SetClientControl(this, !apply);
-}
-
-bool Unit::SetCharmedBy(Unit* charmer, CharmType type)
-{
- if (!charmer)
- return false;
-
- assert(type != CHARM_TYPE_POSSESS || charmer->GetTypeId() == TYPEID_PLAYER);
- assert((type == CHARM_TYPE_VEHICLE) == IsVehicle());
-
- sLog.outDebug("SetCharmedBy: charmer %u, charmed %u, type %u.", charmer->GetEntry(), GetEntry(), (uint32)type);
-
- if (this == charmer)
- {
- sLog.outCrash("Unit::SetCharmedBy: Unit %u is trying to charm itself!", GetEntry());
- return false;
- }
-
- //if (hasUnitState(UNIT_STAT_UNATTACKABLE))
- // return false;
-
- if (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->GetTransport())
- {
- sLog.outCrash("Unit::SetCharmedBy: Player on transport is trying to charm %u", GetEntry());
- return false;
- }
-
- // Already charmed
- if (GetCharmerGUID())
- {
- sLog.outCrash("Unit::SetCharmedBy: %u has already been charmed but %u is trying to charm it!", GetEntry(), charmer->GetEntry());
- return false;
- }
-
- CastStop();
- CombatStop(); //TODO: CombatStop(true) may cause crash (interrupt spells)
- DeleteThreatList();
-
- // Charmer stop charming
- if (charmer->GetTypeId() == TYPEID_PLAYER)
- {
- ((Player*)charmer)->StopCastingCharm();
- ((Player*)charmer)->StopCastingBindSight();
- }
-
- // Charmed stop charming
- if (GetTypeId() == TYPEID_PLAYER)
- {
- ((Player*)this)->StopCastingCharm();
- ((Player*)this)->StopCastingBindSight();
- }
-
- // StopCastingCharm may remove a possessed pet?
- if (!IsInWorld())
- {
- sLog.outCrash("Unit::SetCharmedBy: %u is not in world but %u is trying to charm it!", GetEntry(), charmer->GetEntry());
- return false;
- }
-
- // Set charmed
- setFaction(charmer->getFaction());
- charmer->SetCharm(this, true);
-
- if (GetTypeId() == TYPEID_UNIT)
- {
- ((Creature*)this)->AI()->OnCharmed(true);
- GetMotionMaster()->MoveIdle();
- }
- else
- {
- if (((Player*)this)->isAFK())
- ((Player*)this)->ToggleAFK();
- ((Player*)this)->SetClientControl(this, 0);
- }
-
- // Pets already have a properly initialized CharmInfo, don't overwrite it.
- if (type != CHARM_TYPE_VEHICLE && !GetCharmInfo())
- {
- CharmInfo *charmInfo = InitCharmInfo();
- if (type == CHARM_TYPE_POSSESS)
- charmInfo->InitPossessCreateSpells();
- else
- charmInfo->InitCharmCreateSpells();
- }
-
- if (charmer->GetTypeId() == TYPEID_PLAYER)
- {
- switch(type)
- {
- case CHARM_TYPE_VEHICLE:
- SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
- ((Player*)charmer)->SetClientControl(this, 1);
- ((Player*)charmer)->SetViewpoint(this, true);
- ((Player*)charmer)->VehicleSpellInitialize();
- break;
- case CHARM_TYPE_POSSESS:
- addUnitState(UNIT_STAT_POSSESSED);
- SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
- charmer->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE);
- ((Player*)charmer)->SetClientControl(this, 1);
- ((Player*)charmer)->SetViewpoint(this, true);
- ((Player*)charmer)->PossessSpellInitialize();
- break;
- case CHARM_TYPE_CHARM:
- if (GetTypeId() == TYPEID_UNIT && charmer->getClass() == CLASS_WARLOCK)
- {
- CreatureInfo const *cinfo = ((Creature*)this)->GetCreatureInfo();
- if (cinfo && cinfo->type == CREATURE_TYPE_DEMON)
- {
- //to prevent client crash
- SetByteValue(UNIT_FIELD_BYTES_0, 1, (uint8)CLASS_MAGE);
-
- //just to enable stat window
- if (GetCharmInfo())
- GetCharmInfo()->SetPetNumber(objmgr.GeneratePetNumber(), true);
-
- //if charmed two demons the same session, the 2nd gets the 1st one's name
- SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, time(NULL));
- }
- }
- ((Player*)charmer)->CharmSpellInitialize();
- break;
- default:
- case CHARM_TYPE_CONVERT:
- break;
- }
- }
- return true;
-}
-
-void Unit::RemoveCharmedBy(Unit *charmer)
-{
- if (!isCharmed())
- return;
-
- if (!charmer)
- charmer = GetCharmer();
- if (charmer != GetCharmer()) // one aura overrides another?
- {
-// sLog.outCrash("Unit::RemoveCharmedBy: this: " UI64FMTD " true charmer: " UI64FMTD " false charmer: " UI64FMTD,
-// GetGUID(), GetCharmerGUID(), charmer->GetGUID());
-// assert(false);
- return;
- }
-
- CharmType type;
- if (hasUnitState(UNIT_STAT_POSSESSED))
- type = CHARM_TYPE_POSSESS;
- else if (charmer->IsOnVehicle(this))
- type = CHARM_TYPE_VEHICLE;
- else
- type = CHARM_TYPE_CHARM;
-
- CastStop();
- CombatStop(); //TODO: CombatStop(true) may cause crash (interrupt spells)
- getHostilRefManager().deleteReferences();
- DeleteThreatList();
- RestoreFaction();
- GetMotionMaster()->InitDefault();
-
- if (type == CHARM_TYPE_POSSESS)
- {
- clearUnitState(UNIT_STAT_POSSESSED);
- RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
- }
-
- if (GetTypeId() == TYPEID_UNIT)
- {
- ((Creature*)this)->AI()->OnCharmed(false);
- ((Creature*)this)->AIM_Initialize();
-
- if (((Creature*)this)->AI() && charmer && charmer->isAlive())
- ((Creature*)this)->AI()->AttackStart(charmer);
- /*if (isAlive() && ((Creature*)this)->IsAIEnabled)
- {
- if (charmer && !IsFriendlyTo(charmer))
- ((Creature*)this)->AI()->AttackStart(charmer);
- else
- ((Creature*)this)->AI()->EnterEvadeMode();
- }*/
- }
- else
- ((Player*)this)->SetClientControl(this, 1);
-
- // If charmer still exists
- if (!charmer)
- return;
-
- assert(type != CHARM_TYPE_POSSESS || charmer->GetTypeId() == TYPEID_PLAYER);
- assert(type != CHARM_TYPE_VEHICLE || GetTypeId() == TYPEID_UNIT && IsVehicle());
-
- charmer->SetCharm(this, false);
-
- if (charmer->GetTypeId() == TYPEID_PLAYER)
- {
- switch(type)
- {
- case CHARM_TYPE_VEHICLE:
- ((Player*)charmer)->SetClientControl(charmer, 1);
- ((Player*)charmer)->SetViewpoint(this, false);
- break;
- case CHARM_TYPE_POSSESS:
- ((Player*)charmer)->SetClientControl(charmer, 1);
- ((Player*)charmer)->SetViewpoint(this, false);
- charmer->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE);
- break;
- case CHARM_TYPE_CHARM:
- if (GetTypeId() == TYPEID_UNIT && charmer->getClass() == CLASS_WARLOCK)
- {
- CreatureInfo const *cinfo = ((Creature*)this)->GetCreatureInfo();
- if (cinfo && cinfo->type == CREATURE_TYPE_DEMON)
- {
- SetByteValue(UNIT_FIELD_BYTES_0, 1, uint8(cinfo->unit_class));
- if (GetCharmInfo())
- GetCharmInfo()->SetPetNumber(0, true);
- else
- sLog.outError("Aura::HandleModCharm: target="UI64FMTD" with typeid=%d has a charm aura but no charm info!", GetGUID(), GetTypeId());
- }
- }
- break;
- default:
- case CHARM_TYPE_CONVERT:
- break;
- }
- }
-
- //a guardian should always have charminfo
- if (charmer->GetTypeId() == TYPEID_PLAYER && this != charmer->GetFirstControlled())
- ((Player*)charmer)->SendRemoveControlBar();
- else if (GetTypeId() == TYPEID_PLAYER || GetTypeId() == TYPEID_UNIT && !((Creature*)this)->isGuardian())
- DeleteCharmInfo();
-}
-
-void Unit::RestoreFaction()
-{
- if (GetTypeId() == TYPEID_PLAYER)
- ((Player*)this)->setFactionForRace(getRace());
- else
- {
- if (HasUnitTypeMask(UNIT_MASK_MINION))
- {
- if (Unit* owner = GetOwner())
- {
- setFaction(owner->getFaction());
- return;
- }
- }
-
- if (CreatureInfo const *cinfo = ((Creature*)this)->GetCreatureInfo()) // normal creature
- {
- FactionTemplateEntry const *faction = getFactionTemplateEntry();
- setFaction((faction && faction->friendlyMask & 0x004) ? cinfo->faction_H : cinfo->faction_A);
- }
- }
-}
-
-bool Unit::CreateVehicleKit(uint32 id)
-{
- VehicleEntry const *vehInfo = sVehicleStore.LookupEntry(id);
- if (!vehInfo)
- return false;
-
- m_vehicleKit = new Vehicle(this, vehInfo);
- m_updateFlag |= UPDATEFLAG_VEHICLE;
- m_unitTypeMask |= UNIT_MASK_VEHICLE;
- return true;
-}
-
-void Unit::RemoveVehicleKit()
-{
- if (!m_vehicleKit)
- return;
-
- m_vehicleKit->Uninstall();
- delete m_vehicleKit;
-
- m_vehicleKit = NULL;
-
- m_updateFlag &= ~UPDATEFLAG_VEHICLE;
- m_unitTypeMask &= ~UNIT_MASK_VEHICLE;
- RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
- RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_PLAYER_VEHICLE);
-}
-
-Unit *Unit::GetVehicleBase() const
-{
- return m_vehicle ? m_vehicle->GetBase() : NULL;
-}
-
-Creature *Unit::GetVehicleCreatureBase() const
-{
- Unit *veh = GetVehicleBase();
- if (veh->GetTypeId() == TYPEID_UNIT)
- return (Creature*)veh;
- return NULL;
-}
-
-bool Unit::IsInPartyWith(Unit const *unit) const
-{
- if (this == unit)
- return true;
-
- const Unit *u1 = GetCharmerOrOwnerOrSelf();
- const Unit *u2 = unit->GetCharmerOrOwnerOrSelf();
- if (u1 == u2)
- return true;
-
- if (u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_PLAYER)
- return ((Player*)u1)->IsInSameGroupWith((Player*)u2);
- else
- return false;
-}
-
-bool Unit::IsInRaidWith(Unit const *unit) const
-{
- if (this == unit)
- return true;
-
- const Unit *u1 = GetCharmerOrOwnerOrSelf();
- const Unit *u2 = unit->GetCharmerOrOwnerOrSelf();
- if (u1 == u2)
- return true;
-
- if (u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_PLAYER)
- return ((Player*)u1)->IsInSameRaidWith((Player*)u2);
- else
- return false;
-}
-
-void Unit::GetRaidMember(std::list<Unit*> &nearMembers, float radius)
-{
- Player *owner = GetCharmerOrOwnerPlayerOrPlayerItself();
- if (!owner)
- return;
-
- Group *pGroup = owner->GetGroup();
- if (pGroup)
- {
- for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
- {
- Player* Target = itr->getSource();
-
- if (Target && !IsHostileTo(Target))
- {
- if (Target->isAlive() && IsWithinDistInMap(Target, radius))
- nearMembers.push_back(Target);
-
- if (Guardian* pet = Target->GetGuardianPet())
- if (pet->isAlive() && IsWithinDistInMap(pet, radius))
- nearMembers.push_back(pet);
- }
- }
- }
- else
- {
- if (owner->isAlive() && (owner == this || IsWithinDistInMap(owner, radius)))
- nearMembers.push_back(owner);
- if (Guardian* pet = owner->GetGuardianPet())
- if (pet->isAlive() && (pet == this && IsWithinDistInMap(pet, radius)))
- nearMembers.push_back(pet);
- }
-}
-
-void Unit::GetPartyMemberInDist(std::list<Unit*> &TagUnitMap, float radius)
-{
- Unit *owner = GetCharmerOrOwnerOrSelf();
- Group *pGroup = NULL;
- if (owner->GetTypeId() == TYPEID_PLAYER)
- pGroup = ((Player*)owner)->GetGroup();
-
- if (pGroup)
- {
- uint8 subgroup = ((Player*)owner)->GetSubGroup();
-
- for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
- {
- Player* Target = itr->getSource();
-
- // IsHostileTo check duel and controlled by enemy
- if (Target && Target->GetSubGroup()==subgroup && !IsHostileTo(Target))
- {
- if (Target->isAlive() && IsWithinDistInMap(Target, radius))
- TagUnitMap.push_back(Target);
-
- if (Guardian* pet = Target->GetGuardianPet())
- if (pet->isAlive() && IsWithinDistInMap(pet, radius))
- TagUnitMap.push_back(pet);
- }
- }
- }
- else
- {
- if (owner->isAlive() && (owner == this || IsWithinDistInMap(owner, radius)))
- TagUnitMap.push_back(owner);
- if (Guardian* pet = owner->GetGuardianPet())
- if (pet->isAlive() && (pet == this && IsWithinDistInMap(pet, radius)))
- TagUnitMap.push_back(pet);
- }
-}
-
-void Unit::GetPartyMembers(std::list<Unit*> &TagUnitMap)
-{
- Unit *owner = GetCharmerOrOwnerOrSelf();
- Group *pGroup = NULL;
- if (owner->GetTypeId() == TYPEID_PLAYER)
- pGroup = ((Player*)owner)->GetGroup();
-
- if (pGroup)
- {
- uint8 subgroup = ((Player*)owner)->GetSubGroup();
-
- for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
- {
- Player* Target = itr->getSource();
-
- // IsHostileTo check duel and controlled by enemy
- if (Target && Target->GetSubGroup()==subgroup && !IsHostileTo(Target))
- {
- if (Target->isAlive() && IsInMap(Target))
- TagUnitMap.push_back(Target);
-
- if (Guardian* pet = Target->GetGuardianPet())
- if (pet->isAlive() && IsInMap(Target))
- TagUnitMap.push_back(pet);
- }
- }
- }
- else
- {
- if (owner->isAlive() && (owner == this || IsInMap(owner)))
- TagUnitMap.push_back(owner);
- if (Guardian* pet = owner->GetGuardianPet())
- if (pet->isAlive() && (pet == this || IsInMap(pet)))
- TagUnitMap.push_back(pet);
- }
-}
-
-Aura * Unit::AddAura(uint32 spellId, Unit *target)
-{
- if (!target || !target->isAlive())
- return NULL;
-
- SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
- if (!spellInfo)
- return NULL;
-
- return AddAura(spellInfo, MAX_EFFECT_MASK, target);
-}
-
-Aura * Unit::AddAura(SpellEntry const *spellInfo, uint8 effMask, Unit *target)
-{
- if (!spellInfo)
- return NULL;
-
- if (target->IsImmunedToSpell(spellInfo))
- return NULL;
-
- for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
- {
- if (!(effMask & (1<<i)))
- continue;
- if (target->IsImmunedToSpellEffect(spellInfo, i))
- effMask &= ~(1<<i);
- }
-
- if (Aura * aura = Aura::TryCreate(spellInfo, effMask, target, this))
- {
- aura->ApplyForTargets();
- return aura;
- }
- return NULL;
-}
-
-void Unit::SetAuraStack(uint32 spellId, Unit *target, uint32 stack)
-{
- Aura *aura = target->GetAura(spellId, GetGUID());
- if (!aura)
- aura = AddAura(spellId, target);
- if (aura && stack)
- aura->SetStackAmount(stack);
-}
-
-// Melee based spells can be miss, parry or dodge on this step
-// Crit or block - determined on damage calculation phase! (and can be both in some time)
-float Unit::MeleeSpellMissChance(const Unit *pVictim, WeaponAttackType attType, int32 skillDiff, uint32 spellId) const
-{
- // Calculate hit chance (more correct for chance mod)
- int32 HitChance;
-
- // PvP - PvE melee chances
- /*int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
- int32 leveldif = pVictim->getLevelForTarget(this) - getLevelForTarget(pVictim);
- if (leveldif < 3)
- HitChance = 95 - leveldif;
- else
- HitChance = 93 - (leveldif - 2) * lchance;*/
- if (spellId || attType == RANGED_ATTACK || !haveOffhandWeapon())
- HitChance = 95.0f;
- else
- HitChance = 76.0f;
-
- // Hit chance depends from victim auras
- if (attType == RANGED_ATTACK)
- HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
- else
- HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
-
- // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
- if (spellId)
- {
- if (Player *modOwner = GetSpellModOwner())
- modOwner->ApplySpellMod(spellId, SPELLMOD_RESIST_MISS_CHANCE, HitChance);
- }
-
- // Miss = 100 - hit
- float miss_chance = 100.0f - HitChance;
-
- // Bonuses from attacker aura and ratings
- if (attType == RANGED_ATTACK)
- miss_chance -= m_modRangedHitChance;
- else
- miss_chance -= m_modMeleeHitChance;
-
- // bonus from skills is 0.04%
- //miss_chance -= skillDiff * 0.04f;
- int32 diff = -skillDiff;
- if (pVictim->GetTypeId() == TYPEID_PLAYER)
- miss_chance += diff > 0 ? diff * 0.04 : diff * 0.02;
- else
- miss_chance += diff > 10 ? 2 + (diff - 10) * 0.4 : diff * 0.1;
-
- // Limit miss chance from 0 to 60%
- if (miss_chance < 0.0f)
- return 0.0f;
- if (miss_chance > 60.0f)
- return 60.0f;
- return miss_chance;
-}
-
-void Unit::SetPhaseMask(uint32 newPhaseMask, bool update)
-{
- if (newPhaseMask == GetPhaseMask())
- return;
-
- if (IsInWorld())
- RemoveNotOwnSingleTargetAuras(newPhaseMask); // we can lost access to caster or target
-
- WorldObject::SetPhaseMask(newPhaseMask,update);
-
- if (!IsInWorld())
- return;
-
- for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
- if ((*itr)->GetTypeId() == TYPEID_UNIT)
- (*itr)->SetPhaseMask(newPhaseMask,true);
-
- for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i)
- if (m_SummonSlot[i])
- if (Creature *summon = GetMap()->GetCreature(m_SummonSlot[i]))
- summon->SetPhaseMask(newPhaseMask,true);
-}
-
-void Unit::KnockbackFrom(float x, float y, float speedXY, float speedZ)
-{
- Player *player = NULL;
- if (GetTypeId() == TYPEID_PLAYER)
- player = (Player*)this;
- else
- {
- player = dynamic_cast<Player*>(GetCharmer());
- if (player && player->m_mover != this)
- player = NULL;
- }
-
- if (!player)
- {
- GetMotionMaster()->MoveKnockbackFrom(x, y, speedXY, speedZ);
- }
- else
- {
- float vcos, vsin;
- GetSinCos(x, y, vsin, vcos);
-
- WorldPacket data(SMSG_MOVE_KNOCK_BACK, (8+4+4+4+4+4));
- data.append(GetPackGUID());
- data << uint32(0); // Sequence
- data << float(vcos); // x direction
- data << float(vsin); // y direction
- data << float(speedXY); // Horizontal speed
- data << float(-speedZ); // Z Movement speed (vertical)
-
- player->GetSession()->SendPacket(&data);
- }
-}
-
-float Unit::GetCombatRatingReduction(CombatRating cr) const
-{
- if (GetTypeId() == TYPEID_PLAYER)
- return ((Player const*)this)->GetRatingBonusValue(cr);
- else if (((Creature const*)this)->isPet())
- {
- // Player's pet get resilience from owner
- if (Unit* owner = GetOwner())
- if(owner->GetTypeId() == TYPEID_PLAYER)
- return ((Player*)owner)->GetRatingBonusValue(cr);
- }
-
- return 0.0f;
-}
-
-uint32 Unit::GetCombatRatingDamageReduction(CombatRating cr, float rate, float cap, uint32 damage) const
-{
- float percent = GetCombatRatingReduction(cr) * rate;
- if (percent > cap)
- percent = cap;
- return uint32 (percent * damage / 100.0f);
-}
-
-uint32 Unit::GetModelForForm(ShapeshiftForm form)
-{
- switch(form)
- {
- case FORM_CAT:
- // Based on Hair color
- if (getRace() == RACE_NIGHTELF)
- {
- uint8 hairColor = GetByteValue(PLAYER_BYTES, 3);
- switch (hairColor)
- {
- case 7: // Violet
- case 8:
- return 29405;
- case 3: // Light Blue
- return 29406;
- case 0: // Green
- case 1: // Light Green
- case 2: // Dark Green
- return 29407;
- case 4: // White
- return 29408;
- default: // original - Dark Blue
- return 892;
- }
- }
- // Based on Skin color
- else if (getRace() == RACE_TAUREN)
- {
- uint8 skinColor = GetByteValue(PLAYER_BYTES, 0);
- // Male
- if (getGender() == GENDER_MALE)
- {
- switch(skinColor)
- {
- case 12: // White
- case 13:
- case 14:
- case 18: // Completly White
- return 29409;
- case 9: // Light Brown
- case 10:
- case 11:
- return 29410;
- case 6: // Brown
- case 7:
- case 8:
- return 29411;
- case 0: // Dark
- case 1:
- case 2:
- case 3: // Dark Grey
- case 4:
- case 5:
- return 29412;
- default: // original - Grey
- return 8571;
- }
- }
- // Female
- else switch (skinColor)
- {
- case 10: // White
- return 29409;
- case 6: // Light Brown
- case 7:
- return 29410;
- case 4: // Brown
- case 5:
- return 29411;
- case 0: // Dark
- case 1:
- case 2:
- case 3:
- return 29412;
- default: // original - Grey
- return 8571;
- }
- }
- else if(Player::TeamForRace(getRace())==ALLIANCE)
- return 892;
- else
- return 8571;
- case FORM_DIREBEAR:
- case FORM_BEAR:
- // Based on Hair color
- if (getRace() == RACE_NIGHTELF)
- {
- uint8 hairColor = GetByteValue(PLAYER_BYTES, 3);
- switch (hairColor)
- {
- case 0: // Green
- case 1: // Light Green
- case 2: // Dark Green
- return 29413; // 29415?
- case 6: // Dark Blue
- return 29414;
- case 4: // White
- return 29416;
- case 3: // Light Blue
- return 29417;
- default: // original - Violet
- return 2281;
- }
- }
- // Based on Skin color
- else if (getRace() == RACE_TAUREN)
- {
- uint8 skinColor = GetByteValue(PLAYER_BYTES, 0);
- // Male
- if (getGender() == GENDER_MALE)
- {
- switch (skinColor)
- {
- case 0: // Dark (Black)
- case 1:
- case 2:
- return 29418;
- case 3: // White
- case 4:
- case 5:
- case 12:
- case 13:
- case 14:
- return 29419;
- case 9: // Light Brown/Grey
- case 10:
- case 11:
- case 15:
- case 16:
- case 17:
- return 29420;
- case 18: // Completly White
- return 29421;
- default: // original - Brown
- return 2289;
- }
- }
- // Female
- else switch (skinColor)
- {
- case 0: // Dark (Black)
- case 1:
- return 29418;
- case 2: // White
- case 3:
- return 29419;
- case 6: // Light Brown/Grey
- case 7:
- case 8:
- case 9:
- return 29420;
- case 10: // Completly White
- return 29421;
- default: // original - Brown
- return 2289;
- }
- }
- else if(Player::TeamForRace(getRace())==ALLIANCE)
- return 2281;
- else
- return 2289;
- case FORM_TRAVEL:
- return 632;
- case FORM_AQUA:
- if(Player::TeamForRace(getRace())==ALLIANCE)
- return 2428;
- else
- return 2428;
- case FORM_GHOUL:
- return 24994;
- case FORM_CREATUREBEAR:
- return 902;
- case FORM_GHOSTWOLF:
- return 4613;
- case FORM_FLIGHT:
- if(Player::TeamForRace(getRace())==ALLIANCE)
- return 20857;
- else
- return 20872;
- case FORM_MOONKIN:
- if(Player::TeamForRace(getRace())==ALLIANCE)
- return 15374;
- else
- return 15375;
- case FORM_FLIGHT_EPIC:
- if(Player::TeamForRace(getRace())==ALLIANCE)
- return 21243;
- else
- return 21244;
- case FORM_METAMORPHOSIS:
- return 25277;
- case FORM_MASTER_ANGLER:
- return 15234;
- case FORM_TREE:
- return 864;
- case FORM_SPIRITOFREDEMPTION:
- return 16031;
- }
- return 0;
-}
-
-void Unit::JumpTo(float speedXY, float speedZ, bool forward)
-{
- float angle = forward ? 0 : M_PI;
- if (GetTypeId() == TYPEID_UNIT)
- GetMotionMaster()->MoveJumpTo(angle, speedXY, speedZ);
- else
- {
- float vcos = cos(angle+GetOrientation());
- float vsin = sin(angle+GetOrientation());
-
- WorldPacket data(SMSG_MOVE_KNOCK_BACK, (8+4+4+4+4+4));
- data.append(GetPackGUID());
- data << uint32(0); // Sequence
- data << float(vcos); // x direction
- data << float(vsin); // y direction
- data << float(speedXY); // Horizontal speed
- data << float(-speedZ); // Z Movement speed (vertical)
-
- ((Player*)this)->GetSession()->SendPacket(&data);
- }
-}
-
-void Unit::JumpTo(WorldObject *obj, float speedZ)
-{
- float x, y, z;
- obj->GetContactPoint(this, x, y, z);
- float speedXY = GetExactDist2d(x, y) * 10.0f / speedZ;
- GetMotionMaster()->MoveJump(x, y, z, speedXY, speedZ);
-}
-
-bool Unit::CheckPlayerCondition(Player* pPlayer)
-{
- switch(GetEntry())
- {
- case 35644: //Argent Warhorse
- case 36558: //Argent Battleworg
- if (!pPlayer->HasItemOrGemWithIdEquipped(46106,1)) //Check item Argent Lance
- return false;
- default:
- return true;
- }
-}
-
-void Unit::EnterVehicle(Vehicle *vehicle, int8 seatId)
-{
- if (!isAlive() || GetVehicleKit() == vehicle)
- return;
-
- if (m_vehicle)
- {
- if (m_vehicle == vehicle)
- {
- if (seatId >= 0)
- {
- sLog.outDebug("EnterVehicle: %u leave vehicle %u seat %d and enter %d.", GetEntry(), m_vehicle->GetBase()->GetEntry(), GetTransSeat(), seatId);
- ChangeSeat(seatId);
- }
- return;
- }
- else
- {
- sLog.outDebug("EnterVehicle: %u exit %u and enter %u.", GetEntry(), m_vehicle->GetBase()->GetEntry(), vehicle->GetBase()->GetEntry());
- ExitVehicle();
- }
- }
-
- if (GetTypeId() == TYPEID_PLAYER)
- {
- ((Player*)this)->StopCastingCharm();
- ((Player*)this)->StopCastingBindSight();
- ((Player*)this)->Unmount();
- ((Player*)this)->RemoveAurasByType(SPELL_AURA_MOUNTED);
-
- // drop flag at invisible in bg
- if(((Player*)this)->InBattleGround())
- if(BattleGround *bg = ((Player*)this)->GetBattleGround())
- bg->EventPlayerDroppedFlag((Player*)this);
- }
-
- assert(!m_vehicle);
- m_vehicle = vehicle;
- if (!m_vehicle->AddPassenger(this, seatId))
- {
- m_vehicle = NULL;
- return;
- }
-
- SetControlled(true, UNIT_STAT_ROOT);
- //movementInfo is set in AddPassenger
- //packets are sent in AddPassenger
-
- if (GetTypeId() == TYPEID_PLAYER)
- {
- //((Player*)this)->SetClientControl(vehicle, 1);
- WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
- ((Player*)this)->GetSession()->SendPacket(&data);
- }
-}
-
-void Unit::ChangeSeat(int8 seatId, bool next)
-{
- if (!m_vehicle)
- return;
-
- if (seatId < 0)
- {
- seatId = m_vehicle->GetNextEmptySeat(GetTransSeat(), next);
- if (seatId < 0)
- return;
- }
- else if (seatId == GetTransSeat() || !m_vehicle->HasEmptySeat(seatId))
- return;
-
- m_vehicle->RemovePassenger(this);
- if (!m_vehicle->AddPassenger(this, seatId))
- assert(false);
-}
-
-void Unit::ExitVehicle()
-{
- if (!m_vehicle)
- return;
-
- Unit *vehicleBase = m_vehicle->GetBase();
- const AuraEffectList &modAuras = vehicleBase->GetAuraEffectsByType(SPELL_AURA_CONTROL_VEHICLE);
- for (AuraEffectList::const_iterator itr = modAuras.begin(); itr != modAuras.end(); ++itr)
- {
- if ((*itr)->GetBase()->GetOwner() == this)
- {
- vehicleBase->RemoveAura((*itr)->GetBase());
- break; // there should be no case that a vehicle has two auras for one owner
- }
- }
-
- if (!m_vehicle)
- return;
-
- //sLog.outError("exit vehicle");
-
- m_vehicle->RemovePassenger(this);
-
- // This should be done before dismiss, because there may be some aura removal
- Vehicle *vehicle = m_vehicle;
- m_vehicle = NULL;
-
- SetControlled(false, UNIT_STAT_ROOT);
-
- RemoveUnitMovementFlag(MOVEMENTFLAG_ONTRANSPORT);
- m_movementInfo.t_x = 0;
- m_movementInfo.t_y = 0;
- m_movementInfo.t_z = 0;
- m_movementInfo.t_o = 0;
- m_movementInfo.t_time = 0;
- m_movementInfo.t_seat = 0;
-
- Relocate(vehicle->GetBase());
-
- //Send leave vehicle, not correct
- if (GetTypeId() == TYPEID_PLAYER)
- {
- //((Player*)this)->SetClientControl(this, 1);
- ((Player*)this)->SendTeleportAckMsg();
- ((Player*)this)->SetFallInformation(0, GetPositionZ());
- }
- WorldPacket data;
- BuildHeartBeatMsg(&data);
- SendMessageToSet(&data, false);
-
- if (vehicle->GetBase()->HasUnitTypeMask(UNIT_MASK_MINION))
- if (((Minion*)vehicle->GetBase())->GetOwner() == this)
- vehicle->Dismiss();
-}
-
-void Unit::BuildMovementPacket(ByteBuffer *data) const
-{
- switch (GetTypeId())
- {
- case TYPEID_UNIT:
- if (canFly())
- const_cast<Unit*>(this)->AddUnitMovementFlag(MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_LEVITATING);
- break;
- case TYPEID_PLAYER:
- // remove unknown, unused etc flags for now
- const_cast<Unit*>(this)->RemoveUnitMovementFlag(MOVEMENTFLAG_SPLINE2);
- if (isInFlight())
- {
- WPAssert(const_cast<Unit*>(this)->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE);
- const_cast<Unit*>(this)->AddUnitMovementFlag(MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_SPLINE2);
- }
- break;
- }
-
- *data << uint32(GetUnitMovementFlags()); // movement flags
- *data << uint16(m_movementInfo.unk1); // 2.3.0
- *data << uint32(getMSTime()); // time
- *data << GetPositionX();
- *data << GetPositionY();
- *data << GetPositionZ();
- *data << GetOrientation();
-
- // 0x00000200
- if (GetUnitMovementFlags() & MOVEMENTFLAG_ONTRANSPORT)
- {
- if (m_vehicle)
- data->append(m_vehicle->GetBase()->GetPackGUID());
- else if (GetTransport())
- data->append(GetTransport()->GetPackGUID());
- else
- {
- sLog.outError("Unit %u does not have transport!", GetEntry());
- *data << (uint8)0;
- }
- *data << float (GetTransOffsetX());
- *data << float (GetTransOffsetY());
- *data << float (GetTransOffsetZ());
- *data << float (GetTransOffsetO());
- *data << uint32(GetTransTime());
- *data << uint8 (GetTransSeat());
- }
-
- // 0x02200000
- if ((GetUnitMovementFlags() & (MOVEMENTFLAG_SWIMMING | MOVEMENTFLAG_FLYING))
- || (m_movementInfo.unk1 & 0x20))
- *data << (float)m_movementInfo.s_pitch;
-
- *data << (uint32)m_movementInfo.fallTime;
-
- // 0x00001000
- if (GetUnitMovementFlags() & MOVEMENTFLAG_JUMPING)
- {
- *data << (float)m_movementInfo.j_zspeed;
- *data << (float)m_movementInfo.j_sinAngle;
- *data << (float)m_movementInfo.j_cosAngle;
- *data << (float)m_movementInfo.j_xyspeed;
- }
-
- // 0x04000000
- if (GetUnitMovementFlags() & MOVEMENTFLAG_SPLINE)
- *data << (float)m_movementInfo.u_unk1;
-
- /*if (GetTypeId() == TYPEID_PLAYER)
- {
- sLog.outString("Send MovementInfo:");
- OutMovementInfo();
- }*/
-}
-
-void Unit::OutMovementInfo() const
-{
- sLog.outString("MovementInfo for %u: Flag %u, Unk1 %u, Time %u, Pos %f %f %f %f, Fall %u", GetEntry(), m_movementInfo.flags, (uint32)m_movementInfo.unk1, m_movementInfo.time, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation(), m_movementInfo.fallTime);
- if (m_movementInfo.flags & MOVEMENTFLAG_ONTRANSPORT)
- sLog.outString("Transport: GUID " UI64FMTD ", Pos %f %f %f %f, Time %u, Seat %d", m_movementInfo.t_guid, m_movementInfo.t_x, m_movementInfo.t_y, m_movementInfo.t_z, m_movementInfo.t_o, m_movementInfo.t_time, (int32)m_movementInfo.t_seat);
- if ((m_movementInfo.flags & (MOVEMENTFLAG_SWIMMING | MOVEMENTFLAG_FLYING)) || (m_movementInfo.unk1 & 0x20))
- sLog.outString("Pitch: %f", m_movementInfo.s_pitch);
- if (m_movementInfo.flags & MOVEMENTFLAG_JUMPING)
- sLog.outString("Jump: speedz %f, sin %f, cos %f, speedxy %f", m_movementInfo.j_zspeed, m_movementInfo.j_sinAngle, m_movementInfo.j_cosAngle, m_movementInfo.j_xyspeed);
- if (m_movementInfo.flags & MOVEMENTFLAG_SPLINE)
- sLog.outString("Spline: %f", m_movementInfo.u_unk1);
-}
-
-void Unit::SetFlying(bool apply)
-{
- if (apply)
- {
- SetByteFlag(UNIT_FIELD_BYTES_1, 3, 0x02);
- AddUnitMovementFlag(MOVEMENTFLAG_FLY_MODE | MOVEMENTFLAG_FLYING);
- }
- else
- {
- RemoveByteFlag(UNIT_FIELD_BYTES_1, 3, 0x02);
- RemoveUnitMovementFlag(MOVEMENTFLAG_FLY_MODE | MOVEMENTFLAG_FLYING);
- }
-}
-
-void Unit::NearTeleportTo( float x, float y, float z, float orientation, bool casting /*= false*/ )
-{
- if (GetTypeId() == TYPEID_PLAYER)
- ((Player*)this)->TeleportTo(GetMapId(), x, y, z, orientation, TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET | (casting ? TELE_TO_SPELL : 0));
- else
- {
- WorldPacket data;
- /*data.Initialize(MSG_MOVE_TELEPORT, 30);
- data.append(GetPackGUID());
- data << uint32(GetUnitMovementFlags());
- data << uint16(0); // Probably walk flags here
- data << getMSTime(); // time
- data << x; // destination coords
- data << y;
- data << z;
- data << orientation;
- data << uint32 (0);
- // Other information here: jumping angle etc
- SendMessageToSet(&data, false);*/
-
- // FIXME: this interrupts spell visual
- DestroyForNearbyPlayers();
-
- SetPosition(x, y, z, orientation, true);
- //ObjectAccessor::UpdateObjectVisibility(this);
-
- //WorldPacket data;
- // Work strange for many spells: triggered active mover set for targeted player to creature
- //BuildTeleportAckMsg(&data, x, y, z, orientation);
- //BuildHeartBeatMsg(&data);
- //SendMessageToSet(&data, false);
- }
-}
-
-bool Unit::SetPosition(float x, float y, float z, float orientation, bool teleport)
-{
- // prevent crash when a bad coord is sent by the client
- if (!Trinity::IsValidMapCoord(x,y))
- {
- sLog.outDebug("Unit::SetPosition(%f, %f, %f) .. bad coordinates!",x,y,z);
- return false;
- }
-
- bool turn = (GetOrientation() != orientation);
- bool relocated = (teleport || GetPositionX() != x || GetPositionY() != y || GetPositionZ() != z);
-
- if (turn)
- RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
-
- if (relocated)
- {
- RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE);
-
- // move and update visible state if need
- if(GetTypeId() == TYPEID_PLAYER)
- GetMap()->PlayerRelocation((Player*)this, x, y, z, orientation);
- else
- GetMap()->CreatureRelocation((Creature*)this, x, y, z, orientation);
- }
- else if(turn)
- SetOrientation(orientation);
-
- if ((relocated || turn) && IsVehicle())
- GetVehicleKit()->RelocatePassengers(x,y,z,orientation);
-
- return (relocated || turn);
-}
-
-void Unit::SendThreatListUpdate()
-{
- if (uint32 count = getThreatManager().getThreatList().size())
- {
- //sLog.outDebug( "WORLD: Send SMSG_THREAT_UPDATE Message" );
- WorldPacket data(SMSG_THREAT_UPDATE, 8 + count * 8);
- data.append(GetPackGUID());
- data << uint32(count);
- std::list<HostilReference*>& tlist = getThreatManager().getThreatList();
- for (std::list<HostilReference*>::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr)
- {
- data.appendPackGUID((*itr)->getUnitGuid());
- data << uint32((*itr)->getThreat());
- }
- SendMessageToSet(&data, false);
- }
-}
-
-void Unit::SendChangeCurrentVictimOpcode(HostilReference* pHostilReference)
-{
- if (uint32 count = getThreatManager().getThreatList().size())
- {
- sLog.outDebug( "WORLD: Send SMSG_HIGHEST_THREAT_UPDATE Message" );
- WorldPacket data(SMSG_HIGHEST_THREAT_UPDATE, 8 + 8 + count * 8);
- data.append(GetPackGUID());
- data.appendPackGUID(pHostilReference->getUnitGuid());
- data << uint32(count);
- std::list<HostilReference*>& tlist = getThreatManager().getThreatList();
- for (std::list<HostilReference*>::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr)
- {
- data.appendPackGUID((*itr)->getUnitGuid());
- data << uint32((*itr)->getThreat());
- }
- SendMessageToSet(&data, false);
- }
-}
-
-void Unit::SendClearThreatListOpcode()
-{
- sLog.outDebug( "WORLD: Send SMSG_THREAT_CLEAR Message" );
- WorldPacket data(SMSG_THREAT_CLEAR, 8);
- data.append(GetPackGUID());
- SendMessageToSet(&data, false);
-}
-
-void Unit::SendRemoveFromThreatListOpcode(HostilReference* pHostilReference)
-{
- sLog.outDebug( "WORLD: Send SMSG_THREAT_REMOVE Message" );
- WorldPacket data(SMSG_THREAT_REMOVE, 8 + 8);
- data.append(GetPackGUID());
- data.appendPackGUID(pHostilReference->getUnitGuid());
- SendMessageToSet(&data, false);
-}
-
-void Unit::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
-{
- float addRage;
-
- float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
-
- // Unknown if correct, but lineary adjust rage conversion above level 70
- if (getLevel() > 70)
- rageconversion += 13.27f*(getLevel()-70);
-
- if (attacker)
- {
- addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
-
- // talent who gave more rage on attack
- addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
- }
- else
- {
- addRage = damage/rageconversion*2.5;
-
- // Berserker Rage effect
- if (HasAura(18499))
- addRage *= 2.0;
- }
-
- addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
-
- ModifyPower(POWER_RAGE, uint32(addRage*10));
-}
-
-void Unit::StopAttackFaction(uint32 faction_id)
-{
- if (Unit* victim = getVictim())
- {
- if (victim->getFactionTemplateEntry()->faction==faction_id)
- {
- AttackStop();
- if (IsNonMeleeSpellCasted(false))
- InterruptNonMeleeSpells(false);
-
- // melee and ranged forced attack cancel
- if (GetTypeId() == TYPEID_PLAYER)
- ((Player*)this)->SendAttackSwingCancelAttack();
- }
- }
-
- AttackerSet const& attackers = getAttackers();
- for(AttackerSet::const_iterator itr = attackers.begin(); itr != attackers.end();)
- {
- if ((*itr)->getFactionTemplateEntry()->faction==faction_id)
- {
- (*itr)->AttackStop();
- itr = attackers.begin();
- }
- else
- ++itr;
- }
-
- getHostilRefManager().deleteReferencesForFaction(faction_id);
-
- for(ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
- (*itr)->StopAttackFaction(faction_id);
-}
-
-void Unit::OutDebugInfo() const
-{
- sLog.outError("Unit::OutDebugInfo");
- sLog.outString("GUID "UI64FMTD", entry %u, type %u, name %s", GetGUID(), GetEntry(), (uint32)GetTypeId(), GetName());
- sLog.outString("OwnerGUID "UI64FMTD", MinionGUID "UI64FMTD", CharmerGUID "UI64FMTD", CharmedGUID "UI64FMTD, GetOwnerGUID(), GetMinionGUID(), GetCharmerGUID(), GetCharmGUID());
- sLog.outString("In world %u, unit type mask %u", (uint32)(IsInWorld() ? 1 : 0), m_unitTypeMask);
-
- sLog.outStringInLine("Summon Slot: ");
- for (uint32 i = 0; i < MAX_SUMMON_SLOT; ++i)
- sLog.outStringInLine(UI64FMTD", ", m_SummonSlot[i]);
- sLog.outString();
-
- sLog.outStringInLine("Controlled List: ");
- for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
- sLog.outStringInLine(UI64FMTD", ", (*itr)->GetGUID());
- sLog.outString();
-
- sLog.outStringInLine("Aura List: ");
- for (AuraApplicationMap::const_iterator itr = m_appliedAuras.begin(); itr != m_appliedAuras.end(); ++itr)
- sLog.outStringInLine("%u, ", itr->first);
- sLog.outString();
-
- if (IsVehicle())
- {
- sLog.outStringInLine("Passenger List: ");
- for (SeatMap::iterator itr = GetVehicleKit()->m_Seats.begin(); itr != GetVehicleKit()->m_Seats.end(); ++itr)
- if (Unit *passenger = itr->second.passenger)
- sLog.outStringInLine(UI64FMTD", ", passenger->GetGUID());
- sLog.outString();
- }
-
- if (GetVehicle())
- sLog.outString("On vehicle %u.", GetVehicleBase()->GetEntry());
-}
-
-void CharmInfo::SetIsCommandAttack(bool val)
-{
- m_isCommandAttack = val;
-}
-
-bool CharmInfo::IsCommandAttack()
-{
- return m_isCommandAttack;
-}
-
-void CharmInfo::SaveStayPosition()
-{
- m_unit->GetPosition(m_stayX, m_stayY, m_stayZ);
-}
-
-void CharmInfo::GetStayPosition(float &x, float &y, float &z)
-{
- x = m_stayX;
- y = m_stayY;
- z = m_stayZ;
-}
-
-void CharmInfo::SetIsAtStay(bool val)
-{
- m_isAtStay = val;
-}
-
-bool CharmInfo::IsAtStay()
-{
- return m_isAtStay;
-}
-
-void CharmInfo::SetIsFollowing(bool val)
-{
- m_isFollowing = val;
-}
-
-bool CharmInfo::IsFollowing()
-{
- return m_isFollowing;
-}
-
-void CharmInfo::SetIsReturning(bool val)
-{
- m_isReturning = val;
-}
-
-bool CharmInfo::IsReturning()
-{
- return m_isReturning;
-}
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "Common.h"
+#include "Log.h"
+#include "Opcodes.h"
+#include "WorldPacket.h"
+#include "WorldSession.h"
+#include "World.h"
+#include "ObjectMgr.h"
+#include "SpellMgr.h"
+#include "Unit.h"
+#include "QuestDef.h"
+#include "Player.h"
+#include "Creature.h"
+#include "Spell.h"
+#include "Group.h"
+#include "SpellAuras.h"
+#include "SpellAuraEffects.h"
+#include "MapManager.h"
+#include "ObjectAccessor.h"
+#include "CreatureAI.h"
+#include "Formulas.h"
+#include "Pet.h"
+#include "Util.h"
+#include "Totem.h"
+#include "BattleGround.h"
+#include "OutdoorPvP.h"
+#include "InstanceSaveMgr.h"
+#include "GridNotifiersImpl.h"
+#include "CellImpl.h"
+#include "Path.h"
+#include "CreatureGroups.h"
+#include "PetAI.h"
+#include "PassiveAI.h"
+#include "Traveller.h"
+#include "TemporarySummon.h"
+#include "Vehicle.h"
+#include "Transports.h"
+
+#include <math.h>
+
+float baseMoveSpeed[MAX_MOVE_TYPE] =
+{
+ 2.5f, // MOVE_WALK
+ 7.0f, // MOVE_RUN
+ 2.5f, // MOVE_RUN_BACK
+ 4.722222f, // MOVE_SWIM
+ 4.5f, // MOVE_SWIM_BACK
+ 3.141594f, // MOVE_TURN_RATE
+ 7.0f, // MOVE_FLIGHT
+ 4.5f, // MOVE_FLIGHT_BACK
+ 3.14f // MOVE_PITCH_RATE
+};
+float playerBaseMoveSpeed[MAX_MOVE_TYPE] = {
+ 2.5f, // MOVE_WALK
+ 7.0f, // MOVE_RUN
+ 2.5f, // MOVE_RUN_BACK
+ 4.722222f, // MOVE_SWIM
+ 4.5f, // MOVE_SWIM_BACK
+ 3.141594f, // MOVE_TURN_RATE
+ 7.0f, // MOVE_FLIGHT
+ 4.5f, // MOVE_FLIGHT_BACK
+ 3.14f // MOVE_PITCH_RATE
+};
+
+// Used for prepare can/can`t triggr aura
+static bool InitTriggerAuraData();
+// Define can trigger auras
+static bool isTriggerAura[TOTAL_AURAS];
+// Define can`t trigger auras (need for disable second trigger)
+static bool isNonTriggerAura[TOTAL_AURAS];
+// Prepare lists
+static bool procPrepared = InitTriggerAuraData();
+
+Unit::Unit()
+: WorldObject(), i_motionMaster(this), m_ThreatManager(this), m_HostilRefManager(this)
+, IsAIEnabled(false), NeedChangeAI(false)
+, i_AI(NULL), i_disabledAI(NULL), m_removedAurasCount(0), m_vehicle(NULL), m_transport(NULL)
+, m_ControlledByPlayer(false), m_procDeep(0), m_unitTypeMask(UNIT_MASK_NONE), m_vehicleKit(NULL)
+, m_movedPlayer(NULL)
+{
+ m_objectType |= TYPEMASK_UNIT;
+ m_objectTypeId = TYPEID_UNIT;
+
+ m_updateFlag = (UPDATEFLAG_HIGHGUID | UPDATEFLAG_LIVING | UPDATEFLAG_HAS_POSITION);
+
+ m_attackTimer[BASE_ATTACK] = 0;
+ m_attackTimer[OFF_ATTACK] = 0;
+ m_attackTimer[RANGED_ATTACK] = 0;
+ m_modAttackSpeedPct[BASE_ATTACK] = 1.0f;
+ m_modAttackSpeedPct[OFF_ATTACK] = 1.0f;
+ m_modAttackSpeedPct[RANGED_ATTACK] = 1.0f;
+
+ m_extraAttacks = 0;
+ m_canDualWield = false;
+
+ m_state = 0;
+ m_form = FORM_NONE;
+ m_deathState = ALIVE;
+
+ for (uint8 i = 0; i < CURRENT_MAX_SPELL; ++i)
+ m_currentSpells[i] = NULL;
+
+ m_addDmgOnce = 0;
+
+ for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i)
+ m_SummonSlot[i] = 0;
+
+ m_ObjectSlot[0] = m_ObjectSlot[1] = m_ObjectSlot[2] = m_ObjectSlot[3] = 0;
+
+ m_auraUpdateIterator = m_ownedAuras.end();
+ m_Visibility = VISIBILITY_ON;
+
+ m_interruptMask = 0;
+ m_detectInvisibilityMask = 0;
+ m_invisibilityMask = 0;
+ m_transform = 0;
+ m_ShapeShiftFormSpellId = 0;
+ m_canModifyStats = false;
+
+ for (uint8 i = 0; i < MAX_SPELL_IMMUNITY; ++i)
+ m_spellImmune[i].clear();
+ for (uint8 i = 0; i < UNIT_MOD_END; ++i)
+ {
+ m_auraModifiersGroup[i][BASE_VALUE] = 0.0f;
+ m_auraModifiersGroup[i][BASE_PCT] = 1.0f;
+ m_auraModifiersGroup[i][TOTAL_VALUE] = 0.0f;
+ m_auraModifiersGroup[i][TOTAL_PCT] = 1.0f;
+ }
+ // implement 50% base damage from offhand
+ m_auraModifiersGroup[UNIT_MOD_DAMAGE_OFFHAND][TOTAL_PCT] = 0.5f;
+
+ for (uint8 i = 0; i < MAX_ATTACK; ++i)
+ {
+ m_weaponDamage[i][MINDAMAGE] = BASE_MINDAMAGE;
+ m_weaponDamage[i][MAXDAMAGE] = BASE_MAXDAMAGE;
+ }
+ for (uint8 i = 0; i < MAX_STATS; ++i)
+ m_createStats[i] = 0.0f;
+
+ m_attacking = NULL;
+ m_modMeleeHitChance = 0.0f;
+ m_modRangedHitChance = 0.0f;
+ m_modSpellHitChance = 0.0f;
+ m_baseSpellCritChance = 5;
+
+ m_CombatTimer = 0;
+ m_lastManaUse = 0;
+
+ //m_victimThreat = 0.0f;
+ for (uint8 i = 0; i < MAX_SPELL_SCHOOL; ++i)
+ m_threatModifier[i] = 1.0f;
+ m_isSorted = true;
+ for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i)
+ m_speed_rate[i] = 1.0f;
+
+ m_charmInfo = NULL;
+ //m_unit_movement_flags = 0;
+ m_reducedThreatPercent = 0;
+ m_misdirectionTargetGUID = 0;
+
+ // remove aurastates allowing special moves
+ for (uint8 i = 0; i < MAX_REACTIVE; ++i)
+ m_reactiveTimer[i] = 0;
+
+ m_cleanupDone = false;
+}
+
+Unit::~Unit()
+{
+ // set current spells as deletable
+ for (uint8 i = 0; i < CURRENT_MAX_SPELL; ++i)
+ {
+ if (m_currentSpells[i])
+ {
+ m_currentSpells[i]->SetReferencedFromCurrent(false);
+ m_currentSpells[i] = NULL;
+ }
+ }
+
+ RemoveAllGameObjects();
+ RemoveAllDynObjects();
+ _DeleteRemovedAuras();
+
+ if (m_charmInfo)
+ delete m_charmInfo;
+ if (m_vehicleKit)
+ delete m_vehicleKit;
+
+ assert(!m_attacking);
+ assert(m_attackers.empty());
+ assert(m_sharedVision.empty());
+ assert(m_Controlled.empty());
+ assert(m_appliedAuras.empty());
+ assert(m_ownedAuras.empty());
+ assert(m_removedAuras.empty());
+}
+
+void Unit::Update(uint32 p_time)
+{
+ /*if (p_time > m_AurasCheck)
+ {
+ m_AurasCheck = 2000;
+ _UpdateAura();
+ } else
+ m_AurasCheck -= p_time;*/
+
+ // WARNING! Order of execution here is important, do not change.
+ // Spells must be processed with event system BEFORE they go to _UpdateSpells.
+ // Or else we may have some SPELL_STATE_FINISHED spells stalled in pointers, that is bad.
+ m_Events.Update(p_time);
+
+ if (!IsInWorld())
+ return;
+
+ _UpdateSpells(p_time);
+
+ // If this is set during update SetCantProc(false) call is missing somewhere in the code
+ // Having this would prevent spells from being proced, so let's crash
+ assert(!m_procDeep);
+
+ if (CanHaveThreatList() && getThreatManager().isNeedUpdateToClient(p_time))
+ SendThreatListUpdate();
+
+ // update combat timer only for players and pets (only pets with PetAI)
+ if (isInCombat() && (GetTypeId() == TYPEID_PLAYER || (((Creature *)this)->isPet() && IsControlledByPlayer())))
+ {
+ // Check UNIT_STAT_MELEE_ATTACKING or UNIT_STAT_CHASE (without UNIT_STAT_FOLLOW in this case) so pets can reach far away
+ // targets without stopping half way there and running off.
+ // These flags are reset after target dies or another command is given.
+ if (m_HostilRefManager.isEmpty())
+ {
+ // m_CombatTimer set at aura start and it will be freeze until aura removing
+ if (m_CombatTimer <= p_time)
+ ClearInCombat();
+ else
+ m_CombatTimer -= p_time;
+ }
+ }
+
+ //not implemented before 3.0.2
+ //if (!hasUnitState(UNIT_STAT_CASTING))
+ {
+ if (uint32 base_att = getAttackTimer(BASE_ATTACK))
+ setAttackTimer(BASE_ATTACK, (p_time >= base_att ? 0 : base_att - p_time));
+ if (uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
+ setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time));
+ if (uint32 off_att = getAttackTimer(OFF_ATTACK))
+ setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time));
+ }
+
+ // update abilities available only for fraction of time
+ UpdateReactives(p_time);
+
+ ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, GetHealth() < GetMaxHealth()*0.20f);
+ ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, GetHealth() < GetMaxHealth()*0.35f);
+ ModifyAuraState(AURA_STATE_HEALTH_ABOVE_75_PERCENT, GetHealth() > GetMaxHealth()*0.75f);
+
+ i_motionMaster.UpdateMotion(p_time);
+}
+
+bool Unit::haveOffhandWeapon() const
+{
+ if (GetTypeId() == TYPEID_PLAYER)
+ return ((Player*)this)->GetWeaponForAttack(OFF_ATTACK,true);
+ else
+ return m_canDualWield;
+}
+
+void Unit::SendMonsterMoveWithSpeedToCurrentDestination(Player* player)
+{
+ float x, y, z;
+ if (GetMotionMaster()->GetDestination(x, y, z))
+ SendMonsterMoveWithSpeed(x, y, z, 0, player);
+}
+
+void Unit::SendMonsterMoveWithSpeed(float x, float y, float z, uint32 transitTime, Player* player)
+{
+ if (!transitTime)
+ {
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ Traveller<Player> traveller(*(Player*)this);
+ transitTime = traveller.GetTotalTrevelTimeTo(x,y,z);
+ }
+ else
+ {
+ Traveller<Creature> traveller(*(Creature*)this);
+ transitTime = traveller.GetTotalTrevelTimeTo(x,y,z);
+ }
+ }
+ //float orientation = (float)atan2((double)dy, (double)dx);
+ SendMonsterMove(x, y, z, transitTime, player);
+}
+
+void Unit::SendMonsterStop()
+{
+ WorldPacket data(SMSG_MONSTER_MOVE, (17 + GetPackGUID().size()));
+ data.append(GetPackGUID());
+ data << uint8(0); // new in 3.1
+ data << GetPositionX() << GetPositionY() << GetPositionZ();
+ data << getMSTime();
+ data << uint8(1);
+ SendMessageToSet(&data, true);
+
+ clearUnitState(UNIT_STAT_MOVE);
+}
+
+void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint32 Time, Player* player)
+{
+ WorldPacket data( SMSG_MONSTER_MOVE, 1+12+4+1+4+4+4+12+GetPackGUID().size());
+ data.append(GetPackGUID());
+
+ data << uint8(0); // new in 3.1
+ data << GetPositionX() << GetPositionY() << GetPositionZ();
+ data << getMSTime();
+
+ data << uint8(0);
+ data << uint32((GetUnitMovementFlags() & MOVEMENTFLAG_LEVITATING) ? MOVEFLAG_FLY : MOVEFLAG_WALK);
+ data << Time; // Time in between points
+ data << uint32(1); // 1 single waypoint
+ data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B
+
+ if (player)
+ player->GetSession()->SendPacket(&data);
+ else
+ SendMessageToSet(&data, true);
+
+ addUnitState(UNIT_STAT_MOVE);
+}
+
+void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint32 MoveFlags, uint32 time, float speedZ, Player *player)
+{
+ WorldPacket data( SMSG_MONSTER_MOVE, 12+4+1+4+4+4+12+GetPackGUID().size());
+ data.append(GetPackGUID());
+
+ data << uint8(0); // new in 3.1
+ data << GetPositionX() << GetPositionY() << GetPositionZ();
+ data << getMSTime();
+
+ data << uint8(0);
+ data << MoveFlags;
+
+ if (MoveFlags & MOVEFLAG_JUMP)
+ {
+ data << time;
+ data << speedZ;
+ data << (uint32)0; // walk time after jump
+ }
+ else
+ data << time;
+
+ data << uint32(1); // 1 single waypoint
+ data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B
+
+ if (player)
+ player->GetSession()->SendPacket(&data);
+ else
+ SendMessageToSet(&data, true);
+}
+
+/*void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint8 type, uint32 MovementFlags, uint32 Time, Player* player)
+{
+ float moveTime = Time;
+
+ WorldPacket data(SMSG_MONSTER_MOVE, (41 + GetPackGUID().size()));
+ data.append(GetPackGUID());
+ data << uint8(0); // new in 3.1
+ data << GetPositionX() << GetPositionY() << GetPositionZ();
+ data << uint32(getMSTime());
+
+ data << uint8(type); // unknown
+ switch(type)
+ {
+ case 0: // normal packet
+ break;
+ case 1: // stop packet (raw pos?)
+ SendMessageToSet(&data, true);
+ return;
+ case 2: // facing spot, not used currently
+ data << float(0);
+ data << float(0);
+ data << float(0);
+ break;
+ case 3: // not used currently
+ data << uint64(0); // probably target guid (facing target?)
+ break;
+ case 4: // not used currently
+ data << float(0); // facing angle
+ break;
+ }
+
+ data << uint32(MovementFlags);
+
+ if (MovementFlags & MONSTER_MOVE_WALK)
+ moveTime *= 1.05f;
+
+ data << uint32(moveTime); // Time in between points
+ data << uint32(1); // 1 single waypoint
+ data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B
+
+ if (player)
+ player->GetSession()->SendPacket(&data);
+ else
+ SendMessageToSet(&data, true);
+}*/
+
+void Unit::SendMonsterMoveByPath(Path const& path, uint32 start, uint32 end)
+{
+ uint32 traveltime = uint32(path.GetTotalLength(start, end) * 32);
+
+ uint32 pathSize = end - start;
+
+ WorldPacket data( SMSG_MONSTER_MOVE, (GetPackGUID().size()+1+4+4+4+4+1+4+4+4+pathSize*4*3) );
+ data.append(GetPackGUID());
+ data << uint8(0);
+ data << GetPositionX();
+ data << GetPositionY();
+ data << GetPositionZ();
+ data << uint32(getMSTime());
+ data << uint8( 0 );
+ data << uint32(((GetUnitMovementFlags() & MOVEMENTFLAG_LEVITATING) || isInFlight())? (MOVEFLAG_FLY|MOVEFLAG_WALK) : MOVEFLAG_WALK);
+ data << uint32( traveltime );
+ data << uint32( pathSize );
+ data.append((char*)path.GetNodes(start), pathSize * 4 * 3);
+ SendMessageToSet(&data, true);
+//MONSTER_MOVE_SPLINE_FLY
+ addUnitState(UNIT_STAT_MOVE);
+}
+
+void Unit::SendMonsterMoveTransport(Unit *vehicleOwner)
+{
+ WorldPacket data(SMSG_MONSTER_MOVE_TRANSPORT, GetPackGUID().size()+vehicleOwner->GetPackGUID().size());
+ data.append(GetPackGUID());
+ data.append(vehicleOwner->GetPackGUID());
+ data << int8(GetTransSeat());
+ data << uint8(0);
+ data << GetPositionX() - vehicleOwner->GetPositionX();
+ data << GetPositionY() - vehicleOwner->GetPositionY();
+ data << GetPositionZ() - vehicleOwner->GetPositionZ();
+ data << uint32(getMSTime());
+ data << uint8(4);
+ data << GetTransOffsetO();
+ data << uint32(MOVEFLAG_ENTER_TRANSPORT);
+ data << uint32(0);// move time
+ data << uint32(0);//GetTransOffsetX();
+ data << uint32(0);//GetTransOffsetY();
+ data << uint32(0);//GetTransOffsetZ();
+ SendMessageToSet(&data, true);
+}
+
+void Unit::resetAttackTimer(WeaponAttackType type)
+{
+ m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]);
+}
+
+bool Unit::IsWithinCombatRange(const Unit *obj, float dist2compare) const
+{
+ if (!obj || !IsInMap(obj)) return false;
+
+ float dx = GetPositionX() - obj->GetPositionX();
+ float dy = GetPositionY() - obj->GetPositionY();
+ float dz = GetPositionZ() - obj->GetPositionZ();
+ float distsq = dx*dx + dy*dy + dz*dz;
+
+ float sizefactor = GetCombatReach() + obj->GetCombatReach();
+ float maxdist = dist2compare + sizefactor;
+
+ return distsq < maxdist * maxdist;
+}
+
+bool Unit::IsWithinMeleeRange(const Unit *obj, float dist) const
+{
+ if (!obj || !IsInMap(obj)) return false;
+
+ float dx = GetPositionX() - obj->GetPositionX();
+ float dy = GetPositionY() - obj->GetPositionY();
+ float dz = GetPositionZ() - obj->GetPositionZ();
+ float distsq = dx*dx + dy*dy + dz*dz;
+
+ float sizefactor = GetMeleeReach() + obj->GetMeleeReach();
+ float maxdist = dist + sizefactor;
+
+ return distsq < maxdist * maxdist;
+}
+
+void Unit::GetRandomContactPoint(const Unit* obj, float &x, float &y, float &z, float distance2dMin, float distance2dMax) const
+{
+ float combat_reach = GetCombatReach();
+ if(combat_reach < 0.1) // sometimes bugged for players
+ {
+ //sLog.outError("Unit %u (Type: %u) has invalid combat_reach %f",GetGUIDLow(),GetTypeId(),combat_reach);
+ //if (GetTypeId() == TYPEID_UNIT)
+ // sLog.outError("Creature entry %u has invalid combat_reach", ((Creature*)this)->GetEntry());
+ combat_reach = DEFAULT_COMBAT_REACH;
+ }
+ uint32 attacker_number = getAttackers().size();
+ if (attacker_number > 0)
+ --attacker_number;
+ GetNearPoint(obj,x,y,z,obj->GetCombatReach(), distance2dMin+(distance2dMax-distance2dMin)*rand_norm()
+ , GetAngle(obj) + (attacker_number ? (M_PI/2 - M_PI * rand_norm()) * float(attacker_number) / combat_reach * 0.3 : 0));
+}
+
+void Unit::UpdateInterruptMask()
+{
+ m_interruptMask = 0;
+ for(AuraApplicationList::const_iterator i = m_interruptableAuras.begin(); i != m_interruptableAuras.end(); ++i)
+ m_interruptMask |= (*i)->GetBase()->GetSpellProto()->AuraInterruptFlags;
+
+ if (Spell* spell = m_currentSpells[CURRENT_CHANNELED_SPELL])
+ if (spell->getState() == SPELL_STATE_CASTING)
+ m_interruptMask |= spell->m_spellInfo->ChannelInterruptFlags;
+}
+
+bool Unit::HasAuraTypeWithFamilyFlags(AuraType auraType, uint32 familyName, uint32 familyFlags) const
+{
+ if (!HasAuraType(auraType))
+ return false;
+ AuraEffectList const &auras = GetAuraEffectsByType(auraType);
+ for (AuraEffectList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
+ if (SpellEntry const *iterSpellProto = (*itr)->GetSpellProto())
+ if (iterSpellProto->SpellFamilyName == familyName && iterSpellProto->SpellFamilyFlags[0] & familyFlags)
+ return true;
+ return false;
+}
+
+void Unit::DealDamageMods(Unit *pVictim, uint32 &damage, uint32* absorb)
+{
+ if (!pVictim->isAlive() || pVictim->hasUnitState(UNIT_STAT_UNATTACKABLE) || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
+ {
+ if (absorb)
+ absorb += damage;
+ damage = 0;
+ return;
+ }
+
+ //You don't lose health from damage taken from another player while in a sanctuary
+ //You still see it in the combat log though
+ if (pVictim != this && IsControlledByPlayer() && pVictim->IsControlledByPlayer())
+ {
+ const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
+ if (area && area->IsSanctuary()) //sanctuary
+ {
+ if (absorb)
+ absorb += damage;
+ damage = 0;
+ }
+ }
+
+ uint32 originalDamage = damage;
+
+ //Script Event damage Deal
+ //if (GetTypeId() == TYPEID_UNIT && ((Creature *)this)->AI())
+ // ((Creature *)this)->AI()->DamageDeal(pVictim, damage);
+ //Script Event damage taken
+ //if (pVictim->GetTypeId() == TYPEID_UNIT && ((Creature *)pVictim)->IsAIEnabled)
+ // ((Creature *)pVictim)->AI()->DamageTaken(this, damage);
+
+ if (absorb && originalDamage > damage)
+ absorb += (originalDamage - damage);
+}
+
+uint32 Unit::DealDamage(Unit *pVictim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellEntry const *spellProto, bool durabilityLoss)
+{
+ // if attacker is a player and spell is not empty/fail
+ if (GetTypeId() == TYPEID_PLAYER && spellProto)
+ {
+ // on divine storm dealed damage - heal
+ if (spellProto->SpellFamilyName == SPELLFAMILY_PALADIN && spellProto->SpellFamilyFlags[1] & 0x20000)
+ {
+ Unit *pRaidGrpMember = GetNextRandomRaidMemberOrPet(30.0f);
+
+ int32 divineDmg = damage * (25 + (HasAura(63220) ? 15 : 0)) / 100; //25%, if has Glyph of Divine Storm -> 40%
+
+ if (!pRaidGrpMember)
+ pRaidGrpMember = this;
+
+ CastCustomSpell(pRaidGrpMember, 54172, &divineDmg, 0, 0, true);
+ }
+ }
+
+ if (pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsAIEnabled)
+ ((Creature*)pVictim)->AI()->DamageTaken(this, damage);
+
+ if (damagetype != NODAMAGE)
+ {
+ // interrupting auras with AURA_INTERRUPT_FLAG_DAMAGE before checking !damage (absorbed damage breaks that type of auras)
+ pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TAKE_DAMAGE, spellProto ? spellProto->Id : 0);
+ }
+
+
+ // Rage from Damage made (only from direct weapon damage)
+ if (cleanDamage && damagetype==DIRECT_DAMAGE && this != pVictim && getPowerType() == POWER_RAGE)
+ {
+ uint32 weaponSpeedHitFactor;
+ uint32 rage_damage = damage + cleanDamage->absorbed_damage;
+
+ switch(cleanDamage->attackType)
+ {
+ case BASE_ATTACK:
+ {
+ if (cleanDamage->hitOutCome == MELEE_HIT_CRIT)
+ weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 7);
+ else
+ weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
+
+ RewardRage(rage_damage, weaponSpeedHitFactor, true);
+
+ break;
+ }
+ case OFF_ATTACK:
+ {
+ if (cleanDamage->hitOutCome == MELEE_HIT_CRIT)
+ weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
+ else
+ weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 1.75f);
+
+ RewardRage(rage_damage, weaponSpeedHitFactor, true);
+
+ break;
+ }
+ case RANGED_ATTACK:
+ break;
+ }
+ }
+
+ if (!damage)
+ {
+ // Rage from absorbed damage
+ if (cleanDamage && cleanDamage->absorbed_damage && pVictim->getPowerType() == POWER_RAGE)
+ pVictim->RewardRage(cleanDamage->absorbed_damage, 0, false);
+
+ return 0;
+ }
+
+ // no xp,health if type 8 /critters/
+ if (pVictim->GetTypeId() != TYPEID_PLAYER && pVictim->GetCreatureType() == CREATURE_TYPE_CRITTER)
+ {
+ // allow loot only if has loot_id in creature_template
+ if (damage >= pVictim->GetHealth())
+ {
+ pVictim->setDeathState(JUST_DIED);
+ pVictim->SetHealth(0);
+
+ CreatureInfo const* cInfo = ((Creature*)pVictim)->GetCreatureInfo();
+ if (cInfo && cInfo->lootid)
+ pVictim->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
+
+ // some critters required for quests (need normal entry instead possible heroic in any cases)
+ if (GetTypeId() == TYPEID_PLAYER)
+ if (CreatureInfo const* normalInfo = objmgr.GetCreatureTemplate(pVictim->GetEntry()))
+ ((Player*)this)->KilledMonster(normalInfo,pVictim->GetGUID());
+ }
+ else
+ pVictim->ModifyHealth(- (int32)damage);
+
+ return damage;
+ }
+
+ DEBUG_LOG("DealDamageStart");
+
+ uint32 health = pVictim->GetHealth();
+ sLog.outDetail("deal dmg:%d to health:%d ",damage,health);
+
+ // duel ends when player has 1 or less hp
+ bool duel_hasEnded = false;
+ if (pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->duel && damage >= (health-1))
+ {
+ // prevent kill only if killed in duel and killed by opponent or opponent controlled creature
+ if (((Player*)pVictim)->duel->opponent==this || ((Player*)pVictim)->duel->opponent->GetGUID() == GetOwnerGUID())
+ damage = health-1;
+
+ duel_hasEnded = true;
+ }
+
+ if (GetTypeId() == TYPEID_PLAYER && this != pVictim)
+ {
+ Player *killer = ((Player*)this);
+
+ // in bg, count dmg if victim is also a player
+ if (pVictim->GetTypeId() == TYPEID_PLAYER)
+ {
+ if (BattleGround *bg = killer->GetBattleGround())
+ {
+ // FIXME: kept by compatibility. don't know in BG if the restriction apply.
+ bg->UpdatePlayerScore(killer, SCORE_DAMAGE_DONE, damage);
+ }
+ }
+
+ killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE, damage, 0, pVictim);
+ killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT, damage);
+ }
+
+ if (pVictim->GetTypeId() == TYPEID_PLAYER)
+ ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED, damage);
+ else if (!pVictim->IsControlledByPlayer())
+ {
+ //!pVictim->HasFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_OTHER_TAGGER)
+ if (!((Creature*)pVictim)->hasLootRecipient())
+ ((Creature*)pVictim)->SetLootRecipient(this);
+
+ if (IsControlledByPlayer())
+ ((Creature*)pVictim)->LowerPlayerDamageReq(health < damage ? health : damage);
+ }
+
+ if (health <= damage)
+ {
+ DEBUG_LOG("DealDamage: victim just died");
+
+ if (pVictim->GetTypeId() == TYPEID_PLAYER)
+ ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, health);
+
+ Kill(pVictim, durabilityLoss);
+
+ //Hook for OnPVPKill Event
+ if (pVictim->GetTypeId() == TYPEID_PLAYER && this->GetTypeId() == TYPEID_PLAYER)
+ {
+ Player *killer = ((Player*)this);
+ Player *killed = ((Player*)pVictim);
+ killer->GetSession()->HandleOnPVPKill(killed);
+ }
+ if (pVictim->GetTypeId() == TYPEID_UNIT && this->GetTypeId() == TYPEID_PLAYER)
+ {
+ Player *killer = ((Player*)this);
+ Creature *pCreature = ((Creature*)pVictim);
+ killer->GetSession()->HandleOnCreatureKill(pCreature);
+ }
+ }
+ else // if (health <= damage)
+ {
+ DEBUG_LOG("DealDamageAlive");
+
+ if (pVictim->GetTypeId() == TYPEID_PLAYER)
+ ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, damage);
+
+ pVictim->ModifyHealth(- (int32)damage);
+
+ if (damagetype == DIRECT_DAMAGE || damagetype == SPELL_DIRECT_DAMAGE)
+ {
+ //TODO: This is from procflag, I do not know which spell needs this
+ //Maim?
+ //if (!spellProto || !(spellProto->AuraInterruptFlags&AURA_INTERRUPT_FLAG_DIRECT_DAMAGE))
+ pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DIRECT_DAMAGE, spellProto ? spellProto->Id : 0);
+ }
+ if (pVictim->GetTypeId() != TYPEID_PLAYER)
+ {
+ if (spellProto && IsDamageToThreatSpell(spellProto))
+ pVictim->AddThreat(this, damage*2, damageSchoolMask, spellProto);
+ else
+ pVictim->AddThreat(this, damage, damageSchoolMask, spellProto);
+ }
+ else // victim is a player
+ {
+ // random durability for items (HIT TAKEN)
+ if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
+ {
+ EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
+ ((Player*)pVictim)->DurabilityPointLossForEquipSlot(slot);
+ }
+ }
+
+ // Rage from damage received
+ if (this != pVictim && pVictim->getPowerType() == POWER_RAGE)
+ {
+ uint32 rage_damage = damage + (cleanDamage ? cleanDamage->absorbed_damage : 0);
+ pVictim->RewardRage(rage_damage, 0, false);
+ }
+
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ // random durability for items (HIT DONE)
+ if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
+ {
+ EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
+ ((Player*)this)->DurabilityPointLossForEquipSlot(slot);
+ }
+ }
+
+ if (damagetype != NODAMAGE && damage)// && pVictim->GetTypeId() == TYPEID_PLAYER)
+ {
+ if (pVictim != this && pVictim->GetTypeId() == TYPEID_PLAYER) // does not support creature push_back
+ {
+ if (damagetype != DOT)
+ {
+ if (Spell* spell = pVictim->m_currentSpells[CURRENT_GENERIC_SPELL])
+ {
+ if (spell->getState() == SPELL_STATE_PREPARING)
+ {
+ uint32 interruptFlags = spell->m_spellInfo->InterruptFlags;
+ if (interruptFlags & SPELL_INTERRUPT_FLAG_ABORT_ON_DMG)
+ pVictim->InterruptNonMeleeSpells(false);
+ else if (interruptFlags & SPELL_INTERRUPT_FLAG_PUSH_BACK)
+ spell->Delayed();
+ }
+ }
+ }
+
+ if (Spell* spell = pVictim->m_currentSpells[CURRENT_CHANNELED_SPELL])
+ {
+ if (spell->getState() == SPELL_STATE_CASTING)
+ {
+ uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags;
+ if (channelInterruptFlags & CHANNEL_FLAG_DELAY)
+ spell->DelayedChannel();
+ }
+ }
+ }
+ }
+
+ // last damage from duel opponent
+ if (duel_hasEnded)
+ {
+ assert(pVictim->GetTypeId() == TYPEID_PLAYER);
+ Player *he = (Player*)pVictim;
+
+ assert(he->duel);
+
+ he->SetHealth(1);
+
+ he->duel->opponent->CombatStopWithPets(true);
+ he->CombatStopWithPets(true);
+
+ he->CastSpell(he, 7267, true); // beg
+ he->DuelComplete(DUEL_WON);
+ }
+ }
+
+ DEBUG_LOG("DealDamageEnd returned %d damage", damage);
+
+ return damage;
+}
+
+void Unit::CastStop(uint32 except_spellid)
+{
+ for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
+ if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id!=except_spellid)
+ InterruptSpell(CurrentSpellTypes(i),false);
+}
+
+void Unit::CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem, AuraEffect const * triggeredByAura, uint64 originalCaster)
+{
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
+
+ if (!spellInfo)
+ {
+ sLog.outError("CastSpell: unknown spell id %i by caster: %s %u)", spellId,(GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
+ return;
+ }
+
+ CastSpell(Victim,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
+}
+
+void Unit::CastSpell(Unit* Victim,SpellEntry const *spellInfo, bool triggered, Item *castItem, AuraEffect const * triggeredByAura, uint64 originalCaster)
+{
+ if (!spellInfo)
+ {
+ sLog.outError("CastSpell: unknown spell by caster: %s %u)", (GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
+ return;
+ }
+
+ if (!originalCaster && GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isTotem() && IsControlledByPlayer())
+ if (Unit * owner = GetOwner())
+ originalCaster=owner->GetGUID();
+
+ SpellCastTargets targets;
+ uint32 targetMask = spellInfo->Targets;
+ //if (targetMask & (TARGET_FLAG_UNIT|TARGET_FLAG_UNK2))
+ for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
+ {
+ if (SpellTargetType[spellInfo->EffectImplicitTargetA[i]] == TARGET_TYPE_UNIT_TARGET)
+ {
+ /*SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
+ if (srange && GetSpellMaxRange(srange) == 0.0f)
+ {
+ Victim = this;
+ break;
+ }
+ else */if (!Victim)
+ {
+ sLog.outError("CastSpell: spell id %i by caster: %s %u) does not have unit target", spellInfo->Id,(GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
+ return;
+ }
+ else
+ break;
+ }
+ }
+ targets.setUnitTarget(Victim);
+
+ if (targetMask & (TARGET_FLAG_SOURCE_LOCATION|TARGET_FLAG_DEST_LOCATION))
+ {
+ if (!Victim)
+ {
+ sLog.outError("CastSpell: spell id %i by caster: %s %u) does not have destination", spellInfo->Id,(GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
+ return;
+ }
+ targets.setDst(Victim);
+ }
+
+ if (castItem)
+ DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
+
+ if (!originalCaster && triggeredByAura)
+ originalCaster = triggeredByAura->GetCasterGUID();
+
+ Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
+
+ spell->m_CastItem = castItem;
+ spell->prepare(&targets, triggeredByAura);
+}
+
+void Unit::CastCustomSpell(Unit* target, uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, AuraEffect const * triggeredByAura, uint64 originalCaster)
+{
+ CustomSpellValues values;
+ if (bp0)
+ values.AddSpellMod(SPELLVALUE_BASE_POINT0, *bp0);
+ if (bp1)
+ values.AddSpellMod(SPELLVALUE_BASE_POINT1, *bp1);
+ if (bp2)
+ values.AddSpellMod(SPELLVALUE_BASE_POINT2, *bp2);
+ CastCustomSpell(spellId, values, target, triggered, castItem, triggeredByAura, originalCaster);
+}
+
+void Unit::CastCustomSpell(uint32 spellId, SpellValueMod mod, int32 value, Unit* target, bool triggered, Item *castItem, AuraEffect const * triggeredByAura, uint64 originalCaster)
+{
+ CustomSpellValues values;
+ values.AddSpellMod(mod, value);
+ CastCustomSpell(spellId, values, target, triggered, castItem, triggeredByAura, originalCaster);
+}
+
+void Unit::CastCustomSpell(uint32 spellId, CustomSpellValues const &value, Unit* Victim, bool triggered, Item *castItem, AuraEffect const * triggeredByAura, uint64 originalCaster)
+{
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
+ if (!spellInfo)
+ {
+ sLog.outError("CastSpell: unknown spell id %i by caster: %s %u)", spellId,(GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
+ return;
+ }
+
+ SpellCastTargets targets;
+ uint32 targetMask = spellInfo->Targets;
+
+ //check unit target
+ for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
+ {
+ if (SpellTargetType[spellInfo->EffectImplicitTargetA[i]] == TARGET_TYPE_UNIT_TARGET)
+ {
+ if (!Victim)
+ {
+ sLog.outError("CastSpell: spell id %i by caster: %s %u) does not have unit target", spellInfo->Id,(GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
+ return;
+ }
+ else
+ break;
+ }
+ }
+ targets.setUnitTarget(Victim);
+
+ //check destination
+ if (targetMask & (TARGET_FLAG_SOURCE_LOCATION|TARGET_FLAG_DEST_LOCATION))
+ {
+ if (!Victim)
+ {
+ sLog.outError("CastSpell: spell id %i by caster: %s %u) does not have destination", spellInfo->Id,(GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
+ return;
+ }
+ targets.setDst(Victim);
+ }
+
+ if (!originalCaster && triggeredByAura)
+ originalCaster = triggeredByAura->GetCasterGUID();
+
+ Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
+
+ if (castItem)
+ {
+ DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
+ spell->m_CastItem = castItem;
+ }
+
+ for (CustomSpellValues::const_iterator itr = value.begin(); itr != value.end(); ++itr)
+ spell->SetSpellValue(itr->first, itr->second);
+
+ spell->prepare(&targets, triggeredByAura);
+}
+
+// used for scripting
+void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item *castItem, AuraEffect const * triggeredByAura, uint64 originalCaster, Unit* OriginalVictim)
+{
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
+
+ if (!spellInfo)
+ {
+ sLog.outError("CastSpell(x,y,z): unknown spell id %i by caster: %s %u)", spellId,(GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
+ return;
+ }
+
+ if (castItem)
+ DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
+
+ if (!originalCaster && triggeredByAura)
+ originalCaster = triggeredByAura->GetCasterGUID();
+
+ Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
+
+ SpellCastTargets targets;
+ targets.setDst(x, y, z, GetOrientation());
+ if (OriginalVictim)
+ targets.setUnitTarget(OriginalVictim);
+ spell->m_CastItem = castItem;
+ spell->prepare(&targets, triggeredByAura);
+}
+
+// used for scripting
+void Unit::CastSpell(GameObject *go, uint32 spellId, bool triggered, Item *castItem, AuraEffect* triggeredByAura, uint64 originalCaster)
+{
+ if (!go)
+ return;
+
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
+
+ if (!spellInfo)
+ {
+ sLog.outError("CastSpell(x,y,z): unknown spell id %i by caster: %s %u)", spellId,(GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
+ return;
+ }
+
+ if (!(spellInfo->Targets & ( TARGET_FLAG_OBJECT | TARGET_FLAG_OBJECT_UNK)))
+ {
+ sLog.outError("CastSpell: spell id %i by caster: %s %u) is not gameobject spell", spellId,(GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
+ return;
+ }
+
+ if (castItem)
+ DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
+
+ if (!originalCaster && triggeredByAura)
+ originalCaster = triggeredByAura->GetCasterGUID();
+
+ Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
+
+ SpellCastTargets targets;
+ targets.setGOTarget(go);
+ spell->m_CastItem = castItem;
+ spell->prepare(&targets, triggeredByAura);
+}
+
+// Obsolete func need remove, here only for comotability vs another patches
+uint32 Unit::SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage)
+{
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellID);
+ SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, spellInfo->SchoolMask);
+ damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
+ CalculateSpellDamageTaken(&damageInfo, damage, spellInfo);
+ DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb);
+ SendSpellNonMeleeDamageLog(&damageInfo);
+ DealSpellDamage(&damageInfo, true);
+ return damageInfo.damage;
+}
+
+void Unit::CalculateSpellDamageTaken(SpellNonMeleeDamage *damageInfo, int32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType, bool crit)
+{
+ if (damage < 0)
+ return;
+
+ if (spellInfo->AttributesEx4 & SPELL_ATTR_EX4_FIXED_DAMAGE)
+ {
+ damageInfo->damage = damage;
+ return;
+ }
+
+ Unit *pVictim = damageInfo->target;
+ if (!pVictim || !pVictim->isAlive())
+ return;
+
+ SpellSchoolMask damageSchoolMask = SpellSchoolMask(damageInfo->schoolMask);
+ uint32 crTypeMask = pVictim->GetCreatureTypeMask();
+
+ if (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL)
+ damage = CalcArmorReducedDamage(pVictim, damage, spellInfo, attackType);
+
+ bool blocked = false;
+ // Per-school calc
+ switch (spellInfo->DmgClass)
+ {
+ // Melee and Ranged Spells
+ case SPELL_DAMAGE_CLASS_RANGED:
+ case SPELL_DAMAGE_CLASS_MELEE:
+ {
+ // Physical Damage
+ if (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL)
+ {
+ // Get blocked status
+ blocked = isSpellBlocked(pVictim, spellInfo, attackType);
+ }
+
+ if (crit)
+ {
+ damageInfo->HitInfo |= SPELL_HIT_TYPE_CRIT;
+
+ // Calculate crit bonus
+ uint32 crit_bonus = damage;
+ // Apply crit_damage bonus for melee spells
+ if (Player* modOwner = GetSpellModOwner())
+ modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
+ damage += crit_bonus;
+
+ // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
+ int32 critPctDamageMod = 0;
+ if (attackType == RANGED_ATTACK)
+ critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
+ else
+ {
+ critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
+ critPctDamageMod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
+ }
+ // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
+ critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
+
+ if (critPctDamageMod != 0)
+ damage = int32(damage * float((100.0f + critPctDamageMod)/100.0f));
+
+ // Resilience - reduce crit damage
+ if (attackType != RANGED_ATTACK)
+ damage -= pVictim->GetMeleeCritDamageReduction(damage);
+ else
+ damage -= pVictim->GetRangedCritDamageReduction(damage);
+ }
+ // Spell weapon based damage CAN BE crit & blocked at same time
+ if (blocked)
+ {
+ damageInfo->blocked = uint32(pVictim->GetShieldBlockValue());
+ //double blocked amount if block is critical
+ if (isBlockCritical())
+ damageInfo->blocked+=damageInfo->blocked;
+ if (damage < damageInfo->blocked)
+ damageInfo->blocked = damage;
+ damage -= damageInfo->blocked;
+ }
+ }
+ break;
+ // Magical Attacks
+ case SPELL_DAMAGE_CLASS_NONE:
+ case SPELL_DAMAGE_CLASS_MAGIC:
+ {
+ // If crit add critical bonus
+ if (crit)
+ {
+ damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
+ damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim);
+ // Resilience - reduce crit damage
+ damage -= pVictim->GetSpellCritDamageReduction(damage);
+ }
+ }
+ break;
+ }
+
+ // only from players
+ if (GetTypeId() == TYPEID_PLAYER)
+ damage -= pVictim->GetSpellDamageReduction(damage);
+
+ // Calculate absorb resist
+ if (damage > 0)
+ {
+ switch (spellInfo->SpellIconID)
+ {
+ // Chaos Bolt - "Chaos Bolt cannot be resisted, and pierces through all absorption effects."
+ case 3178:
+ break;
+ default:
+ CalcAbsorbResist(pVictim, damageSchoolMask, SPELL_DIRECT_DAMAGE, damage, &damageInfo->absorb, &damageInfo->resist, spellInfo);
+ damage -= damageInfo->absorb + damageInfo->resist;
+ break;
+ }
+ }
+ else
+ damage = 0;
+ damageInfo->damage = damage;
+}
+
+void Unit::DealSpellDamage(SpellNonMeleeDamage *damageInfo, bool durabilityLoss)
+{
+ if (damageInfo==0)
+ return;
+
+ Unit *pVictim = damageInfo->target;
+
+ if (!pVictim)
+ return;
+
+ if (!pVictim->isAlive() || pVictim->hasUnitState(UNIT_STAT_UNATTACKABLE) || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
+ return;
+
+ SpellEntry const *spellProto = sSpellStore.LookupEntry(damageInfo->SpellID);
+ if (spellProto == NULL)
+ {
+ sLog.outDebug("Unit::DealSpellDamage have wrong damageInfo->SpellID: %u", damageInfo->SpellID);
+ return;
+ }
+
+ //You don't lose health from damage taken from another player while in a sanctuary
+ //You still see it in the combat log though
+ if (pVictim != this && IsControlledByPlayer() && pVictim->IsControlledByPlayer())
+ {
+ const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
+ if (area && area->IsSanctuary()) // sanctuary
+ return;
+ }
+
+ // Call default DealDamage
+ CleanDamage cleanDamage(damageInfo->cleanDamage, damageInfo->absorb, BASE_ATTACK, MELEE_HIT_NORMAL);
+ DealDamage(pVictim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, SpellSchoolMask(damageInfo->schoolMask), spellProto, durabilityLoss);
+}
+
+//TODO for melee need create structure as in
+void Unit::CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType)
+{
+ damageInfo->attacker = this;
+ damageInfo->target = pVictim;
+ damageInfo->damageSchoolMask = GetMeleeDamageSchoolMask();
+ damageInfo->attackType = attackType;
+ damageInfo->damage = 0;
+ damageInfo->cleanDamage = 0;
+ damageInfo->absorb = 0;
+ damageInfo->resist = 0;
+ damageInfo->blocked_amount = 0;
+
+ damageInfo->TargetState = 0;
+ damageInfo->HitInfo = 0;
+ damageInfo->procAttacker = PROC_FLAG_NONE;
+ damageInfo->procVictim = PROC_FLAG_NONE;
+ damageInfo->procEx = PROC_EX_NONE;
+ damageInfo->hitOutCome = MELEE_HIT_EVADE;
+
+ if (!pVictim)
+ return;
+ if (!isAlive() || !pVictim->isAlive())
+ return;
+
+ // Select HitInfo/procAttacker/procVictim flag based on attack type
+ switch (attackType)
+ {
+ case BASE_ATTACK:
+ damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_HIT;
+ damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;
+ damageInfo->HitInfo = HITINFO_NORMALSWING2;
+ break;
+ case OFF_ATTACK:
+ damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_HIT | PROC_FLAG_SUCCESSFUL_OFFHAND_HIT;
+ damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;//|PROC_FLAG_TAKEN_OFFHAND_HIT // not used
+ damageInfo->HitInfo = HITINFO_LEFTSWING;
+ break;
+ case RANGED_ATTACK:
+ damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
+ damageInfo->procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
+ damageInfo->HitInfo = HITINFO_UNK2;// test
+ break;
+ default:
+ break;
+ }
+
+ // Physical Immune check
+ if (damageInfo->target->IsImmunedToDamage(SpellSchoolMask(damageInfo->damageSchoolMask)))
+ {
+ damageInfo->HitInfo |= HITINFO_NORMALSWING;
+ damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE;
+
+ damageInfo->procEx |= PROC_EX_IMMUNE;
+ damageInfo->damage = 0;
+ damageInfo->cleanDamage = 0;
+ return;
+ }
+ damage += CalculateDamage(damageInfo->attackType, false, true);
+ // Add melee damage bonus
+ MeleeDamageBonus(damageInfo->target, &damage, damageInfo->attackType);
+ // Calculate armor reduction
+ damageInfo->damage = CalcArmorReducedDamage(damageInfo->target, damage, NULL , damageInfo->attackType);
+ damageInfo->cleanDamage += damage - damageInfo->damage;
+
+ damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType);
+
+ // Disable parry or dodge for ranged attack
+ if (damageInfo->attackType == RANGED_ATTACK)
+ {
+ if (damageInfo->hitOutCome == MELEE_HIT_PARRY)
+ damageInfo->hitOutCome = MELEE_HIT_NORMAL;
+ else if (damageInfo->hitOutCome == MELEE_HIT_DODGE)
+ damageInfo->hitOutCome = MELEE_HIT_MISS;
+ }
+
+ switch (damageInfo->hitOutCome)
+ {
+ case MELEE_HIT_EVADE:
+ {
+ damageInfo->HitInfo |= HITINFO_MISS|HITINFO_SWINGNOHITSOUND;
+ damageInfo->TargetState = VICTIMSTATE_EVADES;
+
+ damageInfo->procEx|=PROC_EX_EVADE;
+ damageInfo->damage = 0;
+ damageInfo->cleanDamage = 0;
+ return;
+ }
+ case MELEE_HIT_MISS:
+ {
+ damageInfo->HitInfo |= HITINFO_MISS;
+ damageInfo->TargetState = VICTIMSTATE_NORMAL;
+
+ damageInfo->procEx |= PROC_EX_MISS;
+ damageInfo->damage = 0;
+ damageInfo->cleanDamage = 0;
+ break;
+ }
+ case MELEE_HIT_NORMAL:
+ damageInfo->TargetState = VICTIMSTATE_NORMAL;
+ damageInfo->procEx|=PROC_EX_NORMAL_HIT;
+ break;
+ case MELEE_HIT_CRIT:
+ {
+ damageInfo->HitInfo |= HITINFO_CRITICALHIT;
+ damageInfo->TargetState = VICTIMSTATE_NORMAL;
+
+ damageInfo->procEx |= PROC_EX_CRITICAL_HIT;
+ // Crit bonus calc
+ damageInfo->damage += damageInfo->damage;
+ int32 mod = 0;
+ // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
+ if (damageInfo->attackType == RANGED_ATTACK)
+ mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
+ else
+ {
+ mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
+ mod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
+ }
+
+ uint32 crTypeMask = damageInfo->target->GetCreatureTypeMask();
+
+ // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
+ mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
+ if (mod != 0)
+ damageInfo->damage = int32((damageInfo->damage) * float((100.0f + mod)/100.0f));
+
+ // Resilience - reduce crit damage
+ uint32 resilienceReduction;
+ if (attackType != RANGED_ATTACK)
+ resilienceReduction = pVictim->GetMeleeCritDamageReduction(damageInfo->damage);
+ else
+ resilienceReduction = pVictim->GetRangedCritDamageReduction(damageInfo->damage);
+
+ damageInfo->damage -= resilienceReduction;
+ damageInfo->cleanDamage += resilienceReduction;
+ break;
+ }
+ case MELEE_HIT_PARRY:
+ damageInfo->TargetState = VICTIMSTATE_PARRY;
+ damageInfo->procEx |= PROC_EX_PARRY;
+ damageInfo->cleanDamage += damageInfo->damage;
+ damageInfo->damage = 0;
+ break;
+
+ case MELEE_HIT_DODGE:
+ damageInfo->TargetState = VICTIMSTATE_DODGE;
+ damageInfo->procEx |= PROC_EX_DODGE;
+ damageInfo->cleanDamage += damageInfo->damage;
+ damageInfo->damage = 0;
+ break;
+ case MELEE_HIT_BLOCK:
+ {
+ damageInfo->TargetState = VICTIMSTATE_NORMAL;
+ damageInfo->HitInfo |= HITINFO_BLOCK;
+ damageInfo->procEx |= PROC_EX_BLOCK;
+ damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue();
+ //double blocked amount if block is critical
+ if (isBlockCritical())
+ damageInfo->blocked_amount+=damageInfo->blocked_amount;
+ if (damageInfo->blocked_amount >= damageInfo->damage)
+ {
+ damageInfo->TargetState = VICTIMSTATE_BLOCKS;
+ damageInfo->blocked_amount = damageInfo->damage;
+ damageInfo->procEx |= PROC_EX_FULL_BLOCK;
+ }
+ else
+ damageInfo->procEx |= PROC_EX_NORMAL_HIT;
+ damageInfo->damage -= damageInfo->blocked_amount;
+ damageInfo->cleanDamage += damageInfo->blocked_amount;
+ break;
+ }
+ case MELEE_HIT_GLANCING:
+ {
+ damageInfo->HitInfo |= HITINFO_GLANCING;
+ damageInfo->TargetState = VICTIMSTATE_NORMAL;
+ damageInfo->procEx |= PROC_EX_NORMAL_HIT;
+ int32 leveldif = int32(pVictim->getLevel()) - int32(getLevel());
+ if (leveldif > 3) leveldif = 3;
+ float reducePercent = 1 - leveldif * 0.1f;
+ damageInfo->cleanDamage += damageInfo->damage-uint32(reducePercent * damageInfo->damage);
+ damageInfo->damage = uint32(reducePercent * damageInfo->damage);
+ break;
+ }
+ case MELEE_HIT_CRUSHING:
+ {
+ damageInfo->HitInfo |= HITINFO_CRUSHING;
+ damageInfo->TargetState = VICTIMSTATE_NORMAL;
+ damageInfo->procEx |= PROC_EX_NORMAL_HIT;
+ // 150% normal damage
+ damageInfo->damage += (damageInfo->damage / 2);
+ break;
+ }
+ default:
+ break;
+ }
+
+ // only from players
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ if (attackType != RANGED_ATTACK)
+ damage -= pVictim->GetMeleeDamageReduction(damage);
+ else
+ damage -= pVictim->GetRangedDamageReduction(damage);
+ }
+
+ // Calculate absorb resist
+ if (int32(damageInfo->damage) > 0)
+ {
+ damageInfo->procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
+ // Calculate absorb & resists
+ CalcAbsorbResist(damageInfo->target, SpellSchoolMask(damageInfo->damageSchoolMask), DIRECT_DAMAGE, damageInfo->damage, &damageInfo->absorb, &damageInfo->resist);
+ damageInfo->damage -= damageInfo->absorb + damageInfo->resist;
+ if (damageInfo->absorb)
+ {
+ damageInfo->HitInfo |= HITINFO_ABSORB;
+ damageInfo->procEx |= PROC_EX_ABSORB;
+ }
+ if (damageInfo->resist)
+ damageInfo->HitInfo |= HITINFO_RESIST;
+ }
+ else // Impossible get negative result but....
+ damageInfo->damage = 0;
+}
+
+void Unit::DealMeleeDamage(CalcDamageInfo *damageInfo, bool durabilityLoss)
+{
+ if (!damageInfo)
+ return;
+ Unit *pVictim = damageInfo->target;
+
+ if (!pVictim)
+ return;
+
+ if (!pVictim->isAlive() || pVictim->hasUnitState(UNIT_STAT_UNATTACKABLE) || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
+ return;
+
+ //You don't lose health from damage taken from another player while in a sanctuary
+ //You still see it in the combat log though
+ if (pVictim != this && IsControlledByPlayer() && pVictim->IsControlledByPlayer())
+ {
+ const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
+ if (area && area->IsSanctuary()) // sanctuary
+ return;
+ }
+
+ // Hmmmm dont like this emotes client must by self do all animations
+ if (damageInfo->HitInfo&HITINFO_CRITICALHIT)
+ pVictim->HandleEmoteCommand(EMOTE_ONESHOT_WOUNDCRITICAL);
+ if (damageInfo->blocked_amount && damageInfo->TargetState != VICTIMSTATE_BLOCKS)
+ pVictim->HandleEmoteCommand(EMOTE_ONESHOT_PARRYSHIELD);
+
+ if (damageInfo->TargetState == VICTIMSTATE_PARRY)
+ {
+ // Get attack timers
+ float offtime = float(pVictim->getAttackTimer(OFF_ATTACK));
+ float basetime = float(pVictim->getAttackTimer(BASE_ATTACK));
+ // Reduce attack time
+ if (pVictim->haveOffhandWeapon() && offtime < basetime)
+ {
+ float percent20 = pVictim->GetAttackTime(OFF_ATTACK) * 0.20f;
+ float percent60 = 3.0f * percent20;
+ if (offtime > percent20 && offtime <= percent60)
+ pVictim->setAttackTimer(OFF_ATTACK, uint32(percent20));
+ else if (offtime > percent60)
+ {
+ offtime -= 2.0f * percent20;
+ pVictim->setAttackTimer(OFF_ATTACK, uint32(offtime));
+ }
+ }
+ else
+ {
+ float percent20 = pVictim->GetAttackTime(BASE_ATTACK) * 0.20;
+ float percent60 = 3.0f * percent20;
+ if (basetime > percent20 && basetime <= percent60)
+ pVictim->setAttackTimer(BASE_ATTACK, uint32(percent20));
+ else if (basetime > percent60)
+ {
+ basetime -= 2.0f * percent20;
+ pVictim->setAttackTimer(BASE_ATTACK, uint32(basetime));
+ }
+ }
+ }
+
+ // Call default DealDamage
+ CleanDamage cleanDamage(damageInfo->cleanDamage,damageInfo->absorb,damageInfo->attackType,damageInfo->hitOutCome);
+ DealDamage(pVictim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->damageSchoolMask), NULL, durabilityLoss);
+
+ // If this is a creature and it attacks from behind it has a probability to daze it's victim
+ if ((damageInfo->hitOutCome==MELEE_HIT_CRIT || damageInfo->hitOutCome==MELEE_HIT_CRUSHING || damageInfo->hitOutCome==MELEE_HIT_NORMAL || damageInfo->hitOutCome==MELEE_HIT_GLANCING) &&
+ GetTypeId() != TYPEID_PLAYER && !((Creature*)this)->IsControlledByPlayer() && !pVictim->HasInArc(M_PI, this)
+ && (pVictim->GetTypeId() == TYPEID_PLAYER || !((Creature*)pVictim)->isWorldBoss()))
+ {
+ // -probability is between 0% and 40%
+ // 20% base chance
+ float Probability = 20.0f;
+
+ //there is a newbie protection, at level 10 just 7% base chance; assuming linear function
+ if (pVictim->getLevel() < 30)
+ Probability = 0.65f*pVictim->getLevel()+0.5f;
+
+ uint32 VictimDefense=pVictim->GetDefenseSkillValue();
+ uint32 AttackerMeleeSkill=GetUnitMeleeSkill();
+
+ Probability *= AttackerMeleeSkill/(float)VictimDefense;
+
+ if (Probability > 40.0f)
+ Probability = 40.0f;
+
+ if (roll_chance_f(Probability))
+ CastSpell(pVictim, 1604, true);
+ }
+
+ if (GetTypeId() == TYPEID_PLAYER)
+ ((Player *)this)->CastItemCombatSpell(pVictim, damageInfo->attackType, damageInfo->procVictim, damageInfo->procEx);
+
+ // Do effect if any damage done to target
+ if (damageInfo->damage)
+ {
+ // victim's damage shield
+ std::set<AuraEffect*> alreadyDone;
+ uint32 removedAuras = pVictim->m_removedAurasCount;
+ AuraEffectList const& vDamageShields = pVictim->GetAuraEffectsByType(SPELL_AURA_DAMAGE_SHIELD);
+ for (AuraEffectList::const_iterator i = vDamageShields.begin(), next = vDamageShields.begin(); i != vDamageShields.end(); i = next)
+ {
+ ++next;
+ if (alreadyDone.find(*i) == alreadyDone.end())
+ {
+ alreadyDone.insert(*i);
+ uint32 damage=(*i)->GetAmount();
+ SpellEntry const *i_spellProto = (*i)->GetSpellProto();
+ //Calculate absorb resist ??? no data in opcode for this possibly unable to absorb or resist?
+ //uint32 absorb;
+ //uint32 resist;
+ //CalcAbsorbResist(pVictim, SpellSchools(spellProto->School), SPELL_DIRECT_DAMAGE, damage, &absorb, &resist);
+ //damage-=absorb + resist;
+
+ pVictim->DealDamageMods(this,damage,NULL);
+
+ WorldPacket data(SMSG_SPELLDAMAGESHIELD,(8+8+4+4+4+4));
+ data << uint64(pVictim->GetGUID());
+ data << uint64(GetGUID());
+ data << uint32(i_spellProto->Id);
+ data << uint32(damage); // Damage
+ data << uint32(0); // Overkill
+ data << uint32(i_spellProto->SchoolMask);
+ pVictim->SendMessageToSet(&data, true );
+
+ pVictim->DealDamage(this, damage, 0, SPELL_DIRECT_DAMAGE, GetSpellSchoolMask(i_spellProto), i_spellProto, true);
+
+ if (pVictim->m_removedAurasCount > removedAuras)
+ {
+ removedAuras = pVictim->m_removedAurasCount;
+ next = vDamageShields.begin();
+ }
+ }
+ }
+ }
+}
+
+void Unit::HandleEmoteCommand(uint32 anim_id)
+{
+ WorldPacket data( SMSG_EMOTE, 4 + 8 );
+ data << uint32(anim_id);
+ data << uint64(GetGUID());
+ SendMessageToSet(&data, true);
+}
+
+uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType)
+{
+ uint32 newdamage = 0;
+ float armor = pVictim->GetArmor();
+
+ // Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura
+ armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL);
+
+ if (spellInfo)
+ if (Player *modOwner = GetSpellModOwner())
+ modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_IGNORE_ARMOR, armor);
+
+ AuraEffectList const& ResIgnoreAurasAb = GetAuraEffectsByType(SPELL_AURA_MOD_ABILITY_IGNORE_TARGET_RESIST);
+ for (AuraEffectList::const_iterator j = ResIgnoreAurasAb.begin(); j != ResIgnoreAurasAb.end(); ++j)
+ {
+ if ((*j)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL
+ && (*j)->IsAffectedOnSpell(spellInfo))
+ armor= int32(float(armor) * (float(100-(*j)->GetAmount())/100.0f));
+ }
+
+ AuraEffectList const& ResIgnoreAuras = GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_TARGET_RESIST);
+ for (AuraEffectList::const_iterator j = ResIgnoreAuras.begin(); j != ResIgnoreAuras.end(); ++j)
+ {
+ if ((*j)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL)
+ armor= int32(float(armor) * (float(100-(*j)->GetAmount())/100.0f));
+ }
+
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ AuraEffectList const& ResIgnoreAuras = GetAuraEffectsByType(SPELL_AURA_MOD_ARMOR_PENETRATION_PCT);
+ for (AuraEffectList::const_iterator itr = ResIgnoreAuras.begin(); itr != ResIgnoreAuras.end(); ++itr)
+ {
+ // item neutral spell
+ if ((*itr)->GetSpellProto()->EquippedItemClass == -1)
+ {
+ armor = int32(float(armor) * (float(100-(*itr)->GetAmount())/100.0f));
+ continue;
+ }
+
+ // item dependent spell - check curent weapons
+ for (int i = 0; i < MAX_ATTACK; ++i)
+ {
+ Item *weapon = ((Player *)this)->GetWeaponForAttack(WeaponAttackType(i));
+
+ if (weapon && weapon->IsFitToSpellRequirements((*itr)->GetSpellProto()))
+ {
+ armor= int32(float(armor) * (float(100-(*itr)->GetAmount())/100.0f));
+ break;
+ }
+ }
+ }
+ }
+
+ // Apply Player CR_ARMOR_PENETRATION rating
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ float maxArmorPen=0;
+ if (getLevel()<60)
+ maxArmorPen=400+85*pVictim->getLevel();
+ else
+ maxArmorPen=400+85*pVictim->getLevel()+4.5*85*(pVictim->getLevel()-59);
+ // Cap armor penetration to this number
+ maxArmorPen = std::min(((armor+maxArmorPen)/3),armor);
+ // Figure out how much armor do we ignore
+ float armorPen = maxArmorPen*((Player*)this)->GetRatingBonusValue(CR_ARMOR_PENETRATION) / 100.0f;
+ // Got the value, apply it
+ armor -= armorPen;
+ }
+ // Ignore enemy armor by SPELL_AURA_MOD_TARGET_ARMOR_PCT
+ //armor *= 1.0f - GetTotalAuraModifier(SPELL_AURA_MOD_ARMOR_PENETRATION_PCT) / 100.0f;
+
+ if (armor < 0.0f)
+ armor = 0.0f;
+
+ float levelModifier = getLevel();
+ if (levelModifier > 59)
+ levelModifier = levelModifier + (4.5f * (levelModifier-59));
+
+ float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40);
+ tmpvalue = tmpvalue/(1.0f + tmpvalue);
+
+ if (tmpvalue < 0.0f)
+ tmpvalue = 0.0f;
+ if (tmpvalue > 0.75f)
+ tmpvalue = 0.75f;
+
+ newdamage = uint32(damage - (damage * tmpvalue));
+
+ return (newdamage > 1) ? newdamage : 1;
+}
+
+void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist, SpellEntry const *spellInfo)
+{
+ if (!pVictim || !pVictim->isAlive() || !damage)
+ return;
+
+ // Magic damage, check for resists
+ if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL) == 0)
+ {
+ float baseVictimResistance = (float) pVictim->GetResistance(GetFirstSchoolInMask(schoolMask));
+ float ignoredResistance = (float) GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask);
+ float victimResistance = baseVictimResistance + ignoredResistance;
+
+ uint32 BOSS_LEVEL = 83;
+ float BOSS_RESISTANCE_CONSTANT = 510.0;
+ uint32 level = getLevel();
+ float resistanceConstant = 0.0f;
+
+ if (level == BOSS_LEVEL)
+ {
+ resistanceConstant = BOSS_RESISTANCE_CONSTANT;
+ }
+ else
+ {
+ resistanceConstant = level * 5.0f;
+ }
+
+ float averageResist = victimResistance / (victimResistance + resistanceConstant);
+ float discreteResistProbability[11];
+ for (int i = 0; i < 11; i++)
+ {
+ discreteResistProbability[i] = 0.5f - 2.5f * abs(0.1f * i - averageResist);
+ if (discreteResistProbability[i] < 0.0f)
+ {
+ discreteResistProbability[i] = 0.0f;
+ }
+ }
+
+ if (averageResist <= 0.1f)
+ {
+ discreteResistProbability[0] = 1.0f - 7.5f * averageResist;
+ discreteResistProbability[1] = 5.0f * averageResist;
+ discreteResistProbability[2] = 2.5f * averageResist;
+ }
+
+ float r = rand_norm();
+ int i = 0;
+ float probabilitySum = discreteResistProbability[0];
+ while (r >= probabilitySum && i < 10)
+ {
+ i++;
+ probabilitySum += discreteResistProbability[i];
+ }
+ uint32 damageResisted = damage * i / 10;
+
+ *resist += damageResisted;
+
+ AuraEffectList const &ResIgnoreAurasAb = GetAuraEffectsByType(SPELL_AURA_MOD_ABILITY_IGNORE_TARGET_RESIST);
+ for (AuraEffectList::const_iterator j = ResIgnoreAurasAb.begin(); j != ResIgnoreAurasAb.end(); ++j)
+ {
+ if ((*j)->GetMiscValue() & schoolMask
+ && (*j)->IsAffectedOnSpell(spellInfo))
+ *resist= int32(float(*resist) * (float(100-(*j)->GetAmount())/100.0f));
+ }
+
+ AuraEffectList const &ResIgnoreAuras = GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_TARGET_RESIST);
+ for (AuraEffectList::const_iterator j = ResIgnoreAuras.begin(); j != ResIgnoreAuras.end(); ++j)
+ {
+ if ((*j)->GetMiscValue() & schoolMask)
+ *resist= int32(float(*resist) * (float(100-(*j)->GetAmount())/100.0f));
+ }
+ }
+ else
+ *resist = 0;
+
+ int32 RemainingDamage = damage - *resist;
+ int32 TotalAbsorb = RemainingDamage;
+ // Get unit state (need for some absorb check)
+ uint32 unitflag = pVictim->GetUInt32Value(UNIT_FIELD_FLAGS);
+ // Death Prevention Aura
+ SpellEntry const* preventDeathSpell = NULL;
+ int32 preventDeathAmount = 0;
+ // Need remove expired auras after
+ bool existExpired = false;
+ TriggeredSpellInfoVct triggeredSpells;
+ // absorb without mana cost
+ AuraEffectList const& vSchoolAbsorb = pVictim->GetAuraEffectsByType(SPELL_AURA_SCHOOL_ABSORB);
+ for (AuraEffectList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end() && RemainingDamage > 0; ++i)
+ {
+ if (!((*i)->GetMiscValue() & schoolMask))
+ continue;
+
+ SpellEntry const* spellProto = (*i)->GetSpellProto();
+
+ // Max Amount can be absorbed by this aura
+ int32 currentAbsorb = (*i)->GetAmount();
+
+ // Found empty aura (impossible but..)
+ if (currentAbsorb <= 0)
+ {
+ existExpired = true;
+ continue;
+ }
+ // Handle custom absorb auras
+ // TODO: try find better way
+ switch (spellProto->SpellFamilyName)
+ {
+ case SPELLFAMILY_GENERIC:
+ {
+ // Astral Shift
+ if (spellProto->SpellIconID == 3066)
+ {
+ //reduces all damage taken while stun, fear or silence
+ if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
+ RemainingDamage -= RemainingDamage * currentAbsorb / 100;
+ continue;
+ }
+ // Nerves of Steel
+ if (spellProto->SpellIconID == 2115)
+ {
+ // while affected by Stun and Fear
+ if (unitflag&(UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING))
+ RemainingDamage -= RemainingDamage * currentAbsorb / 100;
+ continue;
+ }
+ // Spell Deflection
+ if (spellProto->SpellIconID == 3006)
+ {
+ // You have a chance equal to your Parry chance
+ if (damagetype == DIRECT_DAMAGE && // Only for direct damage
+ roll_chance_f(pVictim->GetUnitParryChance())) // Roll chance
+ RemainingDamage -= RemainingDamage * currentAbsorb / 100;
+ continue;
+ }
+ // Reflective Shield (Lady Malande boss)
+ if (spellProto->Id == 41475)
+ {
+ triggeredSpells.push_back(TriggeredSpellInfo(33619, pVictim, this,
+ std::min(RemainingDamage, currentAbsorb) / 2, *i));
+ break;
+ }
+ if (spellProto->Id == 39228 || // Argussian Compass
+ spellProto->Id == 60218) // Essence of Gossamer
+ {
+ // Max absorb stored in 1 dummy effect
+ if (spellProto->EffectBasePoints[1] < currentAbsorb)
+ currentAbsorb = spellProto->EffectBasePoints[1];
+ break;
+ }
+ break;
+ }
+ case SPELLFAMILY_DRUID:
+ {
+ // Primal Tenacity
+ if (spellProto->SpellIconID == 2253)
+ {
+ //reduces all damage taken while Stunned
+ if (unitflag & UNIT_FLAG_STUNNED)
+ RemainingDamage -= RemainingDamage * currentAbsorb / 100;
+ continue;
+ }
+ // Savage Defense (amount store original percent of attack power applied)
+ if (spellProto->SpellIconID == 50) // only spell with this aura fit
+ {
+ RemainingDamage -= int32(currentAbsorb * pVictim->GetTotalAttackPowerValue(BASE_ATTACK) / 100);
+ continue;
+ }
+ // Moonkin Form passive
+ if (spellProto->Id == 69366)
+ {
+ //reduces all damage taken while Stunned
+ if (unitflag & UNIT_FLAG_STUNNED)
+ RemainingDamage -= RemainingDamage * currentAbsorb / 100;
+ continue;
+ }
+ break;
+ }
+ case SPELLFAMILY_ROGUE:
+ {
+ // Cheat Death (make less prio with Guardian Spirit case)
+ if (spellProto->SpellIconID == 2109)
+ {
+ if (!preventDeathSpell &&
+ pVictim->GetTypeId() == TYPEID_PLAYER && // Only players
+ !((Player*)pVictim)->HasSpellCooldown(31231) && // Only if no cooldown
+ roll_chance_i((*i)->GetAmount())) // Only if roll
+ {
+ preventDeathSpell = (*i)->GetSpellProto();
+ }
+ continue;
+ }
+ break;
+ }
+ case SPELLFAMILY_PRIEST:
+ {
+ // Guardian Spirit
+ if (spellProto->SpellIconID == 2873)
+ {
+ preventDeathSpell = (*i)->GetSpellProto();
+ preventDeathAmount = (*i)->GetAmount();
+ continue;
+ }
+
+ // Power Word: Shield
+ if (spellProto->SpellFamilyFlags.IsEqual(0x1, 0, 0x400))
+ {
+ if (pVictim == this)
+ break;
+ Unit* caster = (*i)->GetCaster();
+ if (!caster)
+ break;
+ // Reflective Shield
+ if (AuraEffect const * aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_PRIEST, 566, 0))
+ {
+ switch(aurEff->GetMiscValue())
+ {
+ case 5065: // Rank 1
+ case 5064: // Rank 2
+ triggeredSpells.push_back(TriggeredSpellInfo(33619, pVictim, this,
+ std::min(RemainingDamage, currentAbsorb) * aurEff->GetAmount() / 100, *i));
+ break;
+ default:
+ sLog.outError("Unit::CalcAbsorbResist: unknown Reflective Shield spell %d", aurEff->GetId());
+ break;
+ }
+ }
+ }
+ break;
+ }
+ case SPELLFAMILY_PALADIN:
+ {
+ // Ardent Defender
+ if (spellProto->SpellIconID == 2135 && pVictim->GetTypeId() == TYPEID_PLAYER)
+ {
+ int32 remainingHealth = pVictim->GetHealth() - RemainingDamage;
+ uint32 allowedHealth = pVictim->GetMaxHealth() * 0.35f;
+ // If damage kills us
+ if (remainingHealth <= 0 && !((Player*)pVictim)->HasSpellCooldown(66235))
+ {
+ // Cast healing spell, completely avoid damage
+ RemainingDamage = 0;
+
+ uint32 defenseSkillValue = pVictim->GetDefenseSkillValue();
+ // Max heal when defense skill denies critical hits from raid bosses
+ // Formula: max defense at level + 140 (raiting from gear)
+ uint32 reqDefForMaxHeal = pVictim->getLevel() * 5 + 140;
+ float pctFromDefense = (defenseSkillValue >= reqDefForMaxHeal)
+ ? 1.0f
+ : float(defenseSkillValue) / float(reqDefForMaxHeal);
+
+ int32 healAmount = pVictim->GetMaxHealth() * (*i)->GetAmount() / 100.0f * pctFromDefense;
+ pVictim->CastCustomSpell(pVictim, 66235, &healAmount, NULL, NULL, true);
+ ((Player*)pVictim)->AddSpellCooldown(66235,0,time(NULL) + 120);
+ }
+ else if (remainingHealth < allowedHealth)
+ {
+ // Reduce damage that brings us under 35% (or full damage if we are already under 35%) by x%
+ uint32 damageToReduce = (pVictim->GetHealth() < allowedHealth)
+ ? RemainingDamage
+ : allowedHealth - remainingHealth;
+ RemainingDamage -= damageToReduce * currentAbsorb / 100;
+ }
+ continue;
+
+ }
+ break;
+ }
+ case SPELLFAMILY_SHAMAN:
+ {
+ // Astral Shift
+ if (spellProto->SpellIconID == 3066)
+ {
+ //reduces all damage taken while stun, fear or silence
+ if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
+ RemainingDamage -= RemainingDamage * currentAbsorb / 100;
+ continue;
+ }
+ break;
+ }
+ case SPELLFAMILY_DEATHKNIGHT:
+ {
+ switch (spellProto->Id)
+ {
+ case 51271: // Unbreakable Armor
+ if (Unit *caster = (*i)->GetCaster())
+ {
+ uint32 absorbed = uint32( currentAbsorb * caster->GetArmor() * 0.01f );
+
+ // Glyph of Unbreakable Armor
+ if (AuraEffect *aurEff = caster->GetAuraEffect(58635, 0))
+ absorbed += uint32(absorbed * aurEff->GetAmount() / 100);
+
+ RemainingDamage -= absorbed;
+ }
+ continue;
+ case 48707: // Anti-Magic Shell (on self)
+ {
+ // damage absorbed by Anti-Magic Shell energizes the DK with additional runic power.
+ // This, if I'm not mistaken, shows that we get back ~2% of the absorbed damage as runic power.
+ int32 absorbed = RemainingDamage * currentAbsorb / 100;
+ RemainingDamage -= absorbed;
+ triggeredSpells.push_back(TriggeredSpellInfo(49088, pVictim, pVictim, absorbed * 2 / 10, *i));
+ continue;
+ }
+ case 50462: // Anti-Magic Shell (on single party/raid member)
+ RemainingDamage -= RemainingDamage * currentAbsorb / 100;
+ continue;
+ case 50461: // Anti-Magic Zone
+ if (Unit *caster = (*i)->GetCaster())
+ {
+ int32 absorbed = RemainingDamage * currentAbsorb / 100;
+ int32 canabsorb = caster->GetHealth();
+ if (canabsorb < absorbed)
+ absorbed = canabsorb;
+
+ RemainingDamage -= absorbed;
+ }
+ continue;
+ default:
+ break;
+ }
+ break;
+ }
+ default:
+ break;
+ }
+
+ // currentAbsorb - damage can be absorbed by shield
+ // If need absorb less damage
+ if (RemainingDamage < currentAbsorb)
+ currentAbsorb = RemainingDamage;
+
+ RemainingDamage -= currentAbsorb;
+
+ // Reduce shield amount
+ (*i)->SetAmount((*i)->GetAmount() -currentAbsorb);
+ // Need remove it later
+ if ((*i)->GetAmount() <= 0)
+ existExpired = true;
+ }
+
+ for (TriggeredSpellInfoVct::const_iterator itr = triggeredSpells.begin(); itr != triggeredSpells.end(); ++itr)
+ {
+ if (itr->spell)
+ itr->source->CastCustomSpell(itr->spell, SPELLVALUE_BASE_POINT0, itr->amount, itr->target, true, NULL, itr->auraEff);
+ else if (itr->amount > 0)
+ {
+ uint32 damage = uint32(itr->amount);
+ itr->source->DealDamageMods(itr->target, damage, NULL);
+ itr->source->DealDamage(itr->target, damage, NULL, damagetype, schoolMask, 0, false);
+ }
+ }
+
+ // Remove all expired absorb auras
+ if (existExpired)
+ {
+ for (AuraEffectList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end();)
+ {
+ AuraEffect * auraEff =(*i);
+ ++i;
+ if (auraEff->GetAmount()<=0)
+ {
+ uint32 removedAuras = pVictim->m_removedAurasCount;
+ auraEff->GetBase()->Remove(AURA_REMOVE_BY_ENEMY_SPELL);
+ if (removedAuras+1<pVictim->m_removedAurasCount)
+ i=vSchoolAbsorb.begin();
+ }
+ }
+ }
+
+ // absorb by mana cost
+ AuraEffectList const& vManaShield = pVictim->GetAuraEffectsByType(SPELL_AURA_MANA_SHIELD);
+ for (AuraEffectList::const_iterator i = vManaShield.begin(), next; i != vManaShield.end() && RemainingDamage > 0; i = next)
+ {
+ next = i; ++next;
+
+ // check damage school mask
+ if (((*i)->GetMiscValue() & schoolMask)==0)
+ continue;
+
+ int32 currentAbsorb;
+ if (RemainingDamage >= (*i)->GetAmount())
+ currentAbsorb = (*i)->GetAmount();
+ else
+ currentAbsorb = RemainingDamage;
+
+ if (float manaMultiplier = (*i)->GetSpellProto()->EffectMultipleValue[(*i)->GetEffIndex()])
+ {
+ if(Player *modOwner = pVictim->GetSpellModOwner())
+ modOwner->ApplySpellMod((*i)->GetId(), SPELLMOD_MULTIPLE_VALUE, manaMultiplier);
+
+ int32 maxAbsorb = int32(pVictim->GetPower(POWER_MANA) / manaMultiplier);
+ if (currentAbsorb > maxAbsorb)
+ currentAbsorb = maxAbsorb;
+
+ int32 manaReduction = int32(currentAbsorb * manaMultiplier);
+ pVictim->ApplyPowerMod(POWER_MANA, manaReduction, false);
+ }
+
+ (*i)->SetAmount((*i)->GetAmount()-currentAbsorb);
+ if ((*i)->GetAmount() <= 0)
+ {
+ (*i)->GetBase()->Remove(AURA_REMOVE_BY_ENEMY_SPELL);
+ next = vManaShield.begin();
+ }
+
+ RemainingDamage -= currentAbsorb;
+ }
+
+ // only split damage if not damaging yourself
+ if (pVictim != this)
+ {
+ AuraEffectList const& vSplitDamageFlat = pVictim->GetAuraEffectsByType(SPELL_AURA_SPLIT_DAMAGE_FLAT);
+ for (AuraEffectList::const_iterator i = vSplitDamageFlat.begin(), next; i != vSplitDamageFlat.end() && RemainingDamage >= 0; i = next)
+ {
+ next = i; ++next;
+
+ // check damage school mask
+ if (((*i)->GetMiscValue() & schoolMask) == 0)
+ continue;
+
+ // Damage can be splitted only if aura has an alive caster
+ Unit *caster = (*i)->GetCaster();
+ if (!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
+ continue;
+
+ int32 currentAbsorb;
+ if (RemainingDamage >= (*i)->GetAmount())
+ currentAbsorb = (*i)->GetAmount();
+ else
+ currentAbsorb = RemainingDamage;
+
+ RemainingDamage -= currentAbsorb;
+
+ uint32 splitted = currentAbsorb;
+ uint32 splitted_absorb = 0;
+ DealDamageMods(caster,splitted,&splitted_absorb);
+
+ SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, splitted_absorb, 0, false, 0, false);
+
+ CleanDamage cleanDamage = CleanDamage(splitted, 0, BASE_ATTACK, MELEE_HIT_NORMAL);
+ DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
+ }
+
+ AuraEffectList const& vSplitDamagePct = pVictim->GetAuraEffectsByType(SPELL_AURA_SPLIT_DAMAGE_PCT);
+ for (AuraEffectList::const_iterator i = vSplitDamagePct.begin(), next; i != vSplitDamagePct.end() && RemainingDamage >= 0; i = next)
+ {
+ next = i; ++next;
+
+ // check damage school mask
+ if (((*i)->GetMiscValue() & schoolMask)==0)
+ continue;
+
+ // Damage can be splitted only if aura has an alive caster
+ Unit *caster = (*i)->GetCaster();
+ if (!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
+ continue;
+
+ uint32 splitted = uint32(RemainingDamage * (*i)->GetAmount() / 100.0f);
+
+ RemainingDamage -= int32(splitted);
+
+ uint32 split_absorb = 0;
+ DealDamageMods(caster,splitted,&split_absorb);
+
+ SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, split_absorb, 0, false, 0, false);
+
+ CleanDamage cleanDamage = CleanDamage(splitted, 0, BASE_ATTACK, MELEE_HIT_NORMAL);
+ DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
+ }
+ }
+
+ TotalAbsorb = (TotalAbsorb - RemainingDamage > 0) ? TotalAbsorb - RemainingDamage : 0;
+ // TODO: School should be checked for absorbing auras or for attacks?
+ int32 auraAbsorbMod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_TARGET_ABSORB_SCHOOL);
+ AuraEffectList const& AbsIgnoreAurasAb = GetAuraEffectsByType(SPELL_AURA_MOD_TARGET_ABILITY_ABSORB_SCHOOL);
+ for (AuraEffectList::const_iterator i = AbsIgnoreAurasAb.begin(); i != AbsIgnoreAurasAb.end(); ++i)
+ {
+ if ((*i)->GetAmount() > auraAbsorbMod
+ && (*i)->IsAffectedOnSpell(spellInfo))
+ auraAbsorbMod = (*i)->GetAmount();
+ }
+
+ // Ignore absorb - add reduced amount again to damage
+ RemainingDamage += auraAbsorbMod * TotalAbsorb / 100;
+
+ // Apply death prevention spells effects
+ if (preventDeathSpell && RemainingDamage >= pVictim->GetHealth())
+ {
+ switch(preventDeathSpell->SpellFamilyName)
+ {
+ case SPELLFAMILY_ROGUE:
+ {
+ // Cheat Death
+ if (preventDeathSpell->SpellIconID == 2109)
+ {
+ pVictim->CastSpell(pVictim,31231,true);
+ ((Player*)pVictim)->AddSpellCooldown(31231,0,time(NULL)+60);
+ // with health > 10% lost health until health==10%, in other case no losses
+ uint32 health10 = pVictim->GetMaxHealth()/10;
+ RemainingDamage = pVictim->GetHealth() > health10 ? pVictim->GetHealth() - health10 : 0;
+ }
+ break;
+ }
+ case SPELLFAMILY_PRIEST:
+ {
+ // Guardian Spirit
+ if (preventDeathSpell->SpellIconID == 2873)
+ {
+ int32 healAmount = pVictim->GetMaxHealth() * preventDeathAmount / 100;
+ pVictim->CastCustomSpell(pVictim, 48153, &healAmount, NULL, NULL, true);
+ pVictim->RemoveAurasDueToSpell(preventDeathSpell->Id);
+ RemainingDamage = 0;
+ }
+ break;
+ }
+ }
+ }
+
+ *absorb = RemainingDamage > 0 ? (damage - RemainingDamage - *resist) : (damage - *resist);
+
+ if (*absorb)
+ {
+ // Incanter's Absorption
+ // TODO: move this code to procflag
+ if (AuraEffect const * aurEff = pVictim->GetDummyAuraEffect(SPELLFAMILY_GENERIC, 2941, 0))
+ {
+ // Get total damage bonus from auras
+ int32 current_dmg = 0;
+ std::pair<AuraApplicationMap::const_iterator, AuraApplicationMap::const_iterator> range = pVictim->GetAppliedAuras().equal_range(44413);
+ for (AuraApplicationMap::const_iterator iter = range.first; iter != range.second; ++iter)
+ if (AuraEffect const * bonusEff = iter->second->GetBase()->GetEffect(0))
+ current_dmg += bonusEff->GetAmount();
+
+ int32 new_dmg = (int32)*absorb * aurEff->GetAmount() / 100;
+ int32 max_dmg = (int32)pVictim->GetMaxHealth() * 5 / 100;
+ // Do not apply more auras if more than 5% hp
+ if (current_dmg + new_dmg > max_dmg)
+ new_dmg = max_dmg - current_dmg;
+ if (new_dmg > 0)
+ pVictim->CastCustomSpell(pVictim, 44413, &new_dmg, NULL, NULL, true);
+ }
+ }
+}
+
+void Unit::AttackerStateUpdate (Unit *pVictim, WeaponAttackType attType, bool extra )
+{
+ if (hasUnitState(UNIT_STAT_CANNOT_AUTOATTACK) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) )
+ return;
+
+ if (!pVictim->isAlive())
+ return;
+
+ CombatStart(pVictim);
+ RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MELEE_ATTACK);
+
+ uint32 hitInfo;
+ if (attType == BASE_ATTACK)
+ hitInfo = HITINFO_NORMALSWING2;
+ else if (attType == OFF_ATTACK)
+ hitInfo = HITINFO_LEFTSWING;
+ else
+ return; // ignore ranged case
+
+ // melee attack spell casted at main hand attack only
+ if (attType == BASE_ATTACK && m_currentSpells[CURRENT_MELEE_SPELL])
+ {
+ m_currentSpells[CURRENT_MELEE_SPELL]->cast();
+ return;
+ }
+
+ // attack can be redirected to another target
+ pVictim = SelectMagnetTarget(pVictim);
+
+ CalcDamageInfo damageInfo;
+ CalculateMeleeDamage(pVictim, 0, &damageInfo, attType);
+ // Send log damage message to client
+ DealDamageMods(pVictim, damageInfo.damage, &damageInfo.absorb);
+ SendAttackStateUpdate(&damageInfo);
+
+ ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.damage, damageInfo.attackType);
+ DealMeleeDamage(&damageInfo,true);
+
+ if (GetTypeId() == TYPEID_PLAYER)
+ DEBUG_LOG("AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
+ GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
+ else
+ DEBUG_LOG("AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
+ GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
+
+ // if damage pVictim call AI reaction
+ //if (pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->AI())
+ // ((Creature*)pVictim)->AI()->AttackedBy(this);
+
+}
+
+MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType) const
+{
+ // This is only wrapper
+
+ // Miss chance based on melee
+ //float miss_chance = MeleeMissChanceCalc(pVictim, attType);
+ float miss_chance = MeleeSpellMissChance(pVictim, attType, int32(GetWeaponSkillValue(attType,pVictim)) - int32(pVictim->GetDefenseSkillValue(this)), 0);
+
+ // Critical hit chance
+ float crit_chance = GetUnitCriticalChance(attType, pVictim);
+
+ // stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case)
+ float dodge_chance = pVictim->GetUnitDodgeChance();
+ float block_chance = pVictim->GetUnitBlockChance();
+ float parry_chance = pVictim->GetUnitParryChance();
+
+ // Useful if want to specify crit & miss chances for melee, else it could be removed
+ DEBUG_LOG("MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance,crit_chance,dodge_chance,parry_chance,block_chance);
+
+ return RollMeleeOutcomeAgainst(pVictim, attType, int32(crit_chance*100), int32(miss_chance*100), int32(dodge_chance*100),int32(parry_chance*100),int32(block_chance*100));
+}
+
+MeleeHitOutcome Unit::RollMeleeOutcomeAgainst (const Unit *pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const
+{
+ if (pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
+ return MELEE_HIT_EVADE;
+
+ int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(pVictim);
+ int32 victimMaxSkillValueForLevel = pVictim->GetMaxSkillValueForLevel(this);
+
+ int32 attackerWeaponSkill = GetWeaponSkillValue(attType,pVictim);
+ int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this);
+
+ // bonus from skills is 0.04%
+ int32 skillBonus = 4 * ( attackerWeaponSkill - victimMaxSkillValueForLevel );
+ int32 sum = 0, tmp = 0;
+ int32 roll = urand (0, 10000);
+
+ DEBUG_LOG ("RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus);
+ DEBUG_LOG ("RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d",
+ roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance);
+
+ tmp = miss_chance;
+
+ if (tmp > 0 && roll < (sum += tmp ))
+ {
+ DEBUG_LOG ("RollMeleeOutcomeAgainst: MISS");
+ return MELEE_HIT_MISS;
+ }
+
+ // always crit against a sitting target (except 0 crit chance)
+ if (pVictim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !pVictim->IsStandState() )
+ {
+ DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT (sitting victim)");
+ return MELEE_HIT_CRIT;
+ }
+
+ // Dodge chance
+
+ // only players can't dodge if attacker is behind
+ if (pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->HasInArc(M_PI,this) && !pVictim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
+ {
+ DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind and victim was a player.");
+ }
+ else
+ {
+ // Reduce dodge chance by attacker expertise rating
+ if (GetTypeId() == TYPEID_PLAYER)
+ dodge_chance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
+ else
+ dodge_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
+
+ // Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
+ dodge_chance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE)*100;
+ dodge_chance = int32 (float (dodge_chance) * GetTotalAuraMultiplier(SPELL_AURA_MOD_ENEMY_DODGE));
+
+ tmp = dodge_chance;
+ if ( (tmp > 0) // check if unit _can_ dodge
+ && ((tmp -= skillBonus) > 0)
+ && roll < (sum += tmp))
+ {
+ DEBUG_LOG ("RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum-tmp, sum);
+ return MELEE_HIT_DODGE;
+ }
+ }
+
+ // parry & block chances
+
+ // check if attack comes from behind, nobody can parry or block if attacker is behind
+ if (!pVictim->HasInArc(M_PI,this) && !pVictim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
+ {
+ DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind.");
+ }
+ else
+ {
+ // Reduce parry chance by attacker expertise rating
+ if (GetTypeId() == TYPEID_PLAYER)
+ parry_chance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
+ else
+ parry_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
+
+ if (pVictim->GetTypeId() == TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY) )
+ {
+ int32 tmp2 = int32(parry_chance);
+ if (tmp2 > 0 // check if unit _can_ parry
+ && (tmp2 -= skillBonus) > 0
+ && roll < (sum += tmp2))
+ {
+ DEBUG_LOG ("RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum-tmp2, sum);
+ return MELEE_HIT_PARRY;
+ }
+ }
+
+ if (pVictim->GetTypeId() == TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) )
+ {
+ tmp = block_chance;
+ if (tmp > 0 // check if unit _can_ block
+ && (tmp -= skillBonus) > 0
+ && roll < (sum += tmp))
+ {
+ DEBUG_LOG ("RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum-tmp, sum);
+ return MELEE_HIT_BLOCK;
+ }
+ }
+ }
+
+ // Critical chance
+ tmp = crit_chance;
+
+ if (tmp > 0 && roll < (sum += tmp))
+ {
+ DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum-tmp, sum);
+ if (GetTypeId() == TYPEID_UNIT && (((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRIT))
+ DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT DISABLED)");
+ else
+ return MELEE_HIT_CRIT;
+ }
+
+ // Max 40% chance to score a glancing blow against mobs that are higher level (can do only players and pets and not with ranged weapon)
+ if (attType != RANGED_ATTACK &&
+ (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet()) &&
+ pVictim->GetTypeId() != TYPEID_PLAYER && !((Creature*)pVictim)->isPet() &&
+ getLevel() < pVictim->getLevelForTarget(this))
+ {
+ // cap possible value (with bonuses > max skill)
+ int32 skill = attackerWeaponSkill;
+ int32 maxskill = attackerMaxSkillValueForLevel;
+ skill = (skill > maxskill) ? maxskill : skill;
+
+ tmp = (10 + (victimDefenseSkill - skill)) * 100;
+ tmp = tmp > 4000 ? 4000 : tmp;
+ if (roll < (sum += tmp))
+ {
+ DEBUG_LOG ("RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum-4000, sum);
+ return MELEE_HIT_GLANCING;
+ }
+ }
+
+ // mobs can score crushing blows if they're 4 or more levels above victim
+ if (getLevelForTarget(pVictim) >= pVictim->getLevelForTarget(this) + 4 &&
+ // can be from by creature (if can) or from controlled player that considered as creature
+ !IsControlledByPlayer() &&
+ !(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH))
+ {
+ // when their weapon skill is 15 or more above victim's defense skill
+ tmp = victimDefenseSkill;
+ int32 tmpmax = victimMaxSkillValueForLevel;
+ // having defense above your maximum (from items, talents etc.) has no effect
+ tmp = tmp > tmpmax ? tmpmax : tmp;
+ // tmp = mob's level * 5 - player's current defense skill
+ tmp = attackerMaxSkillValueForLevel - tmp;
+ if (tmp >= 15)
+ {
+ // add 2% chance per lacking skill point, min. is 15%
+ tmp = tmp * 200 - 1500;
+ if (roll < (sum += tmp))
+ {
+ DEBUG_LOG ("RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum-tmp, sum);
+ return MELEE_HIT_CRUSHING;
+ }
+ }
+ }
+
+ DEBUG_LOG ("RollMeleeOutcomeAgainst: NORMAL");
+ return MELEE_HIT_NORMAL;
+}
+
+uint32 Unit::CalculateDamage(WeaponAttackType attType, bool normalized, bool addTotalPct)
+{
+ float min_damage, max_damage;
+
+ if (GetTypeId() == TYPEID_PLAYER && (normalized || !addTotalPct))
+ ((Player*)this)->CalculateMinMaxDamage(attType,normalized,addTotalPct,min_damage, max_damage);
+ else
+ {
+ switch (attType)
+ {
+ case RANGED_ATTACK:
+ min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE);
+ max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE);
+ break;
+ case BASE_ATTACK:
+ min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE);
+ max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE);
+ break;
+ case OFF_ATTACK:
+ min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE);
+ max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE);
+ break;
+ // Just for good manner
+ default:
+ min_damage = 0.0f;
+ max_damage = 0.0f;
+ break;
+ }
+ }
+
+ if (min_damage > max_damage)
+ {
+ std::swap(min_damage,max_damage);
+ }
+
+ if (max_damage == 0.0f)
+ max_damage = 5.0f;
+
+ return urand((uint32)min_damage, (uint32)max_damage);
+}
+
+float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const
+{
+ if (spellProto->spellLevel <= 0)
+ return 1.0f;
+
+ float LvlPenalty = 0.0f;
+
+ if (spellProto->spellLevel < 20)
+ LvlPenalty = 20.0f - spellProto->spellLevel * 3.75f;
+ float LvlFactor = (float(spellProto->spellLevel) + 6.0f) / float(getLevel());
+ if (LvlFactor > 1.0f)
+ LvlFactor = 1.0f;
+
+ return (100.0f - LvlPenalty) * LvlFactor / 100.0f;
+}
+
+void Unit::SendMeleeAttackStart(Unit* pVictim)
+{
+ WorldPacket data( SMSG_ATTACKSTART, 8 + 8 );
+ data << uint64(GetGUID());
+ data << uint64(pVictim->GetGUID());
+
+ SendMessageToSet(&data, true);
+ DEBUG_LOG( "WORLD: Sent SMSG_ATTACKSTART" );
+}
+
+void Unit::SendMeleeAttackStop(Unit* victim)
+{
+ if (!victim)
+ return;
+
+ WorldPacket data( SMSG_ATTACKSTOP, (4+16) ); // we guess size
+ data.append(GetPackGUID());
+ data.append(victim->GetPackGUID()); // can be 0x00...
+ data << uint32(0); // can be 0x1
+ SendMessageToSet(&data, true);
+ sLog.outDetail("%s %u stopped attacking %s %u", (GetTypeId() == TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), (victim->GetTypeId() == TYPEID_PLAYER ? "player" : "creature"),victim->GetGUIDLow());
+
+ /*if (victim->GetTypeId() == TYPEID_UNIT)
+ ((Creature*)victim)->AI().EnterEvadeMode(this);*/
+}
+
+bool Unit::isSpellBlocked(Unit *pVictim, SpellEntry const * /*spellProto*/, WeaponAttackType attackType)
+{
+ if (pVictim->HasInArc(M_PI,this) || pVictim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
+ {
+ /* Currently not exist spells with ignore block
+ // Ignore combat result aura (parry/dodge check on prepare)
+ AuraList const& ignore = GetAuraEffectsByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
+ for (AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
+ {
+ if (!(*i)->IsAffectedOnSpell(spellProto))
+ continue;
+ if ((*i)->GetMiscValue() == )
+ return false;
+ }
+ */
+
+ // Check creatures flags_extra for disable block
+ if (pVictim->GetTypeId() == TYPEID_UNIT &&
+ ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK )
+ return false;
+
+ float blockChance = pVictim->GetUnitBlockChance();
+ blockChance += (int32(GetWeaponSkillValue(attackType)) - int32(pVictim->GetMaxSkillValueForLevel()))*0.04f;
+ if (roll_chance_f(blockChance))
+ return true;
+ }
+ return false;
+}
+
+bool Unit::isBlockCritical()
+{
+ if (roll_chance_i(GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_CRIT_CHANCE)))
+ return true;
+ return false;
+}
+
+// Melee based spells can be miss, parry or dodge on this step
+// Crit or block - determined on damage calculation phase! (and can be both in some time)
+/*float Unit::MeleeSpellMissChance(Unit *pVictim, WeaponAttackType attType, int32 skillDiff, SpellEntry const *spell)
+{
+ // Calculate hit chance (more correct for chance mod)
+ int32 HitChance;
+
+ // PvP - PvE melee chances
+ int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
+ int32 leveldif = pVictim->getLevelForTarget(this) - getLevelForTarget(pVictim);
+ if (leveldif < 3)
+ HitChance = 95 - leveldif;
+ else
+ HitChance = 93 - (leveldif - 2) * lchance;
+
+ // Hit chance depends from victim auras
+ if (attType == RANGED_ATTACK)
+ HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
+ else
+ HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
+
+ // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
+ if (Player *modOwner = GetSpellModOwner())
+ modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, HitChance);
+
+ // Miss = 100 - hit
+ float miss_chance= 100.0f - HitChance;
+
+ // Bonuses from attacker aura and ratings
+ if (attType == RANGED_ATTACK)
+ miss_chance -= m_modRangedHitChance;
+ else
+ miss_chance -= m_modMeleeHitChance;
+
+ // bonus from skills is 0.04%
+ miss_chance -= skillDiff * 0.04f;
+
+ // Limit miss chance from 0 to 60%
+ if (miss_chance < 0.0f)
+ return 0.0f;
+ if (miss_chance > 60.0f)
+ return 60.0f;
+ return miss_chance;
+}*/
+
+int32 Unit::GetMechanicResistChance(const SpellEntry *spell)
+{
+ if (!spell)
+ return 0;
+ int32 resist_mech = 0;
+ for (uint8 eff = 0; eff < MAX_SPELL_EFFECTS; ++eff)
+ {
+ if (spell->Effect[eff] == 0)
+ break;
+ int32 effect_mech = GetEffectMechanic(spell, eff);
+ if (effect_mech)
+ {
+ int32 temp = GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
+ if (resist_mech < temp)
+ resist_mech = temp;
+ }
+ }
+ return resist_mech;
+}
+
+// Melee based spells hit result calculations
+SpellMissInfo Unit::MeleeSpellHitResult(Unit *pVictim, SpellEntry const *spell)
+{
+ WeaponAttackType attType = BASE_ATTACK;
+
+ // Check damage class instead of attack type to correctly handle judgements
+ // - they are meele, but can't be dodged/parried/deflected because of ranged dmg class
+ if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED)
+ attType = RANGED_ATTACK;
+
+ int32 attackerWeaponSkill;
+ // skill value for these spells (for example judgements) is 5* level
+ if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED && !IsRangedWeaponSpell(spell))
+ attackerWeaponSkill = getLevel() * 5;
+ // bonus from skills is 0.04% per skill Diff
+ else
+ attackerWeaponSkill = int32(GetWeaponSkillValue(attType,pVictim));
+
+ int32 skillDiff = attackerWeaponSkill - int32(pVictim->GetMaxSkillValueForLevel(this));
+ int32 fullSkillDiff = attackerWeaponSkill - int32(pVictim->GetDefenseSkillValue(this));
+
+ uint32 roll = urand (0, 10000);
+
+ uint32 missChance = uint32(MeleeSpellMissChance(pVictim, attType, fullSkillDiff, spell->Id)*100.0f);
+ // Roll miss
+ uint32 tmp = missChance;
+ if (roll < tmp)
+ return SPELL_MISS_MISS;
+
+ // Chance resist mechanic (select max value from every mechanic spell effect)
+ int32 resist_mech = 0;
+ // Get effects mechanic and chance
+ for (uint8 eff = 0; eff < MAX_SPELL_EFFECTS; ++eff)
+ {
+ int32 effect_mech = GetEffectMechanic(spell, eff);
+ if (effect_mech)
+ {
+ int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
+ if (resist_mech < temp*100)
+ resist_mech = temp*100;
+ }
+ }
+ // Roll chance
+ tmp += resist_mech;
+ if (roll < tmp)
+ return SPELL_MISS_RESIST;
+
+ bool canDodge = true;
+ bool canParry = true;
+ bool canBlock = spell->AttributesEx3 & SPELL_ATTR_EX3_BLOCKABLE_SPELL;
+
+ // Same spells cannot be parry/dodge
+ if (spell->Attributes & SPELL_ATTR_IMPOSSIBLE_DODGE_PARRY_BLOCK)
+ return SPELL_MISS_NONE;
+
+ // Chance resist mechanic
+ int32 resist_chance = pVictim->GetMechanicResistChance(spell)*100;
+ tmp += resist_chance;
+ if (roll < tmp)
+ return SPELL_MISS_RESIST;
+
+ // Ranged attacks can only miss, resist and deflect
+ if (attType == RANGED_ATTACK)
+ {
+ // only if in front
+ if (pVictim->HasInArc(M_PI,this) || pVictim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
+ {
+ int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
+ tmp+=deflect_chance;
+ if (roll < tmp)
+ return SPELL_MISS_DEFLECT;
+ }
+ return SPELL_MISS_NONE;
+ }
+
+ // Check for attack from behind
+ if (!pVictim->HasInArc(M_PI,this) && !pVictim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
+ {
+ // Can`t dodge from behind in PvP (but its possible in PvE)
+ if (pVictim->GetTypeId() == TYPEID_PLAYER)
+ canDodge = false;
+ // Can`t parry or block
+ canParry = false;
+ canBlock = false;
+ }
+ // Check creatures flags_extra for disable parry
+ if (pVictim->GetTypeId() == TYPEID_UNIT)
+ {
+ uint32 flagEx = ((Creature*)pVictim)->GetCreatureInfo()->flags_extra;
+ if (flagEx & CREATURE_FLAG_EXTRA_NO_PARRY)
+ canParry = false;
+ // Check creatures flags_extra for disable block
+ if (flagEx & CREATURE_FLAG_EXTRA_NO_BLOCK)
+ canBlock = false;
+ }
+ // Ignore combat result aura
+ AuraEffectList const &ignore = GetAuraEffectsByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
+ for (AuraEffectList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
+ {
+ if (!(*i)->IsAffectedOnSpell(spell))
+ continue;
+ switch ((*i)->GetMiscValue())
+ {
+ case MELEE_HIT_DODGE: canDodge = false; break;
+ case MELEE_HIT_BLOCK: canBlock = false; break;
+ case MELEE_HIT_PARRY: canParry = false; break;
+ default:
+ DEBUG_LOG("Spell %u SPELL_AURA_IGNORE_COMBAT_RESULT have unhandled state %d", (*i)->GetId(), (*i)->GetMiscValue());
+ break;
+ }
+ }
+
+ if (canDodge)
+ {
+ // Roll dodge
+ int32 dodgeChance = int32(pVictim->GetUnitDodgeChance()*100.0f) - skillDiff * 4;
+ // Reduce enemy dodge chance by SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
+ dodgeChance += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE)*100;
+ dodgeChance = int32(float(dodgeChance) * GetTotalAuraMultiplier(SPELL_AURA_MOD_ENEMY_DODGE));
+ // Reduce dodge chance by attacker expertise rating
+ if (GetTypeId() == TYPEID_PLAYER)
+ dodgeChance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
+ else
+ dodgeChance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
+ if (dodgeChance < 0)
+ dodgeChance = 0;
+
+ if (roll < (tmp += dodgeChance))
+ return SPELL_MISS_DODGE;
+ }
+
+ if (canParry)
+ {
+ // Roll parry
+ int32 parryChance = int32(pVictim->GetUnitParryChance()*100.0f) - skillDiff * 4;
+ // Reduce parry chance by attacker expertise rating
+ if (GetTypeId() == TYPEID_PLAYER)
+ parryChance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
+ else
+ parryChance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
+ if (parryChance < 0)
+ parryChance = 0;
+
+ tmp += parryChance;
+ if (roll < tmp)
+ return SPELL_MISS_PARRY;
+ }
+
+ if (canBlock)
+ {
+ int32 blockChance = int32(pVictim->GetUnitBlockChance()*100.0f) - skillDiff * 4;
+ if (blockChance < 0)
+ blockChance = 0;
+ tmp += blockChance;
+
+ if (roll < tmp)
+ return SPELL_MISS_BLOCK;
+ }
+
+ return SPELL_MISS_NONE;
+}
+
+// TODO need use unit spell resistances in calculations
+SpellMissInfo Unit::MagicSpellHitResult(Unit *pVictim, SpellEntry const *spell)
+{
+ // Can`t miss on dead target (on skinning for example)
+ if (!pVictim->isAlive() && pVictim->GetTypeId() != TYPEID_PLAYER)
+ return SPELL_MISS_NONE;
+
+ SpellSchoolMask schoolMask = GetSpellSchoolMask(spell);
+ // PvP - PvE spell misschances per leveldif > 2
+ int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 7 : 11;
+ int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
+
+ // Base hit chance from attacker and victim levels
+ int32 modHitChance;
+ if (leveldif < 3)
+ modHitChance = 96 - leveldif;
+ else
+ modHitChance = 94 - (leveldif - 2) * lchance;
+
+ // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
+ if (Player *modOwner = GetSpellModOwner())
+ modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance);
+ // Increase from attacker SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT auras
+ modHitChance+=GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT, schoolMask);
+ // Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras
+ modHitChance+= pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask);
+ // Reduce spell hit chance for Area of effect spells from victim SPELL_AURA_MOD_AOE_AVOIDANCE aura
+ if (IsAreaOfEffectSpell(spell))
+ modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE);
+ // Reduce spell hit chance for dispel mechanic spells from victim SPELL_AURA_MOD_DISPEL_RESIST
+ if (IsDispelSpell(spell))
+ modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_DISPEL_RESIST);
+
+ int32 HitChance = modHitChance * 100;
+ // Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings
+ HitChance += int32(m_modSpellHitChance*100.0f);
+
+ // Decrease hit chance from victim rating bonus
+ if (pVictim->GetTypeId() == TYPEID_PLAYER)
+ HitChance -= int32(((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_SPELL)*100.0f);
+
+ if (HitChance < 100)
+ HitChance = 100;
+ else if (HitChance > 10000)
+ HitChance = 10000;
+
+ int32 tmp = 10000 - HitChance;
+
+ uint32 rand = urand(0,10000);
+
+ if (rand < tmp)
+ return SPELL_MISS_MISS;
+
+ // Chance resist mechanic (select max value from every mechanic spell effect)
+ int32 resist_chance = pVictim->GetMechanicResistChance(spell);
+ tmp += resist_chance;
+
+ // Chance resist debuff
+ tmp -= pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel));
+
+ // Roll chance
+ if (rand < tmp)
+ return SPELL_MISS_RESIST;
+
+ // cast by caster in front of victim
+ if (pVictim->HasInArc(M_PI,this) || pVictim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
+ {
+ int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
+ tmp+=deflect_chance;
+ if (rand < tmp)
+ return SPELL_MISS_DEFLECT;
+ }
+
+ return SPELL_MISS_NONE;
+}
+
+// Calculate spell hit result can be:
+// Every spell can: Evade/Immune/Reflect/Sucesful hit
+// For melee based spells:
+// Miss
+// Dodge
+// Parry
+// For spells
+// Resist
+SpellMissInfo Unit::SpellHitResult(Unit *pVictim, SpellEntry const *spell, bool CanReflect)
+{
+ // Return evade for units in evade mode
+ if (pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode() && this != pVictim)
+ return SPELL_MISS_EVADE;
+
+ // Check for immune
+ if (pVictim->IsImmunedToSpell(spell))
+ return SPELL_MISS_IMMUNE;
+
+ // All positive spells can`t miss
+ // TODO: client not show miss log for this spells - so need find info for this in dbc and use it!
+ if (IsPositiveSpell(spell->Id)
+ &&(!IsHostileTo(pVictim))) //prevent from affecting enemy by "positive" spell
+ return SPELL_MISS_NONE;
+ // Check for immune
+ if (pVictim->IsImmunedToDamage(spell))
+ return SPELL_MISS_IMMUNE;
+
+ if(this == pVictim)
+ return SPELL_MISS_NONE;
+
+ // Try victim reflect spell
+ if (CanReflect)
+ {
+ int32 reflectchance = pVictim->GetTotalAuraModifier(SPELL_AURA_REFLECT_SPELLS);
+ Unit::AuraEffectList const& mReflectSpellsSchool = pVictim->GetAuraEffectsByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL);
+ for (Unit::AuraEffectList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i)
+ if((*i)->GetMiscValue() & GetSpellSchoolMask(spell))
+ reflectchance += (*i)->GetAmount();
+ if (reflectchance > 0 && roll_chance_i(reflectchance))
+ {
+ // Start triggers for remove charges if need (trigger only for victim, and mark as active spell)
+ ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_TAKEN_NEGATIVE_MAGIC_SPELL, PROC_EX_REFLECT, 1, BASE_ATTACK, spell);
+ return SPELL_MISS_REFLECT;
+ }
+ }
+
+ switch (spell->DmgClass)
+ {
+ case SPELL_DAMAGE_CLASS_RANGED:
+ case SPELL_DAMAGE_CLASS_MELEE:
+ return MeleeSpellHitResult(pVictim, spell);
+ case SPELL_DAMAGE_CLASS_NONE:
+ return SPELL_MISS_NONE;
+ case SPELL_DAMAGE_CLASS_MAGIC:
+ return MagicSpellHitResult(pVictim, spell);
+ }
+ return SPELL_MISS_NONE;
+}
+
+/*float Unit::MeleeMissChanceCalc(const Unit *pVictim, WeaponAttackType attType) const
+{
+ if(!pVictim)
+ return 0.0f;
+
+ // Base misschance 5%
+ float misschance = 5.0f;
+
+ // DualWield - Melee spells and physical dmg spells - 5% , white damage 24%
+ if (haveOffhandWeapon() && attType != RANGED_ATTACK)
+ {
+ bool isNormal = false;
+ for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
+ {
+ if( m_currentSpells[i] && (GetSpellSchoolMask(m_currentSpells[i]->m_spellInfo) & SPELL_SCHOOL_MASK_NORMAL) )
+ {
+ isNormal = true;
+ break;
+ }
+ }
+ if (isNormal || m_currentSpells[CURRENT_MELEE_SPELL])
+ misschance = 5.0f;
+ else
+ misschance = 24.0f;
+ }
+
+ // PvP : PvE melee misschances per leveldif > 2
+ int32 chance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
+
+ int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
+ if(leveldif < 0)
+ leveldif = 0;
+
+ // Hit chance from attacker based on ratings and auras
+ float m_modHitChance;
+ if (attType == RANGED_ATTACK)
+ m_modHitChance = m_modRangedHitChance;
+ else
+ m_modHitChance = m_modMeleeHitChance;
+
+ if(leveldif < 3)
+ misschance += (leveldif - m_modHitChance);
+ else
+ misschance += ((leveldif - 2) * chance - m_modHitChance);
+
+ // Hit chance for victim based on ratings
+ if (pVictim->GetTypeId() == TYPEID_PLAYER)
+ {
+ if (attType == RANGED_ATTACK)
+ misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_RANGED);
+ else
+ misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_MELEE);
+ }
+
+ // Modify miss chance by victim auras
+ if(attType == RANGED_ATTACK)
+ misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
+ else
+ misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
+
+ // Modify miss chance from skill difference ( bonus from skills is 0.04% )
+ int32 skillBonus = int32(GetWeaponSkillValue(attType,pVictim)) - int32(pVictim->GetDefenseSkillValue(this));
+ misschance -= skillBonus * 0.04f;
+
+ // Limit miss chance from 0 to 60%
+ if ( misschance < 0.0f)
+ return 0.0f;
+ if ( misschance > 60.0f)
+ return 60.0f;
+
+ return misschance;
+}*/
+
+uint32 Unit::GetDefenseSkillValue(Unit const* target) const
+{
+ if(GetTypeId() == TYPEID_PLAYER)
+ {
+ // in PvP use full skill instead current skill value
+ uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER)
+ ? ((Player*)this)->GetMaxSkillValue(SKILL_DEFENSE)
+ : ((Player*)this)->GetSkillValue(SKILL_DEFENSE);
+ value += uint32(((Player*)this)->GetRatingBonusValue(CR_DEFENSE_SKILL));
+ return value;
+ }
+ else
+ return GetUnitMeleeSkill(target);
+}
+
+float Unit::GetUnitDodgeChance() const
+{
+ if(hasUnitState(UNIT_STAT_STUNNED))
+ return 0.0f;
+ if( GetTypeId() == TYPEID_PLAYER )
+ return GetFloatValue(PLAYER_DODGE_PERCENTAGE);
+ else
+ {
+ if(((Creature const*)this)->isTotem())
+ return 0.0f;
+ else
+ {
+ float dodge = 5.0f;
+ dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT);
+ return dodge > 0.0f ? dodge : 0.0f;
+ }
+ }
+}
+
+float Unit::GetUnitParryChance() const
+{
+ if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
+ return 0.0f;
+
+ float chance = 0.0f;
+
+ if(GetTypeId() == TYPEID_PLAYER)
+ {
+ Player const* player = (Player const*)this;
+ if(player->CanParry() )
+ {
+ Item *tmpitem = player->GetWeaponForAttack(BASE_ATTACK,true);
+ if(!tmpitem)
+ tmpitem = player->GetWeaponForAttack(OFF_ATTACK,true);
+
+ if(tmpitem)
+ chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE);
+ }
+ }
+ else if(GetTypeId() == TYPEID_UNIT)
+ {
+ if(GetCreatureType() == CREATURE_TYPE_HUMANOID)
+ {
+ chance = 5.0f;
+ chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT);
+ }
+ }
+
+ return chance > 0.0f ? chance : 0.0f;
+}
+
+float Unit::GetUnitBlockChance() const
+{
+ if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
+ return 0.0f;
+
+ if(GetTypeId() == TYPEID_PLAYER)
+ {
+ Player const* player = (Player const*)this;
+ if(player->CanBlock() )
+ {
+ Item *tmpitem = player->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
+ if(tmpitem && !tmpitem->IsBroken() && tmpitem->GetProto()->Block)
+ return GetFloatValue(PLAYER_BLOCK_PERCENTAGE);
+ }
+ // is player but has no block ability or no not broken shield equipped
+ return 0.0f;
+ }
+ else
+ {
+ if(((Creature const*)this)->isTotem())
+ return 0.0f;
+ else
+ {
+ float block = 5.0f;
+ block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT);
+ return block > 0.0f ? block : 0.0f;
+ }
+ }
+}
+
+float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit *pVictim) const
+{
+ float crit;
+
+ if(GetTypeId() == TYPEID_PLAYER)
+ {
+ switch(attackType)
+ {
+ case BASE_ATTACK:
+ crit = GetFloatValue( PLAYER_CRIT_PERCENTAGE );
+ break;
+ case OFF_ATTACK:
+ crit = GetFloatValue( PLAYER_OFFHAND_CRIT_PERCENTAGE );
+ break;
+ case RANGED_ATTACK:
+ crit = GetFloatValue( PLAYER_RANGED_CRIT_PERCENTAGE );
+ break;
+ // Just for good manner
+ default:
+ crit = 0.0f;
+ break;
+ }
+ }
+ else
+ {
+ crit = 5.0f;
+ crit += GetTotalAuraModifier(SPELL_AURA_MOD_WEAPON_CRIT_PERCENT);
+ crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PCT);
+ }
+
+ // flat aura mods
+ if(attackType == RANGED_ATTACK)
+ crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE);
+ else
+ crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE);
+
+ crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
+
+ // reduce crit chance from Rating for players
+ if (attackType != RANGED_ATTACK)
+ {
+ crit -= pVictim->GetMeleeCritChanceReduction();
+ // Glyph of barkskin
+ if (pVictim->HasAura(63057) && pVictim->HasAura(22812))
+ crit-=25.0f;
+ }
+ else
+ crit -= pVictim->GetRangedCritChanceReduction();
+
+ // Apply crit chance from defence skill
+ crit += (int32(GetMaxSkillValueForLevel(pVictim)) - int32(pVictim->GetDefenseSkillValue(this))) * 0.04f;
+
+ if (crit < 0.0f)
+ crit = 0.0f;
+ return crit;
+}
+
+uint32 Unit::GetWeaponSkillValue (WeaponAttackType attType, Unit const* target) const
+{
+ uint32 value = 0;
+ if(GetTypeId() == TYPEID_PLAYER)
+ {
+ Item* item = ((Player*)this)->GetWeaponForAttack(attType,true);
+
+ // feral or unarmed skill only for base attack
+ if (attType != BASE_ATTACK && !item)
+ return 0;
+
+ if (IsInFeralForm())
+ return GetMaxSkillValueForLevel(); // always maximized SKILL_FERAL_COMBAT in fact
+
+ // weapon skill or (unarmed for base attack and fist weapons)
+ uint32 skill = item && item->GetSkill() != SKILL_FIST_WEAPONS ? item->GetSkill() : SKILL_UNARMED;
+
+ // in PvP use full skill instead current skill value
+ value = (target && target->IsControlledByPlayer())
+ ? ((Player*)this)->GetMaxSkillValue(skill)
+ : ((Player*)this)->GetSkillValue(skill);
+ // Modify value from ratings
+ value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL));
+ switch (attType)
+ {
+ case BASE_ATTACK: value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_MAINHAND)); break;
+ case OFF_ATTACK: value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_OFFHAND)); break;
+ case RANGED_ATTACK: value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_RANGED)); break;
+ }
+ }
+ else
+ value = GetUnitMeleeSkill(target);
+ return value;
+}
+
+void Unit::_DeleteRemovedAuras()
+{
+ while(!m_removedAuras.empty())
+ {
+ delete m_removedAuras.front();
+ m_removedAuras.pop_front();
+ }
+}
+
+void Unit::_UpdateSpells( uint32 time )
+{
+ if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
+ _UpdateAutoRepeatSpell();
+
+ // remove finished spells from current pointers
+ for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
+ {
+ if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED)
+ {
+ m_currentSpells[i]->SetReferencedFromCurrent(false);
+ m_currentSpells[i] = NULL; // remove pointer
+ }
+ }
+
+ // m_auraUpdateIterator can be updated in indirect called code at aura remove to skip next planned to update but removed auras
+ for (m_auraUpdateIterator = m_ownedAuras.begin(); m_auraUpdateIterator != m_ownedAuras.end();)
+ {
+ Aura * i_aura = m_auraUpdateIterator->second;
+ ++m_auraUpdateIterator; // need shift to next for allow update if need into aura update
+ i_aura->UpdateOwner(time, this);
+ }
+
+ // remove expired auras - do that after updates(used in scripts?)
+ for (AuraMap::iterator i = m_ownedAuras.begin(); i != m_ownedAuras.end();)
+ {
+ if(i->second->IsExpired())
+ RemoveOwnedAura(i, AURA_REMOVE_BY_EXPIRE);
+ else
+ ++i;
+ }
+
+ for (VisibleAuraMap::iterator itr = m_visibleAuras.begin(); itr != m_visibleAuras.end(); ++itr)
+ if (itr->second->IsNeedClientUpdate())
+ itr->second->ClientUpdate();
+
+ _DeleteRemovedAuras();
+
+ if(!m_gameObj.empty())
+ {
+ GameObjectList::iterator itr;
+ for (itr = m_gameObj.begin(); itr != m_gameObj.end();)
+ {
+ if( !(*itr)->isSpawned() )
+ {
+ (*itr)->SetOwnerGUID(0);
+ (*itr)->SetRespawnTime(0);
+ (*itr)->Delete();
+ m_gameObj.erase(itr++);
+ }
+ else
+ ++itr;
+ }
+ }
+}
+
+void Unit::_UpdateAutoRepeatSpell()
+{
+ //check "realtime" interrupts
+ if ( (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->isMoving()) || IsNonMeleeSpellCasted(false,false,true,m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id == 75) )
+ {
+ // cancel wand shoot
+ if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75)
+ InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
+ m_AutoRepeatFirstCast = true;
+ return;
+ }
+
+ //apply delay
+ if ( m_AutoRepeatFirstCast && getAttackTimer(RANGED_ATTACK) < 500 )
+ setAttackTimer(RANGED_ATTACK,500);
+ m_AutoRepeatFirstCast = false;
+
+ //castroutine
+ if (isAttackReady(RANGED_ATTACK))
+ {
+ // Check if able to cast
+ if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->CheckCast(true) != SPELL_CAST_OK)
+ {
+ InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
+ return;
+ }
+
+ // we want to shoot
+ Spell* spell = new Spell(this, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, true, 0);
+ spell->prepare(&(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_targets));
+
+ // all went good, reset attack
+ resetAttackTimer(RANGED_ATTACK);
+ }
+}
+
+void Unit::SetCurrentCastedSpell( Spell * pSpell )
+{
+ assert(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells
+
+ CurrentSpellTypes CSpellType = pSpell->GetCurrentContainer();
+
+ if (pSpell == m_currentSpells[CSpellType]) return; // avoid breaking self
+
+ // break same type spell if it is not delayed
+ InterruptSpell(CSpellType,false);
+
+ // special breakage effects:
+ switch (CSpellType)
+ {
+ case CURRENT_GENERIC_SPELL:
+ {
+ // generic spells always break channeled not delayed spells
+ InterruptSpell(CURRENT_CHANNELED_SPELL,false);
+
+ // autorepeat breaking
+ if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
+ {
+ // break autorepeat if not Auto Shot
+ if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75)
+ InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
+ m_AutoRepeatFirstCast = true;
+ }
+ addUnitState(UNIT_STAT_CASTING);
+ } break;
+
+ case CURRENT_CHANNELED_SPELL:
+ {
+ // channel spells always break generic non-delayed and any channeled spells
+ InterruptSpell(CURRENT_GENERIC_SPELL,false);
+ InterruptSpell(CURRENT_CHANNELED_SPELL);
+
+ // it also does break autorepeat if not Auto Shot
+ if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] &&
+ m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75 )
+ InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
+ addUnitState(UNIT_STAT_CASTING);
+ } break;
+
+ case CURRENT_AUTOREPEAT_SPELL:
+ {
+ // only Auto Shoot does not break anything
+ if (pSpell->m_spellInfo->Id != 75)
+ {
+ // generic autorepeats break generic non-delayed and channeled non-delayed spells
+ InterruptSpell(CURRENT_GENERIC_SPELL,false);
+ InterruptSpell(CURRENT_CHANNELED_SPELL,false);
+ }
+ // special action: set first cast flag
+ m_AutoRepeatFirstCast = true;
+ } break;
+
+ default:
+ {
+ // other spell types don't break anything now
+ } break;
+ }
+
+ // current spell (if it is still here) may be safely deleted now
+ if (m_currentSpells[CSpellType])
+ m_currentSpells[CSpellType]->SetReferencedFromCurrent(false);
+
+ // set new current spell
+ m_currentSpells[CSpellType] = pSpell;
+ pSpell->SetReferencedFromCurrent(true);
+
+ pSpell->m_selfContainer = &(m_currentSpells[pSpell->GetCurrentContainer()]);
+}
+
+void Unit::InterruptSpell(CurrentSpellTypes spellType, bool withDelayed, bool withInstant)
+{
+ assert(spellType < CURRENT_MAX_SPELL);
+
+ //sLog.outDebug("Interrupt spell for unit %u.", GetEntry());
+ Spell *spell = m_currentSpells[spellType];
+ if(spell
+ && (withDelayed || spell->getState() != SPELL_STATE_DELAYED)
+ && (withInstant || spell->GetCastTime() > 0))
+ {
+ // for example, do not let self-stun aura interrupt itself
+ if(!spell->IsInterruptable())
+ return;
+
+ m_currentSpells[spellType] = NULL;
+
+ // send autorepeat cancel message for autorepeat spells
+ if (spellType == CURRENT_AUTOREPEAT_SPELL)
+ {
+ if(GetTypeId() == TYPEID_PLAYER)
+ ((Player*)this)->SendAutoRepeatCancel(this);
+ }
+
+ if (spell->getState() != SPELL_STATE_FINISHED)
+ spell->cancel();
+ spell->SetReferencedFromCurrent(false);
+ }
+}
+
+void Unit::FinishSpell(CurrentSpellTypes spellType, bool ok /*= true*/)
+{
+ Spell* spell = m_currentSpells[spellType];
+ if (!spell)
+ return;
+
+ if (spellType == CURRENT_CHANNELED_SPELL)
+ spell->SendChannelUpdate(0);
+
+ spell->finish(ok);
+}
+
+bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat, bool isAutoshoot) const
+{
+ // We don't do loop here to explicitly show that melee spell is excluded.
+ // Maybe later some special spells will be excluded too.
+
+ // generic spells are casted when they are not finished and not delayed
+ if ( m_currentSpells[CURRENT_GENERIC_SPELL] &&
+ (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
+ (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
+ {
+ if (!isAutoshoot || !(m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_NOT_RESET_AUTOSHOT))
+ return(true);
+ }
+ // channeled spells may be delayed, but they are still considered casted
+ else if ( !skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] &&
+ (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED) )
+ {
+ if (!isAutoshoot || !(m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->AttributesEx2 & SPELL_ATTR_EX2_NOT_RESET_AUTOSHOT))
+ return(true);
+ }
+ // autorepeat spells may be finished or delayed, but they are still considered casted
+ else if ( !skipAutorepeat && m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
+ return(true);
+
+ return(false);
+}
+
+void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id, bool withInstant)
+{
+ // generic spells are interrupted if they are not finished or delayed
+ if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id==spell_id))
+ InterruptSpell(CURRENT_GENERIC_SPELL,withDelayed,withInstant);
+
+ // autorepeat spells are interrupted if they are not finished or delayed
+ if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id==spell_id))
+ InterruptSpell(CURRENT_AUTOREPEAT_SPELL,withDelayed,withInstant);
+
+ // channeled spells are interrupted if they are not finished, even if they are delayed
+ if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id==spell_id))
+ InterruptSpell(CURRENT_CHANNELED_SPELL,true,true);
+}
+
+Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const
+{
+ for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
+ if(m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id==spell_id)
+ return m_currentSpells[i];
+ return NULL;
+}
+
+int32 Unit::GetCurrentSpellCastTime(uint32 spell_id) const
+{
+ if (Spell const * spell = FindCurrentSpellBySpellId(spell_id))
+ return spell->GetCastTime();
+ return 0;
+}
+
+bool Unit::isInFrontInMap(Unit const* target, float distance, float arc) const
+{
+ return IsWithinDistInMap(target, distance) && HasInArc( arc, target );
+}
+
+bool Unit::isInBackInMap(Unit const* target, float distance, float arc) const
+{
+ return IsWithinDistInMap(target, distance) && !HasInArc( 2 * M_PI - arc, target );
+}
+
+void Unit::SetFacingToObject(WorldObject* pObject)
+{
+ // update orientation at server
+ SetOrientation(GetAngle(pObject));
+
+ // and client
+ WorldPacket data;
+ BuildHeartBeatMsg(&data);
+ SendMessageToSet(&data, false);
+}
+
+bool Unit::isInAccessiblePlaceFor(Creature const* c) const
+{
+ if(IsInWater())
+ return c->canSwim();
+ else
+ return c->canWalk() || c->canFly();
+}
+
+bool Unit::IsInWater() const
+{
+ return GetBaseMap()->IsInWater(GetPositionX(),GetPositionY(), GetPositionZ());
+}
+
+bool Unit::IsUnderWater() const
+{
+ return GetBaseMap()->IsUnderWater(GetPositionX(),GetPositionY(),GetPositionZ());
+}
+
+void Unit::DeMorph()
+{
+ SetDisplayId(GetNativeDisplayId());
+}
+
+void Unit::_AddAura(UnitAura * aura, Unit * caster)
+{
+ assert(!m_cleanupDone);
+ m_ownedAuras.insert(AuraMap::value_type(aura->GetId(), aura));
+
+ // passive and Incanter's Absorption and auras with different type can stack with themselves any number of times
+ if (!aura->IsPassive() && aura->GetId() != 44413)
+ {
+ // find current aura from spell and change it's stackamount
+ if (Aura * foundAura = GetOwnedAura(aura->GetId(), aura->GetCasterGUID(), 0, aura))
+ {
+ if(aura->GetSpellProto()->StackAmount)
+ aura->ModStackAmount(foundAura->GetStackAmount());
+
+ // Use the new one to replace the old one
+ // This is the only place where AURA_REMOVE_BY_STACK should be used
+ RemoveOwnedAura(foundAura, AURA_REMOVE_BY_STACK);
+ }
+ }
+ _RemoveNoStackAurasDueToAura(aura);
+
+ if (aura->IsRemoved())
+ return;
+
+ aura->SetIsSingleTarget(caster && IsSingleTargetSpell(aura->GetSpellProto()));
+ if (aura->IsSingleTarget())
+ {
+ // register single target aura
+ caster->GetSingleCastAuras().push_back(aura);
+ // remove other single target auras
+ for (;;)
+ {
+ bool restart = false;
+ Unit::AuraList& scAuras = caster->GetSingleCastAuras();
+ for (Unit::AuraList::iterator itr = scAuras.begin(); itr != scAuras.end(); ++itr)
+ {
+ if( (*itr) != aura &&
+ IsSingleTargetSpells((*itr)->GetSpellProto(), aura->GetSpellProto()))
+ {
+ (*itr)->Remove();
+ restart = true;
+ break;
+ }
+ }
+
+ if(!restart)
+ break;
+ }
+ }
+}
+
+// creates aura application instance and registers it in lists
+// aura application effects are handled separately to prevent aura list corruption
+AuraApplication * Unit::_CreateAuraApplication(Aura * aura, uint8 effMask)
+{
+ // can't apply aura on unit which is going to be deleted - to not create a memory leak
+ assert(!m_cleanupDone);
+ // aura musn't be removed
+ assert(!aura->IsRemoved());
+
+ SpellEntry const* aurSpellInfo = aura->GetSpellProto();
+ uint32 aurId = aurSpellInfo->Id;
+
+ // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load)
+ if( !isAlive() && !IsDeathPersistentSpell(aurSpellInfo) &&
+ (GetTypeId() != TYPEID_PLAYER || !((Player*)this)->GetSession()->PlayerLoading()) )
+ return NULL;
+
+ Unit * caster = aura->GetCaster();
+
+ AuraApplication * aurApp = new AuraApplication(this, caster, aura, effMask);
+ m_appliedAuras.insert(AuraApplicationMap::value_type(aurId, aurApp));
+
+ if(aurSpellInfo->AuraInterruptFlags)
+ {
+ m_interruptableAuras.push_back(aurApp);
+ AddInterruptMask(aurSpellInfo->AuraInterruptFlags);
+ }
+
+ if(AuraState aState = GetSpellAuraState(aura->GetSpellProto()))
+ m_auraStateAuras.insert(AuraStateAurasMap::value_type(aState, aurApp));
+
+ aura->_ApplyForTarget(this, caster, aurApp);
+ return aurApp;
+}
+
+void Unit::_ApplyAuraEffect(Aura * aura, uint8 effIndex)
+{
+ assert(aura);
+ assert(aura->HasEffect(effIndex));
+ AuraApplication * aurApp = aura->GetApplicationOfTarget(GetGUID());
+ assert(aurApp);
+ if (!aurApp->GetEffectMask())
+ _ApplyAura(aurApp, 1<<effIndex);
+ else
+ aurApp->_HandleEffect(effIndex, true);
+}
+
+// handles effects of aura application
+// should be done after registering aura in lists
+void Unit::_ApplyAura(AuraApplication * aurApp, uint8 effMask)
+{
+ Aura * aura = aurApp->GetBase();
+
+ _RemoveNoStackAurasDueToAura(aura);
+
+ if (aurApp->GetRemoveMode())
+ return;
+
+ // Update target aura state flag
+ if(AuraState aState = GetSpellAuraState(aura->GetSpellProto()))
+ ModifyAuraState(aState, true);
+
+ if (aurApp->GetRemoveMode())
+ return;
+
+ // Sitdown on apply aura req seated
+ if (aura->GetSpellProto()->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED && !IsSitState())
+ SetStandState(UNIT_STAND_STATE_SIT);
+
+ Unit * caster = aura->GetCaster();
+
+ if (aurApp->GetRemoveMode())
+ return;
+
+ aura->HandleAuraSpecificMods(aurApp, caster, true);
+
+ // apply effects of the aura
+ for (uint8 i = 0 ; i < MAX_SPELL_EFFECTS; ++i)
+ {
+ if (effMask & 1<<i && (!aurApp->GetRemoveMode()))
+ aurApp->_HandleEffect(i, true);
+ }
+}
+
+// removes aura application from lists and unapplies effects
+void Unit::_UnapplyAura(AuraApplicationMap::iterator &i, AuraRemoveMode removeMode)
+{
+ AuraApplication * aurApp = i->second;
+ assert(aurApp);
+ assert(!aurApp->GetRemoveMode());
+ assert(aurApp->GetTarget() == this);
+ aurApp->SetRemoveMode(removeMode);
+ Aura * aura = aurApp->GetBase();
+ sLog.outDebug("Aura %u now is remove mode %d", aura->GetId(), removeMode);
+
+ // dead loop is killing the server probably
+ assert(m_removedAurasCount < 0xFFFFFFFF);
+
+ ++m_removedAurasCount;
+
+ Unit * caster = aura->GetCaster();
+
+ // Remove all pointers from lists here to prevent possible pointer invalidation on spellcast/auraapply/auraremove
+ m_appliedAuras.erase(i);
+
+ if (aura->GetSpellProto()->AuraInterruptFlags)
+ {
+ m_interruptableAuras.remove(aurApp);
+ UpdateInterruptMask();
+ }
+
+ bool auraStateFound = false;
+ AuraState auraState;
+ if (auraState = GetSpellAuraState(aura->GetSpellProto()))
+ {
+ bool canBreak = false;
+ // Get mask of all aurastates from remaining auras
+ for (AuraStateAurasMap::iterator itr = m_auraStateAuras.lower_bound(auraState); itr != m_auraStateAuras.upper_bound(auraState) && !(auraStateFound && canBreak);)
+ {
+ if (itr->second == aurApp)
+ {
+ m_auraStateAuras.erase(itr);
+ itr = m_auraStateAuras.lower_bound(auraState);
+ canBreak = true;
+ continue;
+ }
+ auraStateFound = true;
+ ++itr;
+ }
+ }
+
+ aurApp->_Remove();
+ aura->_UnapplyForTarget(this, caster, aurApp);
+
+ // remove effects of the spell - needs to be done after removing aura from lists
+ for (uint8 itr = 0 ; itr < MAX_SPELL_EFFECTS; ++itr)
+ {
+ if (aurApp->HasEffect(itr))
+ aurApp->_HandleEffect(itr, false);
+ }
+
+ // all effect mustn't be applied
+ assert(!aurApp->GetEffectMask());
+
+ // Remove totem at next update if totem looses its aura
+ if (aurApp->GetRemoveMode() == AURA_REMOVE_BY_EXPIRE && GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isTotem()&& ((TempSummon*)this)->GetSummonerGUID() == aura->GetCasterGUID())
+ {
+ if (((Totem*)this)->GetSpell() == aura->GetId() && ((Totem*)this)->GetTotemType() == TOTEM_PASSIVE)
+ ((Totem*)this)->setDeathState(JUST_DIED);
+ }
+
+ // Remove aurastates only if were not found
+ if (!auraStateFound)
+ ModifyAuraState(auraState, false);
+
+ aura->HandleAuraSpecificMods(aurApp, caster, false);
+
+ // only way correctly remove all auras from list
+ //if(removedAuras != m_removedAurasCount) new aura may be added
+ i = m_appliedAuras.begin();
+}
+
+void Unit::_UnapplyAura(AuraApplication * aurApp, AuraRemoveMode removeMode)
+{
+ // aura can be removed from unit only if it's applied on it, shouldn't happen
+ assert(aurApp->GetBase()->GetApplicationOfTarget(GetGUID()) == aurApp);
+ uint32 spellId = aurApp->GetBase()->GetId();
+ for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound(spellId); iter != m_appliedAuras.upper_bound(spellId);)
+ {
+ if (iter->second == aurApp)
+ {
+ _UnapplyAura(iter, removeMode);
+ return;
+ }
+ else
+ ++iter;
+ }
+ assert(false);
+}
+
+void Unit::_RemoveNoStackAuraApplicationsDueToAura(Aura * aura)
+{
+ // dynobj auras can stack infinite number of times
+ if (aura->GetType() == DYNOBJ_AURA_TYPE)
+ return;
+
+ SpellEntry const* spellProto = aura->GetSpellProto();
+
+ uint32 spellId = spellProto->Id;
+
+ // passive spell special case (only non stackable with ranks)
+ if(IsPassiveSpell(spellId) && IsPassiveSpellStackableWithRanks(spellProto))
+ return;
+
+ bool remove = false;
+ for (AuraApplicationMap::iterator i = m_appliedAuras.begin(); i != m_appliedAuras.end(); ++i)
+ {
+ if(remove)
+ {
+ remove = false;
+ i = m_appliedAuras.begin();
+ }
+
+ if (!_IsNoStackAuraDueToAura(aura, i->second->GetBase()))
+ continue;
+
+ RemoveAura(i, AURA_REMOVE_BY_DEFAULT);
+ if(i == m_appliedAuras.end())
+ break;
+ remove = true;
+ }
+}
+
+void Unit::_RemoveNoStackAurasDueToAura(Aura * aura)
+{
+ SpellEntry const* spellProto = aura->GetSpellProto();
+
+ uint32 spellId = spellProto->Id;
+
+ // passive spell special case (only non stackable with ranks)
+ if(IsPassiveSpell(spellId) && IsPassiveSpellStackableWithRanks(spellProto))
+ return;
+
+ bool remove = false;
+ for (AuraMap::iterator i = m_ownedAuras.begin(); i != m_ownedAuras.end(); ++i)
+ {
+ if(remove)
+ {
+ remove = false;
+ i = m_ownedAuras.begin();
+ }
+
+ if (!_IsNoStackAuraDueToAura(aura, i->second))
+ continue;
+
+ RemoveOwnedAura(i, AURA_REMOVE_BY_DEFAULT);
+ if(i == m_ownedAuras.end())
+ break;
+ remove = true;
+ }
+}
+
+bool Unit::_IsNoStackAuraDueToAura(Aura * appliedAura, Aura * existingAura) const
+{
+ SpellEntry const* spellProto = appliedAura->GetSpellProto();
+ // Do not check already applied aura
+ if (existingAura == appliedAura)
+ return false;
+
+ // Do not check dynobj auras for stacking
+ if (existingAura->GetType() != UNIT_AURA_TYPE)
+ return false;
+
+ SpellEntry const* i_spellProto = existingAura->GetSpellProto();
+ uint32 i_spellId = i_spellProto->Id;
+ bool sameCaster = appliedAura->GetCasterGUID() == existingAura->GetCasterGUID();
+
+ if(IsPassiveSpell(i_spellId))
+ {
+ // passive non-stackable spells not stackable only for same caster
+ if(!sameCaster)
+ return false;
+
+ // passive non-stackable spells not stackable only with another rank of same spell
+ if (!spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
+ return false;
+ }
+
+ bool is_triggered_by_spell = false;
+ // prevent triggering aura of removing aura that triggered it
+ // prevent triggered aura of removing aura that triggering it (triggered effect early some aura of parent spell
+ for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j)
+ {
+ if (i_spellProto->EffectTriggerSpell[j] == spellProto->Id
+ || spellProto->EffectTriggerSpell[j] == i_spellProto->Id) // I do not know what is this for
+ {
+ is_triggered_by_spell = true;
+ break;
+ }
+ }
+
+ if (is_triggered_by_spell)
+ return false;
+
+ if(spellmgr.CanAurasStack(spellProto, i_spellProto, sameCaster))
+ return false;
+ return true;
+}
+
+void Unit::_HandleAuraEffect(AuraEffect * aurEff, bool apply)
+{
+ if (apply)
+ m_modAuras[aurEff->GetAuraType()].push_back(aurEff);
+ else
+ m_modAuras[aurEff->GetAuraType()].remove(aurEff);
+}
+
+// All aura base removes should go threw this function!
+void Unit::RemoveOwnedAura(AuraMap::iterator &i, AuraRemoveMode removeMode)
+{
+ Aura * aura = i->second;
+ assert(!aura->IsRemoved());
+
+ // if unit currently update aura list then make safe update iterator shift to next
+ if (m_auraUpdateIterator == i)
+ ++m_auraUpdateIterator;
+
+ m_ownedAuras.erase(i);
+ m_removedAuras.push_back(aura);
+
+ // Unregister single target aura
+ if (aura->IsSingleTarget())
+ aura->UnregisterSingleTarget();
+
+ aura->_Remove(removeMode);
+
+ i = m_ownedAuras.begin();
+}
+
+void Unit::RemoveOwnedAura(uint32 spellId, uint64 caster, uint8 reqEffMask, AuraRemoveMode removeMode)
+{
+ for (AuraMap::iterator itr = m_ownedAuras.lower_bound(spellId); itr != m_ownedAuras.upper_bound(spellId);)
+ if(((itr->second->GetEffectMask() & reqEffMask) == reqEffMask) && (!caster || itr->second->GetCasterGUID() == caster))
+ {
+ RemoveOwnedAura(itr, removeMode);
+ itr = m_ownedAuras.lower_bound(spellId);
+ }
+ else
+ ++itr;
+}
+
+void Unit::RemoveOwnedAura(Aura * aura, AuraRemoveMode removeMode)
+{
+ if (aura->IsRemoved())
+ return;
+
+ assert(aura->GetOwner() == this);
+
+ uint32 spellId = aura->GetId();
+ for (AuraMap::iterator itr = m_ownedAuras.lower_bound(spellId); itr != m_ownedAuras.upper_bound(spellId); ++itr)
+ if (itr->second == aura)
+ {
+ RemoveOwnedAura(itr, removeMode);
+ return;
+ }
+ assert(false);
+}
+
+Aura * Unit::GetOwnedAura(uint32 spellId, uint64 caster, uint8 reqEffMask, Aura * except) const
+{
+ for (AuraMap::const_iterator itr = m_ownedAuras.lower_bound(spellId); itr != m_ownedAuras.upper_bound(spellId); ++itr)
+ if(((itr->second->GetEffectMask() & reqEffMask) == reqEffMask) && (!caster || itr->second->GetCasterGUID() == caster) && (!except || except != itr->second))
+ return itr->second;
+ return NULL;
+}
+
+void Unit::RemoveAura(AuraApplicationMap::iterator &i, AuraRemoveMode mode)
+{
+ AuraApplication * aurApp = i->second;
+ // Do not remove aura which is already being removed
+ if (aurApp->GetRemoveMode())
+ return;
+ Aura * aura = aurApp->GetBase();
+ _UnapplyAura(i, mode);
+ // Remove aura - for Area and Target auras
+ if (aura->GetOwner() == this)
+ aura->Remove(mode);
+}
+
+void Unit::RemoveAura(uint32 spellId, uint64 caster, uint8 reqEffMask, AuraRemoveMode removeMode)
+{
+ for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound(spellId); iter != m_appliedAuras.upper_bound(spellId);)
+ {
+ Aura const * aura = iter->second->GetBase();
+ if (((aura->GetEffectMask() & reqEffMask) == reqEffMask)
+ && (!caster || aura->GetCasterGUID() == caster))
+ {
+ RemoveAura(iter, removeMode);
+ return;
+ }
+ else
+ ++iter;
+ }
+}
+
+void Unit::RemoveAura(AuraApplication * aurApp, AuraRemoveMode mode)
+{
+ assert(aurApp->GetBase()->GetApplicationOfTarget(GetGUID()) == aurApp);
+ // no need to remove
+ if (aurApp->GetRemoveMode() || aurApp->GetBase()->IsRemoved())
+ return;
+ uint32 spellId = aurApp->GetBase()->GetId();
+ for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound(spellId); iter != m_appliedAuras.upper_bound(spellId);)
+ {
+ if (aurApp == iter->second)
+ {
+ RemoveAura(iter, mode);
+ return;
+ }
+ else
+ ++iter;
+ }
+}
+
+void Unit::RemoveAura(Aura * aura, AuraRemoveMode mode)
+{
+ if (aura->IsRemoved())
+ return;
+ if (AuraApplication * aurApp = aura->GetApplicationOfTarget(GetGUID()))
+ RemoveAura(aurApp, mode);
+ else
+ assert(false);
+}
+
+void Unit::RemoveAurasDueToSpell(uint32 spellId, uint64 caster, uint8 reqEffMask, AuraRemoveMode removeMode)
+{
+ for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound(spellId); iter != m_appliedAuras.upper_bound(spellId);)
+ {
+ Aura const * aura = iter->second->GetBase();
+ if (((aura->GetEffectMask() & reqEffMask) == reqEffMask)
+ && (!caster || aura->GetCasterGUID() == caster))
+ {
+ RemoveAura(iter, removeMode);
+ iter = m_appliedAuras.lower_bound(spellId);
+ }
+ else
+ ++iter;
+ }
+}
+
+void Unit::RemoveAuraFromStack(uint32 spellId, uint64 caster, AuraRemoveMode removeMode)
+{
+ for (AuraMap::iterator iter = m_ownedAuras.lower_bound(spellId); iter != m_ownedAuras.upper_bound(spellId);)
+ {
+ Aura const * aura = iter->second;
+ if ((aura->GetType() == UNIT_AURA_TYPE)
+ && (!caster || aura->GetCasterGUID() == caster))
+ {
+ RemoveAuraFromStack(iter, removeMode);
+ return;
+ }
+ else
+ ++iter;
+ }
+}
+
+inline void Unit::RemoveAuraFromStack(AuraMap::iterator &iter, AuraRemoveMode removeMode)
+{
+ if (iter->second->ModStackAmount(-1))
+ RemoveOwnedAura(iter, removeMode);
+}
+
+void Unit::RemoveAurasDueToSpellByDispel(uint32 spellId, uint64 casterGUID, Unit *dispeller)
+{
+ for (AuraMap::iterator iter = m_ownedAuras.lower_bound(spellId); iter != m_ownedAuras.upper_bound(spellId);)
+ {
+ Aura * aura = iter->second;
+ if (aura->GetCasterGUID() == casterGUID)
+ {
+ if (aura->GetSpellProto()->AttributesEx7 & SPELL_ATTR_EX7_DISPEL_CHARGES)
+ aura->DropCharge();
+ else
+ RemoveAuraFromStack(iter, AURA_REMOVE_BY_ENEMY_SPELL);
+
+ // Unstable Affliction (crash if before removeaura?)
+ if (aura->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && (aura->GetSpellProto()->SpellFamilyFlags[1] & 0x0100))
+ {
+ if (AuraEffect const * aurEff = aura->GetEffect(0))
+ {
+ int32 damage = aurEff->GetAmount()*9;
+ // backfire damage and silence
+ dispeller->CastCustomSpell(dispeller, 31117, &damage, NULL, NULL, true, NULL, NULL, GetGUID());
+ }
+ }
+ // Flame Shock
+ if (aura->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN && (aura->GetSpellProto()->SpellFamilyFlags[0] & 0x10000000))
+ {
+ Unit * caster = aura->GetCaster();
+ if (caster)
+ {
+ uint32 triggeredSpellId = 0;
+ // Lava Flows
+ if (AuraEffect const * aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_SHAMAN, 3087, 0))
+ {
+ switch(aurEff->GetId())
+ {
+ case 51482: // Rank 3
+ triggeredSpellId = 65264;
+ break;
+ case 51481: // Rank 2
+ triggeredSpellId = 65263;
+ break;
+ case 51480: // Rank 1
+ triggeredSpellId = 64694;
+ break;
+ default:
+ sLog.outError("Aura::HandleAuraSpecificMods: Unknown rank of Lava Flows (%d) found", aurEff->GetId());
+ }
+ }
+ if (triggeredSpellId)
+ caster->CastSpell(caster, triggeredSpellId, true);
+ }
+ }
+ return;
+ }
+ else
+ ++iter;
+ }
+}
+
+void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit *stealer)
+{
+ for (AuraMap::iterator iter = m_ownedAuras.lower_bound(spellId); iter != m_ownedAuras.upper_bound(spellId);)
+ {
+ Aura * aura = iter->second;
+ if (aura->GetCasterGUID() == casterGUID)
+ {
+ int32 damage[MAX_SPELL_EFFECTS];
+ int32 baseDamage[MAX_SPELL_EFFECTS];
+ uint8 effMask = 0;
+ uint8 recalculateMask = 0;
+ for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
+ {
+ if (aura->GetEffect(i))
+ {
+ baseDamage[i] = aura->GetEffect(i)->GetBaseAmount();
+ damage[i] = aura->GetEffect(i)->GetAmount();
+ effMask |= (1<<i);
+ if (aura->GetEffect(i)->CanBeRecalculated())
+ recalculateMask |= (1<<i);
+ }
+ else
+ {
+ baseDamage[i] = NULL;
+ damage[i] = NULL;
+ }
+ }
+
+ bool stealCharge = aura->GetSpellProto()->AttributesEx7 & SPELL_ATTR_EX7_DISPEL_CHARGES;
+
+ if (stealCharge)
+ aura->DropCharge();
+ else
+ RemoveAuraFromStack(iter, AURA_REMOVE_BY_ENEMY_SPELL);
+
+
+ if (Aura * newAura = stealCharge ? stealer->GetAura(aura->GetId(), aura->GetCasterGUID()) : NULL)
+ {
+ uint8 newCharges = newAura->GetCharges() + 1;
+ uint8 maxCharges = newAura->GetSpellProto()->procCharges;
+ // We must be able to steal as much charges as original caster can have
+ if (Unit * caster = newAura->GetCaster())
+ if (Player* modOwner = caster->GetSpellModOwner())
+ modOwner->ApplySpellMod(aura->GetId(), SPELLMOD_CHARGES, maxCharges);
+ newAura->SetCharges(maxCharges < newCharges ? maxCharges : newCharges);
+ }
+ else
+ {
+ int32 dur = 2*MINUTE*IN_MILISECONDS < aura->GetDuration() ? 2*MINUTE*IN_MILISECONDS : aura->GetDuration();
+
+ newAura = Aura::TryCreate(aura->GetSpellProto(), effMask, stealer, NULL, &baseDamage[0], NULL, aura->GetCasterGUID());
+ if (!newAura)
+ return;
+ newAura->SetLoadedState(dur, dur, stealCharge ? 1 : aura->GetCharges(), aura->GetStackAmount(), recalculateMask, &damage[0]);
+ // strange but intended behaviour: Stolen single target auras won't be treated as single targeted
+ if (newAura->IsSingleTarget())
+ newAura->UnregisterSingleTarget();
+ newAura->ApplyForTargets();
+ }
+ return;
+ }
+ else
+ ++iter;
+ }
+}
+
+void Unit::RemoveAurasDueToItemSpell(Item* castItem,uint32 spellId)
+{
+ for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound(spellId); iter != m_appliedAuras.upper_bound(spellId);)
+ {
+ if (!castItem || iter->second->GetBase()->GetCastItemGUID() == castItem->GetGUID())
+ {
+ RemoveAura(iter);
+ iter = m_appliedAuras.upper_bound(spellId); // overwrite by more appropriate
+ }
+ else
+ ++iter;
+ }
+}
+
+void Unit::RemoveAurasByType(AuraType auraType, uint64 casterGUID, Aura * except, bool negative, bool positive)
+{
+ for (AuraEffectList::iterator iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end();)
+ {
+ Aura * aura = (*iter)->GetBase();
+ AuraApplication * aurApp = aura ->GetApplicationOfTarget(GetGUID());
+
+ ++iter;
+ if (aura != except && (!casterGUID || aura->GetCasterGUID() == casterGUID)
+ && ((negative && !aurApp->IsPositive()) || (positive && aurApp->IsPositive())))
+ {
+ uint32 removedAuras = m_removedAurasCount;
+ RemoveAura(aurApp);
+ if (m_removedAurasCount > removedAuras + 1)
+ iter = m_modAuras[auraType].begin();
+ }
+ }
+}
+
+void Unit::RemoveNotOwnSingleTargetAuras(uint32 newPhase)
+{
+ // single target auras from other casters
+ for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
+ {
+ AuraApplication const * aurApp = iter->second;
+ Aura const * aura = aurApp->GetBase();
+
+ if (aura->GetCasterGUID() !=GetGUID() && IsSingleTargetSpell(aura->GetSpellProto()))
+ {
+ if (!newPhase)
+ RemoveAura(iter);
+ else
+ {
+ Unit* caster = aura->GetCaster();
+ if (!caster || !caster->InSamePhase(newPhase))
+ RemoveAura(iter);
+ else
+ ++iter;
+ }
+ }
+ else
+ ++iter;
+ }
+
+ // single target auras at other targets
+ AuraList& scAuras = GetSingleCastAuras();
+ for (AuraList::iterator iter = scAuras.begin(); iter != scAuras.end();)
+ {
+ Aura * aura = *iter;
+ ++iter;
+ if (aura->GetUnitOwner() != this && !aura->GetUnitOwner()->InSamePhase(newPhase))
+ {
+ uint32 removedAuras = m_removedAurasCount;
+ aura->Remove();
+ if (m_removedAurasCount > removedAuras + 1)
+ iter = scAuras.begin();
+ }
+ }
+}
+
+
+void Unit::RemoveAurasWithInterruptFlags(uint32 flag, uint32 except)
+{
+ if (!(m_interruptMask & flag))
+ return;
+
+ // interrupt auras
+ for (AuraApplicationList::iterator iter = m_interruptableAuras.begin(); iter != m_interruptableAuras.end();)
+ {
+ Aura * aura = (*iter)->GetBase();
+ ++iter;
+ if ((aura->GetSpellProto()->AuraInterruptFlags & flag) && (!except || aura->GetId() != except))
+ {
+ uint32 removedAuras = m_removedAurasCount;
+ RemoveAura(aura);
+ if (m_removedAurasCount > removedAuras + 1)
+ iter = m_interruptableAuras.begin();
+ }
+ }
+
+ // interrupt channeled spell
+ if (Spell* spell = m_currentSpells[CURRENT_CHANNELED_SPELL])
+ if (spell->getState() == SPELL_STATE_CASTING
+ && (spell->m_spellInfo->ChannelInterruptFlags & flag)
+ && spell->m_spellInfo->Id != except)
+ InterruptNonMeleeSpells(false);
+
+ UpdateInterruptMask();
+}
+
+void Unit::RemoveAurasWithFamily(SpellFamilyNames family, uint32 familyFlag1, uint32 familyFlag2, uint32 familyFlag3, uint64 casterGUID)
+{
+ for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
+ {
+ Aura const * aura = iter->second->GetBase();
+ if (!casterGUID || aura->GetCasterGUID() == casterGUID)
+ {
+ SpellEntry const *spell = aura->GetSpellProto();
+ if (spell->SpellFamilyName == family && spell->SpellFamilyFlags.HasFlag(familyFlag1, familyFlag2, familyFlag3))
+ {
+ RemoveAura(iter);
+ continue;
+ }
+ }
+ ++iter;
+ }
+}
+
+void Unit::RemoveMovementImpairingAuras()
+{
+ RemoveAurasWithMechanic((1<<MECHANIC_SNARE)|(1<<MECHANIC_ROOT));
+}
+
+void Unit::RemoveAurasWithMechanic(uint32 mechanic_mask, AuraRemoveMode removemode, uint32 except)
+{
+ for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
+ {
+ Aura const * aura = iter->second->GetBase();
+ if (!except || aura->GetId() != except)
+ {
+ if (GetAllSpellMechanicMask(aura->GetSpellProto()) & mechanic_mask)
+ {
+ RemoveAura(iter, removemode);
+ continue;
+ }
+ }
+ ++iter;
+ }
+}
+
+void Unit::RemoveAreaAurasDueToLeaveWorld()
+{
+ bool cleanRun;
+ do
+ {
+ cleanRun = true;
+ // make sure that all area auras not applied on self are removed - prevent access to deleted pointer later
+ for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();)
+ {
+ Aura * aura = iter->second;
+ ++iter;
+ Aura::ApplicationMap const & appMap = aura->GetApplicationMap();
+ for(Aura::ApplicationMap::const_iterator itr = appMap.begin(); itr!= appMap.end();)
+ {
+ AuraApplication * aurApp = itr->second;
+ ++itr;
+ Unit * target = aurApp->GetTarget();
+ if (target == this)
+ continue;
+ target->RemoveAura(aurApp);
+ cleanRun = false;
+ // things linked on aura remove may apply new area aura - so start from the beginning
+ iter = m_ownedAuras.begin();
+ }
+ }
+
+ // remove area auras owned by others
+ for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
+ {
+ if (iter->second->GetBase()->GetOwner()!=this)
+ {
+ RemoveAura(iter);
+ cleanRun = false;
+ }
+ else
+ ++iter;
+ }
+ }
+ while (!cleanRun);
+}
+
+void Unit::RemoveAllAuras()
+{
+ while (!m_appliedAuras.empty() || !m_ownedAuras.empty())
+ {
+ AuraApplicationMap::iterator aurAppIter = m_appliedAuras.begin();
+ while (!m_appliedAuras.empty())
+ _UnapplyAura(aurAppIter, AURA_REMOVE_BY_DEFAULT);
+
+ AuraMap::iterator aurIter = m_ownedAuras.begin();
+ while (!m_ownedAuras.empty())
+ RemoveOwnedAura(aurIter);
+ }
+}
+
+void Unit::RemoveArenaAuras(bool onleave)
+{
+ // in join, remove positive buffs, on end, remove negative
+ // used to remove positive visible auras in arenas
+ for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
+ {
+ AuraApplication const * aurApp = iter->second;
+ Aura const * aura = aurApp->GetBase();
+ if ( !(aura->GetSpellProto()->AttributesEx4 & (1<<21)) // don't remove stances, shadowform, pally/hunter auras
+ && !aura->IsPassive() // don't remove passive auras
+ && (!(aura->GetSpellProto()->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY) || !(aura->GetSpellProto()->Attributes & SPELL_ATTR_UNK8)) // not unaffected by invulnerability auras or not having that unknown flag (that seemed the most probable)
+ && (aurApp->IsPositive() ^ onleave)) // remove positive buffs on enter, negative buffs on leave
+ RemoveAura(iter);
+ else
+ ++iter;
+ }
+}
+
+void Unit::RemoveAllAurasOnDeath()
+{
+ // used just after dieing to remove all visible auras
+ // and disable the mods for the passive ones
+ for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
+ {
+ Aura const * aura = iter->second->GetBase();
+ if (!aura->IsPassive() && !aura->IsDeathPersistent())
+ _UnapplyAura(iter, AURA_REMOVE_BY_DEATH);
+ else
+ ++iter;
+ }
+
+ for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();)
+ {
+ Aura * aura = iter->second;
+ if (!aura->IsPassive() && !aura->IsDeathPersistent())
+ RemoveOwnedAura(iter, AURA_REMOVE_BY_DEATH);
+ else
+ ++iter;
+ }
+}
+
+void Unit::DelayOwnedAuras(uint32 spellId, uint64 caster, int32 delaytime)
+{
+ for (AuraMap::iterator iter = m_ownedAuras.lower_bound(spellId); iter != m_ownedAuras.upper_bound(spellId);++iter)
+ {
+ Aura * aura = iter->second;
+ if (!caster || aura->GetCasterGUID() == caster)
+ {
+ if (aura->GetDuration() < delaytime)
+ aura->SetDuration(0);
+ else
+ aura->SetDuration(aura->GetDuration() - delaytime);
+
+ // update for out of range group members (on 1 slot use)
+ aura->SetNeedClientUpdateForTargets();
+ sLog.outDebug("Aura %u partially interrupted on unit %u, new duration: %u ms",aura->GetId() , GetGUIDLow(), aura->GetDuration());
+ }
+ }
+}
+
+void Unit::_RemoveAllAuraStatMods()
+{
+ for (AuraApplicationMap::iterator i = m_appliedAuras.begin(); i != m_appliedAuras.end(); ++i)
+ (*i).second->GetBase()->HandleAllEffects(i->second, AURA_EFFECT_HANDLE_STAT, false);
+}
+
+void Unit::_ApplyAllAuraStatMods()
+{
+ for (AuraApplicationMap::iterator i = m_appliedAuras.begin(); i != m_appliedAuras.end(); ++i)
+ (*i).second->GetBase()->HandleAllEffects(i->second, AURA_EFFECT_HANDLE_STAT, true);
+}
+
+AuraEffect * Unit::GetAuraEffect(uint32 spellId, uint8 effIndex, uint64 caster) const
+{
+ for (AuraApplicationMap::const_iterator itr = m_appliedAuras.lower_bound(spellId); itr != m_appliedAuras.upper_bound(spellId); ++itr)
+ if(itr->second->HasEffect(effIndex) && (!caster || itr->second->GetBase()->GetCasterGUID() == caster))
+ return itr->second->GetBase()->GetEffect(effIndex);
+ return NULL;
+}
+
+AuraEffect * Unit::GetAuraEffectOfRankedSpell(uint32 spellId, uint8 effIndex, uint64 caster) const
+{
+ uint32 rankSpell = spellmgr.GetFirstSpellInChain(spellId);
+ while(true)
+ {
+ if (AuraEffect * aurEff = GetAuraEffect(rankSpell, effIndex, caster))
+ return aurEff;
+ SpellChainNode const * chainNode = spellmgr.GetSpellChainNode(rankSpell);
+ if (!chainNode)
+ break;
+ else
+ rankSpell = chainNode->next;
+ }
+ return NULL;
+}
+
+AuraEffect* Unit::GetAuraEffect(AuraType type, SpellFamilyNames name, uint32 iconId, uint8 effIndex) const
+{
+ AuraEffectList const& auras = GetAuraEffectsByType(type);
+ for (Unit::AuraEffectList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
+ {
+ if (effIndex != (*itr)->GetEffIndex())
+ continue;
+ SpellEntry const * spell = (*itr)->GetSpellProto();
+ if (spell->SpellIconID == iconId && spell->SpellFamilyName == name && !spell->SpellFamilyFlags)
+ return *itr;
+ }
+ return NULL;
+}
+
+AuraEffect* Unit::GetAuraEffect(AuraType type, SpellFamilyNames family, uint32 familyFlag1, uint32 familyFlag2, uint32 familyFlag3, uint64 casterGUID)
+{
+ AuraEffectList const& auras = GetAuraEffectsByType(type);
+ for (AuraEffectList::const_iterator i = auras.begin(); i != auras.end(); ++i)
+ {
+ SpellEntry const *spell = (*i)->GetSpellProto();
+ if (spell->SpellFamilyName == family && spell->SpellFamilyFlags.HasFlag(familyFlag1, familyFlag2, familyFlag3))
+ {
+ if (casterGUID && (*i)->GetCasterGUID()!=casterGUID)
+ continue;
+ return (*i);
+ }
+ }
+ return NULL;
+}
+
+AuraApplication * Unit::GetAuraApplication(uint32 spellId, uint64 casterGUID, uint8 reqEffMask, AuraApplication * except) const
+{
+ for (AuraApplicationMap::const_iterator itr = m_appliedAuras.lower_bound(spellId); itr != m_appliedAuras.upper_bound(spellId); ++itr)
+ {
+ Aura const * aura = itr->second->GetBase();
+ if(((aura->GetEffectMask() & reqEffMask) == reqEffMask) && (!casterGUID || aura->GetCasterGUID() == casterGUID) && (!except || except!=itr->second))
+ return itr->second;
+ }
+ return NULL;
+}
+
+Aura * Unit::GetAura(uint32 spellId, uint64 casterGUID, uint8 reqEffMask) const
+{
+ AuraApplication * aurApp = GetAuraApplication(spellId, casterGUID, reqEffMask);
+ return aurApp ? aurApp->GetBase():NULL;
+}
+
+AuraApplication * Unit::GetAuraApplicationOfRankedSpel(uint32 spellId, uint64 casterGUID, uint8 reqEffMask, AuraApplication * except) const
+{
+ uint32 rankSpell = spellmgr.GetFirstSpellInChain(spellId);
+ while(true)
+ {
+ if (AuraApplication * aurApp = GetAuraApplication(rankSpell, casterGUID, reqEffMask, except))
+ return aurApp;
+ SpellChainNode const * chainNode = spellmgr.GetSpellChainNode(rankSpell);
+ if (!chainNode)
+ break;
+ else
+ rankSpell = chainNode->next;
+ }
+ return NULL;
+}
+
+Aura * Unit::GetAuraOfRankedSpell(uint32 spellId, uint64 casterGUID, uint8 reqEffMask) const
+{
+ AuraApplication * aurApp = GetAuraApplicationOfRankedSpel(spellId, casterGUID, reqEffMask);
+ return aurApp ? aurApp->GetBase() : NULL;
+}
+
+bool Unit::HasAuraEffect(uint32 spellId, uint8 effIndex, uint64 caster) const
+{
+ for (AuraApplicationMap::const_iterator itr = m_appliedAuras.lower_bound(spellId); itr != m_appliedAuras.upper_bound(spellId); ++itr)
+ if(itr->second->HasEffect(effIndex) && (!caster || itr->second->GetBase()->GetCasterGUID() == caster))
+ return true;
+ return false;
+}
+
+bool Unit::HasAura(uint32 spellId, uint64 caster, uint8 reqEffMask) const
+{
+ //Special case for non existing spell
+ if (spellId==61988)
+ return HasAura(61987, caster, reqEffMask) || HasAura(25771, caster, reqEffMask);
+
+ if (GetAuraApplication(spellId, caster, reqEffMask))
+ return true;
+ return false;
+}
+
+bool Unit::HasAuraType(AuraType auraType) const
+{
+ return (!m_modAuras[auraType].empty());
+}
+
+bool Unit::HasAuraTypeWithMiscvalue(AuraType auratype, uint32 miscvalue) const
+{
+ AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
+ for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
+ if (miscvalue == (*i)->GetMiscValue())
+ return true;
+ return false;
+}
+
+bool Unit::HasAuraTypeWithValue(AuraType auratype, uint32 value) const
+{
+ AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
+ for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
+ if (value == (*i)->GetAmount())
+ return true;
+ return false;
+}
+
+bool Unit::HasNegativeAuraWithInterruptFlag(uint32 flag)
+{
+ if (!(m_interruptMask & flag))
+ return false;
+ for (AuraApplicationList::iterator iter = m_interruptableAuras.begin(); iter != m_interruptableAuras.end(); ++iter)
+ {
+ if (!(*iter)->IsPositive() && (*iter)->GetBase()->GetSpellProto()->AuraInterruptFlags & flag)
+ return true;
+ }
+ return false;
+}
+
+AuraEffect * Unit::IsScriptOverriden(SpellEntry const * spell, int32 script) const
+{
+ AuraEffectList const& auras = GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
+ for (AuraEffectList::const_iterator i = auras.begin(); i != auras.end(); ++i)
+ {
+ if ((*i)->GetMiscValue() == script)
+ if ((*i)->IsAffectedOnSpell(spell))
+ return (*i);
+ }
+ return NULL;
+}
+
+uint32 Unit::GetDiseasesByCaster(uint64 casterGUID, bool remove)
+{
+ static const AuraType diseaseAuraTypes[] =
+ {
+ SPELL_AURA_PERIODIC_DAMAGE, // Frost Fever and Blood Plague
+ SPELL_AURA_LINKED, // Crypt Fever and Ebon Plague
+ SPELL_AURA_NONE
+ };
+
+ uint32 diseases=0;
+ for (AuraType const* itr = &diseaseAuraTypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
+ {
+ for (AuraEffectList::iterator i = m_modAuras[*itr].begin(); i != m_modAuras[*itr].end();)
+ {
+ // Get auras with disease dispel type by caster
+ if ((*i)->GetSpellProto()->Dispel == DISPEL_DISEASE
+ && (*i)->GetCasterGUID()==casterGUID)
+ {
+ ++diseases;
+
+ if (remove)
+ {
+ RemoveAura((*i)->GetId(), (*i)->GetCasterGUID());
+ i = m_modAuras[*itr].begin();
+ continue;
+ }
+ }
+ ++i;
+ }
+ }
+ return diseases;
+}
+
+uint32 Unit::GetDoTsByCaster(uint64 casterGUID) const
+{
+ static const AuraType diseaseAuraTypes[] =
+ {
+ SPELL_AURA_PERIODIC_DAMAGE,
+ SPELL_AURA_PERIODIC_DAMAGE_PERCENT,
+ SPELL_AURA_NONE
+ };
+
+ uint32 dots=0;
+ for (AuraType const* itr = &diseaseAuraTypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
+ {
+ Unit::AuraEffectList const& auras = GetAuraEffectsByType(*itr);
+ for (AuraEffectList::const_iterator i = auras.begin(); i != auras.end(); ++i)
+ {
+ // Get auras by caster
+ if ((*i)->GetCasterGUID()==casterGUID)
+ ++dots;
+ }
+ }
+ return dots;
+}
+
+int32 Unit::GetTotalAuraModifier(AuraType auratype) const
+{
+ int32 modifier = 0;
+
+ AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
+ for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
+ modifier += (*i)->GetAmount();
+
+ return modifier;
+}
+
+float Unit::GetTotalAuraMultiplier(AuraType auratype) const
+{
+ float multiplier = 1.0f;
+
+ AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
+ for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
+ multiplier *= (100.0f + (*i)->GetAmount())/100.0f;
+
+ return multiplier;
+}
+
+int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype)
+{
+ int32 modifier = 0;
+
+ AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
+ for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
+ {
+ if ((*i)->GetAmount() > modifier)
+ modifier = (*i)->GetAmount();
+ }
+
+ return modifier;
+}
+
+int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const
+{
+ int32 modifier = 0;
+
+ AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
+ for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
+ if ((*i)->GetAmount() < modifier)
+ modifier = (*i)->GetAmount();
+
+ return modifier;
+}
+
+int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
+{
+ int32 modifier = 0;
+
+ AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
+ for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
+ {
+ if ((*i)->GetMiscValue()& misc_mask)
+ modifier += (*i)->GetAmount();
+ }
+ return modifier;
+}
+
+float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const
+{
+ float multiplier = 1.0f;
+
+ AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
+ for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
+ {
+ if ((*i)->GetMiscValue()& misc_mask)
+ multiplier *= (100.0f + (*i)->GetAmount())/100.0f;
+ }
+ return multiplier;
+}
+
+int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
+{
+ int32 modifier = 0;
+
+ AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
+ for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
+ {
+ if ((*i)->GetMiscValue()& misc_mask && (*i)->GetAmount() > modifier)
+ modifier = (*i)->GetAmount();
+ }
+
+ return modifier;
+}
+
+int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
+{
+ int32 modifier = 0;
+
+ AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
+ for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
+ {
+ if ((*i)->GetMiscValue()& misc_mask && (*i)->GetAmount() < modifier)
+ modifier = (*i)->GetAmount();
+ }
+
+ return modifier;
+}
+
+int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
+{
+ int32 modifier = 0;
+
+ AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
+ for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
+ {
+ if ((*i)->GetMiscValue()== misc_value)
+ modifier += (*i)->GetAmount();
+ }
+ return modifier;
+}
+
+float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const
+{
+ float multiplier = 1.0f;
+
+ AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
+ for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
+ {
+ if ((*i)->GetMiscValue()== misc_value)
+ multiplier *= (100.0f + (*i)->GetAmount())/100.0f;
+ }
+ return multiplier;
+}
+
+int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
+{
+ int32 modifier = 0;
+
+ AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
+ for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
+ {
+ if ((*i)->GetMiscValue()== misc_value && (*i)->GetAmount() > modifier)
+ modifier = (*i)->GetAmount();
+ }
+
+ return modifier;
+}
+
+int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
+{
+ int32 modifier = 0;
+
+ AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
+ for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
+ {
+ if ((*i)->GetMiscValue()== misc_value && (*i)->GetAmount() < modifier)
+ modifier = (*i)->GetAmount();
+ }
+
+ return modifier;
+}
+
+void Unit::AddDynObject(DynamicObject* dynObj)
+{
+ m_dynObjGUIDs.push_back(dynObj->GetGUID());
+}
+
+void Unit::RemoveDynObject(uint32 spellid)
+{
+ if(m_dynObjGUIDs.empty())
+ return;
+ for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
+ {
+ DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
+ if(!dynObj) // may happen if a dynobj is removed when grid unload
+ {
+ i = m_dynObjGUIDs.erase(i);
+ }
+ else if(spellid == 0 || dynObj->GetSpellId() == spellid)
+ {
+ dynObj->Delete();
+ i = m_dynObjGUIDs.erase(i);
+ }
+ else
+ ++i;
+ }
+}
+
+void Unit::RemoveAllDynObjects()
+{
+ while(!m_dynObjGUIDs.empty())
+ {
+ DynamicObject* dynObj = GetMap()->GetDynamicObject(*m_dynObjGUIDs.begin());
+ if(dynObj)
+ dynObj->Delete();
+ m_dynObjGUIDs.erase(m_dynObjGUIDs.begin());
+ }
+}
+
+DynamicObject * Unit::GetDynObject(uint32 spellId)
+{
+ for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
+ {
+ DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
+ if(!dynObj)
+ {
+ i = m_dynObjGUIDs.erase(i);
+ continue;
+ }
+
+ if (dynObj->GetSpellId() == spellId)
+ return dynObj;
+ ++i;
+ }
+ return NULL;
+}
+
+GameObject* Unit::GetGameObject(uint32 spellId) const
+{
+ for (GameObjectList::const_iterator i = m_gameObj.begin(); i != m_gameObj.end(); ++i)
+ if ((*i)->GetSpellId() == spellId)
+ return *i;
+
+ return NULL;
+}
+
+void Unit::AddGameObject(GameObject* gameObj)
+{
+ if(!gameObj || !gameObj->GetOwnerGUID()==0) return;
+ m_gameObj.push_back(gameObj);
+ gameObj->SetOwnerGUID(GetGUID());
+
+ if ( GetTypeId() == TYPEID_PLAYER && gameObj->GetSpellId() )
+ {
+ SpellEntry const* createBySpell = sSpellStore.LookupEntry(gameObj->GetSpellId());
+ // Need disable spell use for owner
+ if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
+ // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
+ ((Player*)this)->AddSpellAndCategoryCooldowns(createBySpell,0,NULL,true);
+ }
+}
+
+void Unit::RemoveGameObject(GameObject* gameObj, bool del)
+{
+ if(!gameObj || !gameObj->GetOwnerGUID()==GetGUID()) return;
+
+ gameObj->SetOwnerGUID(0);
+
+ for (uint32 i = 0; i < 4; ++i)
+ {
+ if(m_ObjectSlot[i] == gameObj->GetGUID())
+ {
+ m_ObjectSlot[i] = 0;
+ break;
+ }
+ }
+
+ // GO created by some spell
+ if (uint32 spellid = gameObj->GetSpellId())
+ {
+ RemoveAurasDueToSpell(spellid);
+
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ SpellEntry const* createBySpell = sSpellStore.LookupEntry(spellid );
+ // Need activate spell use for owner
+ if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
+ // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
+ ((Player*)this)->SendCooldownEvent(createBySpell);
+ }
+ }
+
+ m_gameObj.remove(gameObj);
+
+ if(del)
+ {
+ gameObj->SetRespawnTime(0);
+ gameObj->Delete();
+ }
+}
+
+void Unit::RemoveGameObject(uint32 spellid, bool del)
+{
+ if(m_gameObj.empty())
+ return;
+ GameObjectList::iterator i, next;
+ for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next)
+ {
+ next = i;
+ if(spellid == 0 || (*i)->GetSpellId() == spellid)
+ {
+ (*i)->SetOwnerGUID(0);
+ if(del)
+ {
+ (*i)->SetRespawnTime(0);
+ (*i)->Delete();
+ }
+
+ next = m_gameObj.erase(i);
+ }
+ else
+ ++next;
+ }
+}
+
+void Unit::RemoveAllGameObjects()
+{
+ // remove references to unit
+ for (GameObjectList::iterator i = m_gameObj.begin(); i != m_gameObj.end();)
+ {
+ (*i)->SetOwnerGUID(0);
+ (*i)->SetRespawnTime(0);
+ (*i)->Delete();
+ i = m_gameObj.erase(i);
+ }
+}
+
+void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage *log)
+{
+ WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+4+1+4+4+1+1+4+4+1)); // we guess size
+ data.append(log->target->GetPackGUID());
+ data.append(log->attacker->GetPackGUID());
+ data << uint32(log->SpellID);
+ data << uint32(log->damage); // damage amount
+ int32 overkill = log->damage - log->target->GetHealth();
+ data << uint32(overkill > 0 ? overkill : 0);
+ //data << uint32(log->overkill); // overkill
+ data << uint8 (log->schoolMask); // damage school
+ data << uint32(log->absorb); // AbsorbedDamage
+ data << uint32(log->resist); // resist
+ data << uint8 (log->physicalLog); // if 1, then client show spell name (example: %s's ranged shot hit %s for %u school or %s suffers %u school damage from %s's spell_name
+ data << uint8 (log->unused); // unused
+ data << uint32(log->blocked); // blocked
+ data << uint32(log->HitInfo);
+ data << uint8 (0); // flag to use extend data
+ SendMessageToSet( &data, true );
+}
+
+void Unit::SendSpellNonMeleeDamageLog(Unit *target, uint32 SpellID, uint32 Damage, SpellSchoolMask damageSchoolMask, uint32 AbsorbedDamage, uint32 Resist, bool PhysicalDamage, uint32 Blocked, bool CriticalHit)
+{
+ SpellNonMeleeDamage log(this, target, SpellID, damageSchoolMask);
+ log.damage = Damage - AbsorbedDamage - Resist - Blocked;
+ log.absorb = AbsorbedDamage;
+ log.resist = Resist;
+ log.physicalLog = PhysicalDamage;
+ log.blocked = Blocked;
+ log.HitInfo = SPELL_HIT_TYPE_UNK1 | SPELL_HIT_TYPE_UNK3 | SPELL_HIT_TYPE_UNK6;
+ if(CriticalHit)
+ log.HitInfo |= SPELL_HIT_TYPE_CRIT;
+ SendSpellNonMeleeDamageLog(&log);
+}
+
+void Unit::ProcDamageAndSpell(Unit *pVictim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellEntry const *procSpell, SpellEntry const * procAura)
+{
+ // Not much to do if no flags are set.
+ if (procAttacker)
+ ProcDamageAndSpellFor(false, pVictim,procAttacker, procExtra,attType, procSpell, amount, procAura);
+ // Now go on with a victim's events'n'auras
+ // Not much to do if no flags are set or there is no victim
+ if(pVictim && pVictim->isAlive() && procVictim)
+ pVictim->ProcDamageAndSpellFor(true, this, procVictim, procExtra, attType, procSpell, amount, procAura);
+}
+
+void Unit::SendPeriodicAuraLog(SpellPeriodicAuraLogInfo *pInfo)
+{
+ AuraEffect const * aura = pInfo->auraEff;
+
+ WorldPacket data(SMSG_PERIODICAURALOG, 30);
+ data.append(GetPackGUID());
+ data.appendPackGUID(aura->GetCasterGUID());
+ data << uint32(aura->GetId()); // spellId
+ data << uint32(1); // count
+ data << uint32(aura->GetAuraType()); // auraId
+ switch(aura->GetAuraType())
+ {
+ case SPELL_AURA_PERIODIC_DAMAGE:
+ case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
+ data << uint32(pInfo->damage); // damage
+ data << uint32(pInfo->overDamage); // overkill?
+ data << uint32(GetSpellSchoolMask(aura->GetSpellProto()));
+ data << uint32(pInfo->absorb); // absorb
+ data << uint32(pInfo->resist); // resist
+ data << uint8(pInfo->critical); // new 3.1.2 critical tick
+ break;
+ case SPELL_AURA_PERIODIC_HEAL:
+ case SPELL_AURA_OBS_MOD_HEALTH:
+ data << uint32(pInfo->damage); // damage
+ data << uint32(pInfo->overDamage); // overheal?
+ data << uint8(pInfo->critical); // new 3.1.2 critical tick
+ break;
+ case SPELL_AURA_OBS_MOD_POWER:
+ case SPELL_AURA_PERIODIC_ENERGIZE:
+ data << uint32(aura->GetMiscValue()); // power type
+ data << uint32(pInfo->damage); // damage
+ break;
+ case SPELL_AURA_PERIODIC_MANA_LEECH:
+ data << uint32(aura->GetMiscValue()); // power type
+ data << uint32(pInfo->damage); // amount
+ data << float(pInfo->multiplier); // gain multiplier
+ break;
+ default:
+ sLog.outError("Unit::SendPeriodicAuraLog: unknown aura %u", uint32(aura->GetAuraType()));
+ return;
+ }
+
+ SendMessageToSet(&data, true);
+}
+
+void Unit::SendSpellMiss(Unit *target, uint32 spellID, SpellMissInfo missInfo)
+{
+ WorldPacket data(SMSG_SPELLLOGMISS, (4+8+1+4+8+1));
+ data << uint32(spellID);
+ data << uint64(GetGUID());
+ data << uint8(0); // can be 0 or 1
+ data << uint32(1); // target count
+ // for (i = 0; i < target count; ++i)
+ data << uint64(target->GetGUID()); // target GUID
+ data << uint8(missInfo);
+ // end loop
+ SendMessageToSet(&data, true);
+}
+
+void Unit::SendAttackStateUpdate(CalcDamageInfo *damageInfo)
+{
+ sLog.outDebug("WORLD: Sending SMSG_ATTACKERSTATEUPDATE");
+
+ uint32 count = 1;
+ WorldPacket data(SMSG_ATTACKERSTATEUPDATE, 16 + 45); // we guess size
+ data << uint32(damageInfo->HitInfo);
+ data.append(damageInfo->attacker->GetPackGUID());
+ data.append(damageInfo->target->GetPackGUID());
+ data << uint32(damageInfo->damage); // Full damage
+ int32 overkill = damageInfo->damage - damageInfo->target->GetHealth();
+ data << uint32(overkill < 0 ? 0 : overkill); // Overkill
+ data << uint8(count); // Sub damage count
+
+ for (uint32 i = 0; i < count; ++i)
+ {
+ data << uint32(damageInfo->damageSchoolMask); // School of sub damage
+ data << float(damageInfo->damage); // sub damage
+ data << uint32(damageInfo->damage); // Sub Damage
+ }
+
+ if(damageInfo->HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
+ {
+ for (uint32 i = 0; i < count; ++i)
+ data << uint32(damageInfo->absorb); // Absorb
+ }
+
+ if(damageInfo->HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
+ {
+ for (uint32 i = 0; i < count; ++i)
+ data << uint32(damageInfo->resist); // Resist
+ }
+
+ data << uint8(damageInfo->TargetState);
+ data << uint32(0);
+ data << uint32(0);
+
+ if(damageInfo->HitInfo & HITINFO_BLOCK)
+ data << uint32(damageInfo->blocked_amount);
+
+ if(damageInfo->HitInfo & HITINFO_UNK3)
+ data << uint32(0);
+
+ if(damageInfo->HitInfo & HITINFO_UNK1)
+ {
+ data << uint32(0);
+ data << float(0);
+ data << float(0);
+ data << float(0);
+ data << float(0);
+ data << float(0);
+ data << float(0);
+ data << float(0);
+ data << float(0);
+ for (uint8 i = 0; i < 5; ++i)
+ {
+ data << float(0);
+ data << float(0);
+ }
+ data << uint32(0);
+ }
+
+ SendMessageToSet( &data, true );
+}
+
+void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit *target, uint8 SwingType, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount)
+{
+ CalcDamageInfo dmgInfo;
+ dmgInfo.HitInfo = HitInfo;
+ dmgInfo.attacker = this;
+ dmgInfo.target = target;
+ dmgInfo.damage = Damage - AbsorbDamage - Resist - BlockedAmount;
+ dmgInfo.damageSchoolMask = damageSchoolMask;
+ dmgInfo.absorb = AbsorbDamage;
+ dmgInfo.resist = Resist;
+ dmgInfo.TargetState = TargetState;
+ dmgInfo.blocked_amount = BlockedAmount;
+ SendAttackStateUpdate(&dmgInfo);
+}
+
+bool Unit::HandleHasteAuraProc(Unit *pVictim, uint32 damage, AuraEffect* triggeredByAura, SpellEntry const * procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
+{
+ SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto();
+
+ Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
+ ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
+
+ uint32 triggered_spell_id = 0;
+ Unit* target = pVictim;
+ int32 basepoints0 = 0;
+
+ switch(hasteSpell->SpellFamilyName)
+ {
+ case SPELLFAMILY_ROGUE:
+ {
+ switch(hasteSpell->Id)
+ {
+ // Blade Flurry
+ case 13877:
+ case 33735:
+ {
+ target = SelectNearbyTarget();
+ if (!target || target == pVictim)
+ return false;
+ basepoints0 = damage;
+ triggered_spell_id = 22482;
+ break;
+ }
+ }
+ break;
+ }
+ }
+
+ // processed charge only counting case
+ if (!triggered_spell_id)
+ return true;
+
+ SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
+
+ if (!triggerEntry)
+ {
+ sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",hasteSpell->Id,triggered_spell_id);
+ return false;
+ }
+
+ // default case
+ if ((!target && !spellmgr.IsSrcTargetSpell(triggerEntry)) || (target && target!=this && !target->isAlive()))
+ return false;
+
+ if (cooldown && GetTypeId() == TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
+ return false;
+
+ if (basepoints0)
+ CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
+ else
+ CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
+
+ if (cooldown && GetTypeId() == TYPEID_PLAYER)
+ ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
+
+ return true;
+}
+
+bool Unit::HandleSpellCritChanceAuraProc(Unit *pVictim, uint32 /*damage*/, AuraEffect* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
+{
+ SpellEntry const *triggeredByAuraSpell = triggeredByAura->GetSpellProto();
+
+ Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
+ ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
+
+ uint32 triggered_spell_id = 0;
+ Unit* target = pVictim;
+ int32 basepoints0 = 0;
+
+ switch(triggeredByAuraSpell->SpellFamilyName)
+ {
+ case SPELLFAMILY_MAGE:
+ {
+ switch(triggeredByAuraSpell->Id)
+ {
+ // Focus Magic
+ case 54646:
+ {
+ Unit* caster = triggeredByAura->GetCaster();
+ if(!caster)
+ return false;
+
+ triggered_spell_id = 54648;
+ target = caster;
+ break;
+ }
+ }
+ }
+ }
+
+ // processed charge only counting case
+ if(!triggered_spell_id)
+ return true;
+
+ SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
+
+ if(!triggerEntry)
+ {
+ sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",triggeredByAuraSpell->Id,triggered_spell_id);
+ return false;
+ }
+
+ // default case
+ if(!target || target!=this && !target->isAlive())
+ return false;
+
+ if( cooldown && GetTypeId() == TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
+ return false;
+
+ if(basepoints0)
+ CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
+ else
+ CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
+
+ if( cooldown && GetTypeId() == TYPEID_PLAYER )
+ ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
+
+ return true;
+}
+
+bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
+{
+ SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
+ uint32 effIndex = triggeredByAura->GetEffIndex();
+ int32 triggerAmount = triggeredByAura->GetAmount();
+
+ Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
+ ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
+
+ uint32 triggered_spell_id = 0;
+ Unit* target = pVictim;
+ int32 basepoints0 = 0;
+ uint64 originalCaster = 0;
+
+ switch(dummySpell->SpellFamilyName)
+ {
+ case SPELLFAMILY_GENERIC:
+ {
+ switch (dummySpell->Id)
+ {
+ // Bloodworms Health Leech
+ case 50453:
+ {
+ if (Unit *owner = this->GetOwner())
+ {
+ basepoints0 = int32(damage*1.50);
+ target = owner;
+ triggered_spell_id = 50454;
+ break;
+ }
+ return false;
+ }
+ // Eye for an Eye
+ case 9799:
+ case 25988:
+ {
+ // return damage % to attacker but < 50% own total health
+ basepoints0 = triggerAmount*int32(damage)/100;
+ if(basepoints0 > GetMaxHealth()/2)
+ basepoints0 = GetMaxHealth()/2;
+
+ triggered_spell_id = 25997;
+ break;
+ }
+ // Sweeping Strikes
+ case 18765:
+ case 35429:
+ {
+ target = SelectNearbyTarget();
+ if(!target)
+ return false;
+
+ triggered_spell_id = 26654;
+ break;
+ }
+ // Unstable Power
+ case 24658:
+ {
+ if (!procSpell || procSpell->Id == 24659)
+ return false;
+ // Need remove one 24659 aura
+ RemoveAuraFromStack(24659);
+ return true;
+ }
+ // Restless Strength
+ case 24661:
+ {
+ // Need remove one 24662 aura
+ RemoveAuraFromStack(24662);
+ return true;
+ }
+ // Adaptive Warding (Frostfire Regalia set)
+ case 28764:
+ {
+ if(!procSpell)
+ return false;
+
+ // find Mage Armor
+ if (!GetAuraEffect(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT, SPELLFAMILY_MAGE, 0x10000000, 0, 0))
+ return false;
+
+ switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
+ {
+ case SPELL_SCHOOL_NORMAL:
+ case SPELL_SCHOOL_HOLY:
+ return false; // ignored
+ case SPELL_SCHOOL_FIRE: triggered_spell_id = 28765; break;
+ case SPELL_SCHOOL_NATURE: triggered_spell_id = 28768; break;
+ case SPELL_SCHOOL_FROST: triggered_spell_id = 28766; break;
+ case SPELL_SCHOOL_SHADOW: triggered_spell_id = 28769; break;
+ case SPELL_SCHOOL_ARCANE: triggered_spell_id = 28770; break;
+ default:
+ return false;
+ }
+
+ target = this;
+ break;
+ }
+ // Obsidian Armor (Justice Bearer`s Pauldrons shoulder)
+ case 27539:
+ {
+ if(!procSpell)
+ return false;
+
+ switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
+ {
+ case SPELL_SCHOOL_NORMAL:
+ return false; // ignore
+ case SPELL_SCHOOL_HOLY: triggered_spell_id = 27536; break;
+ case SPELL_SCHOOL_FIRE: triggered_spell_id = 27533; break;
+ case SPELL_SCHOOL_NATURE: triggered_spell_id = 27538; break;
+ case SPELL_SCHOOL_FROST: triggered_spell_id = 27534; break;
+ case SPELL_SCHOOL_SHADOW: triggered_spell_id = 27535; break;
+ case SPELL_SCHOOL_ARCANE: triggered_spell_id = 27540; break;
+ default:
+ return false;
+ }
+
+ target = this;
+ break;
+ }
+ // Mana Leech (Passive) (Priest Pet Aura)
+ case 28305:
+ {
+ // Cast on owner
+ target = GetOwner();
+ if(!target)
+ return false;
+
+ triggered_spell_id = 34650;
+ break;
+ }
+ // Spirit Walk
+ case 58875:
+ {
+ // Cast on owner
+ target = GetOwner();
+ if(!target)
+ return false;
+
+ triggered_spell_id = 58876;
+ break;
+ }
+ // Mark of Malice
+ case 33493:
+ {
+ // Cast finish spell at last charge
+ if (triggeredByAura->GetBase()->GetCharges() > 1)
+ return false;
+
+ target = this;
+ triggered_spell_id = 33494;
+ break;
+ }
+ // Twisted Reflection (boss spell)
+ case 21063:
+ triggered_spell_id = 21064;
+ break;
+ // Vampiric Aura (boss spell)
+ case 38196:
+ {
+ basepoints0 = 3 * damage; // 300%
+ if (basepoints0 < 0)
+ return false;
+
+ triggered_spell_id = 31285;
+ target = this;
+ break;
+ }
+ // Aura of Madness (Darkmoon Card: Madness trinket)
+ //=====================================================
+ // 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior)
+ // 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid)
+ // 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid)
+ // 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin)
+ // 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes)
+ // 41005 Manic: +35 haste (spell, melee and ranged) (All classes)
+ // 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter)
+ // 41011 Martyr Complex: +35 stamina (All classes)
+ // 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
+ // 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
+ case 39446:
+ {
+ if(GetTypeId() != TYPEID_PLAYER || !this->isAlive())
+ return false;
+
+ // Select class defined buff
+ switch (getClass())
+ {
+ case CLASS_PALADIN: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
+ case CLASS_DRUID: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
+ {
+ uint32 RandomSpell[]={39511,40997,40998,40999,41002,41005,41009,41011,41409};
+ triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
+ break;
+ }
+ case CLASS_ROGUE: // 39511,40997,40998,41002,41005,41011
+ case CLASS_WARRIOR: // 39511,40997,40998,41002,41005,41011
+ {
+ uint32 RandomSpell[]={39511,40997,40998,41002,41005,41011};
+ triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
+ break;
+ }
+ case CLASS_PRIEST: // 40999,41002,41005,41009,41011,41406,41409
+ case CLASS_SHAMAN: // 40999,41002,41005,41009,41011,41406,41409
+ case CLASS_MAGE: // 40999,41002,41005,41009,41011,41406,41409
+ case CLASS_WARLOCK: // 40999,41002,41005,41009,41011,41406,41409
+ {
+ uint32 RandomSpell[]={40999,41002,41005,41009,41011,41406,41409};
+ triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
+ break;
+ }
+ case CLASS_HUNTER: // 40997,40999,41002,41005,41009,41011,41406,41409
+ {
+ uint32 RandomSpell[]={40997,40999,41002,41005,41009,41011,41406,41409};
+ triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
+ break;
+ }
+ default:
+ return false;
+ }
+
+ target = this;
+ if (roll_chance_i(10))
+ ((Player*)this)->Say("This is Madness!", LANG_UNIVERSAL);
+ break;
+ }
+ /*
+ // Sunwell Exalted Caster Neck (??? neck)
+ // cast ??? Light's Wrath if Exalted by Aldor
+ // cast ??? Arcane Bolt if Exalted by Scryers*/
+ case 46569:
+ return false; // old unused version
+ // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck)
+ // cast 45479 Light's Wrath if Exalted by Aldor
+ // cast 45429 Arcane Bolt if Exalted by Scryers
+ case 45481:
+ {
+ if(GetTypeId() != TYPEID_PLAYER)
+ return false;
+
+ // Get Aldor reputation rank
+ if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
+ {
+ target = this;
+ triggered_spell_id = 45479;
+ break;
+ }
+ // Get Scryers reputation rank
+ if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
+ {
+ // triggered at positive/self casts also, current attack target used then
+ if(IsFriendlyTo(target))
+ {
+ target = getVictim();
+ if(!target)
+ {
+ uint64 selected_guid = ((Player *)this)->GetSelection();
+ target = ObjectAccessor::GetUnit(*this,selected_guid);
+ if(!target)
+ return false;
+ }
+ if(IsFriendlyTo(target))
+ return false;
+ }
+
+ triggered_spell_id = 45429;
+ break;
+ }
+ return false;
+ }
+ // Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck)
+ // cast 45480 Light's Strength if Exalted by Aldor
+ // cast 45428 Arcane Strike if Exalted by Scryers
+ case 45482:
+ {
+ if(GetTypeId() != TYPEID_PLAYER)
+ return false;
+
+ // Get Aldor reputation rank
+ if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
+ {
+ target = this;
+ triggered_spell_id = 45480;
+ break;
+ }
+ // Get Scryers reputation rank
+ if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
+ {
+ triggered_spell_id = 45428;
+ break;
+ }
+ return false;
+ }
+ // Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck)
+ // cast 45431 Arcane Insight if Exalted by Aldor
+ // cast 45432 Light's Ward if Exalted by Scryers
+ case 45483:
+ {
+ if(GetTypeId() != TYPEID_PLAYER)
+ return false;
+
+ // Get Aldor reputation rank
+ if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
+ {
+ target = this;
+ triggered_spell_id = 45432;
+ break;
+ }
+ // Get Scryers reputation rank
+ if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
+ {
+ target = this;
+ triggered_spell_id = 45431;
+ break;
+ }
+ return false;
+ }
+ // Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck)
+ // cast 45478 Light's Salvation if Exalted by Aldor
+ // cast 45430 Arcane Surge if Exalted by Scryers
+ case 45484:
+ {
+ if(GetTypeId() != TYPEID_PLAYER)
+ return false;
+
+ // Get Aldor reputation rank
+ if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
+ {
+ target = this;
+ triggered_spell_id = 45478;
+ break;
+ }
+ // Get Scryers reputation rank
+ if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
+ {
+ triggered_spell_id = 45430;
+ break;
+ }
+ return false;
+ }
+ // Living Seed
+ case 48504:
+ {
+ triggered_spell_id = 48503;
+ basepoints0 = triggerAmount;
+ target = this;
+ break;
+ }
+ // Kill command
+ case 58914:
+ {
+ // Remove aura stack from pet
+ RemoveAuraFromStack(58914);
+ Unit* owner = GetOwner();
+ if(!owner)
+ return true;
+ // reduce the owner's aura stack
+ owner->RemoveAuraFromStack(34027);
+ return true;
+ }
+ // Vampiric Touch (generic, used by some boss)
+ case 52723:
+ case 60501:
+ {
+ triggered_spell_id = 52724;
+ basepoints0 = damage / 2;
+ target = this;
+ break;
+ }
+ // Shadowfiend Death (Gain mana if pet dies with Glyph of Shadowfiend)
+ case 57989:
+ {
+ Unit *owner = GetOwner();
+ if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
+ return false;
+ // Glyph of Shadowfiend (need cast as self cast for owner, no hidden cooldown)
+ owner->CastSpell(owner,58227,true,castItem,triggeredByAura);
+ return true;
+ }
+ // Divine purpose
+ case 31871:
+ case 31872:
+ {
+ // Roll chane
+ if (!pVictim || !pVictim->isAlive() || !roll_chance_i(triggerAmount))
+ return false;
+
+ // Remove any stun effect on target
+ pVictim->RemoveAurasWithMechanic(1<<MECHANIC_STUN, AURA_REMOVE_BY_ENEMY_SPELL);
+ return true;
+ }
+ }
+ break;
+ }
+ case SPELLFAMILY_MAGE:
+ {
+ // Magic Absorption
+ if (dummySpell->SpellIconID == 459) // only this spell have SpellIconID == 459 and dummy aura
+ {
+ if (getPowerType() != POWER_MANA)
+ return false;
+
+ // mana reward
+ basepoints0 = (triggerAmount * GetMaxPower(POWER_MANA) / 100);
+ target = this;
+ triggered_spell_id = 29442;
+ break;
+ }
+ // Master of Elements
+ if (dummySpell->SpellIconID == 1920)
+ {
+ if(!procSpell)
+ return false;
+
+ // mana cost save
+ int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
+ basepoints0 = cost * triggerAmount/100;
+ if( basepoints0 <=0 )
+ return false;
+
+ target = this;
+ triggered_spell_id = 29077;
+ break;
+ }
+ // Arcane Potency
+ if (dummySpell->SpellIconID == 2120)
+ {
+ if(!procSpell)
+ return false;
+
+ target = this;
+ switch (dummySpell->Id)
+ {
+ case 31571: triggered_spell_id = 57529; break;
+ case 31572: triggered_spell_id = 57531; break;
+ default:
+ sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u",dummySpell->Id);
+ return false;
+ }
+ break;
+ }
+
+ // Hot Streak
+ if (dummySpell->SpellIconID == 2999)
+ {
+ if (effIndex!=0)
+ return false;
+ AuraEffect *counter = triggeredByAura->GetBase()->GetEffect(1);
+ if (!counter)
+ return true;
+
+ // Count spell criticals in a row in second aura
+ if (procEx & PROC_EX_CRITICAL_HIT)
+ {
+ counter->SetAmount(counter->GetAmount()*2);
+ if (counter->GetAmount() < 100) // not enough
+ return true;
+ // Crititcal counted -> roll chance
+ if (roll_chance_i(triggerAmount))
+ CastSpell(this, 48108, true, castItem, triggeredByAura);
+ }
+ counter->SetAmount(25);
+ return true;
+ }
+ // Burnout
+ if (dummySpell->SpellIconID == 2998)
+ {
+ if(!procSpell)
+ return false;
+
+ int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
+ basepoints0 = cost * triggerAmount/100;
+ if( basepoints0 <=0 )
+ return false;
+ triggered_spell_id = 44450;
+ target = this;
+ break;
+ }
+ // Incanter's Regalia set (add trigger chance to Mana Shield)
+ if (dummySpell->SpellFamilyFlags[0] & 0x8000)
+ {
+ if(GetTypeId() != TYPEID_PLAYER)
+ return false;
+
+ target = this;
+ triggered_spell_id = 37436;
+ break;
+ }
+ switch(dummySpell->Id)
+ {
+ // Glyph of Polymorph
+ case 56375:
+ {
+ target->RemoveAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
+ target->RemoveAurasByType(SPELL_AURA_PERIODIC_DAMAGE_PERCENT);
+ return true;
+ }
+ // Glyph of Drain Soul
+ case 58070:
+ {
+ triggered_spell_id = 58068;
+ break;
+ }
+ // Glyph of Icy Veins
+ case 56374:
+ {
+ RemoveAurasByType(SPELL_AURA_MOD_HASTE, 0, 0, true, false);
+ RemoveAurasByType(SPELL_AURA_MOD_DECREASE_SPEED);
+ return true;
+ }
+ // Ignite
+ case 11119:
+ case 11120:
+ case 12846:
+ case 12847:
+ case 12848:
+ {
+ switch (dummySpell->Id)
+ {
+ case 11119: basepoints0 = int32(0.04f*damage); break;
+ case 11120: basepoints0 = int32(0.08f*damage); break;
+ case 12846: basepoints0 = int32(0.12f*damage); break;
+ case 12847: basepoints0 = int32(0.16f*damage); break;
+ case 12848: basepoints0 = int32(0.20f*damage); break;
+ default:
+ sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (IG)",dummySpell->Id);
+ return false;
+ }
+
+ AuraEffectList const& DoTAuras = target->GetAuraEffectsByType(SPELL_AURA_PERIODIC_DAMAGE);
+ for (Unit::AuraEffectList::const_iterator i = DoTAuras.begin(); i != DoTAuras.end(); ++i)
+ {
+ if ((*i)->GetCasterGUID() != GetGUID() || (*i)->GetId() != 12654 || (*i)->GetEffIndex() != 0)
+ continue;
+ basepoints0 += ((*i)->GetAmount() * ((*i)->GetTotalTicks() - ((*i)->GetTickNumber()))) / 2;
+ break;
+ }
+
+ triggered_spell_id = 12654;
+ break;
+ }
+ // Glyph of Ice Block
+ case 56372:
+ {
+ if(GetTypeId() != TYPEID_PLAYER)
+ return false;
+
+ SpellCooldowns const SpellCDs = ((Player*)this)->GetSpellCooldowns();
+ // remove cooldowns on all ranks of Frost Nova
+ for (SpellCooldowns::const_iterator itr = SpellCDs.begin(); itr != SpellCDs.end(); itr++)
+ {
+ SpellEntry const* SpellCDs_entry = sSpellStore.LookupEntry(itr->first);
+ // Frost Nova
+ if(SpellCDs_entry && SpellCDs_entry->SpellFamilyName == SPELLFAMILY_MAGE
+ && SpellCDs_entry->SpellFamilyFlags[0] & 0x00000040)
+ ((Player*)this)->RemoveSpellCooldown(SpellCDs_entry->Id, true);
+ }
+ break;
+ }
+ }
+ break;
+ }
+ case SPELLFAMILY_WARRIOR:
+ {
+ switch(dummySpell->Id)
+ {
+ // Sweeping Strikes
+ case 12328:
+ {
+ target = SelectNearbyTarget();
+ if(!target)
+ return false;
+
+ triggered_spell_id = 26654;
+ break;
+ }
+ // Improved Spell Reflection
+ case 59088:
+ case 59089:
+ {
+ triggered_spell_id = 59725;
+ target = this;
+ break;
+ }
+ }
+
+ // Retaliation
+ if(dummySpell->SpellFamilyFlags[1] & 0x8)
+ {
+ // check attack comes not from behind
+ if (!HasInArc(M_PI, pVictim))
+ return false;
+
+ triggered_spell_id = 22858;
+ break;
+ }
+ // Second Wind
+ if (dummySpell->SpellIconID == 1697)
+ {
+ // only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example)
+ if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
+ return false;
+ // Need stun or root mechanic
+ if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_STUN))))
+ return false;
+
+ switch (dummySpell->Id)
+ {
+ case 29838: triggered_spell_id=29842; break;
+ case 29834: triggered_spell_id=29841; break;
+ case 42770: triggered_spell_id=42771; break;
+ default:
+ sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)",dummySpell->Id);
+ return false;
+ }
+
+ target = this;
+ break;
+ }
+ // Damage Shield
+ if (dummySpell->SpellIconID == 3214)
+ {
+ triggered_spell_id = 59653;
+ // % of amount blocked
+ basepoints0 = GetShieldBlockValue() * triggerAmount / 100;
+ break;
+ }
+ // Glyph of Blocking
+ if (dummySpell->Id == 58375)
+ {
+ triggered_spell_id = 58374;
+ break;
+ }
+ // Glyph of Sunder Armor
+ if (dummySpell->Id == 58387)
+ {
+ if (!pVictim || !pVictim->isAlive() || !procSpell)
+ return false;
+
+ target = SelectNearbyTarget();
+ if (!target || target == pVictim)
+ return false;
+
+ CastSpell(target, 58567, true);
+ return true;
+ }
+ break;
+ }
+ case SPELLFAMILY_WARLOCK:
+ {
+ // Seed of Corruption
+ if (dummySpell->SpellFamilyFlags[1] & 0x00000010)
+ {
+ if(procSpell && procSpell->Id == 27285)
+ return false;
+ // if damage is more than need or target die from damage deal finish spell
+ if( triggeredByAura->GetAmount() <= damage || GetHealth() <= damage )
+ {
+ // remember guid before aura delete
+ uint64 casterGuid = triggeredByAura->GetCasterGUID();
+
+ // Remove aura (before cast for prevent infinite loop handlers)
+ RemoveAurasDueToSpell(triggeredByAura->GetId());
+
+ // Cast finish spell (triggeredByAura already not exist!)
+ if(Unit* caster = GetUnit(*this, casterGuid))
+ caster->CastSpell(this, 27285, true, castItem);
+ return true; // no hidden cooldown
+ }
+
+ // Damage counting
+ triggeredByAura->SetAmount(triggeredByAura->GetAmount() - damage);
+ return true;
+ }
+ // Seed of Corruption (Mobs cast) - no die req
+ if (dummySpell->SpellFamilyFlags.IsEqual(0,0,0) && dummySpell->SpellIconID == 1932)
+ {
+ // if damage is more than need deal finish spell
+ if( triggeredByAura->GetAmount() <= damage )
+ {
+ // remember guid before aura delete
+ uint64 casterGuid = triggeredByAura->GetCasterGUID();
+
+ // Remove aura (before cast for prevent infinite loop handlers)
+ RemoveAurasDueToSpell(triggeredByAura->GetId());
+
+ // Cast finish spell (triggeredByAura already not exist!)
+ if(Unit* caster = GetUnit(*this, casterGuid))
+ caster->CastSpell(this, 32865, true, castItem);
+ return true; // no hidden cooldown
+ }
+ // Damage counting
+ triggeredByAura->SetAmount(triggeredByAura->GetAmount() - damage);
+ return true;
+ }
+ // Fel Synergy
+ if (dummySpell->SpellIconID == 3222)
+ {
+ target = GetGuardianPet();
+ if (!target)
+ return false;
+ basepoints0 = damage * triggerAmount / 100;
+ triggered_spell_id = 54181;
+ break;
+ }
+ switch (dummySpell->Id)
+ {
+ // Siphon Life
+ case 63108:
+ {
+ // Glyph of Siphon Life
+ if (HasAura(56216))
+ triggerAmount += triggerAmount / 4;
+ triggered_spell_id = 63106;
+ target = this;
+ basepoints0 = int32(damage*triggerAmount/100);
+ break;
+ }
+ // Glyph of Shadowflame
+ case 63310:
+ {
+ triggered_spell_id = 63311;
+ break;
+ }
+ // Glyph of Life Tap
+ case 63320:
+ {
+ triggered_spell_id = 63321;
+ break;
+ }
+ // Nightfall
+ case 18094:
+ case 18095:
+ // Glyph of corruption
+ case 56218:
+ {
+ target = this;
+ triggered_spell_id = 17941;
+ break;
+ }
+ //Soul Leech
+ case 30293:
+ case 30295:
+ case 30296:
+ {
+ // Improved Soul Leech
+ AuraEffectList const& SoulLeechAuras = GetAuraEffectsByType(SPELL_AURA_DUMMY);
+ for (Unit::AuraEffectList::const_iterator i = SoulLeechAuras.begin(); i != SoulLeechAuras.end(); ++i)
+ {
+ if ((*i)->GetId()==54117 || (*i)->GetId()==54118)
+ {
+ if ((*i)->GetEffIndex() != 0)
+ continue;
+ basepoints0 = int32((*i)->GetAmount());
+ if (target = GetGuardianPet())
+ {
+ // regen mana for pet
+ CastCustomSpell(target,54607,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
+ }
+ // regen mana for caster
+ CastCustomSpell(this,59117,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
+ // Get second aura of spell for replenishment effect on party
+ if (AuraEffect const * aurEff = (*i)->GetBase()->GetEffect(1))
+ {
+ // Replenishment - roll chance
+ if (roll_chance_i(aurEff->GetAmount()))
+ {
+ CastSpell(this,57669,true, castItem, triggeredByAura);
+ }
+ }
+ break;
+ }
+ }
+ // health
+ basepoints0 = int32(damage*triggerAmount/100);
+ target = this;
+ triggered_spell_id = 30294;
+ break;
+ }
+ // Shadowflame (Voidheart Raiment set bonus)
+ case 37377:
+ {
+ triggered_spell_id = 37379;
+ break;
+ }
+ // Pet Healing (Corruptor Raiment or Rift Stalker Armor)
+ case 37381:
+ {
+ target = GetGuardianPet();
+ if(!target)
+ return false;
+
+ // heal amount
+ basepoints0 = damage * triggerAmount/100;
+ triggered_spell_id = 37382;
+ break;
+ }
+ // Shadowflame Hellfire (Voidheart Raiment set bonus)
+ case 39437:
+ {
+ triggered_spell_id = 37378;
+ break;
+ }
+ }
+ break;
+ }
+ case SPELLFAMILY_PRIEST:
+ {
+ // Vampiric Touch
+ if( dummySpell->SpellFamilyFlags[1] & 0x00000400 )
+ {
+ if(!pVictim || !pVictim->isAlive())
+ return false;
+
+ if (effIndex!=0)
+ return false;
+
+ // pVictim is caster of aura
+ if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
+ return false;
+
+ // Energize 0.25% of max. mana
+ pVictim->CastSpell(pVictim,57669,true,castItem,triggeredByAura);
+ return true; // no hidden cooldown
+ }
+ // Divine Aegis
+ if (dummySpell->SpellIconID == 2820)
+ {
+ // Multiple effects stack, so let's try to find this aura.
+ int32 bonus = 0;
+ if (AuraEffect *aurEff = target->GetAuraEffect(47753, 0))
+ bonus = aurEff->GetAmount();
+
+ basepoints0 = damage * triggerAmount/100 + bonus;
+ if (basepoints0 > target->getLevel() * 125)
+ basepoints0 = target->getLevel() * 125;
+
+ triggered_spell_id = 47753;
+ break;
+ }
+ // Body and Soul
+ if (dummySpell->SpellIconID == 2218)
+ {
+ // Proc only from Abolish desease on self cast
+ if (procSpell->Id != 552 || pVictim != this || !roll_chance_i(triggerAmount))
+ return false;
+ triggered_spell_id = 64136;
+ target = this;
+ break;
+ }
+ switch(dummySpell->Id)
+ {
+ // Vampiric Embrace
+ case 15286:
+ {
+ if(!pVictim || !pVictim->isAlive())
+ return false;
+
+ // heal amount
+ int32 team = triggerAmount*damage/500;
+ int32 self = triggerAmount*damage/100 - team;
+ CastCustomSpell(this,15290,&team,&self,NULL,true,castItem,triggeredByAura);
+ return true; // no hidden cooldown
+ }
+ // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen)
+ case 40438:
+ {
+ // Shadow Word: Pain
+ if( procSpell->SpellFamilyFlags[0] & 0x8000 )
+ triggered_spell_id = 40441;
+ // Renew
+ else if( procSpell->SpellFamilyFlags[0] & 0x40 )
+ triggered_spell_id = 40440;
+ else
+ return false;
+
+ target = this;
+ break;
+ }
+ // Glyph of Prayer of Healing
+ case 55680:
+ {
+ triggered_spell_id = 56161;
+
+ SpellEntry const* GoPoH = sSpellStore.LookupEntry(triggered_spell_id);
+ if(!GoPoH)
+ return false;
+
+ int EffIndex = 0;
+ for (uint8 i = 0; i < MAX_SPELL_EFFECTS; i++)
+ {
+ if(GoPoH->Effect[i] == SPELL_EFFECT_APPLY_AURA)
+ {
+ EffIndex = i;
+ break;
+ }
+ }
+ int32 tickcount = GetSpellMaxDuration(GoPoH) / GoPoH->EffectAmplitude[EffIndex];
+ if(!tickcount)
+ return false;
+
+ basepoints0 = damage * triggerAmount / tickcount / 100;
+ break;
+ }
+ // Improved Shadowform
+ case 47570:
+ case 47569:
+ {
+ if (!roll_chance_i(triggerAmount))
+ return false;
+
+ RemoveMovementImpairingAuras();
+ break;
+ }
+ // Glyph of Dispel Magic
+ case 55677:
+ {
+ // Dispel Magic shares spellfamilyflag with abolish disease
+ if (procSpell->SpellIconID != 74)
+ return false;
+ if(!target || !target->IsFriendlyTo(this))
+ return false;
+
+ basepoints0 = int32(target->GetMaxHealth() * triggerAmount / 100);
+ triggered_spell_id = 56131;
+ break;
+ }
+ // Oracle Healing Bonus ("Garments of the Oracle" set)
+ case 26169:
+ {
+ // heal amount
+ basepoints0 = int32(damage * 10/100);
+ target = this;
+ triggered_spell_id = 26170;
+ break;
+ }
+ // Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set
+ case 39372:
+ {
+ if(!procSpell || (GetSpellSchoolMask(procSpell) & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW))==0 )
+ return false;
+
+ // heal amount
+ basepoints0 = damage * triggerAmount/100;
+ target = this;
+ triggered_spell_id = 39373;
+ break;
+ }
+ // Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus)
+ case 28809:
+ {
+ triggered_spell_id = 28810;
+ break;
+ }
+ }
+ break;
+ }
+ case SPELLFAMILY_DRUID:
+ {
+ switch(dummySpell->Id)
+ {
+ // Glyph of Innervate
+ case 54832:
+ {
+ if (procSpell->SpellIconID != 62)
+ return false;
+
+ int32 mana_perc = triggeredByAura->GetSpellProto()->EffectBasePoints[triggeredByAura->GetEffIndex()]+1;
+ basepoints0 = uint32((GetPower(POWER_MANA) * mana_perc / 100) / 10);
+ triggered_spell_id = 54833;
+ target = this;
+ break;
+ }
+ // Glyph of Starfire
+ case 54845:
+ {
+ triggered_spell_id = 54846;
+ break;
+ }
+ // Glyph of Shred
+ case 54815:
+ {
+ triggered_spell_id = 63974;
+ break;
+ }
+ // Glyph of Rake
+ case 54821:
+ {
+ if (procSpell->SpellVisual[0] == 750 && procSpell->EffectApplyAuraName[1] == 3)
+ {
+ if (target->GetTypeId() == TYPEID_UNIT)
+ {
+ triggered_spell_id = 54820;
+ break;
+ }
+ }
+ return false;
+ }
+ // Leader of the Pack
+ case 24932:
+ {
+ if (triggerAmount <= 0)
+ return false;
+ basepoints0 = triggerAmount * GetMaxHealth() / 100;
+ target = this;
+ triggered_spell_id = 34299;
+ if (triggeredByAura->GetCasterGUID() != GetGUID())
+ break;
+ int32 basepoints1 = triggerAmount * 2;
+ // Improved Leader of the Pack
+ // Check cooldown of heal spell cooldown
+ if (GetTypeId() == TYPEID_PLAYER && !((Player *)this)->HasSpellCooldown(34299))
+ CastCustomSpell(this,60889,&basepoints1,0,0,true,0,triggeredByAura);
+ break;
+ }
+ // Healing Touch (Dreamwalker Raiment set)
+ case 28719:
+ {
+ // mana back
+ basepoints0 = int32(procSpell->manaCost * 30 / 100);
+ target = this;
+ triggered_spell_id = 28742;
+ break;
+ }
+ // Glyph of Rejuvenation
+ case 54754:
+ {
+ if (!pVictim || pVictim->GetHealth() >= triggerAmount * pVictim->GetMaxHealth()/100)
+ return false;
+ basepoints0 = int32(triggerAmount * damage / 100);
+ triggered_spell_id = 54755;
+ break;
+ }
+ // Healing Touch Refund (Idol of Longevity trinket)
+ case 28847:
+ {
+ target = this;
+ triggered_spell_id = 28848;
+ break;
+ }
+ // Mana Restore (Malorne Raiment set / Malorne Regalia set)
+ case 37288:
+ case 37295:
+ {
+ target = this;
+ triggered_spell_id = 37238;
+ break;
+ }
+ // Druid Tier 6 Trinket
+ case 40442:
+ {
+ float chance;
+
+ // Starfire
+ if( procSpell->SpellFamilyFlags[0] & 0x4 )
+ {
+ triggered_spell_id = 40445;
+ chance = 25.0f;
+ }
+ // Rejuvenation
+ else if( procSpell->SpellFamilyFlags[0] & 0x10 )
+ {
+ triggered_spell_id = 40446;
+ chance = 25.0f;
+ }
+ // Mangle (Bear) and Mangle (Cat)
+ else if( procSpell->SpellFamilyFlags[1] & 0x00000440)
+ {
+ triggered_spell_id = 40452;
+ chance = 40.0f;
+ }
+ else
+ return false;
+
+ if (!roll_chance_f(chance))
+ return false;
+
+ target = this;
+ break;
+ }
+ // Maim Interrupt
+ case 44835:
+ {
+ // Deadly Interrupt Effect
+ triggered_spell_id = 32747;
+ break;
+ }
+ }
+ // Eclipse
+ if (dummySpell->SpellIconID == 2856 && GetTypeId() == TYPEID_PLAYER)
+ {
+ if (!procSpell || effIndex != 0)
+ return false;
+
+ bool isWrathSpell = (procSpell->SpellFamilyFlags[0] & 1);
+
+ if (!roll_chance_f(dummySpell->procChance * (isWrathSpell ? 0.6f : 1.0f)))
+ return false;
+
+ target = this;
+ if (target->HasAura(isWrathSpell ? 48517 : 48518))
+ return false;
+
+ triggered_spell_id = isWrathSpell ? 48518 : 48517;
+ break;
+ }
+ // Living Seed
+ else if (dummySpell->SpellIconID == 2860)
+ {
+ triggered_spell_id = 48504;
+ basepoints0 = triggerAmount * damage / 100;
+ break;
+ }
+ // King of the Jungle
+ else if (dummySpell->SpellIconID == 2850)
+ {
+ // Effect 0 - mod damage while having Enrage
+ if (effIndex==0)
+ {
+ if (!(procSpell->SpellFamilyFlags[0] & 0x00080000))
+ return false;
+ triggered_spell_id = 51185;
+ basepoints0 = triggerAmount;
+ target = this;
+ break;
+ }
+ // Effect 1 - Tiger's Fury restore energy
+ else if (effIndex==1)
+ {
+ if (!(procSpell->SpellFamilyFlags[2] & 0x00000800))
+ return false;
+ triggered_spell_id = 51178;
+ basepoints0 = triggerAmount;
+ target = this;
+ break;
+ }
+ }
+ break;
+ }
+ case SPELLFAMILY_ROGUE:
+ {
+ switch(dummySpell->Id)
+ {
+ // Glyph of Backstab
+ case 56800:
+ {
+ triggered_spell_id = 63975;
+ break;
+ }
+ // Deadly Throw Interrupt
+ case 32748:
+ {
+ // Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw
+ if(this == pVictim)
+ return false;
+
+ triggered_spell_id = 32747;
+ break;
+ }
+ }
+ // Cut to the Chase
+ if( dummySpell->SpellIconID == 2909 )
+ {
+ // "refresh your Slice and Dice duration to its 5 combo point maximum"
+ // lookup Slice and Dice
+ if (AuraEffect const* aur = GetAuraEffect(SPELL_AURA_MOD_HASTE, SPELLFAMILY_ROGUE,0x40000, 0, 0))
+ {
+ aur->GetBase()->SetDuration(GetSpellMaxDuration(aur->GetSpellProto()), true);
+ return true;
+ }
+ return false;
+ }
+ // Deadly Brew
+ else if( dummySpell->SpellIconID == 2963 )
+ {
+ triggered_spell_id = 3409;
+ break;
+ }
+ // Quick Recovery
+ else if( dummySpell->SpellIconID == 2116 )
+ {
+ if(!procSpell)
+ return false;
+
+ // energy cost save
+ basepoints0 = procSpell->manaCost * triggerAmount/100;
+ if(basepoints0 <= 0)
+ return false;
+
+ target = this;
+ triggered_spell_id = 31663;
+ break;
+ }
+ break;
+ }
+ case SPELLFAMILY_HUNTER:
+ {
+ // Thrill of the Hunt
+ if ( dummySpell->SpellIconID == 2236 )
+ {
+ if(!procSpell)
+ return false;
+
+ // mana cost save
+ int32 mana = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
+ basepoints0 = mana * 40/100;
+ if(basepoints0 <= 0)
+ return false;
+
+ target = this;
+ triggered_spell_id = 34720;
+ break;
+ }
+ // Hunting Party
+ if ( dummySpell->SpellIconID == 3406 )
+ {
+ triggered_spell_id = 57669;
+ target = this;
+ break;
+ }
+ // Improved Mend Pet
+ if ( dummySpell->SpellIconID == 267 )
+ {
+ int32 chance = triggeredByAura->GetSpellProto()->EffectBasePoints[triggeredByAura->GetEffIndex()];
+ if(!roll_chance_i(chance))
+ return false;
+
+ triggered_spell_id = 24406;
+ break;
+ }
+ // Lock and Load
+ if ( dummySpell->SpellIconID == 3579 )
+ {
+ // Proc only from periodic (from trap activation proc another aura of this spell)
+ if (!(procFlag & PROC_FLAG_ON_DO_PERIODIC) || !roll_chance_i(triggerAmount))
+ return false;
+ triggered_spell_id = 56453;
+ target = this;
+ break;
+ }
+ // Rapid Recuperation
+ if (dummySpell->SpellIconID == 3560)
+ {
+ // This effect only from Rapid Killing (mana regen)
+ if (!(procSpell->SpellFamilyFlags[1] & 0x01000000))
+ return false;
+ triggered_spell_id = 56654;
+
+ target = this;
+
+ switch(dummySpell->Id)
+ {
+ case 53228: // Rank 1
+ triggered_spell_id = 56654;
+ break;
+ case 53232: // Rank 2
+ triggered_spell_id = 58882;
+ break;
+ }
+ break;
+ }
+ break;
+ }
+ case SPELLFAMILY_PALADIN:
+ {
+ // Seal of Righteousness - melee proc dummy (addition ${$MWS*(0.022*$AP+0.044*$SPH)} damage)
+ if (dummySpell->SpellFamilyFlags[0]&0x8000000)
+ {
+ if (effIndex!=0)
+ return false;
+ triggered_spell_id = 25742;
+ float ap = GetTotalAttackPowerValue(BASE_ATTACK);
+ int32 holy = SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
+ SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, pVictim);
+ basepoints0 = (int32)GetAttackTime(BASE_ATTACK) * int32(ap*0.022f + 0.044f * holy) / 1000;
+ break;
+ }
+ // Light's Beacon - Beacon of Light
+ if (dummySpell->Id == 53651)
+ {
+ // Get target of beacon of light
+ if (Unit * beaconTarget = triggeredByAura->GetBase()->GetCaster())
+ {
+ // do not proc when target of beacon of light is healed
+ if (beaconTarget == this)
+ return false;
+ // check if it was heal by paladin which casted this beacon of light
+ if (Aura const * aura = beaconTarget->GetAura(53563, pVictim->GetGUID()))
+ {
+ basepoints0 = damage;
+ triggered_spell_id = 53654;
+ target = beaconTarget;
+ break;
+ }
+ }
+ return false;
+ }
+ // Judgements of the Wise
+ if (dummySpell->SpellIconID == 3017)
+ {
+ target = this;
+ triggered_spell_id = 31930;
+ // replenishment
+ CastSpell(this,57669,true, castItem, triggeredByAura);
+ break;
+ }
+ // Sanctified Wrath
+ if (dummySpell->SpellIconID == 3029)
+ {
+ triggered_spell_id = 57318;
+ target = this;
+ basepoints0 = triggerAmount;
+ CastCustomSpell(target,triggered_spell_id,&basepoints0,&basepoints0,NULL,true,castItem,triggeredByAura);
+ return true;
+ }
+ // Sacred Shield
+ if (dummySpell->SpellFamilyFlags[1]&0x00080000)
+ {
+ if (procFlag & PROC_FLAG_TAKEN_POSITIVE_MAGIC_SPELL)
+ {
+ if (procSpell->SpellFamilyName == SPELLFAMILY_PALADIN
+ && (procSpell->SpellFamilyFlags[0] & 0x40000000))
+ {
+ basepoints0 = int32(float(damage)/12.0f);
+ CastCustomSpell(this,66922,&basepoints0,NULL,NULL,true,0,triggeredByAura, pVictim->GetGUID());
+ return true;
+ }
+ else
+ return false;
+ }
+ else
+ triggered_spell_id = 58597;
+ target = this;
+ break;
+ }
+ // Righteous Vengeance
+ if (dummySpell->SpellIconID == 3025)
+ {
+ // 4 damage tick
+ basepoints0 = triggerAmount*damage/400;
+ triggered_spell_id = 61840;
+ break;
+ }
+ // Sheath of Light
+ if (dummySpell->SpellIconID == 3030)
+ {
+ // 4 healing tick
+ basepoints0 = triggerAmount*damage/400;
+ triggered_spell_id = 54203;
+ break;
+ }
+ switch (dummySpell->Id)
+ {
+ // Heart of the Crusader
+ case 20335: // rank 1
+ triggered_spell_id = 21183;
+ break;
+ case 20336: // rank 2
+ triggered_spell_id = 54498;
+ break;
+ case 20337: // rank 3
+ triggered_spell_id = 54499;
+ break;
+ // Judgement of Light
+ case 20185:
+ {
+ if (pVictim->getPowerType() == POWER_MANA)
+ {
+ // 2% of base mana
+ basepoints0 = int32(pVictim->GetMaxHealth() * 2 / 100);
+ pVictim->CastCustomSpell(pVictim, 20267, &basepoints0, 0, 0, true, 0, triggeredByAura);
+ }
+ return true;
+ }
+ // Judgement of Wisdom
+ case 20186:
+ {
+ if (pVictim && pVictim->isAlive() && pVictim->getPowerType() == POWER_MANA)
+ {
+ // 2% of base mana
+ basepoints0 = int32(pVictim->GetCreateMana() * 2 / 100);
+ pVictim->CastCustomSpell(pVictim, 20268, &basepoints0, NULL, NULL, true, 0, triggeredByAura);
+ }
+ return true;
+ }
+ // Holy Power (Redemption Armor set)
+ case 28789:
+ {
+ if(!pVictim)
+ return false;
+
+ // Set class defined buff
+ switch (pVictim->getClass())
+ {
+ case CLASS_PALADIN:
+ case CLASS_PRIEST:
+ case CLASS_SHAMAN:
+ case CLASS_DRUID:
+ triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
+ break;
+ case CLASS_MAGE:
+ case CLASS_WARLOCK:
+ triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
+ break;
+ case CLASS_HUNTER:
+ case CLASS_ROGUE:
+ triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d.
+ break;
+ case CLASS_WARRIOR:
+ triggered_spell_id = 28790; // Increases the friendly target's armor
+ break;
+ default:
+ return false;
+ }
+ break;
+ }
+ case 25899: // Greater Blessing of Sanctuary
+ case 20911: // Blessing of Sanctuary
+ {
+ target = this;
+ switch (target->getPowerType())
+ {
+ case POWER_MANA:
+ triggered_spell_id = 57319;
+ break;
+ default:
+ return false;
+ }
+ break;
+ }
+ // Seal of Vengeance (damage calc on apply aura)
+ case 31801:
+ {
+ if(effIndex != 0) // effect 1,2 used by seal unleashing code
+ return false;
+
+ // At melee attack or Hammer of the Righteous spell damage considered as melee attack
+ if ((procFlag & PROC_FLAG_SUCCESSFUL_MELEE_HIT) || (procSpell && procSpell->Id == 53595) )
+ triggered_spell_id = 31803;
+ // On target with 5 stacks of Holy Vengeance direct damage is done
+ if (Aura * aur = pVictim->GetAura(triggered_spell_id, GetGUID()))
+ {
+ if (aur->GetStackAmount() == 5)
+ {
+ aur->RefreshDuration();
+ CastSpell(pVictim, 42463, true);
+ return true;
+ }
+ }
+
+ // Only Autoattack can stack debuff
+ if (procFlag & PROC_FLAG_SUCCESSFUL_MELEE_SPELL_HIT)
+ return false;
+ break;
+ }
+ // Seal of Corruption
+ case 53736:
+ {
+ if(effIndex != 0) // effect 1,2 used by seal unleashing code
+ return false;
+
+ // At melee attack or Hammer of the Righteous spell damage considered as melee attack
+ if ((procFlag & PROC_FLAG_SUCCESSFUL_MELEE_HIT) || (procSpell && procSpell->Id == 53595))
+ triggered_spell_id = 53742;
+ // On target with 5 stacks of Blood Corruption direct damage is done
+ if (Aura * aur = pVictim->GetAura(triggered_spell_id, GetGUID()))
+ {
+ if (aur->GetStackAmount() == 5)
+ {
+ aur->RefreshDuration();
+ CastSpell(pVictim, 53739, true);
+ return true;
+ }
+ }
+
+ // Only Autoattack can stack debuff
+ if (procFlag & PROC_FLAG_SUCCESSFUL_MELEE_SPELL_HIT)
+ return false;
+ break;
+ }
+ // Spiritual Attunement
+ case 31785:
+ case 33776:
+ {
+ // if healed by another unit (pVictim)
+ if(this == pVictim)
+ return false;
+
+ // heal amount
+ basepoints0 = triggerAmount*damage/100;
+ target = this;
+
+ if(basepoints0)
+ triggered_spell_id = 31786;
+ break;
+ }
+ // Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal)
+ case 40470:
+ {
+ if( !procSpell )
+ return false;
+
+ float chance;
+
+ // Flash of light/Holy light
+ if( procSpell->SpellFamilyFlags[0] & 0xC0000000)
+ {
+ triggered_spell_id = 40471;
+ chance = 15.0f;
+ }
+ // Judgement (any)
+ else if (GetSpellSpecific(procSpell) == SPELL_SPECIFIC_JUDGEMENT)
+ {
+ triggered_spell_id = 40472;
+ chance = 50.0f;
+ }
+ else
+ return false;
+
+ if (!roll_chance_f(chance))
+ return false;
+
+ break;
+ }
+ // Glyph of Divinity
+ case 54939:
+ {
+ // Lookup base amount mana restore
+ for (uint8 i=0; i<MAX_SPELL_EFFECTS; i++)
+ if (procSpell->Effect[i] == SPELL_EFFECT_ENERGIZE)
+ {
+ int32 mana = procSpell->EffectBasePoints[i];
+ CastCustomSpell(this, 54986, 0, &mana, 0, true, castItem, triggeredByAura);
+ break;
+ }
+ return true;
+ }
+ // Glyph of Flash of Light
+ case 54936:
+ {
+ triggered_spell_id = 54957;
+ basepoints0 = triggerAmount*damage/100;
+ break;
+ }
+ // Glyph of Holy Light
+ case 54937:
+ {
+ triggered_spell_id = 54968;
+ basepoints0 = triggerAmount*damage/100;
+ break;
+ }
+ }
+ break;
+ }
+ case SPELLFAMILY_SHAMAN:
+ {
+ switch(dummySpell->Id)
+ {
+ // Earthen Power (Rank 1, 2)
+ case 51523:
+ case 51524:
+ {
+ // Totem itself must be a caster of this spell
+ Unit* caster = NULL;
+ for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr) {
+ if ((*itr)->GetEntry() != 2630)
+ continue;
+
+ caster = (*itr);
+ break;
+ }
+
+ if (!caster)
+ return false;
+
+ caster->CastSpell(caster, 59566, true, castItem, triggeredByAura, originalCaster);
+ return true;
+ }
+ // Tidal Force
+ case 55198:
+ {
+ // Remove aura stack from caster
+ RemoveAuraFromStack(55166);
+ // drop charges
+ return false;
+ }
+ // Totemic Power (The Earthshatterer set)
+ case 28823:
+ {
+ if( !pVictim )
+ return false;
+
+ // Set class defined buff
+ switch (pVictim->getClass())
+ {
+ case CLASS_PALADIN:
+ case CLASS_PRIEST:
+ case CLASS_SHAMAN:
+ case CLASS_DRUID:
+ triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
+ break;
+ case CLASS_MAGE:
+ case CLASS_WARLOCK:
+ triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
+ break;
+ case CLASS_HUNTER:
+ case CLASS_ROGUE:
+ triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d.
+ break;
+ case CLASS_WARRIOR:
+ triggered_spell_id = 28827; // Increases the friendly target's armor
+ break;
+ default:
+ return false;
+ }
+ break;
+ }
+ // Lesser Healing Wave (Totem of Flowing Water Relic)
+ case 28849:
+ {
+ target = this;
+ triggered_spell_id = 28850;
+ break;
+ }
+ // Windfury Weapon (Passive) 1-5 Ranks
+ case 33757:
+ {
+ if(GetTypeId()!=TYPEID_PLAYER || !castItem || !castItem->IsEquipped() || !pVictim || !pVictim->isAlive())
+ return false;
+
+ // custom cooldown processing case
+ if( cooldown && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
+ return false;
+
+ if (triggeredByAura->GetBase() && castItem->GetGUID() != triggeredByAura->GetBase()->GetCastItemGUID())
+ return false;
+
+ WeaponAttackType attType = WeaponAttackType(((Player*)this)->GetAttackBySlot(castItem->GetSlot()));
+ if ((attType != BASE_ATTACK && attType != OFF_ATTACK) || !isAttackReady(attType))
+ return false;
+
+ // Now compute real proc chance...
+ uint32 chance = 20;
+ ((Player*)this)->ApplySpellMod(dummySpell->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
+
+ Item* addWeapon = ((Player*)this)->GetWeaponForAttack(attType == BASE_ATTACK ? OFF_ATTACK : BASE_ATTACK, true);
+ uint32 enchant_id_add = addWeapon ? addWeapon->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)) : 0;
+ SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id_add);
+ if (pEnchant && pEnchant->spellid[0] == dummySpell->Id)
+ chance += 14;
+
+ if (!roll_chance_i(chance))
+ return false;
+
+ // Now amount of extra power stored in 1 effect of Enchant spell
+ // Get it by item enchant id
+ uint32 spellId;
+ switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)))
+ {
+ case 283: spellId = 8232; break; // 1 Rank
+ case 284: spellId = 8235; break; // 2 Rank
+ case 525: spellId = 10486; break; // 3 Rank
+ case 1669:spellId = 16362; break; // 4 Rank
+ case 2636:spellId = 25505; break; // 5 Rank
+ case 3785:spellId = 58801; break; // 6 Rank
+ case 3786:spellId = 58803; break; // 7 Rank
+ case 3787:spellId = 58804; break; // 8 Rank
+ default:
+ {
+ sLog.outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)",
+ castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)),dummySpell->Id);
+ return false;
+ }
+ }
+
+ SpellEntry const* windfurySpellEntry = sSpellStore.LookupEntry(spellId);
+ if(!windfurySpellEntry)
+ {
+ sLog.outError("Unit::HandleDummyAuraProc: non existed spell id: %u (Windfury)",spellId);
+ return false;
+ }
+
+ int32 extra_attack_power = CalculateSpellDamage(windfurySpellEntry, 1, windfurySpellEntry->EffectBasePoints[1], pVictim);
+
+ // Value gained from additional AP
+ basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(BASE_ATTACK)/1000);
+ triggered_spell_id = 25504;
+
+ // apply cooldown before cast to prevent processing itself
+ if( cooldown )
+ ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
+
+ // Attack Twice
+ for (uint32 i = 0; i<2; ++i )
+ CastCustomSpell(pVictim,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
+
+ return true;
+ }
+ // Shaman Tier 6 Trinket
+ case 40463:
+ {
+ if (!procSpell)
+ return false;
+
+ float chance;
+ if (procSpell->SpellFamilyFlags[0] & 0x1)
+ {
+ triggered_spell_id = 40465; // Lightning Bolt
+ chance = 15.0f;
+ }
+ else if (procSpell->SpellFamilyFlags[0] & 0x80)
+ {
+ triggered_spell_id = 40465; // Lesser Healing Wave
+ chance = 10.0f;
+ }
+ else if (procSpell->SpellFamilyFlags[1] & 0x00000010)
+ {
+ triggered_spell_id = 40466; // Stormstrike
+ chance = 50.0f;
+ }
+ else
+ return false;
+
+ if (!roll_chance_f(chance))
+ return false;
+
+ target = this;
+ break;
+ }
+ // Glyph of Healing Wave
+ case 55440:
+ {
+ // Not proc from self heals
+ if (this == pVictim)
+ return false;
+ basepoints0 = triggerAmount * damage / 100;
+ target = this;
+ triggered_spell_id = 55533;
+ break;
+ }
+ // Spirit Hunt
+ case 58877:
+ {
+ // Cast on owner
+ target = GetOwner();
+ if(!target)
+ return false;
+ basepoints0 = triggerAmount * damage / 100;
+ triggered_spell_id = 58879;
+ break;
+ }
+ // Shaman T8 Elemental 4P Bonus
+ case 64928:
+ {
+ basepoints0 = int32( triggerAmount * damage / 100 );
+ triggered_spell_id = 64930; // Electrified
+ break;
+ }
+ }
+ // Frozen Power
+ if (dummySpell->SpellIconID == 3780)
+ {
+ if (this->GetDistance(target) < 15.0f)
+ return false;
+ float chance = triggerAmount;
+ if (!roll_chance_f(chance))
+ return false;
+
+ triggered_spell_id = 63685;
+ break;
+ }
+ // Storm, Earth and Fire
+ if (dummySpell->SpellIconID == 3063)
+ {
+ // Earthbind Totem summon only
+ if(procSpell->Id != 2484)
+ return false;
+
+ float chance = triggerAmount;
+ if (!roll_chance_f(chance))
+ return false;
+
+ triggered_spell_id = 64695;
+ break;
+ }
+ // Ancestral Awakening
+ if (dummySpell->SpellIconID == 3065)
+ {
+ triggered_spell_id = 52759;
+ basepoints0 = triggerAmount * damage / 100;
+ target = this;
+ break;
+ }
+ // Earth Shield
+ if(dummySpell->SpellFamilyFlags[1] & 0x00000400)
+ {
+ // 3.0.8: Now correctly uses the Shaman's own spell critical strike chance to determine the chance of a critical heal.
+ originalCaster = triggeredByAura->GetCasterGUID();
+ target = this;
+ basepoints0 = triggerAmount;
+
+ // Glyph of Earth Shield
+ if (AuraEffect* aur = GetAuraEffect(63279,0))
+ {
+ int32 aur_mod = aur->GetAmount();
+ basepoints0 = int32(basepoints0 * (aur_mod + 100.0f) / 100.0f);
+ }
+ triggered_spell_id = 379;
+ break;
+ }
+ // Flametongue Weapon (Passive)
+ if (dummySpell->SpellFamilyFlags[0] & 0x200000)
+ {
+ if(GetTypeId()!=TYPEID_PLAYER || !pVictim || !pVictim->isAlive() || !castItem || !castItem->IsEquipped())
+ return false;
+
+ // firehit = dummySpell->EffectBasePoints[0] / ((4*19.25) * 1.3);
+ float fire_onhit = dummySpell->EffectBasePoints[0] / 100.0;
+
+ float add_spellpower = SpellBaseDamageBonus(SPELL_SCHOOL_MASK_FIRE)
+ + SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_FIRE, pVictim);
+
+ // 1.3speed = 5%, 2.6speed = 10%, 4.0 speed = 15%, so, 1.0speed = 3.84%
+ add_spellpower= add_spellpower / 100.0 * 3.84;
+
+ // Enchant on Off-Hand and ready?
+ if ( castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND && isAttackReady(OFF_ATTACK))
+ {
+ float BaseWeaponSpeed = GetAttackTime(OFF_ATTACK)/1000.0;
+
+ // Value1: add the tooltip damage by swingspeed + Value2: add spelldmg by swingspeed
+ basepoints0 = int32( (fire_onhit * BaseWeaponSpeed) + (add_spellpower * BaseWeaponSpeed) );
+ triggered_spell_id = 10444;
+ }
+
+ // Enchant on Main-Hand and ready?
+ else if ( castItem->GetSlot() == EQUIPMENT_SLOT_MAINHAND && isAttackReady(BASE_ATTACK))
+ {
+ float BaseWeaponSpeed = GetAttackTime(BASE_ATTACK)/1000.0;
+
+ // Value1: add the tooltip damage by swingspeed + Value2: add spelldmg by swingspeed
+ basepoints0 = int32( (fire_onhit * BaseWeaponSpeed) + (add_spellpower * BaseWeaponSpeed) );
+ triggered_spell_id = 10444;
+ }
+
+ // If not ready, we should return, shouldn't we?!
+ else
+ return false;
+
+ CastCustomSpell(pVictim,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
+ return true;
+ }
+ // Improved Water Shield
+ if (dummySpell->SpellIconID == 2287)
+ {
+ // Default chance for Healing Wave and Riptide
+ float chance = triggeredByAura->GetAmount();
+
+ if (procSpell->SpellFamilyFlags[0] & 0x80)
+ // Lesser Healing Wave - 0.6 of default
+ chance *= 0.6f;
+ else if (procSpell->SpellFamilyFlags[0] & 0x100)
+ // Chain heal - 0.3 of default
+ chance *= 0.3f;
+
+ if (!roll_chance_f(chance))
+ return false;
+
+ // Water Shield
+ if (AuraEffect const * aurEff = GetAuraEffect(SPELL_AURA_PROC_TRIGGER_SPELL, SPELLFAMILY_SHAMAN, 0, 0x00000020, 0))
+ {
+ uint32 spell = aurEff->GetSpellProto()->EffectTriggerSpell[aurEff->GetEffIndex()];
+ CastSpell(this, spell, true, castItem, triggeredByAura);
+ return true;
+ }
+ return false;
+ }
+ // Lightning Overload
+ if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura
+ {
+ if(!procSpell || GetTypeId() != TYPEID_PLAYER || !pVictim )
+ return false;
+
+ // custom cooldown processing case
+ if( cooldown && GetTypeId() == TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
+ return false;
+
+ uint32 spellId = 0;
+ // Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost
+ switch (procSpell->Id)
+ {
+ // Lightning Bolt
+ case 403: spellId = 45284; break; // Rank 1
+ case 529: spellId = 45286; break; // Rank 2
+ case 548: spellId = 45287; break; // Rank 3
+ case 915: spellId = 45288; break; // Rank 4
+ case 943: spellId = 45289; break; // Rank 5
+ case 6041: spellId = 45290; break; // Rank 6
+ case 10391: spellId = 45291; break; // Rank 7
+ case 10392: spellId = 45292; break; // Rank 8
+ case 15207: spellId = 45293; break; // Rank 9
+ case 15208: spellId = 45294; break; // Rank 10
+ case 25448: spellId = 45295; break; // Rank 11
+ case 25449: spellId = 45296; break; // Rank 12
+ case 49237: spellId = 49239; break; // Rank 13
+ case 49238: spellId = 49240; break; // Rank 14
+ // Chain Lightning
+ case 421: spellId = 45297; break; // Rank 1
+ case 930: spellId = 45298; break; // Rank 2
+ case 2860: spellId = 45299; break; // Rank 3
+ case 10605: spellId = 45300; break; // Rank 4
+ case 25439: spellId = 45301; break; // Rank 5
+ case 25442: spellId = 45302; break; // Rank 6
+ case 49270: spellId = 49268; break; // Rank 7
+ case 49271: spellId = 49269; break; // Rank 8
+ default:
+ sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (LO)", procSpell->Id);
+ return false;
+ }
+ // No thread generated mod
+ // TODO: exist special flag in spell attributes for this, need found and use!
+ SpellModifier *mod = new SpellModifier;
+ mod->op = SPELLMOD_THREAT;
+ mod->value = -100;
+ mod->type = SPELLMOD_PCT;
+ mod->spellId = dummySpell->Id;
+ mod->mask[0] = 0x02;
+ mod->mask[2] = 0x00;
+ ((Player*)this)->AddSpellMod(mod, true);
+
+ // Remove cooldown (Chain Lightning - have Category Recovery time)
+ if (procSpell->SpellFamilyFlags[0] & 0x2)
+ ((Player*)this)->RemoveSpellCooldown(spellId);
+
+ CastSpell(pVictim, spellId, true, castItem, triggeredByAura);
+
+ ((Player*)this)->AddSpellMod(mod, false);
+
+ if( cooldown && GetTypeId() == TYPEID_PLAYER )
+ ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
+
+ return true;
+ }
+ // Static Shock
+ if(dummySpell->SpellIconID == 3059)
+ {
+ // Lightning Shield
+ if (AuraEffect const * aurEff = GetAuraEffect(SPELL_AURA_PROC_TRIGGER_SPELL, SPELLFAMILY_SHAMAN, 0x400, 0, 0))
+ {
+ uint32 spell = spellmgr.GetSpellWithRank(26364, spellmgr.GetSpellRank(aurEff->GetId()));
+
+ // custom cooldown processing case
+ if (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(spell))
+ ((Player*)this)->RemoveSpellCooldown(spell);
+
+ CastSpell(target, spell, true, castItem, triggeredByAura);
+ aurEff->GetBase()->DropCharge();
+ return true;
+ }
+ return false;
+ }
+ break;
+ }
+ case SPELLFAMILY_DEATHKNIGHT:
+ {
+ // Blood-Caked Strike - Blood-Caked Blade
+ if (dummySpell->SpellIconID == 138)
+ {
+ if (!target || !target->isAlive())
+ return false;
+
+ triggered_spell_id = dummySpell->EffectTriggerSpell[effIndex];
+ break;
+ }
+ // Improved Blood Presence
+ if (dummySpell->SpellIconID == 2636)
+ {
+ if (GetTypeId() != TYPEID_PLAYER)
+ return false;
+ basepoints0 = triggerAmount * damage / 100;
+ break;
+ }
+ // Butchery
+ if (dummySpell->SpellIconID == 2664)
+ {
+ basepoints0 = triggerAmount;
+ triggered_spell_id = 50163;
+ target = this;
+ break;
+ }
+ // Dancing Rune Weapon
+ if (dummySpell->Id == 49028)
+ {
+ // 1 dummy aura for dismiss rune blade
+ if (effIndex!=2)
+ return false;
+ uint64 PetGUID = NULL;
+ for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr) //Find Rune Weapon
+ if ((*itr)->GetEntry() == 27893)
+ {
+ PetGUID = (*itr)->GetGUID();
+ break;
+ }
+
+ if (PetGUID && pVictim && damage && procSpell)
+ {
+ int32 procDmg = damage / 2;
+ CastCustomSpell(pVictim, procSpell->Id, &procDmg, NULL, NULL, true, NULL, NULL, PetGUID);
+ break;
+ }
+ else
+ return false;
+ }
+ // Mark of Blood
+ if (dummySpell->Id == 49005)
+ {
+ // TODO: need more info (cooldowns/PPM)
+ triggered_spell_id = 61607;
+ break;
+ }
+ // Unholy Blight
+ if (dummySpell->Id == 49194)
+ {
+ basepoints0 = triggerAmount * damage / 100;
+ // Glyph of Unholy Blight
+ if (AuraEffect *glyph=GetAuraEffect(63332,0))
+ basepoints0 += basepoints0 * glyph->GetAmount() / 100;
+ // Find replaced aura to use it's remaining amount
+ AuraEffectList const& DoTAuras = target->GetAuraEffectsByType(SPELL_AURA_PERIODIC_DAMAGE);
+ for (Unit::AuraEffectList::const_iterator i = DoTAuras.begin(); i != DoTAuras.end(); ++i)
+ {
+ if ((*i)->GetCasterGUID() != GetGUID() || (*i)->GetId() != 50536)
+ continue;
+ basepoints0 += ((*i)->GetAmount() * ((*i)->GetTotalTicks() - ((*i)->GetTickNumber()))) / (*i)->GetTotalTicks();
+ break;
+ }
+
+ triggered_spell_id = 50536;
+ break;
+ }
+ // Vendetta
+ if (dummySpell->SpellFamilyFlags[0] & 0x10000)
+ {
+ basepoints0 = triggerAmount * GetMaxHealth() / 100;
+ triggered_spell_id = 50181;
+ target = this;
+ break;
+ }
+ // Necrosis
+ if (dummySpell->SpellIconID == 2709)
+ {
+ basepoints0 = triggerAmount * damage / 100;
+ triggered_spell_id = 51460;
+ break;
+ }
+ // Threat of Thassarian
+ if (dummySpell->SpellIconID == 2023)
+ {
+ // Must Dual Wield
+ if (!procSpell || !haveOffhandWeapon())
+ return false;
+ // Chance as basepoints for dummy aura
+ if (!roll_chance_i(triggerAmount))
+ return false;
+
+ switch (procSpell->Id)
+ {
+ // Obliterate
+ case 49020: triggered_spell_id = 66198; break; // Rank 1
+ case 51423: triggered_spell_id = 66972; break; // Rank 2
+ case 51424: triggered_spell_id = 66973; break; // Rank 3
+ case 51425: triggered_spell_id = 66974; break; // Rank 4
+
+ // Frost Strike
+ case 49143: triggered_spell_id = 66196; break; // Rank 1
+ case 51416: triggered_spell_id = 66958; break; // Rank 2
+ case 51417: triggered_spell_id = 66959; break; // Rank 3
+ case 51418: triggered_spell_id = 66960; break; // Rank 4
+ case 51419: triggered_spell_id = 66961; break; // Rank 5
+ case 51420: triggered_spell_id = 66962; break; // Rank 6
+
+ // Plague Strike
+ case 45462: triggered_spell_id = 66216; break; // Rank 1
+ case 49917: triggered_spell_id = 66988; break; // Rank 2
+ case 49918: triggered_spell_id = 66989; break; // Rank 3
+ case 49919: triggered_spell_id = 66990; break; // Rank 4
+ case 49920: triggered_spell_id = 66991; break; // Rank 5
+ case 49921: triggered_spell_id = 66992; break; // Rank 6
+
+ // Death Strike
+ case 49998: triggered_spell_id = 66188; break; // Rank 1
+ case 49999: triggered_spell_id = 66950; break; // Rank 2
+ case 45463: triggered_spell_id = 66951; break; // Rank 3
+ case 49923: triggered_spell_id = 66952; break; // Rank 4
+ case 49924: triggered_spell_id = 66953; break; // Rank 5
+
+ // Rune Strike
+ case 56815: triggered_spell_id = 66217; break; // Rank 1
+
+ // Blood Strike
+ case 45902: triggered_spell_id = 66215; break; // Rank 1
+ case 49926: triggered_spell_id = 66975; break; // Rank 2
+ case 49927: triggered_spell_id = 66976; break; // Rank 3
+ case 49928: triggered_spell_id = 66977; break; // Rank 4
+ case 49929: triggered_spell_id = 66978; break; // Rank 5
+ case 49930: triggered_spell_id = 66979; break; // Rank 6
+ default:
+ return false;
+ }
+ break;
+ }
+ // Runic Power Back on Snare/Root
+ if (dummySpell->Id == 61257)
+ {
+ // only for spells and hit/crit (trigger start always) and not start from self casted spells
+ if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
+ return false;
+ // Need snare or root mechanic
+ if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_SNARE))))
+ return false;
+ triggered_spell_id = 61258;
+ target = this;
+ break;
+ }
+ // Wandering Plague
+ if (dummySpell->SpellIconID == 1614)
+ {
+ if (!roll_chance_f(GetUnitCriticalChance(BASE_ATTACK, pVictim)))
+ return false;
+ basepoints0 = triggerAmount * damage / 100;
+ triggered_spell_id = 50526;
+ break;
+ }
+ // Sudden Doom
+ if (dummySpell->SpellIconID == 1939 && GetTypeId() == TYPEID_PLAYER)
+ {
+ SpellChainNode const* chain = NULL;
+ // get highest rank of the Death Coil spell
+ const PlayerSpellMap& sp_list = ((Player*)this)->GetSpellMap();
+ for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
+ {
+ // check if shown in spell book
+ if(!itr->second->active || itr->second->disabled || itr->second->state == PLAYERSPELL_REMOVED)
+ continue;
+
+ SpellEntry const *spellProto = sSpellStore.LookupEntry(itr->first);
+ if (!spellProto)
+ continue;
+
+ if (spellProto->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT
+ && spellProto->SpellFamilyFlags[0] & 0x2000)
+ {
+ SpellChainNode const* newChain = spellmgr.GetSpellChainNode(itr->first);
+
+ // No chain entry or entry lower than found entry
+ if (!chain || !newChain || (chain->rank < newChain->rank))
+ {
+ triggered_spell_id = itr->first;
+ chain = newChain;
+ }
+ else
+ continue;
+ // Found spell is last in chain - do not need to look more
+ // Optimisation for most common case
+ if (chain && chain->last == itr->first)
+ break;
+ }
+ }
+ }
+ break;
+ }
+ case SPELLFAMILY_POTION:
+ {
+ // alchemist's stone
+ if (dummySpell->Id == 17619)
+ {
+ if (procSpell->SpellFamilyName == SPELLFAMILY_POTION)
+ {
+ for (uint8 i=0; i<MAX_SPELL_EFFECTS; i++)
+ {
+ if (procSpell->Effect[i]==SPELL_EFFECT_HEAL)
+ {
+ triggered_spell_id = 21399;
+ }
+ else if (procSpell->Effect[i]==SPELL_EFFECT_ENERGIZE)
+ {
+ triggered_spell_id = 21400;
+ }
+ else
+ continue;
+
+ basepoints0 = CalculateSpellDamage(procSpell,i,procSpell->EffectBasePoints[i],this) * 0.4f;
+ CastCustomSpell(this,triggered_spell_id,&basepoints0,NULL,NULL,true,NULL,triggeredByAura);
+ }
+ return true;
+ }
+ }
+ break;
+ }
+ case SPELLFAMILY_PET:
+ {
+ // improved cower
+ if (dummySpell->SpellIconID == 958 && procSpell->SpellIconID == 958)
+ {
+ triggered_spell_id = dummySpell->Id == 53180 ? 54200 : 54201;
+ target = this;
+ break;
+ }
+ // guard dog
+ if (dummySpell->SpellIconID == 201 && procSpell->SpellIconID == 201)
+ {
+ triggered_spell_id = 54445;
+ target = this;
+ pVictim->AddThreat(this,procSpell->EffectBasePoints[0]*triggerAmount/100.0f);
+ break;
+ }
+ break;
+ }
+ default:
+ break;
+ }
+
+ // processed charge only counting case
+ if(!triggered_spell_id)
+ return true;
+
+ SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
+
+ if(!triggerEntry)
+ {
+ sLog.outError("Unit::HandleDummyAuraProc: Spell %u have not existed triggered spell %u",dummySpell->Id,triggered_spell_id);
+ return false;
+ }
+
+ // default case
+ if((!target && !spellmgr.IsSrcTargetSpell(triggerEntry)) || (target && target!=this && !target->isAlive()))
+ return false;
+
+ if( cooldown && GetTypeId() == TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
+ return false;
+
+ if(basepoints0)
+ CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura, originalCaster);
+ else
+ CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura, originalCaster);
+
+ if( cooldown && GetTypeId() == TYPEID_PLAYER )
+ ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
+
+ return true;
+}
+bool Unit::HandleObsModEnergyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
+{
+ SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
+ uint32 effIndex = triggeredByAura->GetEffIndex();
+ int32 triggerAmount = triggeredByAura->GetAmount();
+
+ Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
+ ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
+
+ uint32 triggered_spell_id = 0;
+ Unit* target = pVictim;
+ int32 basepoints0 = 0;
+
+ switch(dummySpell->SpellFamilyName)
+ {
+ case SPELLFAMILY_HUNTER:
+ {
+ // Aspect of the Viper
+ if ( dummySpell->SpellFamilyFlags[1] & 0x40000 )
+ {
+ uint32 maxmana = GetMaxPower(POWER_MANA);
+ basepoints0 = maxmana* GetAttackTime(RANGED_ATTACK)/1000.0f/100.0f;
+ target = this;
+ triggered_spell_id = 34075;
+ break;
+ }
+ break;
+ }
+ }
+ // processed charge only counting case
+ if(!triggered_spell_id)
+ return true;
+
+ SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
+
+ // Try handle unknown trigger spells
+ if(!triggerEntry)
+ {
+ sLog.outError("Unit::HandleObsModEnergyAuraProc: Spell %u have not existed triggered spell %u",dummySpell->Id,triggered_spell_id);
+ return false;
+ }
+
+ // default case
+ if((!target && !spellmgr.IsSrcTargetSpell(triggerEntry)) || (target && target!=this && !target->isAlive()))
+ return false;
+
+ if( cooldown && GetTypeId() == TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
+ return false;
+ if(basepoints0)
+ CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
+ else
+ CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
+
+ if( cooldown && GetTypeId() == TYPEID_PLAYER )
+ ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
+ return true;
+}
+bool Unit::HandleModDamagePctTakenAuraProc(Unit *pVictim, uint32 damage, AuraEffect* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
+{
+ SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
+ uint32 effIndex = triggeredByAura->GetEffIndex();
+ int32 triggerAmount = triggeredByAura->GetAmount();
+
+ Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
+ ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
+
+ uint32 triggered_spell_id = 0;
+ Unit* target = pVictim;
+ int32 basepoints0 = 0;
+
+ switch(dummySpell->SpellFamilyName)
+ {
+ case SPELLFAMILY_PALADIN:
+ {
+ // Blessing of Sanctuary
+ if ( dummySpell->SpellFamilyFlags[0] & 0x10000000 )
+ {
+ switch (getPowerType())
+ {
+ case POWER_MANA: triggered_spell_id = 57319; break;
+ default:
+ return false;
+ }
+ }
+ break;
+ }
+ }
+ // processed charge only counting case
+ if(!triggered_spell_id)
+ return true;
+
+ SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
+
+ if(!triggerEntry)
+ {
+ sLog.outError("Unit::HandleModDamagePctTakenAuraProc: Spell %u have not existed triggered spell %u",dummySpell->Id,triggered_spell_id);
+ return false;
+ }
+
+ // default case
+ if((!target && !spellmgr.IsSrcTargetSpell(triggerEntry)) || (target && target!=this && !target->isAlive()))
+ return false;
+
+ if( cooldown && GetTypeId() == TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
+ return false;
+
+ if(basepoints0)
+ CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
+ else
+ CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
+
+ if( cooldown && GetTypeId() == TYPEID_PLAYER )
+ ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
+
+ return true;
+}
+
+// Used in case when access to whole aura is needed
+// All procs should be handled like this...
+bool Unit::HandleAuraProc(Unit *pVictim, uint32 damage, Aura * triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown, bool * handled)
+{
+ SpellEntry const *dummySpell = triggeredByAura->GetSpellProto();
+
+ switch(dummySpell->SpellFamilyName)
+ {
+ case SPELLFAMILY_MAGE:
+ {
+ // Combustion
+ switch (dummySpell->Id)
+ {
+ case 11129:
+ {
+ *handled = true;
+ Unit *caster = triggeredByAura->GetCaster();
+ if (!caster || !damage)
+ return false;
+
+ //last charge and crit
+ if (triggeredByAura->GetCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT) )
+ {
+ RemoveAurasDueToSpell(28682); //-> remove Combustion auras
+ return true; // charge counting (will removed)
+ }
+
+ this->CastSpell(this, 28682, true);
+ return false; // ordinary chrages will be removed during crit chance computations.
+ }
+ // Empowered Fire
+ case 31656:
+ case 31657:
+ case 31658:
+ {
+ *handled = true;
+
+ SpellEntry const *spInfo = sSpellStore.LookupEntry(67545);
+ if (!spInfo)
+ return false;
+
+ int32 bp0 = this->GetCreateMana() * spInfo->CalculateSimpleValue(0) / 100;
+ this->CastCustomSpell(this, 67545, &bp0, NULL, NULL, true, NULL, triggeredByAura->GetEffect(0), this->GetGUID());
+ return true;
+ }
+ }
+ break;
+ }
+ case SPELLFAMILY_DEATHKNIGHT:
+ {
+ // Blood of the North
+ // Reaping
+ // Death Rune Mastery
+ if (dummySpell->SpellIconID == 3041 || dummySpell->SpellIconID == 22 || dummySpell->SpellIconID == 2622)
+ {
+ *handled = true;
+ // Convert recently used Blood Rune to Death Rune
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ if(((Player*)this)->getClass() != CLASS_DEATH_KNIGHT)
+ return false;
+ RuneType rune = ((Player*)this)->GetLastUsedRune();
+ // can't proc from death rune use
+ if (rune == RUNE_DEATH)
+ return false;
+ AuraEffect * aurEff = triggeredByAura->GetEffect(0);
+ if (!aurEff)
+ return false;
+ // Reset amplitude - set death rune remove timer to 30s
+ aurEff->ResetPeriodic();
+ uint32 runesLeft;
+
+ if (dummySpell->SpellIconID == 2622)
+ runesLeft = 2;
+ else
+ runesLeft = 1;
+
+ for (uint8 i=0; i < MAX_RUNES && runesLeft; ++i)
+ {
+ if (dummySpell->SpellIconID == 2622)
+ {
+ if (((Player*)this)->GetCurrentRune(i) == RUNE_DEATH ||
+ ((Player*)this)->GetBaseRune(i) == RUNE_BLOOD )
+ continue;
+ }
+ else
+ {
+ if (((Player*)this)->GetCurrentRune(i) == RUNE_DEATH ||
+ ((Player*)this)->GetBaseRune(i) != RUNE_BLOOD )
+ continue;
+ }
+ if (((Player*)this)->GetRuneCooldown(i) != ((Player*)this)->GetRuneBaseCooldown(i))
+ continue;
+
+ --runesLeft;
+ // Mark aura as used
+ ((Player*)this)->AddRuneByAuraEffect(i, RUNE_DEATH, aurEff);
+ }
+ return true;
+ }
+ return false;
+ }
+
+ switch(dummySpell->Id)
+ {
+ // Hungering Cold aura drop
+ case 51209:
+ *handled = true;
+ // Drop only in not disease case
+ if (procSpell && procSpell->Dispel == DISPEL_DISEASE)
+ return false;
+ return true;
+ }
+ break;
+ }
+ }
+ return false;
+}
+
+bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, AuraEffect* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown)
+{
+ // Get triggered aura spell info
+ SpellEntry const* auraSpellInfo = triggeredByAura->GetSpellProto();
+
+ // Basepoints of trigger aura
+ int32 triggerAmount = triggeredByAura->GetAmount();
+
+ // Set trigger spell id, target, custom basepoints
+ uint32 trigger_spell_id = auraSpellInfo->EffectTriggerSpell[triggeredByAura->GetEffIndex()];
+
+ Unit* target = NULL;
+ int32 basepoints0 = 0;
+
+ if(triggeredByAura->GetAuraType() == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE)
+ basepoints0 = triggerAmount;
+
+ Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
+ ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
+
+ // Try handle unknown trigger spells
+ if (sSpellStore.LookupEntry(trigger_spell_id) == NULL)
+ {
+ switch (auraSpellInfo->SpellFamilyName)
+ {
+ case SPELLFAMILY_GENERIC:
+ switch (auraSpellInfo->Id)
+ {
+ case 23780: // Aegis of Preservation (Aegis of Preservation trinket)
+ trigger_spell_id = 23781;
+ break;
+ case 33896: // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher)
+ trigger_spell_id = 33898;
+ break;
+ case 43820: // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket)
+ // Pct value stored in dummy
+ basepoints0 = pVictim->GetCreateHealth() * auraSpellInfo->EffectBasePoints[1] / 100;
+ target = pVictim;
+ break;
+ case 57345: // Darkmoon Card: Greatness
+ {
+ float stat = 0.0f;
+ // strength
+ if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); }
+ // agility
+ if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); }
+ // intellect
+ if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);}
+ // spirit
+ if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235; }
+ break;
+ }
+ case 67702: // Death's Choice, Item - Coliseum 25 Normal Melee Trinket
+ {
+ float stat = 0.0f;
+ // strength
+ if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67708;stat = GetStat(STAT_STRENGTH); }
+ // agility
+ if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67703; }
+ break;
+ }
+ case 67771: // Death's Choice (heroic), Item - Coliseum 25 Heroic Melee Trinket
+ {
+ float stat = 0.0f;
+ // strength
+ if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67773;stat = GetStat(STAT_STRENGTH); }
+ // agility
+ if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67772; }
+ break;
+ }
+ // Mana Drain Trigger
+ case 27522:
+ case 40336:
+ {
+ // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target.
+ if (this && this->isAlive())
+ CastSpell(this, 29471, true, castItem, triggeredByAura);
+ if (pVictim && pVictim->isAlive())
+ CastSpell(pVictim, 27526, true, castItem, triggeredByAura);
+ return true;
+ }
+ }
+ break;
+ case SPELLFAMILY_MAGE:
+ if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed
+ {
+ switch (auraSpellInfo->Id)
+ {
+ case 31641: // Rank 1
+ case 31642: // Rank 2
+ trigger_spell_id = 31643;
+ break;
+ default:
+ sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blazing Speed",auraSpellInfo->Id);
+ return false;
+ }
+ }
+ break;
+ case SPELLFAMILY_WARRIOR:
+ if (auraSpellInfo->Id == 50421) // Scent of Blood
+ trigger_spell_id = 50422;
+ break;
+ case SPELLFAMILY_WARLOCK:
+ {
+ // Drain Soul
+ if (auraSpellInfo->SpellFamilyFlags[0] & 0x4000)
+ {
+ // Improved Drain Soul
+ Unit::AuraEffectList const& mAddFlatModifier = GetAuraEffectsByType(SPELL_AURA_DUMMY);
+ for (Unit::AuraEffectList::const_iterator i = mAddFlatModifier.begin(); i != mAddFlatModifier.end(); ++i)
+ {
+ if ((*i)->GetMiscValue() == SPELLMOD_CHANCE_OF_SUCCESS && (*i)->GetSpellProto()->SpellIconID == 113)
+ {
+ int32 value2 = CalculateSpellDamage((*i)->GetSpellProto(),2,(*i)->GetSpellProto()->EffectBasePoints[2],this);
+ basepoints0 = value2 * GetMaxPower(POWER_MANA) / 100;
+ // Drain Soul
+ CastCustomSpell(this, 18371, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
+ break;
+ }
+ }
+ // Not remove charge (aura removed on death in any cases)
+ // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura
+ return false;
+ }
+ // Nether Protection
+ else if (auraSpellInfo->SpellIconID == 1985)
+ {
+ if (!procSpell)
+ return false;
+ switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
+ {
+ case SPELL_SCHOOL_NORMAL:
+ return false; // ignore
+ case SPELL_SCHOOL_HOLY: trigger_spell_id = 54370; break;
+ case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break;
+ case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break;
+ case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break;
+ case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break;
+ case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
+ default:
+ return false;
+ }
+ }
+ break;
+ }
+ case SPELLFAMILY_PRIEST:
+ {
+ // Greater Heal Refund
+ if (auraSpellInfo->Id==37594)
+ trigger_spell_id = 37595;
+ // Blessed Recovery
+ else if (auraSpellInfo->SpellIconID == 1875)
+ {
+ switch (auraSpellInfo->Id)
+ {
+ case 27811: trigger_spell_id = 27813; break;
+ case 27815: trigger_spell_id = 27817; break;
+ case 27816: trigger_spell_id = 27818; break;
+ default:
+ sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id);
+ return false;
+ }
+ basepoints0 = damage * triggerAmount / 100 / 3;
+ target = this;
+ }
+ break;
+ }
+ case SPELLFAMILY_DRUID:
+ {
+ // Druid Forms Trinket
+ if (auraSpellInfo->Id==37336)
+ {
+ switch(m_form)
+ {
+ case FORM_NONE: trigger_spell_id = 37344;break;
+ case FORM_CAT: trigger_spell_id = 37341;break;
+ case FORM_BEAR:
+ case FORM_DIREBEAR: trigger_spell_id = 37340;break;
+ case FORM_TREE: trigger_spell_id = 37342;break;
+ case FORM_MOONKIN: trigger_spell_id = 37343;break;
+ default:
+ return false;
+ }
+ }
+ // Druid T9 Feral Relic (Lacerate, Swipe, Mangle, and Shred)
+ else if (auraSpellInfo->Id==67353)
+ {
+ switch(m_form)
+ {
+ case FORM_CAT: trigger_spell_id = 67355; break;
+ case FORM_BEAR:
+ case FORM_DIREBEAR: trigger_spell_id = 67354; break;
+ default:
+ return false;
+ }
+ }
+ break;
+ }
+ case SPELLFAMILY_HUNTER:
+ {
+ if (auraSpellInfo->SpellIconID == 3247) // Piercing Shots
+ {
+ switch (auraSpellInfo->Id)
+ {
+ case 53234: // Rank 1
+ case 53237: // Rank 2
+ case 53238: // Rank 3
+ trigger_spell_id = 63468;
+ break;
+ default:
+ sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Piercing Shots",auraSpellInfo->Id);
+ return false;
+ }
+ SpellEntry const *TriggerPS = sSpellStore.LookupEntry(trigger_spell_id);
+ if(!TriggerPS)
+ return false;
+ basepoints0 = int32(damage * triggerAmount / 100 / (GetSpellMaxDuration(TriggerPS) / TriggerPS->EffectAmplitude[0]));
+ target = pVictim;
+ }
+ break;
+ }
+ case SPELLFAMILY_PALADIN:
+ {
+ switch (auraSpellInfo->Id)
+ {
+ // Healing Discount
+ case 37705:
+ {
+ trigger_spell_id = 37706;
+ target = this;
+ break;
+ }
+ // Soul Preserver
+ case 60510:
+ {
+ trigger_spell_id = 60515;
+ target = this;
+ break;
+ }
+ // Lightning Capacitor
+ case 37657:
+ {
+ if(!pVictim || !pVictim->isAlive())
+ return false;
+ // stacking
+ CastSpell(this, 37658, true, NULL, triggeredByAura);
+
+ Aura * dummy = GetAura(37658);
+ // release at 3 aura in stack (cont contain in basepoint of trigger aura)
+ if(!dummy || dummy->GetStackAmount() < triggerAmount)
+ return false;
+
+ RemoveAurasDueToSpell(37658);
+ trigger_spell_id = 37661;
+ target = pVictim;
+ break;
+ }
+ // Thunder Capacitor
+ case 54841:
+ {
+ if(!pVictim || !pVictim->isAlive())
+ return false;
+ // stacking
+ CastSpell(this, 54842, true, NULL, triggeredByAura);
+
+ // counting
+ Aura * dummy = GetAura(54842);
+ // release at 3 aura in stack (cont contain in basepoint of trigger aura)
+ if(!dummy || dummy->GetStackAmount() < triggerAmount)
+ return false;
+
+ RemoveAurasDueToSpell(54842);
+ trigger_spell_id = 54843;
+ target = pVictim;
+ break;
+ }
+ default:
+ // Illumination
+ if (auraSpellInfo->SpellIconID==241)
+ {
+ if(!procSpell)
+ return false;
+ // procspell is triggered spell but we need mana cost of original casted spell
+ uint32 originalSpellId = procSpell->Id;
+ // Holy Shock heal
+ if(procSpell->SpellFamilyFlags[1] & 0x00010000)
+ {
+ switch(procSpell->Id)
+ {
+ case 25914: originalSpellId = 20473; break;
+ case 25913: originalSpellId = 20929; break;
+ case 25903: originalSpellId = 20930; break;
+ case 27175: originalSpellId = 27174; break;
+ case 33074: originalSpellId = 33072; break;
+ case 48820: originalSpellId = 48824; break;
+ case 48821: originalSpellId = 48825; break;
+ default:
+ sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in HShock",procSpell->Id);
+ return false;
+ }
+ }
+ SpellEntry const *originalSpell = sSpellStore.LookupEntry(originalSpellId);
+ if(!originalSpell)
+ {
+ sLog.outError("Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu",originalSpellId);
+ return false;
+ }
+ // percent stored in effect 1 (class scripts) base points
+ int32 cost = originalSpell->manaCost + originalSpell->ManaCostPercentage * GetCreateMana() / 100;
+ basepoints0 = cost*auraSpellInfo->CalculateSimpleValue(1)/100;
+ trigger_spell_id = 20272;
+ target = this;
+ }
+ break;
+ }
+ break;
+ }
+ case SPELLFAMILY_SHAMAN:
+ {
+ switch (auraSpellInfo->Id)
+ {
+ // Lightning Shield (The Ten Storms set)
+ case 23551:
+ {
+ trigger_spell_id = 23552;
+ target = pVictim;
+ break;
+ }
+ // Damage from Lightning Shield (The Ten Storms set)
+ case 23552:
+ {
+ trigger_spell_id = 27635;
+ break;
+ }
+ // Mana Surge (The Earthfury set)
+ case 23572:
+ {
+ if(!procSpell)
+ return false;
+ basepoints0 = procSpell->manaCost * 35 / 100;
+ trigger_spell_id = 23571;
+ target = this;
+ break;
+ }
+ default:
+ {
+ // Lightning Shield (overwrite non existing triggered spell call in spell.dbc
+ if(auraSpellInfo->SpellFamilyFlags[0] & 0x400)
+ {
+ trigger_spell_id = spellmgr.GetSpellWithRank(26364, spellmgr.GetSpellRank(auraSpellInfo->Id));
+ }
+ // Nature's Guardian
+ else if (auraSpellInfo->SpellIconID == 2013)
+ {
+ // Check health condition - should drop to less 30% (damage deal after this!)
+ if (!(10*(int32(GetHealth() - damage)) < 3 * GetMaxHealth()))
+ return false;
+
+ if(pVictim && pVictim->isAlive())
+ pVictim->getThreatManager().modifyThreatPercent(this,-10);
+
+ basepoints0 = triggerAmount * GetMaxHealth() / 100;
+ trigger_spell_id = 31616;
+ target = this;
+ }
+ }
+ }
+ break;
+ }
+ case SPELLFAMILY_DEATHKNIGHT:
+ {
+ // Acclimation
+ if (auraSpellInfo->SpellIconID == 1930)
+ {
+ if (!procSpell)
+ return false;
+ switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
+ {
+ case SPELL_SCHOOL_NORMAL:
+ return false; // ignore
+ case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break;
+ case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break;
+ case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break;
+ case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break;
+ case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break;
+ case SPELL_SCHOOL_ARCANE: trigger_spell_id = 50486; break;
+ default:
+ return false;
+ }
+ }
+ // Blood Presence (Improved)
+ else if (auraSpellInfo->Id == 63611)
+ {
+ if (GetTypeId() != TYPEID_PLAYER)
+ return false;
+
+ trigger_spell_id = 50475;
+ basepoints0 = damage * triggerAmount / 100;
+ }
+ break;
+ }
+ default:
+ break;
+ }
+ }
+
+ // All ok. Check current trigger spell
+ SpellEntry const* triggerEntry = sSpellStore.LookupEntry(trigger_spell_id);
+ if ( triggerEntry == NULL )
+ {
+ // Not cast unknown spell
+ // sLog.outError("Unit::HandleProcTriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?",auraSpellInfo->Id,triggeredByAura->GetEffIndex());
+ return false;
+ }
+
+ // not allow proc extra attack spell at extra attack
+ if( m_extraAttacks && IsSpellHaveEffect(triggerEntry, SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
+ return false;
+
+ // Custom requirements (not listed in procEx) Warning! damage dealing after this
+ // Custom triggered spells
+ switch (auraSpellInfo->Id)
+ {
+ // Persistent Shield (Scarab Brooch trinket)
+ // This spell originally trigger 13567 - Dummy Trigger (vs dummy efect)
+ case 26467:
+ {
+ basepoints0 = damage * 15 / 100;
+ target = pVictim;
+ trigger_spell_id = 26470;
+ break;
+ }
+ // Unyielding Knights (item exploit 29108\29109)
+ case 38164:
+ {
+ if(pVictim->GetEntry() != 19457) // Proc only if you target is Grillok
+ return false;
+ break;
+ }
+ // Deflection
+ case 52420:
+ {
+ if(GetHealth()*100 / GetMaxHealth() >= 35)
+ return false;
+ break;
+ }
+
+ // Cheat Death
+ case 28845:
+ {
+ // When your health drops below 20%
+ if (GetHealth() - damage > GetMaxHealth() / 5 || GetHealth() < GetMaxHealth() / 5)
+ return false;
+ break;
+ }
+ // Deadly Swiftness (Rank 1)
+ case 31255:
+ {
+ // whenever you deal damage to a target who is below 20% health.
+ if (!pVictim || !pVictim->isAlive() || (pVictim->GetHealth() > pVictim->GetMaxHealth() / 5))
+ return false;
+
+ target = this;
+ trigger_spell_id = 22588;
+ }
+ // Greater Heal Refund (Avatar Raiment set)
+ case 37594:
+ {
+ if (!pVictim || !pVictim->isAlive())
+ return false;
+
+ // Not give if target already have full health
+ if (pVictim->GetHealth() == pVictim->GetMaxHealth())
+ return false;
+ // If your Greater Heal brings the target to full health, you gain $37595s1 mana.
+ if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
+ return false;
+ break;
+ }
+ // Bonus Healing (Crystal Spire of Karabor mace)
+ case 40971:
+ {
+ // If your target is below $s1% health
+ if (!pVictim || !pVictim->isAlive() || (pVictim->GetHealth() > pVictim->GetMaxHealth() * triggerAmount / 100))
+ return false;
+ break;
+ }
+ // Evasive Maneuvers (Commendation of Kael`thas trinket)
+ case 45057:
+ {
+ // reduce you below $s1% health
+ if (GetHealth() - damage > GetMaxHealth() * triggerAmount / 100)
+ return false;
+ break;
+ }
+ // Rapid Recuperation
+ case 53228:
+ case 53232:
+ {
+ // This effect only from Rapid Fire (ability cast)
+ if (!(procSpell->SpellFamilyFlags[0] & 0x20))
+ return false;
+ break;
+ }
+ // Blessing of Ancient Kings (Val'anyr, Hammer of Ancient Kings)
+ case 64411:
+ {
+ basepoints0 = damage * 15 / 100;
+ target = pVictim;
+ trigger_spell_id = 26470;
+ break;
+ }
+ // Decimation
+ case 63156:
+ case 63158:
+ // Can proc only if target has hp below 35%
+ if(!pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, procSpell, this))
+ return false;
+ break;
+ }
+
+ // Blade Barrier
+ if (auraSpellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && auraSpellInfo->SpellIconID == 85)
+ {
+ if (this->GetTypeId() != TYPEID_PLAYER || !((Player*)this)->IsBaseRuneSlotsOnCooldown(RUNE_BLOOD))
+ return false;
+ }
+
+ // Rime
+ else if (auraSpellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && auraSpellInfo->SpellIconID == 56)
+ {
+ if (GetTypeId() != TYPEID_PLAYER)
+ return false;
+
+ // Howling Blast
+ ((Player*)this)->RemoveSpellCategoryCooldown(1248, true);
+ }
+
+ // Custom basepoints/target for exist spell
+ // dummy basepoints or other customs
+ switch(trigger_spell_id)
+ {
+ // Auras which should proc on area aura source (caster in this case):
+ // Turn the Tables
+ case 52914:
+ case 52915:
+ case 52910:
+ // Honor Among Thieves
+ case 52916:
+ {
+ target = triggeredByAura->GetBase()->GetCaster();
+ if(!target)
+ return false;
+
+ if( cooldown && GetTypeId() == TYPEID_PLAYER && ((Player*)target)->HasSpellCooldown(trigger_spell_id))
+ return false;
+
+ target->CastSpell(target,trigger_spell_id,true,castItem,triggeredByAura);
+
+ if( cooldown && GetTypeId() == TYPEID_PLAYER )
+ ((Player*)this)->AddSpellCooldown(trigger_spell_id,0,time(NULL) + cooldown);
+ return true;
+ }
+ // Cast positive spell on enemy target
+ case 7099: // Curse of Mending
+ case 39647: // Curse of Mending
+ case 29494: // Temptation
+ case 20233: // Improved Lay on Hands (cast on target)
+ {
+ target = pVictim;
+ break;
+ }
+ // Combo points add triggers (need add combopoint only for main target, and after possible combopoints reset)
+ case 15250: // Rogue Setup
+ {
+ if(!pVictim || pVictim != getVictim()) // applied only for main target
+ return false;
+ break; // continue normal case
+ }
+ // Finish movies that add combo
+ case 14189: // Seal Fate (Netherblade set)
+ case 14157: // Ruthlessness
+ {
+ if (!pVictim || pVictim == this)
+ return false;
+ // Need add combopoint AFTER finish movie (or they dropped in finish phase)
+ break;
+ }
+ // Bloodthirst (($m/100)% of max health)
+ case 23880:
+ {
+ basepoints0 = int32(GetMaxHealth() * triggerAmount / 100);
+ break;
+ }
+ // Shamanistic Rage triggered spell
+ case 30824:
+ {
+ basepoints0 = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
+ break;
+ }
+ // Enlightenment (trigger only from mana cost spells)
+ case 35095:
+ {
+ if(!procSpell || procSpell->powerType!=POWER_MANA || procSpell->manaCost==0 && procSpell->ManaCostPercentage==0 && procSpell->manaCostPerlevel==0)
+ return false;
+ break;
+ }
+ // Demonic Pact
+ case 48090:
+ {
+ // Get talent aura from owner
+ if (isPet())
+ if (Unit * owner = GetOwner())
+ {
+ if (AuraEffect * aurEff = owner->GetDummyAuraEffect(SPELLFAMILY_WARLOCK, 3220, 0))
+ {
+ basepoints0 = int32((aurEff->GetAmount() * owner->SpellBaseDamageBonus(SpellSchoolMask(SPELL_SCHOOL_MASK_MAGIC)) + 100.0f) / 100.0f);
+ CastCustomSpell(this,trigger_spell_id,&basepoints0,&basepoints0,NULL,true,castItem,triggeredByAura);
+ return true;
+ }
+ }
+ break;
+ }
+ // Sword and Board
+ case 50227:
+ {
+ // Remove cooldown on Shield Slam
+ if (GetTypeId() == TYPEID_PLAYER)
+ ((Player*)this)->RemoveSpellCategoryCooldown(1209, true);
+ break;
+ }
+ // Maelstrom Weapon
+ case 53817:
+ {
+ // have rank dependent proc chance, ignore too often cases
+ // PPM = 2.5 * (rank of talent),
+ uint32 rank = spellmgr.GetSpellRank(auraSpellInfo->Id);
+ // 5 rank -> 100% 4 rank -> 80% and etc from full rate
+ if(!roll_chance_i(20*rank))
+ return false;
+ break;
+ }
+ // Astral Shift
+ case 52179:
+ {
+ if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
+ return false;
+
+ // Need stun, fear or silence mechanic
+ if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_SILENCE)|(1<<MECHANIC_STUN)|(1<<MECHANIC_FEAR))))
+ return false;
+ break;
+ }
+ // Burning Determination
+ case 54748:
+ {
+ if(!procSpell)
+ return false;
+ // Need Interrupt or Silenced mechanic
+ if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_INTERRUPT)|(1<<MECHANIC_SILENCE))))
+ return false;
+ break;
+ }
+ // Lock and Load
+ case 56453:
+ {
+ // Proc only from Frost/Freezing trap activation or from Freezing Arrow (the periodic dmg proc handled elsewhere)
+ if (!(procFlags & PROC_FLAG_ON_TRAP_ACTIVATION) || !procSpell || !(procSpell->SchoolMask & SPELL_SCHOOL_MASK_FROST) || !roll_chance_i(triggerAmount))
+ return false;
+ break;
+ }
+ // Glyph of Death's Embrace
+ case 58679:
+ {
+ // Proc only from healing part of Death Coil. Check is essential as all Death Coil spells have 0x2000 mask in SpellFamilyFlags
+ if (!procSpell || !(procSpell->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && procSpell->SpellFamilyFlags[0] == 0x80002000))
+ return false;
+ break;
+ }
+ // Glyph of Death Grip
+ case 58628:
+ {
+ // remove cooldown of Death Grip
+ if (GetTypeId() == TYPEID_PLAYER)
+ ((Player*)this)->RemoveCategoryCooldown(82);
+ return true;
+ }
+ // Savage Defense
+ case 62606:
+ {
+ basepoints0 = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100.0f);
+ break;
+ }
+ // Body and Soul
+ case 64128:
+ case 65081:
+ {
+ // Proc only from PW:S cast
+ if (!(procSpell->SpellFamilyFlags[0] & 0x00000001))
+ return false;
+ break;
+ }
+ }
+
+ if( cooldown && GetTypeId() == TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(trigger_spell_id))
+ return false;
+
+ // try detect target manually if not set
+ if ( target == NULL )
+ target = !(procFlags & (PROC_FLAG_SUCCESSFUL_POSITIVE_MAGIC_SPELL | PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL_HIT)) && IsPositiveSpell(trigger_spell_id) ? this : pVictim;
+
+ // default case
+ if((!target && !spellmgr.IsSrcTargetSpell(triggerEntry)) || (target && target!=this && !target->isAlive()))
+ return false;
+
+ if(basepoints0)
+ CastCustomSpell(target,trigger_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
+ else
+ CastSpell(target,trigger_spell_id,true,castItem,triggeredByAura);
+
+ if( cooldown && GetTypeId() == TYPEID_PLAYER )
+ ((Player*)this)->AddSpellCooldown(trigger_spell_id,0,time(NULL) + cooldown);
+
+ return true;
+}
+
+bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, uint32 damage, AuraEffect *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown)
+{
+ int32 scriptId = triggeredByAura->GetMiscValue();
+
+ if(!pVictim || !pVictim->isAlive())
+ return false;
+
+ Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
+ ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
+
+ uint32 triggered_spell_id = 0;
+
+ switch(scriptId)
+ {
+ case 836: // Improved Blizzard (Rank 1)
+ {
+ if (!procSpell || procSpell->SpellVisual[0]!=9487)
+ return false;
+ triggered_spell_id = 12484;
+ break;
+ }
+ case 988: // Improved Blizzard (Rank 2)
+ {
+ if (!procSpell || procSpell->SpellVisual[0]!=9487)
+ return false;
+ triggered_spell_id = 12485;
+ break;
+ }
+ case 989: // Improved Blizzard (Rank 3)
+ {
+ if (!procSpell || procSpell->SpellVisual[0]!=9487)
+ return false;
+ triggered_spell_id = 12486;
+ break;
+ }
+ case 4533: // Dreamwalker Raiment 2 pieces bonus
+ {
+ // Chance 50%
+ if (!roll_chance_i(50))
+ return false;
+
+ switch (pVictim->getPowerType())
+ {
+ case POWER_MANA: triggered_spell_id = 28722; break;
+ case POWER_RAGE: triggered_spell_id = 28723; break;
+ case POWER_ENERGY: triggered_spell_id = 28724; break;
+ default:
+ return false;
+ }
+ break;
+ }
+ case 4537: // Dreamwalker Raiment 6 pieces bonus
+ triggered_spell_id = 28750; // Blessing of the Claw
+ break;
+ case 5497: // Improved Mana Gems
+ triggered_spell_id = 37445; // Mana Surge
+ break;
+ case 7010: // Revitalize - can proc on full hp target
+ case 7011:
+ case 7012:
+ {
+ if (!roll_chance_i(triggeredByAura->GetAmount()))
+ return false;
+ switch(pVictim->getPowerType())
+ {
+ case POWER_MANA: triggered_spell_id = 48542; break;
+ case POWER_RAGE: triggered_spell_id = 48541; break;
+ case POWER_ENERGY: triggered_spell_id = 48540; break;
+ case POWER_RUNIC_POWER: triggered_spell_id = 48543; break;
+ }
+ break;
+ }
+ }
+
+ // not processed
+ if(!triggered_spell_id)
+ return false;
+
+ // standard non-dummy case
+ SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
+
+ if(!triggerEntry)
+ {
+ sLog.outError("Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u",triggered_spell_id,scriptId);
+ return false;
+ }
+
+ if( cooldown && GetTypeId() == TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
+ return false;
+
+ CastSpell(pVictim, triggered_spell_id, true, castItem, triggeredByAura);
+
+ if( cooldown && GetTypeId() == TYPEID_PLAYER )
+ ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
+
+ return true;
+}
+
+void Unit::setPowerType(Powers new_powertype)
+{
+ SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype);
+
+ if(GetTypeId() == TYPEID_PLAYER)
+ {
+ if(((Player*)this)->GetGroup())
+ ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE);
+ }
+ else if(((Creature*)this)->isPet())
+ {
+ Pet *pet = ((Pet*)this);
+ if(pet->isControlled())
+ {
+ Unit *owner = GetOwner();
+ if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
+ ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE);
+ }
+ }
+
+ switch(new_powertype)
+ {
+ default:
+ case POWER_MANA:
+ break;
+ case POWER_RAGE:
+ SetMaxPower(POWER_RAGE, GetCreatePowers(POWER_RAGE));
+ SetPower(POWER_RAGE, 0);
+ break;
+ case POWER_FOCUS:
+ SetMaxPower(POWER_FOCUS, GetCreatePowers(POWER_FOCUS));
+ SetPower(POWER_FOCUS, GetCreatePowers(POWER_FOCUS));
+ break;
+ case POWER_ENERGY:
+ SetMaxPower(POWER_ENERGY, GetCreatePowers(POWER_ENERGY));
+ break;
+ case POWER_HAPPINESS:
+ SetMaxPower(POWER_HAPPINESS, GetCreatePowers(POWER_HAPPINESS));
+ SetPower(POWER_HAPPINESS, GetCreatePowers(POWER_HAPPINESS));
+ break;
+ }
+}
+
+FactionTemplateEntry const* Unit::getFactionTemplateEntry() const
+{
+ FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry(getFaction());
+ if(!entry)
+ {
+ static uint64 guid = 0; // prevent repeating spam same faction problem
+
+ if(GetGUID() != guid)
+ {
+ if(GetTypeId() == TYPEID_PLAYER)
+ sLog.outError("Player %s have invalid faction (faction template id) #%u", ((Player*)this)->GetName(), getFaction());
+ else
+ sLog.outError("Creature (template id: %u) have invalid faction (faction template id) #%u", ((Creature*)this)->GetCreatureInfo()->Entry, getFaction());
+ guid = GetGUID();
+ }
+ }
+ return entry;
+}
+
+bool Unit::IsHostileTo(Unit const* unit) const
+{
+ if(!unit)
+ return false;
+ // always non-hostile to self
+ if(unit==this)
+ return false;
+
+ // always non-hostile to GM in GM mode
+ if(unit->GetTypeId() == TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
+ return false;
+
+ // always hostile to enemy
+ if(getVictim()==unit || unit->getVictim()==this)
+ return true;
+
+ // test pet/charm masters instead pers/charmeds
+ Unit const* testerOwner = GetCharmerOrOwner();
+ Unit const* targetOwner = unit->GetCharmerOrOwner();
+
+ // always hostile to owner's enemy
+ if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
+ return true;
+
+ // always hostile to enemy owner
+ if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
+ return true;
+
+ // always hostile to owner of owner's enemy
+ if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
+ return true;
+
+ Unit const* tester = testerOwner ? testerOwner : this;
+ Unit const* target = targetOwner ? targetOwner : unit;
+
+ // always non-hostile to target with common owner, or to owner/pet
+ if(tester==target)
+ return false;
+
+ // special cases (Duel, etc)
+ if(tester->GetTypeId() == TYPEID_PLAYER && target->GetTypeId() == TYPEID_PLAYER)
+ {
+ Player const* pTester = (Player const*)tester;
+ Player const* pTarget = (Player const*)target;
+
+ // Duel
+ if(pTester->duel && pTester->duel->opponent == pTarget && pTester->duel->startTime != 0)
+ return true;
+
+ // Group
+ if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
+ return false;
+
+ // Sanctuary
+ if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
+ return false;
+
+ // PvP FFA state
+ if(pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
+ return true;
+
+ //= PvP states
+ // Green/Blue (can't attack)
+ if (!pTester->HasAuraType(SPELL_AURA_MOD_FACTION) && !pTarget->HasAuraType(SPELL_AURA_MOD_FACTION))
+ {
+ if(pTester->GetTeam()==pTarget->GetTeam())
+ return false;
+
+ // Red (can attack) if true, Blue/Yellow (can't attack) in another case
+ return pTester->IsPvP() && pTarget->IsPvP();
+ }
+ }
+
+ // faction base cases
+ FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
+ FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
+ if(!tester_faction || !target_faction)
+ return false;
+
+ if(target->isAttackingPlayer() && tester->IsContestedGuard())
+ return true;
+
+ // PvC forced reaction and reputation case
+ if(tester->GetTypeId() == TYPEID_PLAYER && !tester->HasAuraType(SPELL_AURA_MOD_FACTION))
+ {
+ // forced reaction
+ if(target_faction->faction)
+ {
+ if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
+ return *force <= REP_HOSTILE;
+
+ // if faction have reputation then hostile state for tester at 100% dependent from at_war state
+ if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
+ if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
+ return (factionState->Flags & FACTION_FLAG_AT_WAR);
+ }
+ }
+ // CvP forced reaction and reputation case
+ else if(target->GetTypeId() == TYPEID_PLAYER && !target->HasAuraType(SPELL_AURA_MOD_FACTION))
+ {
+ // forced reaction
+ if(tester_faction->faction)
+ {
+ if(ReputationRank const* force = ((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
+ return *force <= REP_HOSTILE;
+
+ // apply reputation state
+ FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction);
+ if(raw_tester_faction && raw_tester_faction->reputationListID >=0 )
+ return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) <= REP_HOSTILE;
+ }
+ }
+
+ // common faction based case (CvC,PvC,CvP)
+ return tester_faction->IsHostileTo(*target_faction);
+}
+
+bool Unit::IsFriendlyTo(Unit const* unit) const
+{
+ // always friendly to self
+ if(unit==this)
+ return true;
+
+ // always friendly to GM in GM mode
+ if(unit->GetTypeId() == TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
+ return true;
+
+ // always non-friendly to enemy
+ if(getVictim()==unit || unit->getVictim()==this)
+ return false;
+
+ // test pet/charm masters instead pers/charmeds
+ Unit const* testerOwner = GetCharmerOrOwner();
+ Unit const* targetOwner = unit->GetCharmerOrOwner();
+
+ // always non-friendly to owner's enemy
+ if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
+ return false;
+
+ // always non-friendly to enemy owner
+ if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
+ return false;
+
+ // always non-friendly to owner of owner's enemy
+ if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
+ return false;
+
+ Unit const* tester = testerOwner ? testerOwner : this;
+ Unit const* target = targetOwner ? targetOwner : unit;
+
+ // always friendly to target with common owner, or to owner/pet
+ if(tester==target)
+ return true;
+
+ // special cases (Duel)
+ if(tester->GetTypeId() == TYPEID_PLAYER && target->GetTypeId() == TYPEID_PLAYER)
+ {
+ Player const* pTester = (Player const*)tester;
+ Player const* pTarget = (Player const*)target;
+
+ // Duel
+ if(pTester->duel && pTester->duel->opponent == target && pTester->duel->startTime != 0)
+ return false;
+
+ // Group
+ if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
+ return true;
+
+ // Sanctuary
+ if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
+ return true;
+
+ // PvP FFA state
+ if(pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
+ return false;
+
+ //= PvP states
+ // Green/Blue (non-attackable)
+ if (!pTester->HasAuraType(SPELL_AURA_MOD_FACTION) && !pTarget->HasAuraType(SPELL_AURA_MOD_FACTION))
+ {
+ if(pTester->GetTeam()==pTarget->GetTeam())
+ return true;
+
+ // Blue (friendly/non-attackable) if not PVP, or Yellow/Red in another case (attackable)
+ return !pTarget->IsPvP();
+ }
+ }
+
+ // faction base cases
+ FactionTemplateEntry const *tester_faction = tester->getFactionTemplateEntry();
+ FactionTemplateEntry const *target_faction = target->getFactionTemplateEntry();
+ if (!tester_faction || !target_faction)
+ return false;
+
+ if (target->isAttackingPlayer() && tester->IsContestedGuard())
+ return false;
+
+ // PvC forced reaction and reputation case
+ if (tester->GetTypeId() == TYPEID_PLAYER && !tester->HasAuraType(SPELL_AURA_MOD_FACTION))
+ {
+ // forced reaction
+ if (target_faction->faction)
+ {
+ if (ReputationRank const *force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
+ return *force >= REP_FRIENDLY;
+
+ // if faction have reputation then friendly state for tester at 100% dependent from at_war state
+ if (FactionEntry const *raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
+ if (FactionState const *factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
+ return !(factionState->Flags & FACTION_FLAG_AT_WAR);
+ }
+ }
+ // CvP forced reaction and reputation case
+ else if (target->GetTypeId() == TYPEID_PLAYER && !target->HasAuraType(SPELL_AURA_MOD_FACTION))
+ {
+ // forced reaction
+ if (tester_faction->faction)
+ {
+ if (ReputationRank const *force =((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
+ return *force >= REP_FRIENDLY;
+
+ // apply reputation state
+ if (FactionEntry const *raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction))
+ if (raw_tester_faction->reputationListID >= 0)
+ return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) >= REP_FRIENDLY;
+ }
+ }
+
+ // common faction based case (CvC,PvC,CvP)
+ return tester_faction->IsFriendlyTo(*target_faction);
+}
+
+bool Unit::IsHostileToPlayers() const
+{
+ FactionTemplateEntry const *my_faction = getFactionTemplateEntry();
+ if (!my_faction || !my_faction->faction)
+ return false;
+
+ FactionEntry const *raw_faction = sFactionStore.LookupEntry(my_faction->faction);
+ if (raw_faction && raw_faction->reputationListID >= 0)
+ return false;
+
+ return my_faction->IsHostileToPlayers();
+}
+
+bool Unit::IsNeutralToAll() const
+{
+ FactionTemplateEntry const *my_faction = getFactionTemplateEntry();
+ if (!my_faction || !my_faction->faction)
+ return true;
+
+ FactionEntry const *raw_faction = sFactionStore.LookupEntry(my_faction->faction);
+ if (raw_faction && raw_faction->reputationListID >= 0)
+ return false;
+
+ return my_faction->IsNeutralToAll();
+}
+
+bool Unit::Attack(Unit *victim, bool meleeAttack)
+{
+ if(!victim || victim == this)
+ return false;
+
+ // dead units can neither attack nor be attacked
+ if(!isAlive() || !victim->IsInWorld() || !victim->isAlive())
+ return false;
+
+ // player cannot attack in mount state
+ if(GetTypeId() == TYPEID_PLAYER && IsMounted())
+ return false;
+
+ // nobody can attack GM in GM-mode
+ if(victim->GetTypeId() == TYPEID_PLAYER)
+ {
+ if(((Player*)victim)->isGameMaster())
+ return false;
+ }
+ else
+ {
+ if(((Creature*)victim)->IsInEvadeMode())
+ return false;
+ }
+
+ // remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack)
+ if(HasAuraType(SPELL_AURA_MOD_UNATTACKABLE))
+ RemoveAurasByType(SPELL_AURA_MOD_UNATTACKABLE);
+
+ if (m_attacking)
+ {
+ if (m_attacking == victim)
+ {
+ // switch to melee attack from ranged/magic
+ if (meleeAttack)
+ {
+ if (!hasUnitState(UNIT_STAT_MELEE_ATTACKING))
+ {
+ addUnitState(UNIT_STAT_MELEE_ATTACKING);
+ SendMeleeAttackStart(victim);
+ return true;
+ }
+ }
+ else if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
+ {
+ clearUnitState(UNIT_STAT_MELEE_ATTACKING);
+ SendMeleeAttackStop(victim);
+ return true;
+ }
+ return false;
+ }
+
+ //switch target
+ InterruptSpell(CURRENT_MELEE_SPELL);
+ if (!meleeAttack)
+ clearUnitState(UNIT_STAT_MELEE_ATTACKING);
+ }
+
+ if (m_attacking)
+ m_attacking->_removeAttacker(this);
+
+ m_attacking = victim;
+ m_attacking->_addAttacker(this);
+
+ // Set our target
+ SetUInt64Value(UNIT_FIELD_TARGET, victim->GetGUID());
+
+ if (meleeAttack)
+ addUnitState(UNIT_STAT_MELEE_ATTACKING);
+
+ // set position before any AI calls/assistance
+ //if(GetTypeId() == TYPEID_UNIT)
+ // ((Creature*)this)->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ());
+
+ if (GetTypeId() == TYPEID_UNIT)
+ {
+ // should not let player enter combat by right clicking target
+ SetInCombatWith(victim);
+ if (victim->GetTypeId() == TYPEID_PLAYER)
+ victim->SetInCombatWith(this);
+ AddThreat(victim, 0.0f);
+
+ ((Creature*)this)->SendAIReaction(AI_REACTION_AGGRO);
+ ((Creature*)this)->CallAssistance();
+ }
+
+ // delay offhand weapon attack to next attack time
+ if(haveOffhandWeapon())
+ resetAttackTimer(OFF_ATTACK);
+
+ if (meleeAttack)
+ SendMeleeAttackStart(victim);
+
+ return true;
+}
+
+bool Unit::AttackStop()
+{
+ if (!m_attacking)
+ return false;
+
+ Unit* victim = m_attacking;
+
+ m_attacking->_removeAttacker(this);
+ m_attacking = NULL;
+
+ // Clear our target
+ SetUInt64Value(UNIT_FIELD_TARGET, 0);
+
+ clearUnitState(UNIT_STAT_MELEE_ATTACKING);
+
+ InterruptSpell(CURRENT_MELEE_SPELL);
+
+ // reset only at real combat stop
+ if (GetTypeId() == TYPEID_UNIT)
+ {
+ ((Creature*)this)->SetNoCallAssistance(false);
+
+ if (((Creature*)this)->HasSearchedAssistance())
+ {
+ ((Creature*)this)->SetNoSearchAssistance(false);
+ UpdateSpeed(MOVE_RUN, false);
+ }
+ }
+
+ SendMeleeAttackStop(victim);
+
+ return true;
+}
+
+void Unit::CombatStop(bool includingCast)
+{
+ if (includingCast && IsNonMeleeSpellCasted(false))
+ InterruptNonMeleeSpells(false);
+
+ AttackStop();
+ RemoveAllAttackers();
+ if (GetTypeId() == TYPEID_PLAYER)
+ ((Player*)this)->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel
+ ClearInCombat();
+}
+
+void Unit::CombatStopWithPets(bool includingCast)
+{
+ CombatStop(includingCast);
+
+ for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
+ (*itr)->CombatStop(includingCast);
+}
+
+bool Unit::isAttackingPlayer() const
+{
+ if (hasUnitState(UNIT_STAT_ATTACK_PLAYER))
+ return true;
+
+ for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
+ if ((*itr)->isAttackingPlayer())
+ return true;
+
+ for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i)
+ if (m_SummonSlot[i])
+ if (Creature *summon = GetMap()->GetCreature(m_SummonSlot[i]))
+ if (summon->isAttackingPlayer())
+ return true;
+
+ return false;
+}
+
+void Unit::RemoveAllAttackers()
+{
+ while (!m_attackers.empty())
+ {
+ AttackerSet::iterator iter = m_attackers.begin();
+ if (!(*iter)->AttackStop())
+ {
+ sLog.outError("WORLD: Unit has an attacker that isn't attacking it!");
+ m_attackers.erase(iter);
+ }
+ }
+}
+
+void Unit::ModifyAuraState(AuraState flag, bool apply)
+{
+ if (apply)
+ {
+ if (!HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)))
+ {
+ SetFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ PlayerSpellMap const& sp_list = ((Player*)this)->GetSpellMap();
+ for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
+ {
+ if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled) continue;
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first);
+ if (!spellInfo || !IsPassiveSpell(itr->first)) continue;
+ if (spellInfo->CasterAuraState == flag)
+ CastSpell(this, itr->first, true, NULL);
+ }
+ }
+ else if (((Creature*)this)->isPet())
+ {
+ Pet *pet = ((Pet*)this);
+ for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
+ {
+ if (itr->second.state == PETSPELL_REMOVED) continue;
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first);
+ if (!spellInfo || !IsPassiveSpell(itr->first)) continue;
+ if (spellInfo->CasterAuraState == flag)
+ CastSpell(this, itr->first, true, NULL);
+ }
+ }
+ }
+ }
+ else
+ {
+ if (HasFlag(UNIT_FIELD_AURASTATE,1<<(flag-1)))
+ {
+ RemoveFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
+
+ if (flag != AURA_STATE_ENRAGE) // enrage aura state triggering continues auras
+ {
+ Unit::AuraApplicationMap& tAuras = GetAppliedAuras();
+ for (Unit::AuraApplicationMap::iterator itr = tAuras.begin(); itr != tAuras.end();)
+ {
+ SpellEntry const* spellProto = (*itr).second->GetBase()->GetSpellProto();
+ if (spellProto->CasterAuraState == flag)
+ RemoveAura(itr);
+ else
+ ++itr;
+ }
+ }
+ }
+ }
+}
+
+uint32 Unit::BuildAuraStateUpdateForTarget(Unit * target) const
+{
+ uint32 auraStates = GetUInt32Value(UNIT_FIELD_AURASTATE) &~(PER_CASTER_AURA_STATE_MASK);
+ for (AuraStateAurasMap::const_iterator itr = m_auraStateAuras.begin(); itr != m_auraStateAuras.end(); ++itr)
+ if ((1<<(itr->first-1)) & PER_CASTER_AURA_STATE_MASK)
+ if (itr->second->GetBase()->GetCasterGUID() == target->GetGUID())
+ auraStates |= (1<<(itr->first-1));
+
+ return auraStates;
+}
+
+bool Unit::HasAuraState(AuraState flag, SpellEntry const *spellProto, Unit const * Caster) const
+{
+ if (Caster)
+ {
+ if (spellProto)
+ {
+ AuraEffectList const& stateAuras = Caster->GetAuraEffectsByType(SPELL_AURA_ABILITY_IGNORE_AURASTATE);
+ for (AuraEffectList::const_iterator j = stateAuras.begin(); j != stateAuras.end(); ++j)
+ if ((*j)->IsAffectedOnSpell(spellProto))
+ return true;
+ }
+ // Check per caster aura state
+ // If aura with aurastate by caster not found return false
+ if ((1<<(flag-1)) & PER_CASTER_AURA_STATE_MASK)
+ {
+ for (AuraStateAurasMap::const_iterator itr = m_auraStateAuras.lower_bound(flag); itr != m_auraStateAuras.upper_bound(flag); ++itr)
+ if (itr->second->GetBase()->GetCasterGUID() == Caster->GetGUID())
+ return true;
+ return false;
+ }
+ }
+
+ return HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
+}
+
+Unit *Unit::GetOwner(bool inWorld) const
+{
+ if (uint64 ownerid = GetOwnerGUID())
+ {
+ if (inWorld)
+ return ObjectAccessor::GetUnit(*this, ownerid);
+ return ObjectAccessor::GetUnitInOrOutOfWorld(*this, ownerid);
+ }
+ return NULL;
+}
+
+Unit *Unit::GetCharmer() const
+{
+ if (uint64 charmerid = GetCharmerGUID())
+ return ObjectAccessor::GetUnit(*this, charmerid);
+ return NULL;
+}
+
+Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself() const
+{
+ uint64 guid = GetCharmerOrOwnerGUID();
+ if (IS_PLAYER_GUID(guid))
+ return ObjectAccessor::GetPlayer(*this, guid);
+
+ return GetTypeId() == TYPEID_PLAYER ? (Player*)this : NULL;
+}
+
+Minion *Unit::GetFirstMinion() const
+{
+ if (uint64 pet_guid = GetMinionGUID())
+ {
+ if (Creature* pet = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, pet_guid))
+ if (pet->HasUnitTypeMask(UNIT_MASK_MINION))
+ return (Minion*)pet;
+
+ sLog.outError("Unit::GetFirstMinion: Minion %u not exist.",GUID_LOPART(pet_guid));
+ const_cast<Unit*>(this)->SetMinionGUID(0);
+ }
+
+ return NULL;
+}
+
+Guardian* Unit::GetGuardianPet() const
+{
+ if (uint64 pet_guid = GetPetGUID())
+ {
+ if (Creature* pet = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, pet_guid))
+ if (pet->HasUnitTypeMask(UNIT_MASK_GUARDIAN))
+ return (Guardian*)pet;
+
+ sLog.outCrash("Unit::GetGuardianPet: Guardian " I64FMT " not exist.", pet_guid);
+ const_cast<Unit*>(this)->SetPetGUID(0);
+ }
+
+ return NULL;
+}
+
+Unit* Unit::GetCharm() const
+{
+ if (uint64 charm_guid = GetCharmGUID())
+ {
+ if (Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid))
+ return pet;
+
+ sLog.outError("Unit::GetCharm: Charmed creature %u not exist.",GUID_LOPART(charm_guid));
+ const_cast<Unit*>(this)->SetUInt64Value(UNIT_FIELD_CHARM, 0);
+ }
+
+ return NULL;
+}
+
+void Unit::SetMinion(Minion *minion, bool apply)
+{
+ sLog.outDebug("SetMinion %u for %u, apply %u", minion->GetEntry(), GetEntry(), apply);
+
+ if (apply)
+ {
+ if (!minion->AddUInt64Value(UNIT_FIELD_SUMMONEDBY, GetGUID()))
+ {
+ sLog.outCrash("SetMinion: Minion %u is not the minion of owner %u", minion->GetEntry(), GetEntry());
+ return;
+ }
+
+ m_Controlled.insert(minion);
+
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ minion->m_ControlledByPlayer = true;
+ minion->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
+ }
+
+ // Can only have one pet. If a new one is summoned, dismiss the old one.
+ if (minion->IsGuardianPet())
+ {
+ if (Guardian* oldPet = GetGuardianPet())
+ {
+ if (oldPet != minion && (oldPet->isPet() || minion->isPet() || oldPet->GetEntry() != minion->GetEntry()))
+ {
+ // remove existing minion pet
+ if (oldPet->isPet())
+ ((Pet*)oldPet)->Remove(PET_SAVE_AS_CURRENT);
+ else
+ oldPet->UnSummon();
+ SetPetGUID(minion->GetGUID());
+ SetMinionGUID(0);
+ }
+ }
+ else
+ {
+ SetPetGUID(minion->GetGUID());
+ SetMinionGUID(0);
+ }
+ }
+
+ if (minion->HasUnitTypeMask(UNIT_MASK_CONTROLABLE_GUARDIAN))
+ {
+ if (AddUInt64Value(UNIT_FIELD_SUMMON, minion->GetGUID()))
+ {
+ }
+ }
+ //else if(minion->m_Properties && minion->m_Properties->Type == SUMMON_TYPE_MINIPET)
+ // AddUInt64Value(UNIT_FIELD_CRITTER, minion->GetGUID());
+
+ // PvP, FFAPvP
+ minion->SetByteValue(UNIT_FIELD_BYTES_2, 1, GetByteValue(UNIT_FIELD_BYTES_2, 1));
+
+ // FIXME: hack, speed must be set only at follow
+ if (GetTypeId() == TYPEID_PLAYER && minion->isPet())
+ for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i)
+ minion->SetSpeed(UnitMoveType(i), m_speed_rate[i], true);
+
+ // Ghoul pets have energy instead of mana (is anywhere better place for this code?)
+ if (minion->IsPetGhoul())
+ minion->setPowerType(POWER_ENERGY);
+
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ // Send infinity cooldown - client does that automatically but after relog cooldown needs to be set again
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(minion->GetUInt32Value(UNIT_CREATED_BY_SPELL));
+ if (spellInfo && (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE))
+ ((Player*)this)->AddSpellAndCategoryCooldowns(spellInfo, 0, NULL ,true);
+ }
+ }
+ else
+ {
+ if (minion->GetOwnerGUID() != GetGUID())
+ {
+ sLog.outCrash("SetMinion: Minion %u is not the minion of owner %u", minion->GetEntry(), GetEntry());
+ return;
+ }
+
+ m_Controlled.erase(minion);
+
+ if (minion->IsGuardianPet())
+ {
+ if (GetPetGUID() == minion->GetGUID())
+ SetPetGUID(0);
+ }
+ else if (minion->isTotem())
+ {
+ // All summoned by totem minions must disappear when it is removed.
+ if (const SpellEntry* spInfo = sSpellStore.LookupEntry(((Totem*)minion)->GetSpell()))
+ for (int i = 0; i < MAX_SPELL_EFFECTS; ++i)
+ {
+ if (spInfo->Effect[i] != SPELL_EFFECT_SUMMON)
+ continue;
+
+ this->RemoveAllMinionsByEntry(spInfo->EffectMiscValue[i]);
+ }
+ }
+
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(minion->GetUInt32Value(UNIT_CREATED_BY_SPELL));
+ // Remove infinity cooldown
+ if (spellInfo && (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE))
+ ((Player*)this)->SendCooldownEvent(spellInfo);
+ }
+
+ //if(minion->HasUnitTypeMask(UNIT_MASK_GUARDIAN))
+ {
+ if (RemoveUInt64Value(UNIT_FIELD_SUMMON, minion->GetGUID()))
+ {
+ //Check if there is another minion
+ for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
+ {
+ // do not use this check, creature do not have charm guid
+ //if(GetCharmGUID() == (*itr)->GetGUID())
+ if (GetGUID() == (*itr)->GetCharmerGUID())
+ continue;
+
+ //assert((*itr)->GetOwnerGUID() == GetGUID());
+ if ((*itr)->GetOwnerGUID() != GetGUID())
+ {
+ OutDebugInfo();
+ (*itr)->OutDebugInfo();
+ assert(false);
+ }
+ assert((*itr)->GetTypeId() == TYPEID_UNIT);
+
+ if (!(*itr)->HasUnitTypeMask(UNIT_MASK_CONTROLABLE_GUARDIAN))
+ continue;
+
+ if (AddUInt64Value(UNIT_FIELD_SUMMON, (*itr)->GetGUID()))
+ {
+ //show another pet bar if there is no charm bar
+ if (GetTypeId() == TYPEID_PLAYER && !GetCharmGUID())
+ {
+ if ((*itr)->isPet())
+ ((Player*)this)->PetSpellInitialize();
+ else
+ ((Player*)this)->CharmSpellInitialize();
+ }
+ }
+ break;
+ }
+ }
+ }
+ //else if(minion->m_Properties && minion->m_Properties->Type == SUMMON_TYPE_MINIPET)
+ // RemoveUInt64Value(UNIT_FIELD_CRITTER, minion->GetGUID());
+ }
+}
+
+void Unit::GetAllMinionsByEntry(std::list<Creature*>& Minions, uint32 entry)
+{
+ for (Unit::ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end();)
+ {
+ Unit *unit = *itr;
+ ++itr;
+ if (unit->GetEntry() == entry && unit->GetTypeId() == TYPEID_UNIT
+ && ((Creature*)unit)->isSummon()) // minion, actually
+ Minions.push_back((Creature*)unit);
+ }
+}
+
+void Unit::RemoveAllMinionsByEntry(uint32 entry)
+{
+ for (Unit::ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end();)
+ {
+ Unit *unit = *itr;
+ ++itr;
+ if (unit->GetEntry() == entry && unit->GetTypeId() == TYPEID_UNIT
+ && ((Creature*)unit)->isSummon()) // minion, actually
+ ((TempSummon*)unit)->UnSummon();
+ // i think this is safe because i have never heard that a despawned minion will trigger a same minion
+ }
+}
+
+void Unit::SetCharm(Unit* charm, bool apply)
+{
+ if (apply)
+ {
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ if (!AddUInt64Value(UNIT_FIELD_CHARM, charm->GetGUID()))
+ sLog.outCrash("Player %s is trying to charm unit %u, but it already has a charmed unit %u", GetName(), charm->GetEntry(), GetCharmGUID());
+
+ charm->m_ControlledByPlayer = true;
+ // TODO: maybe we can use this flag to check if controlled by player
+ charm->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
+ }
+ else
+ charm->m_ControlledByPlayer = false;
+
+ // PvP, FFAPvP
+ charm->SetByteValue(UNIT_FIELD_BYTES_2, 1, GetByteValue(UNIT_FIELD_BYTES_2, 1));
+
+ if (!charm->AddUInt64Value(UNIT_FIELD_CHARMEDBY, GetGUID()))
+ sLog.outCrash("Unit %u is being charmed, but it already has a charmer %u", charm->GetEntry(), charm->GetCharmerGUID());
+
+ if (charm->HasUnitMovementFlag(MOVEMENTFLAG_WALK_MODE))
+ {
+ charm->RemoveUnitMovementFlag(MOVEMENTFLAG_WALK_MODE);
+ charm->SendMovementFlagUpdate();
+ }
+
+ m_Controlled.insert(charm);
+ }
+ else
+ {
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ if (!RemoveUInt64Value(UNIT_FIELD_CHARM, charm->GetGUID()))
+ sLog.outCrash("Player %s is trying to uncharm unit %u, but it has another charmed unit %u", GetName(), charm->GetEntry(), GetCharmGUID());
+ }
+
+ if (!charm->RemoveUInt64Value(UNIT_FIELD_CHARMEDBY, GetGUID()))
+ sLog.outCrash("Unit %u is being uncharmed, but it has another charmer %u", charm->GetEntry(), charm->GetCharmerGUID());
+
+ if (charm->GetTypeId() == TYPEID_PLAYER)
+ {
+ charm->m_ControlledByPlayer = true;
+ charm->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
+ ((Player*)charm)->UpdatePvPState();
+ }
+ else if(Player *player = charm->GetCharmerOrOwnerPlayerOrPlayerItself())
+ {
+ charm->m_ControlledByPlayer = true;
+ charm->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
+ charm->SetByteValue(UNIT_FIELD_BYTES_2, 1, player->GetByteValue(UNIT_FIELD_BYTES_2, 1));
+ }
+ else
+ {
+ charm->m_ControlledByPlayer = false;
+ charm->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
+ charm->SetByteValue(UNIT_FIELD_BYTES_2, 1, 0);
+ }
+
+ if (charm->GetTypeId() == TYPEID_PLAYER
+ || !((Creature*)charm)->HasUnitTypeMask(UNIT_MASK_MINION)
+ || charm->GetOwnerGUID() != GetGUID())
+ m_Controlled.erase(charm);
+ }
+}
+
+int32 Unit::DealHeal(Unit *pVictim, uint32 addhealth, SpellEntry const *spellProto, bool critical)
+{
+ int32 gain = pVictim->ModifyHealth(int32(addhealth));
+
+ Unit* unit = this;
+
+ if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isTotem())
+ unit = GetOwner();
+
+ if (unit->GetTypeId() == TYPEID_PLAYER)
+ {
+ // overheal = addhealth - gain
+ unit->SendHealSpellLog(pVictim, spellProto->Id, addhealth, addhealth - gain, critical);
+
+ if (BattleGround *bg = ((Player*)unit)->GetBattleGround())
+ bg->UpdatePlayerScore((Player*)unit, SCORE_HEALING_DONE, gain);
+
+ // use the actual gain, as the overheal shall not be counted, skip gain 0 (it ignored anyway in to criteria)
+ if (gain)
+ ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE, gain, 0, pVictim);
+
+ ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED, addhealth);
+ }
+
+ if (pVictim->GetTypeId() == TYPEID_PLAYER)
+ {
+ ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED, gain);
+ ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED, addhealth);
+ }
+
+ return gain;
+}
+
+Unit* Unit::SelectMagnetTarget(Unit *victim, SpellEntry const *spellInfo)
+{
+ if (!victim)
+ return NULL;
+
+ // Magic case
+ if (spellInfo && (spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC))
+ {
+ //I am not sure if this should be redirected.
+ if (spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE)
+ return victim;
+
+ Unit::AuraEffectList const& magnetAuras = victim->GetAuraEffectsByType(SPELL_AURA_SPELL_MAGNET);
+ for (Unit::AuraEffectList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
+ if (Unit* magnet = (*itr)->GetBase()->GetUnitOwner())
+ if (magnet->isAlive())
+ {
+ (*itr)->GetBase()->DropCharge();
+ return magnet;
+ }
+ }
+ // Melee && ranged case
+ else
+ {
+ AuraEffectList const& hitTriggerAuras = victim->GetAuraEffectsByType(SPELL_AURA_ADD_CASTER_HIT_TRIGGER);
+ for (AuraEffectList::const_iterator i = hitTriggerAuras.begin(); i != hitTriggerAuras.end(); ++i)
+ if (Unit* magnet = (*i)->GetBase()->GetUnitOwner())
+ if (magnet->isAlive() && magnet->IsWithinLOSInMap(this))
+ if (roll_chance_i((*i)->GetAmount()))
+ {
+ (*i)->GetBase()->DropCharge();
+ return magnet;
+ }
+ }
+
+ return victim;
+}
+
+Unit* Unit::GetFirstControlled() const
+{
+ //Sequence: charmed, pet, other guardians
+ Unit *unit = GetCharm();
+ if (!unit)
+ if (uint64 guid = GetUInt64Value(UNIT_FIELD_SUMMON))
+ unit = ObjectAccessor::GetUnit(*this, guid);
+
+ return unit;
+}
+
+void Unit::RemoveAllControlled()
+{
+ //possessed pet and vehicle
+ if (GetTypeId() == TYPEID_PLAYER)
+ ((Player*)this)->StopCastingCharm();
+
+ while (!m_Controlled.empty())
+ {
+ Unit *target = *m_Controlled.begin();
+ m_Controlled.erase(m_Controlled.begin());
+ if (target->GetCharmerGUID() == GetGUID())
+ target->RemoveCharmAuras();
+ else if (target->GetOwnerGUID() == GetGUID() && target->isSummon())
+ ((TempSummon*)target)->UnSummon();
+ else
+ sLog.outError("Unit %u is trying to release unit %u which is neither charmed nor owned by it", GetEntry(), target->GetEntry());
+ }
+ if (GetPetGUID())
+ sLog.outCrash("Unit %u is not able to release its pet " I64FMT, GetEntry(), GetPetGUID());
+ if (GetMinionGUID())
+ sLog.outCrash("Unit %u is not able to release its minion " I64FMT, GetEntry(), GetMinionGUID());
+ if (GetCharmGUID())
+ sLog.outCrash("Unit %u is not able to release its charm " I64FMT, GetEntry(), GetCharmGUID());
+}
+
+Unit* Unit::GetNextRandomRaidMemberOrPet(float radius)
+{
+ Player* player = NULL;
+ if (GetTypeId() == TYPEID_PLAYER)
+ player = (Player*)this;
+ // Should we enable this also for charmed units?
+ else if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
+ player = (Player*)GetOwner();
+
+ if (!player)
+ return NULL;
+ Group *pGroup = player->GetGroup();
+ //When there is no group check pet presence
+ if (!pGroup)
+ {
+ // We are pet now, return owner
+ if (player!=this)
+ return IsWithinDistInMap(player, radius) ? player : NULL;
+ Unit * pet = GetGuardianPet();
+ //No pet, no group, nothing to return
+ if (!pet)
+ return NULL;
+ // We are owner now, return pet
+ return IsWithinDistInMap(pet, radius) ? pet : NULL;
+ }
+
+ std::vector<Unit*> nearMembers;
+ //reserve place for players and pets because resizing vector every unit push is unefficient (vector is reallocated then)
+ nearMembers.reserve(pGroup->GetMembersCount()*2);
+
+ for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
+ if (Player *Target = itr->getSource())
+ {
+ // IsHostileTo check duel and controlled by enemy
+ if (Target !=this && Target->isAlive() && IsWithinDistInMap(Target, radius) && !IsHostileTo(Target))
+ nearMembers.push_back(Target);
+
+ // Push player's pet to vector
+ if (Unit *pet = Target->GetGuardianPet())
+ if (pet != this && pet->isAlive() && IsWithinDistInMap(pet, radius) && !IsHostileTo(pet))
+ nearMembers.push_back(pet);
+ }
+
+ if (nearMembers.empty())
+ return NULL;
+
+ uint32 randTarget = urand(0,nearMembers.size()-1);
+ return nearMembers[randTarget];
+}
+
+/*
+Player * Unit::GetMoverSource() const
+{
+ if (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->m_mover == this)
+ return (Player*)this;
+ if (Unit *charmer = GetCharmer())
+ if (charmer->GetTypeId() == TYPEID_PLAYER && ((Player*)charmer)->m_mover == this)
+ return (Player*)charmer;
+ return NULL;
+}
+*/
+
+//only called in Player::SetSeer
+void Unit::AddPlayerToVision(Player* plr)
+{
+ if (m_sharedVision.empty())
+ {
+ setActive(true);
+ SetWorldObject(true);
+ }
+ m_sharedVision.push_back(plr);
+}
+
+//only called in Player::SetSeer
+void Unit::RemovePlayerFromVision(Player* plr)
+{
+ m_sharedVision.remove(plr);
+ if (m_sharedVision.empty())
+ {
+ setActive(false);
+ SetWorldObject(false);
+ }
+}
+
+void Unit::RemoveBindSightAuras()
+{
+ RemoveAurasByType(SPELL_AURA_BIND_SIGHT);
+}
+
+void Unit::RemoveCharmAuras()
+{
+ RemoveAurasByType(SPELL_AURA_MOD_CHARM);
+ RemoveAurasByType(SPELL_AURA_MOD_POSSESS_PET);
+ RemoveAurasByType(SPELL_AURA_MOD_POSSESS);
+ RemoveAurasByType(SPELL_AURA_AOE_CHARM);
+}
+
+void Unit::UnsummonAllTotems()
+{
+ for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i)
+ {
+ if (!m_SummonSlot[i])
+ continue;
+
+ if (Creature *OldTotem = GetMap()->GetCreature(m_SummonSlot[i]))
+ if (OldTotem->isSummon())
+ ((TempSummon*)OldTotem)->UnSummon();
+ }
+}
+
+void Unit::SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, uint32 OverHeal, bool critical)
+{
+ // we guess size
+ WorldPacket data(SMSG_SPELLHEALLOG, (8+8+4+4+4+4+1));
+ data.append(pVictim->GetPackGUID());
+ data.append(GetPackGUID());
+ data << uint32(SpellID);
+ data << uint32(Damage);
+ data << uint32(OverHeal);
+ data << uint32(0); // Absorb amount
+ data << uint8(critical ? 1 : 0);
+ SendMessageToSet(&data, true);
+}
+
+void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
+{
+ WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1));
+ data.append(pVictim->GetPackGUID());
+ data.append(GetPackGUID());
+ data << uint32(SpellID);
+ data << uint32(powertype);
+ data << uint32(Damage);
+ SendMessageToSet(&data, true);
+}
+
+void Unit::EnergizeBySpell(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
+{
+ SendEnergizeSpellLog(pVictim, SpellID, Damage, powertype);
+ // needs to be called after sending spell log
+ pVictim->ModifyPower(powertype, Damage);
+}
+
+uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack)
+{
+ if (!spellProto || !pVictim || damagetype == DIRECT_DAMAGE)
+ return pdamage;
+
+ // For totems get damage bonus from owner
+ if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isTotem())
+ if (Unit *owner = GetOwner())
+ return owner->SpellDamageBonus(pVictim, spellProto, pdamage, damagetype);
+
+ // Taken/Done total percent damage auras
+ float DoneTotalMod = 1.0f;
+ float TakenTotalMod = 1.0f;
+ float ApCoeffMod = 1.0f;
+ int32 DoneTotal = 0;
+ int32 TakenTotal = 0;
+
+ // ..done
+ // Pet damage
+ if (GetTypeId() == TYPEID_UNIT && !((Creature*)this)->isPet())
+ DoneTotalMod *= ((Creature*)this)->GetSpellDamageMod(((Creature*)this)->GetCreatureInfo()->rank);
+
+ AuraEffectList const &mModDamagePercentDone = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
+ for (AuraEffectList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
+ if (((*i)->GetMiscValue() & GetSpellSchoolMask(spellProto)) &&
+ (*i)->GetSpellProto()->EquippedItemClass == -1 && // -1 == any item class (not wand)
+ (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0) // 0 == any inventory type (not wand)
+ DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
+
+ uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
+ // Add flat bonus from spell damage versus
+ DoneTotal += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask);
+ AuraEffectList const &mDamageDoneVersus = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
+ for (AuraEffectList::const_iterator i = mDamageDoneVersus.begin(); i != mDamageDoneVersus.end(); ++i)
+ if (creatureTypeMask & uint32((*i)->GetMiscValue()))
+ DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
+
+ // done scripted mod (take it from owner)
+ Unit *owner = GetOwner() ? GetOwner() : this;
+ AuraEffectList const &mOverrideClassScript= owner->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
+ for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
+ {
+ if (!(*i)->IsAffectedOnSpell(spellProto))
+ continue;
+ switch ((*i)->GetMiscValue())
+ {
+ case 4920: // Molten Fury
+ case 4919:
+ case 6917: // Death's Embrace
+ case 6926:
+ case 6928:
+ {
+ if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this))
+ DoneTotalMod *= (100.0f+(*i)->GetAmount())/100.0f;
+ break;
+ }
+ // Soul Siphon
+ case 4992:
+ case 4993:
+ {
+ // effect 1 m_amount
+ int32 maxPercent = (*i)->GetAmount();
+ // effect 0 m_amount
+ int32 stepPercent = CalculateSpellDamage((*i)->GetSpellProto(), 0, (*i)->GetSpellProto()->EffectBasePoints[0], this);
+ // count affliction effects and calc additional damage in percentage
+ int32 modPercent = 0;
+ AuraApplicationMap const &victimAuras = pVictim->GetAppliedAuras();
+ for (AuraApplicationMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
+ {
+ Aura const * aura = itr->second->GetBase();
+ SpellEntry const *m_spell = aura->GetSpellProto();
+ if (m_spell->SpellFamilyName != SPELLFAMILY_WARLOCK || !(m_spell->SpellFamilyFlags[1] & 0x0004071B || m_spell->SpellFamilyFlags[0] & 0x8044C402))
+ continue;
+ modPercent += stepPercent * aura->GetStackAmount();
+ if (modPercent >= maxPercent)
+ {
+ modPercent = maxPercent;
+ break;
+ }
+ }
+ DoneTotalMod *= (modPercent+100.0f)/100.0f;
+ break;
+ }
+ case 6916: // Death's Embrace
+ case 6925:
+ case 6927:
+ if (HasAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, spellProto, this))
+ DoneTotalMod *= (100.0f+(*i)->GetAmount())/100.0f;
+ break;
+ case 5481: // Starfire Bonus
+ {
+ if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x200002, 0, 0))
+ DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
+ break;
+ }
+ case 4418: // Increased Shock Damage
+ case 4554: // Increased Lightning Damage
+ case 4555: // Improved Moonfire
+ case 5142: // Increased Lightning Damage
+ case 5147: // Improved Consecration / Libram of Resurgence
+ case 5148: // Idol of the Shooting Star
+ case 6008: // Increased Lightning Damage / Totem of Hex
+ {
+ DoneTotal += (*i)->GetAmount();
+ break;
+ }
+ // Tundra Stalker
+ // Merciless Combat
+ case 7277:
+ {
+ // Merciless Combat
+ if ((*i)->GetSpellProto()->SpellIconID == 2656)
+ {
+ if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this))
+ DoneTotalMod *= (100.0f+(*i)->GetAmount())/100.0f;
+ }
+ // Tundra Stalker
+ else
+ {
+ // Frost Fever (target debuff)
+ if (pVictim->HasAura(55095))
+ DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
+ break;
+ }
+ break;
+ }
+ // Rage of Rivendare
+ case 7293:
+ {
+ if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0,0x02000000,0))
+ {
+ if (SpellChainNode const *chain = spellmgr.GetSpellChainNode((*i)->GetId()))
+ DoneTotalMod *= (chain->rank * 2.0f + 100.0f)/100.0f;
+ }
+ break;
+ }
+ // Twisted Faith
+ case 7377:
+ {
+ if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x8000, 0,0, GetGUID()))
+ DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
+ break;
+ }
+ // Marked for Death
+ case 7598:
+ case 7599:
+ case 7600:
+ case 7601:
+ case 7602:
+ {
+ if (pVictim->GetAuraEffect(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, 0x400, 0, 0))
+ DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
+ break;
+ }
+ }
+ }
+
+ // Custom scripted damage
+ switch(spellProto->SpellFamilyName)
+ {
+ case SPELLFAMILY_MAGE:
+ // Ice Lance
+ if (spellProto->SpellIconID == 186)
+ {
+ if (pVictim->HasAuraState(AURA_STATE_FROZEN, spellProto, this))
+ {
+ // Glyph of Ice Lance
+ if (owner->HasAura(56377) && pVictim->getLevel() > owner->getLevel())
+ DoneTotalMod *= 4.0f;
+ else
+ DoneTotalMod *= 3.0f;
+ }
+ }
+
+ // Torment the weak
+ if (spellProto->SpellFamilyFlags[0]&0x20200021 || spellProto->SpellFamilyFlags[1]& 0x9000)
+ if (pVictim->HasAuraType(SPELL_AURA_MOD_DECREASE_SPEED))
+ {
+ AuraEffectList const& mDumyAuras = GetAuraEffectsByType(SPELL_AURA_DUMMY);
+ for (AuraEffectList::const_iterator i = mDumyAuras.begin(); i != mDumyAuras.end(); ++i)
+ if ((*i)->GetSpellProto()->SpellIconID == 3263)
+ {
+ DoneTotalMod *= float((*i)->GetAmount() + 100.f) / 100.f;
+ break;
+ }
+ }
+ break;
+ // Glyph of Shadow Word: Pain
+ case SPELLFAMILY_PRIEST:
+ if (spellProto->SpellFamilyFlags[0] & 0x800000)
+ {
+ // Increase Mind Flay damage
+ if (AuraEffect * aurEff = GetAuraEffect(55687, 0))
+ // if Shadow Word: Pain present
+ if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x8000, 0,0, GetGUID()))
+ DoneTotalMod *= (aurEff->GetAmount() + 100.0f) / 100.f;
+ }
+ break;
+
+ case SPELLFAMILY_PALADIN:
+ // Judgement of Vengeance/Judgement of Corruption
+ if ((spellProto->SpellFamilyFlags[1] & 0x400000) && spellProto->SpellIconID==2292)
+ {
+ // Get stack of Holy Vengeance/Blood Corruption on the target added by caster
+ uint32 stacks = 0;
+ Unit::AuraEffectList const& auras = pVictim->GetAuraEffectsByType(SPELL_AURA_PERIODIC_DAMAGE);
+ for (Unit::AuraEffectList::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr)
+ if (((*itr)->GetId() == 31803 || (*itr)->GetId() == 53742) && (*itr)->GetCasterGUID()==GetGUID())
+ {
+ stacks = (*itr)->GetBase()->GetStackAmount();
+ break;
+ }
+ // + 10% for each application of Holy Vengeance/Blood Corruption on the target
+ if (stacks)
+ DoneTotalMod *= (10.0f + float(stacks)) / 10.0f;
+ }
+ break;
+ case SPELLFAMILY_WARLOCK:
+ //Fire and Brimstone
+ if (spellProto->SpellFamilyFlags[1] & 0x00020040)
+ if (pVictim->HasAuraState(AURA_STATE_CONFLAGRATE))
+ {
+ AuraEffectList const& mDumyAuras = GetAuraEffectsByType(SPELL_AURA_DUMMY);
+ for (AuraEffectList::const_iterator i = mDumyAuras.begin(); i != mDumyAuras.end(); ++i)
+ if ((*i)->GetSpellProto()->SpellIconID == 3173)
+ {
+ DoneTotalMod *= float((*i)->GetAmount() + 100.f) / 100.f;
+ break;
+ }
+ }
+ break;
+ case SPELLFAMILY_DEATHKNIGHT:
+ // Improved Icy Touch
+ if (spellProto->SpellFamilyFlags[0] & 0x2)
+ if (AuraEffect * aurEff = GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 2721, 0))
+ DoneTotalMod *= (100.0f + aurEff->GetAmount()) / 100.0f;
+
+ // Glacier Rot
+ if (spellProto->SpellFamilyFlags[0] & 0x2 || spellProto->SpellFamilyFlags[1] & 0x6)
+ if (AuraEffect * aurEff = GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 196, 0))
+ if (pVictim->GetDiseasesByCaster(owner->GetGUID()) > 0)
+ DoneTotalMod *= (100.0f + aurEff->GetAmount()) / 100.0f;
+
+ // Impurity (dummy effect)
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ PlayerSpellMap playerSpells = ((Player*)this)->GetSpellMap();
+ for (PlayerSpellMap::const_iterator itr = playerSpells.begin(); itr != playerSpells.end(); ++itr)
+ {
+ if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
+ continue;
+ switch (itr->first)
+ {
+ case 49220:
+ case 49633:
+ case 49635:
+ case 49636:
+ case 49638:
+ {
+ if (const SpellEntry *proto=sSpellStore.LookupEntry(itr->first))
+ ApCoeffMod *= (100.0f + proto->CalculateSimpleValue(0)) / 100.0f;
+ }
+ break;
+ }
+ }
+ }
+ break;
+ }
+
+ // ..taken
+ AuraEffectList const& mModDamagePercentTaken = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
+ for (AuraEffectList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
+ if ((*i)->GetMiscValue() & GetSpellSchoolMask(spellProto) )
+ TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
+
+ // .. taken pct: dummy auras
+ AuraEffectList const& mDummyAuras = pVictim->GetAuraEffectsByType(SPELL_AURA_DUMMY);
+ for (AuraEffectList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
+ {
+ switch((*i)->GetSpellProto()->SpellIconID)
+ {
+ // Cheat Death
+ case 2109:
+ if ((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL)
+ {
+ if (pVictim->GetTypeId() != TYPEID_PLAYER)
+ continue;
+ float mod = ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f);
+ if (mod < (*i)->GetAmount())
+ mod = (*i)->GetAmount();
+ TakenTotalMod *= (mod+100.0f)/100.0f;
+ }
+ break;
+ // Ebon Plague
+ case 1933:
+ if ((*i)->GetMiscValue() & (spellProto ? GetSpellSchoolMask(spellProto) : 0))
+ TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
+ break;
+ }
+ }
+
+ // From caster spells
+ AuraEffectList const& mOwnerTaken = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_FROM_CASTER);
+ for (AuraEffectList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i)
+ if ((*i)->GetCasterGUID() == GetGUID() && (*i)->IsAffectedOnSpell(spellProto))
+ TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
+
+ // Mod damage from spell mechanic
+ if (uint32 mechanicMask = GetAllSpellMechanicMask(spellProto))
+ {
+ AuraEffectList const& mDamageDoneMechanic = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT);
+ for (AuraEffectList::const_iterator i = mDamageDoneMechanic.begin(); i != mDamageDoneMechanic.end(); ++i)
+ if (mechanicMask & uint32(1<<((*i)->GetMiscValue())))
+ TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
+ }
+
+ // Taken/Done fixed damage bonus auras
+ int32 DoneAdvertisedBenefit = SpellBaseDamageBonus(GetSpellSchoolMask(spellProto));
+ int32 TakenAdvertisedBenefit = SpellBaseDamageBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
+ // Pets just add their bonus damage to their spell damage
+ // note that their spell damage is just gain of their own auras
+ if (HasUnitTypeMask(UNIT_MASK_GUARDIAN))
+ DoneAdvertisedBenefit += ((Guardian*)this)->GetBonusDamage();
+
+ // Check for table values
+ float coeff = 0;
+ SpellBonusEntry const *bonus = spellmgr.GetSpellBonusData(spellProto->Id);
+ if (bonus)
+ {
+ if (damagetype == DOT)
+ {
+ coeff = bonus->dot_damage;
+ if (bonus->ap_dot_bonus > 0)
+ DoneTotal += bonus->ap_dot_bonus * stack * ApCoeffMod * GetTotalAttackPowerValue(
+ (IsRangedWeaponSpell(spellProto) && spellProto->DmgClass !=SPELL_DAMAGE_CLASS_MELEE) ? RANGED_ATTACK : BASE_ATTACK);
+ }
+ else
+ {
+ coeff = bonus->direct_damage;
+ if (bonus->ap_bonus > 0)
+ DoneTotal += bonus->ap_bonus * stack * ApCoeffMod * GetTotalAttackPowerValue(
+ (IsRangedWeaponSpell(spellProto) && spellProto->DmgClass !=SPELL_DAMAGE_CLASS_MELEE)? RANGED_ATTACK : BASE_ATTACK);
+ }
+ }
+ // Default calculation
+ if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
+ {
+ if (!bonus || coeff < 0)
+ {
+ // Damage Done from spell damage bonus
+ int32 CastingTime = IsChanneledSpell(spellProto) ? GetSpellDuration(spellProto) : GetSpellCastTime(spellProto);
+ // Damage over Time spells bonus calculation
+ float DotFactor = 1.0f;
+ if (damagetype == DOT)
+ {
+ int32 DotDuration = GetSpellDuration(spellProto);
+ // 200% limit
+ if (DotDuration > 0)
+ {
+ if (DotDuration > 30000)
+ DotDuration = 30000;
+ if (!IsChanneledSpell(spellProto))
+ DotFactor = DotDuration / 15000.0f;
+ uint8 x = 0;
+ for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j)
+ {
+ if (spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
+ spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
+ spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH))
+ {
+ x = j;
+ break;
+ }
+ }
+ int32 DotTicks = 6;
+ if (spellProto->EffectAmplitude[x] != 0)
+ DotTicks = DotDuration / spellProto->EffectAmplitude[x];
+ if (DotTicks)
+ {
+ DoneAdvertisedBenefit /= DotTicks;
+ TakenAdvertisedBenefit /= DotTicks;
+ }
+ }
+ }
+ // Distribute Damage over multiple effects, reduce by AoE
+ CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
+
+ // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
+ for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j)
+ {
+ if (spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
+ spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH)
+ {
+ CastingTime /= 2;
+ break;
+ }
+ }
+ if (spellProto->SchoolMask != SPELL_SCHOOL_MASK_NORMAL)
+ coeff = (CastingTime / 3500.0f) * DotFactor;
+ else
+ coeff = DotFactor;
+ }
+
+ float coeff2 = CalculateLevelPenalty(spellProto) * stack;
+ if (spellProto->SpellFamilyName) //TODO: fix this
+ TakenTotal+= TakenAdvertisedBenefit * coeff * coeff2;
+ if (Player* modOwner = GetSpellModOwner())
+ {
+ coeff *= 100.0f;
+ modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_SPELL_BONUS_DAMAGE, coeff);
+ coeff /= 100.0f;
+ }
+ DoneTotal += DoneAdvertisedBenefit * coeff * coeff2;
+ }
+
+ float tmpDamage = (int32(pdamage) + DoneTotal) * DoneTotalMod;
+ // apply spellmod to Done damage (flat and pct)
+ if (Player* modOwner = GetSpellModOwner())
+ modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
+
+ tmpDamage = (tmpDamage + TakenTotal) * TakenTotalMod;
+
+ return uint32(std::max(tmpDamage, 0.0f));
+}
+
+int32 Unit::SpellBaseDamageBonus(SpellSchoolMask schoolMask)
+{
+ int32 DoneAdvertisedBenefit = 0;
+
+ // ..done
+ AuraEffectList const& mDamageDone = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE);
+ for (AuraEffectList::const_iterator i = mDamageDone.begin(); i != mDamageDone.end(); ++i)
+ if (((*i)->GetMiscValue() & schoolMask) != 0 &&
+ (*i)->GetSpellProto()->EquippedItemClass == -1 &&
+ // -1 == any item class (not wand then)
+ (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
+ // 0 == any inventory type (not wand then)
+ DoneAdvertisedBenefit += (*i)->GetAmount();
+
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ // Base value
+ DoneAdvertisedBenefit +=((Player*)this)->GetBaseSpellPowerBonus();
+
+ // Damage bonus from stats
+ AuraEffectList const& mDamageDoneOfStatPercent = GetAuraEffectsByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT);
+ for (AuraEffectList::const_iterator i = mDamageDoneOfStatPercent.begin(); i != mDamageDoneOfStatPercent.end(); ++i)
+ {
+ if ((*i)->GetMiscValue() & schoolMask)
+ {
+ // stat used stored in miscValueB for this aura
+ Stats usedStat = Stats((*i)->GetMiscValueB());
+ DoneAdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetAmount() / 100.0f);
+ }
+ }
+ // ... and attack power
+ AuraEffectList const& mDamageDonebyAP = GetAuraEffectsByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER);
+ for (AuraEffectList::const_iterator i =mDamageDonebyAP.begin(); i != mDamageDonebyAP.end(); ++i)
+ if ((*i)->GetMiscValue() & schoolMask)
+ DoneAdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetAmount() / 100.0f);
+
+ }
+ return DoneAdvertisedBenefit > 0 ? DoneAdvertisedBenefit : 0;
+}
+
+int32 Unit::SpellBaseDamageBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
+{
+ uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
+
+ int32 TakenAdvertisedBenefit = 0;
+ // ..done (for creature type by mask) in taken
+ AuraEffectList const& mDamageDoneCreature = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
+ for (AuraEffectList::const_iterator i = mDamageDoneCreature.begin(); i != mDamageDoneCreature.end(); ++i)
+ if (creatureTypeMask & uint32((*i)->GetMiscValue()))
+ TakenAdvertisedBenefit += (*i)->GetAmount();
+
+ // ..taken
+ AuraEffectList const& mDamageTaken = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
+ for (AuraEffectList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i)
+ if (((*i)->GetMiscValue() & schoolMask) != 0)
+ TakenAdvertisedBenefit += (*i)->GetAmount();
+
+ return TakenAdvertisedBenefit > 0 ? TakenAdvertisedBenefit : 0;
+}
+
+bool Unit::isSpellCrit(Unit *pVictim, SpellEntry const *spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType) const
+{
+ // not critting spell
+ if ((spellProto->AttributesEx2 & SPELL_ATTR_EX2_CANT_CRIT))
+ return false;
+
+ float crit_chance = 0.0f;
+ switch(spellProto->DmgClass)
+ {
+ case SPELL_DAMAGE_CLASS_NONE: // Exception for Earth Shield and Lifebloom Final Bloom
+ if (spellProto->Id != 379 && spellProto->Id != 33778) // We need more spells to find a general way (if there is any)
+ return false;
+ case SPELL_DAMAGE_CLASS_MAGIC:
+ {
+ if (schoolMask & SPELL_SCHOOL_MASK_NORMAL)
+ crit_chance = 0.0f;
+ // For other schools
+ else if (GetTypeId() == TYPEID_PLAYER)
+ crit_chance = GetFloatValue( PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask));
+ else
+ {
+ crit_chance = m_baseSpellCritChance;
+ crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
+ }
+ // taken
+ if (pVictim)
+ {
+ if (!IsPositiveSpell(spellProto->Id))
+ {
+ // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE
+ crit_chance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask);
+ // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE
+ crit_chance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
+ // Modify by player victim resilience
+ crit_chance -= pVictim->GetSpellCritChanceReduction();
+ }
+ // scripted (increase crit chance ... against ... target by x%
+ AuraEffectList const& mOverrideClassScript = GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
+ for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
+ {
+ if (!((*i)->IsAffectedOnSpell(spellProto)))
+ continue;
+ int32 modChance=0;
+ switch((*i)->GetMiscValue())
+ {
+ // Shatter
+ case 911: modChance+= 16.0f;
+ case 910: modChance+= 17.0f;
+ case 849: modChance+= 17.0f;
+ if (!pVictim->HasAuraState(AURA_STATE_FROZEN, spellProto, this))
+ break;
+ crit_chance+=modChance;
+ break;
+ case 7917: // Glyph of Shadowburn
+ if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this))
+ crit_chance+=(*i)->GetAmount();
+ break;
+ case 7997: // Renewed Hope
+ case 7998:
+ if (pVictim->HasAura(6788))
+ crit_chance+=(*i)->GetAmount();
+ break;
+ case 21: // Test of Faith
+ case 6935:
+ case 6918:
+ if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
+ crit_chance+=(*i)->GetAmount();
+ break;
+ default:
+ break;
+ }
+ }
+ // Custom crit by class
+ switch(spellProto->SpellFamilyName)
+ {
+ case SPELLFAMILY_DRUID:
+ // Starfire
+ if (spellProto->SpellFamilyFlags[0] & 0x4 && spellProto->SpellIconID == 1485)
+ {
+ // Improved Insect Swarm
+ if (AuraEffect const * aurEff = GetDummyAuraEffect(SPELLFAMILY_DRUID, 1771, 0))
+ if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x00000002, 0, 0))
+ crit_chance+=aurEff->GetAmount();
+ break;
+ }
+ break;
+ case SPELLFAMILY_PALADIN:
+ // Flash of light
+ if (spellProto->SpellFamilyFlags[0] & 0x40000000)
+ {
+ // Sacred Shield
+ AuraEffect const* aura = pVictim->GetAuraEffect(58597,1);
+ if (aura && aura->GetCasterGUID() == GetGUID())
+ crit_chance+=aura->GetAmount();
+ break;
+ }
+ // Exorcism
+ else if (spellProto->Category == 19)
+ {
+ if (pVictim->GetCreatureTypeMask() & CREATURE_TYPEMASK_DEMON_OR_UNDEAD)
+ return true;
+ break;
+ }
+ break;
+ case SPELLFAMILY_SHAMAN:
+ // Lava Burst
+ if (spellProto->SpellFamilyFlags[1] & 0x00001000)
+ {
+ if (AuraEffect const* flameShock = pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, 0x10000000, 0,0, GetGUID()))
+ return true;
+ break;
+ }
+ break;
+ }
+ }
+ break;
+ }
+ case SPELL_DAMAGE_CLASS_MELEE:
+ if (pVictim)
+ {
+ // Custom crit by class
+ switch(spellProto->SpellFamilyName)
+ {
+ case SPELLFAMILY_DRUID:
+ // Rend and Tear - bonus crit chance for Ferocious Bite on bleeding targets
+ if (spellProto->SpellFamilyFlags[0] & 0x00800000
+ && spellProto->SpellIconID == 1680
+ && pVictim->HasAuraState(AURA_STATE_BLEEDING))
+ {
+ if (AuraEffect const *rendAndTear = GetDummyAuraEffect(SPELLFAMILY_DRUID, 2859, 1))
+ crit_chance += rendAndTear->GetAmount();
+ break;
+ }
+ break;
+ case SPELLFAMILY_PALADIN:
+ // Judgement of Command proc always crits on stunned target
+ if (spellProto->SpellFamilyName == SPELLFAMILY_PALADIN)
+ if (spellProto->SpellFamilyFlags[0] & 0x0000000000800000LL && spellProto->SpellIconID == 561)
+ if (pVictim->hasUnitState(UNIT_STAT_STUNNED))
+ return true;
+ }
+ }
+ case SPELL_DAMAGE_CLASS_RANGED:
+ {
+ if (pVictim)
+ {
+ crit_chance += GetUnitCriticalChance(attackType, pVictim);
+ crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
+ }
+ break;
+ }
+ default:
+ return false;
+ }
+ // percent done
+ // only players use intelligence for critical chance computations
+ if (Player* modOwner = GetSpellModOwner())
+ modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance);
+
+ crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f;
+ if (roll_chance_f(crit_chance))
+ return true;
+ return false;
+}
+
+uint32 Unit::SpellCriticalDamageBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
+{
+ // Calculate critical bonus
+ int32 crit_bonus;
+ switch(spellProto->DmgClass)
+ {
+ case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
+ case SPELL_DAMAGE_CLASS_RANGED:
+ // TODO: write here full calculation for melee/ranged spells
+ crit_bonus = damage;
+ break;
+ default:
+ crit_bonus = damage / 2; // for spells is 50%
+ break;
+ }
+
+ // adds additional damage to crit_bonus (from talents)
+ if (Player* modOwner = GetSpellModOwner())
+ modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
+
+ if (pVictim)
+ {
+ uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
+ crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
+ }
+
+ if (crit_bonus > 0)
+ damage += crit_bonus;
+
+ return damage;
+}
+
+uint32 Unit::SpellCriticalHealingBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
+{
+ // Calculate critical bonus
+ int32 crit_bonus;
+ switch(spellProto->DmgClass)
+ {
+ case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
+ case SPELL_DAMAGE_CLASS_RANGED:
+ // TODO: write here full calculation for melee/ranged spells
+ crit_bonus = damage;
+ break;
+ default:
+ crit_bonus = damage / 2; // for spells is 50%
+ break;
+ }
+
+ if (pVictim)
+ {
+ uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
+ crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
+ }
+
+ if (crit_bonus > 0)
+ damage += crit_bonus;
+
+ damage = int32(float(damage) * GetTotalAuraMultiplier(SPELL_AURA_MOD_CRITICAL_HEALING_AMOUNT));
+
+ return damage;
+}
+
+uint32 Unit::SpellHealingBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 healamount, DamageEffectType damagetype, uint32 stack)
+{
+ // For totems get healing bonus from owner (statue isn't totem in fact)
+ if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isTotem())
+ if (Unit* owner = GetOwner())
+ return owner->SpellHealingBonus(pVictim, spellProto, healamount, damagetype, stack);
+
+ // Healing Done
+ // Taken/Done total percent damage auras
+ float DoneTotalMod = 1.0f;
+ float TakenTotalMod = 1.0f;
+ int32 DoneTotal = 0;
+ int32 TakenTotal = 0;
+
+ // Healing done percent
+ AuraEffectList const& mHealingDonePct = GetAuraEffectsByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT);
+ for (AuraEffectList::const_iterator i = mHealingDonePct.begin(); i != mHealingDonePct.end(); ++i)
+ DoneTotalMod *= (100.0f + (*i)->GetAmount()) / 100.0f;
+
+ // done scripted mod (take it from owner)
+ Unit *owner = GetOwner() ? GetOwner() : this;
+ AuraEffectList const &mOverrideClassScript= owner->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
+ for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
+ {
+ if (!(*i)->IsAffectedOnSpell(spellProto))
+ continue;
+ switch((*i)->GetMiscValue())
+ {
+ case 4415: // Increased Rejuvenation Healing
+ case 4953:
+ case 3736: // Hateful Totem of the Third Wind / Increased Lesser Healing Wave / LK Arena (4/5/6) Totem of the Third Wind / Savage Totem of the Third Wind
+ DoneTotal+=(*i)->GetAmount();
+ break;
+ case 7997: // Renewed Hope
+ case 7998:
+ if (pVictim->HasAura(6788))
+ DoneTotalMod *=((*i)->GetAmount() + 100.0f)/100.0f;
+ break;
+ case 21: // Test of Faith
+ case 6935:
+ case 6918:
+ if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
+ DoneTotalMod *=((*i)->GetAmount() + 100.0f)/100.0f;
+ break;
+ case 7798: // Glyph of Regrowth
+ {
+ if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, 0x40, 0, 0))
+ DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
+ break;
+ }
+ case 8477: // Nourish Heal Boost
+ {
+ int32 stepPercent = (*i)->GetAmount();
+ int32 modPercent = 0;
+ AuraApplicationMap const& victimAuras = pVictim->GetAppliedAuras();
+ for (AuraApplicationMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
+ {
+ Aura const * aura = itr->second->GetBase();
+ if (aura->GetCasterGUID()!=GetGUID())
+ continue;
+ SpellEntry const* m_spell = aura->GetSpellProto();
+ if ( m_spell->SpellFamilyName != SPELLFAMILY_DRUID ||
+ !(m_spell->SpellFamilyFlags[1] & 0x00000010 || m_spell->SpellFamilyFlags[0] & 0x50))
+ continue;
+ modPercent += stepPercent * aura->GetStackAmount();
+ }
+ DoneTotalMod *= (modPercent+100.0f)/100.0f;
+ break;
+ }
+ case 7871: // Glyph of Lesser Healing Wave
+ {
+ if (pVictim->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, 0 , 0x00000400, 0, GetGUID()))
+ DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
+ break;
+ }
+ default:
+ break;
+ }
+ }
+
+ // Taken/Done fixed damage bonus auras
+ int32 DoneAdvertisedBenefit = SpellBaseHealingBonus(GetSpellSchoolMask(spellProto));
+ int32 TakenAdvertisedBenefit = SpellBaseHealingBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
+
+ bool scripted = false;
+
+ for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
+ {
+ switch (spellProto->EffectApplyAuraName[i])
+ {
+ // These auras do not use healing coeff
+ case SPELL_AURA_PERIODIC_LEECH:
+ case SPELL_AURA_PERIODIC_HEALTH_FUNNEL:
+ scripted = true;
+ break;
+ }
+ }
+
+ // Check for table values
+ SpellBonusEntry const* bonus = !scripted ? spellmgr.GetSpellBonusData(spellProto->Id) : NULL;
+ float coeff = 0;
+ float factorMod = 1.0f;
+ if (bonus)
+ {
+ if (damagetype == DOT)
+ {
+ coeff = bonus->dot_damage;
+ if (bonus->ap_dot_bonus > 0)
+ DoneTotal+=bonus->ap_dot_bonus * stack * GetTotalAttackPowerValue(
+ (IsRangedWeaponSpell(spellProto) && spellProto->DmgClass !=SPELL_DAMAGE_CLASS_MELEE)? RANGED_ATTACK : BASE_ATTACK);
+ }
+ else
+ {
+ coeff = bonus->direct_damage;
+ if (bonus->ap_bonus > 0)
+ DoneTotal+=bonus->ap_bonus * stack * GetTotalAttackPowerValue(
+ (IsRangedWeaponSpell(spellProto) && spellProto->DmgClass !=SPELL_DAMAGE_CLASS_MELEE)? RANGED_ATTACK : BASE_ATTACK);
+ }
+ }
+ else // scripted bonus
+ {
+ // Gift of the Naaru
+ if (spellProto->SpellFamilyFlags[2] & 0x80000000 && spellProto->SpellIconID == 329)
+ {
+ scripted = true;
+ int32 apBonus = std::max(GetTotalAttackPowerValue(BASE_ATTACK), GetTotalAttackPowerValue(RANGED_ATTACK));
+ if (apBonus > DoneAdvertisedBenefit)
+ {
+ DoneTotal += apBonus * 0.2f;
+ coeff = 0.0f;
+ }
+ else
+ coeff = 1.0f;
+ }
+ // Earthliving - 0.45% of normal hot coeff
+ else if (spellProto->SpellFamilyName==SPELLFAMILY_SHAMAN && spellProto->SpellFamilyFlags[1] & 0x80000)
+ factorMod *= 0.45f;
+ // Already set to scripted? so not uses healing bonus coefficient
+ // No heal coeff for SPELL_DAMAGE_CLASS_NONE class spells by default
+ else if (scripted || spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE)
+ {
+ scripted = true;
+ coeff = 0.0f;
+ }
+ }
+
+ // Default calculation
+ if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
+ {
+ if ((!bonus && !scripted) || coeff < 0)
+ {
+ // Damage Done from spell damage bonus
+ int32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
+ // Damage over Time spells bonus calculation
+ float DotFactor = 1.0f;
+ if (damagetype == DOT)
+ {
+ int32 DotDuration = GetSpellDuration(spellProto);
+ // 200% limit
+ if (DotDuration > 0)
+ {
+ if (DotDuration > 30000) DotDuration = 30000;
+ if (!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
+ uint32 x = 0;
+ for (uint8 j = 0; j < MAX_SPELL_EFFECTS; j++)
+ {
+ if (spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
+ spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
+ spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH))
+ {
+ x = j;
+ break;
+ }
+ }
+ int32 DotTicks = 6;
+ if (spellProto->EffectAmplitude[x] != 0)
+ DotTicks = DotDuration / spellProto->EffectAmplitude[x];
+ if (DotTicks)
+ {
+ DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
+ TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
+ }
+ }
+ }
+ // Distribute Damage over multiple effects, reduce by AoE
+ CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
+ // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
+ for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j)
+ {
+ if (spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
+ spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
+ {
+ CastingTime /= 2;
+ break;
+ }
+ }
+ // As wowwiki says: C = (Cast Time / 3.5) * 1.88 (for healing spells)
+ coeff = (CastingTime / 3500.0f) * DotFactor * 1.88f;
+ }
+
+ factorMod *= CalculateLevelPenalty(spellProto)* stack;
+ TakenTotal += TakenAdvertisedBenefit * coeff * factorMod;
+ if (Player* modOwner = GetSpellModOwner())
+ {
+ coeff *= 100.0f;
+ modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_SPELL_BONUS_DAMAGE, coeff);
+ coeff /= 100.0f;
+ }
+ DoneTotal += DoneAdvertisedBenefit * coeff * factorMod;
+ }
+
+ // use float as more appropriate for negative values and percent applying
+ float heal = (int32(healamount) + DoneTotal) * DoneTotalMod;
+ // apply spellmod to Done amount
+ if (Player* modOwner = GetSpellModOwner())
+ modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal);
+
+ // Nourish cast
+ if (spellProto->SpellFamilyName == SPELLFAMILY_DRUID && spellProto->SpellFamilyFlags[1] & 0x2000000)
+ {
+ // Rejuvenation, Regrowth, Lifebloom, or Wild Growth
+ if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, 0x50, 0x4000010, 0))
+ //increase healing by 20%
+ TakenTotalMod *= 1.2f;
+ }
+
+ // Taken mods
+
+ // Healing Wave
+ if (spellProto->SpellFamilyName == SPELLFAMILY_SHAMAN && spellProto->SpellFamilyFlags[0] & 0x40)
+ {
+ // Search for Healing Way on Victim
+ if (AuraEffect const* HealingWay = pVictim->GetAuraEffect(29203, 0))
+ TakenTotalMod *= (HealingWay->GetAmount() + 100.0f) / 100.0f;
+ }
+
+ // Tenacity increase healing % taken
+ if (AuraEffect const* Tenacity = pVictim->GetAuraEffect(58549, 0))
+ TakenTotalMod *= (Tenacity->GetAmount() + 100.0f) / 100.0f;
+
+
+ // Healing taken percent
+ float minval = pVictim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
+ if (minval)
+ TakenTotalMod *= (100.0f + minval) / 100.0f;
+
+ float maxval = pVictim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
+ if (maxval)
+ TakenTotalMod *= (100.0f + maxval) / 100.0f;
+
+ if (damagetype == DOT)
+ {
+ // Healing over time taken percent
+ float minval_hot = pVictim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HOT_PCT);
+ if (minval_hot)
+ TakenTotalMod *= (100.0f + minval_hot) / 100.0f;
+
+ float maxval_hot = pVictim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HOT_PCT);
+ if (maxval_hot)
+ TakenTotalMod *= (100.0f + maxval_hot) / 100.0f;
+ }
+
+ AuraEffectList const& mHealingGet= pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_HEALING_RECEIVED);
+ for (AuraEffectList::const_iterator i = mHealingGet.begin(); i != mHealingGet.end(); ++i)
+ if (GetGUID()==(*i)->GetCasterGUID() && (*i)->IsAffectedOnSpell(spellProto) )
+ TakenTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f;
+
+ heal = (int32(heal) + TakenTotal) * TakenTotalMod;
+
+ return uint32(std::max(heal, 0.0f));
+}
+
+int32 Unit::SpellBaseHealingBonus(SpellSchoolMask schoolMask)
+{
+ int32 AdvertisedBenefit = 0;
+
+ AuraEffectList const& mHealingDone = GetAuraEffectsByType(SPELL_AURA_MOD_HEALING_DONE);
+ for (AuraEffectList::const_iterator i = mHealingDone.begin(); i != mHealingDone.end(); ++i)
+ if (((*i)->GetMiscValue() & schoolMask) != 0)
+ AdvertisedBenefit += (*i)->GetAmount();
+
+ // Healing bonus of spirit, intellect and strength
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ // Base value
+ AdvertisedBenefit +=((Player*)this)->GetBaseSpellPowerBonus();
+
+ // Healing bonus from stats
+ AuraEffectList const& mHealingDoneOfStatPercent = GetAuraEffectsByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT);
+ for (AuraEffectList::const_iterator i = mHealingDoneOfStatPercent.begin(); i != mHealingDoneOfStatPercent.end(); ++i)
+ {
+ // stat used dependent from misc value (stat index)
+ Stats usedStat = Stats((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()]);
+ AdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetAmount() / 100.0f);
+ }
+
+ // ... and attack power
+ AuraEffectList const& mHealingDonebyAP = GetAuraEffectsByType(SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER);
+ for (AuraEffectList::const_iterator i = mHealingDonebyAP.begin(); i != mHealingDonebyAP.end(); ++i)
+ if ((*i)->GetMiscValue() & schoolMask)
+ AdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetAmount() / 100.0f);
+ }
+ return AdvertisedBenefit;
+}
+
+int32 Unit::SpellBaseHealingBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
+{
+ int32 AdvertisedBenefit = 0;
+ AuraEffectList const& mDamageTaken = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_HEALING);
+ for (AuraEffectList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i)
+ if (((*i)->GetMiscValue() & schoolMask) != 0)
+ AdvertisedBenefit += (*i)->GetAmount();
+ return AdvertisedBenefit;
+}
+
+bool Unit::IsImmunedToDamage(SpellSchoolMask shoolMask)
+{
+ //If m_immuneToSchool type contain this school type, IMMUNE damage.
+ SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
+ for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
+ if (itr->type & shoolMask)
+ return true;
+
+ //If m_immuneToDamage type contain magic, IMMUNE damage.
+ SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
+ for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
+ if (itr->type & shoolMask)
+ return true;
+
+ return false;
+}
+
+bool Unit::IsImmunedToDamage(SpellEntry const* spellInfo)
+{
+ if (spellInfo->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY)
+ return false;
+
+ uint32 shoolMask = GetSpellSchoolMask(spellInfo);
+ if (spellInfo->Id != 42292 && spellInfo->Id !=59752)
+ {
+ //If m_immuneToSchool type contain this school type, IMMUNE damage.
+ SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
+ for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
+ if (itr->type & shoolMask &&!IsDispelableBySpell(spellInfo, itr->spellId))
+ return true;
+ }
+
+ //If m_immuneToDamage type contain magic, IMMUNE damage.
+ SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
+ for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
+ if (itr->type & shoolMask)
+ return true;
+
+ return false;
+}
+
+bool Unit::IsImmunedToSpell(SpellEntry const* spellInfo)
+{
+ if (!spellInfo)
+ return false;
+
+ // Single spell immunity.
+ SpellImmuneList const& idList = m_spellImmune[IMMUNITY_ID];
+ for (SpellImmuneList::const_iterator itr = idList.begin(); itr != idList.end(); ++itr)
+ if (itr->type == spellInfo->Id)
+ return true;
+
+ if (spellInfo->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY)
+ return false;
+
+ if (spellInfo->Dispel)
+ {
+ SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_DISPEL];
+ for (SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr)
+ if (itr->type == spellInfo->Dispel)
+ return true;
+ }
+
+ if (spellInfo->Mechanic)
+ {
+ SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
+ for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
+ if (itr->type == spellInfo->Mechanic)
+ return true;
+ }
+
+ for (int i=0;i<3;++i)
+ {
+ // State/effect immunities applied by aura expect full spell immunity
+ // Ignore effects with mechanic, they are supposed to be checked separately
+ if (!spellInfo->EffectMechanic[i])
+ if (IsImmunedToSpellEffect(spellInfo, i))
+ return true;
+ }
+
+ if (spellInfo->Id != 42292 && spellInfo->Id !=59752)
+ {
+ SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
+ for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
+ if ((itr->type & GetSpellSchoolMask(spellInfo))
+ && !(IsPositiveSpell(itr->spellId) && IsPositiveSpell(spellInfo->Id))
+ && !IsDispelableBySpell(spellInfo, itr->spellId))
+ return true;
+ }
+
+ return false;
+}
+
+bool Unit::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
+{
+ if (!spellInfo)
+ return false;
+ //If m_immuneToEffect type contain this effect type, IMMUNE effect.
+ uint32 effect = spellInfo->Effect[index];
+ SpellImmuneList const& effectList = m_spellImmune[IMMUNITY_EFFECT];
+ for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr)
+ if (itr->type == effect)
+ return true;
+
+ if (uint32 mechanic = spellInfo->EffectMechanic[index])
+ {
+ SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
+ for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
+ if (itr->type == spellInfo->EffectMechanic[index])
+ return true;
+ }
+
+ if (uint32 aura = spellInfo->EffectApplyAuraName[index])
+ {
+ SpellImmuneList const& list = m_spellImmune[IMMUNITY_STATE];
+ for (SpellImmuneList::const_iterator itr = list.begin(); itr != list.end(); ++itr)
+ if (itr->type == aura)
+ return true;
+ // Check for immune to application of harmful magical effects
+ AuraEffectList const& immuneAuraApply = GetAuraEffectsByType(SPELL_AURA_MOD_IMMUNE_AURA_APPLY_SCHOOL);
+ for (AuraEffectList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
+ if (spellInfo->Dispel == DISPEL_MAGIC && // Magic debuff
+ ((*iter)->GetMiscValue() & GetSpellSchoolMask(spellInfo)) && // Check school
+ !IsPositiveEffect(spellInfo->Id, index)) // Harmful
+ return true;
+ }
+
+ return false;
+}
+
+bool Unit::IsDamageToThreatSpell(SpellEntry const * spellInfo) const
+{
+ if (!spellInfo)
+ return false;
+
+ switch(spellInfo->SpellFamilyName)
+ {
+ case SPELLFAMILY_WARLOCK:
+ if (spellInfo->SpellFamilyFlags[0] == 0x100) // Searing Pain
+ return true;
+ break;
+ case SPELLFAMILY_SHAMAN:
+ if (spellInfo->SpellFamilyFlags[0] == SPELLFAMILYFLAG_SHAMAN_FROST_SHOCK)
+ return true;
+ break;
+ case SPELLFAMILY_DEATHKNIGHT:
+ if (spellInfo->SpellFamilyFlags[1] == 0x20000000) // Rune Strike
+ return true;
+ break;
+ }
+
+ return false;
+}
+
+void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage, WeaponAttackType attType, SpellEntry const *spellProto)
+{
+ if (!pVictim)
+ return;
+
+ if (*pdamage == 0)
+ return;
+
+ uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
+
+ // Taken/Done fixed damage bonus auras
+ int32 DoneFlatBenefit = 0;
+ int32 TakenFlatBenefit = 0;
+
+ // ..done (for creature type by mask) in taken
+ AuraEffectList const& mDamageDoneCreature = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
+ for (AuraEffectList::const_iterator i = mDamageDoneCreature.begin(); i != mDamageDoneCreature.end(); ++i)
+ if (creatureTypeMask & uint32((*i)->GetMiscValue()))
+ DoneFlatBenefit += (*i)->GetAmount();
+
+ // ..done
+ // SPELL_AURA_MOD_DAMAGE_DONE included in weapon damage
+
+ // ..done (base at attack power for marked target and base at attack power for creature type)
+ int32 APbonus = 0;
+
+ if (attType == RANGED_ATTACK && pVictim->GetTypeId() == TYPEID_UNIT)
+ {
+ APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_RANGED_AP_ATTACKER_CREATURES_BONUS);
+
+ // ..done (base at attack power and creature type)
+ AuraEffectList const& mCreatureAttackPower = GetAuraEffectsByType(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS);
+ for (AuraEffectList::const_iterator i = mCreatureAttackPower.begin(); i != mCreatureAttackPower.end(); ++i)
+ if (creatureTypeMask & uint32((*i)->GetMiscValue()))
+ APbonus += (*i)->GetAmount();
+ }
+ else if (attType == RANGED_ATTACK)
+ {
+ APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS);
+
+ // ..done (base at attack power and creature type)
+ AuraEffectList const& mCreatureAttackPower = GetAuraEffectsByType(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS);
+ for (AuraEffectList::const_iterator i = mCreatureAttackPower.begin(); i != mCreatureAttackPower.end(); ++i)
+ if (creatureTypeMask & uint32((*i)->GetMiscValue()))
+ APbonus += (*i)->GetAmount();
+ }
+ else
+ {
+ APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS);
+
+ // ..done (base at attack power and creature type)
+ AuraEffectList const& mCreatureAttackPower = GetAuraEffectsByType(SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS);
+ for (AuraEffectList::const_iterator i = mCreatureAttackPower.begin(); i != mCreatureAttackPower.end(); ++i)
+ if (creatureTypeMask & uint32((*i)->GetMiscValue()))
+ APbonus += (*i)->GetAmount();
+ }
+
+ if (APbonus != 0) // Can be negative
+ {
+ bool normalized = false;
+ if (spellProto)
+ for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
+ if (spellProto->Effect[i] == SPELL_EFFECT_NORMALIZED_WEAPON_DMG)
+ {
+ normalized = true;
+ break;
+ }
+ DoneFlatBenefit += int32(APbonus/14.0f * GetAPMultiplier(attType,normalized));
+ }
+
+ // ..taken
+ AuraEffectList const& mDamageTaken = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
+ for (AuraEffectList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i)
+ if ((*i)->GetMiscValue() & GetMeleeDamageSchoolMask())
+ TakenFlatBenefit += (*i)->GetAmount();
+
+ if (attType!=RANGED_ATTACK)
+ TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN);
+ else
+ TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN);
+
+ // Done/Taken total percent damage auras
+ float DoneTotalMod = 1.0f;
+ float TakenTotalMod = 1.0f;
+
+ // ..done
+ // SPELL_AURA_MOD_DAMAGE_PERCENT_DONE included in weapon damage
+ // SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT included in weapon damage
+
+ // SPELL_AURA_MOD_DAMAGE_PERCENT_DONE for non-physical spells like Scourge Strike, Frost Strike, this is NOT included in weapon damage
+ if (spellProto)
+ if (GetSpellSchoolMask(spellProto) != SPELL_SCHOOL_MASK_NORMAL)
+ {
+ AuraEffectList const &mModDamagePercentDone = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
+ for (AuraEffectList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
+ if (((*i)->GetMiscValue() & GetSpellSchoolMask(spellProto)) && !((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL))
+ DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
+ }
+
+ AuraEffectList const &mDamageDoneVersus = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
+ for (AuraEffectList::const_iterator i = mDamageDoneVersus.begin(); i != mDamageDoneVersus.end(); ++i)
+ if (creatureTypeMask & uint32((*i)->GetMiscValue()))
+ DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
+
+ // done scripted mod (take it from owner)
+ Unit *owner = GetOwner() ? GetOwner() : this;
+ AuraEffectList const &mOverrideClassScript= owner->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
+ for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
+ {
+ if (!(*i)->IsAffectedOnSpell(spellProto))
+ continue;
+ switch ((*i)->GetMiscValue())
+ {
+ // Tundra Stalker
+ // Merciless Combat
+ case 7277:
+ {
+ // Merciless Combat
+ if ((*i)->GetSpellProto()->SpellIconID == 2656)
+ {
+ if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this))
+ DoneTotalMod *= (100.0f+(*i)->GetAmount())/100.0f;
+ }
+ // Tundra Stalker
+ else
+ {
+ // Frost Fever (target debuff)
+ if (pVictim->HasAura(55095))
+ DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
+ }
+ break;
+ }
+ // Rage of Rivendare
+ case 7293:
+ {
+ if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0,0x02000000,0))
+ if (SpellChainNode const *chain = spellmgr.GetSpellChainNode((*i)->GetId()))
+ DoneTotalMod *= (chain->rank * 2.0f + 100.0f)/100.0f;
+ break;
+ }
+ }
+ }
+
+ // Custom scripted damage
+ if (spellProto)
+ switch(spellProto->SpellFamilyName)
+ {
+ case SPELLFAMILY_DEATHKNIGHT:
+ // Glacier Rot
+ if (spellProto->SpellFamilyFlags[0] & 0x2 || spellProto->SpellFamilyFlags[1] & 0x6)
+ if (AuraEffect * aurEff = GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 196, 0))
+ if (pVictim->GetDiseasesByCaster(owner->GetGUID()) > 0)
+ DoneTotalMod *= (100.0f + aurEff->GetAmount()) / 100.0f;
+ break;
+ }
+
+ // ..taken
+ AuraEffectList const& mModDamagePercentTaken = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
+ for (AuraEffectList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
+ if ((*i)->GetMiscValue() & GetMeleeDamageSchoolMask())
+ TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
+
+ // .. taken pct (special attacks)
+ if (spellProto)
+ {
+ // Mod damage from spell mechanic
+ uint32 mechanicMask = GetAllSpellMechanicMask(spellProto);
+
+ // Shred, Maul - "Effects which increase Bleed damage also increase Shred damage"
+ if (spellProto->SpellFamilyName == SPELLFAMILY_DRUID && spellProto->SpellFamilyFlags[0] & 0x00008800)
+ mechanicMask |= (1<<MECHANIC_BLEED);
+
+ if (mechanicMask)
+ {
+ AuraEffectList const& mDamageDoneMechanic = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT);
+ for (AuraEffectList::const_iterator i = mDamageDoneMechanic.begin(); i != mDamageDoneMechanic.end(); ++i)
+ if (mechanicMask & uint32(1<<((*i)->GetMiscValue())))
+ TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
+ }
+ }
+
+ // .. taken pct: dummy auras
+ AuraEffectList const& mDummyAuras = pVictim->GetAuraEffectsByType(SPELL_AURA_DUMMY);
+ for (AuraEffectList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
+ {
+ switch((*i)->GetSpellProto()->SpellIconID)
+ {
+ //Cheat Death
+ case 2109:
+ if ((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL)
+ {
+ if (pVictim->GetTypeId() != TYPEID_PLAYER)
+ continue;
+ float mod = ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f);
+ if (mod < (*i)->GetAmount())
+ mod = (*i)->GetAmount();
+ TakenTotalMod *= (mod+100.0f)/100.0f;
+ }
+ break;
+ // Blessing of Sanctuary
+ // Greater Blessing of Sanctuary
+ case 19:
+ case 1804:
+ {
+ if ((*i)->GetSpellProto()->SpellFamilyName != SPELLFAMILY_PALADIN)
+ continue;
+
+ if ((*i)->GetMiscValue() & (spellProto ? GetSpellSchoolMask(spellProto) : 0))
+ TakenTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f;
+ break;
+ }
+ // Ebon Plague
+ case 1933:
+ if ((*i)->GetMiscValue() & (spellProto ? GetSpellSchoolMask(spellProto) : 0))
+ TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
+ break;
+ }
+ }
+
+ // .. taken pct: class scripts
+ AuraEffectList const& mclassScritAuras = GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
+ for (AuraEffectList::const_iterator i = mclassScritAuras.begin(); i != mclassScritAuras.end(); ++i)
+ {
+ switch((*i)->GetMiscValue())
+ {
+ case 6427: case 6428: // Dirty Deeds
+ if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this))
+ {
+ AuraEffect* eff0 = (*i)->GetBase()->GetEffect(0);
+ if (!eff0 || (*i)->GetEffIndex()!=1)
+ {
+ sLog.outError("Spell structure of DD (%u) changed.",(*i)->GetId());
+ continue;
+ }
+
+ // effect 0 have expected value but in negative state
+ TakenTotalMod *= (-eff0->GetAmount()+100.0f)/100.0f;
+ }
+ break;
+ }
+ }
+
+ if (attType != RANGED_ATTACK)
+ {
+ AuraEffectList const& mModMeleeDamageTakenPercent = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT);
+ for (AuraEffectList::const_iterator i = mModMeleeDamageTakenPercent.begin(); i != mModMeleeDamageTakenPercent.end(); ++i)
+ TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
+ }
+ else
+ {
+ AuraEffectList const& mModRangedDamageTakenPercent = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT);
+ for (AuraEffectList::const_iterator i = mModRangedDamageTakenPercent.begin(); i != mModRangedDamageTakenPercent.end(); ++i)
+ TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f;
+ }
+
+ float tmpDamage = float(int32(*pdamage) + DoneFlatBenefit) * DoneTotalMod;
+
+ // apply spellmod to Done damage
+ if (spellProto)
+ if (Player* modOwner = GetSpellModOwner())
+ modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, tmpDamage);
+
+ tmpDamage = (tmpDamage + TakenFlatBenefit)*TakenTotalMod;
+
+ // bonus result can be negative
+ *pdamage = uint32(std::max(tmpDamage, 0.0f));
+}
+
+void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply)
+{
+ if (apply)
+ {
+ for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(), next; itr != m_spellImmune[op].end(); itr = next)
+ {
+ next = itr; ++next;
+ if (itr->type == type)
+ {
+ m_spellImmune[op].erase(itr);
+ next = m_spellImmune[op].begin();
+ }
+ }
+ SpellImmune Immune;
+ Immune.spellId = spellId;
+ Immune.type = type;
+ m_spellImmune[op].push_back(Immune);
+ }
+ else
+ {
+ for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(); itr != m_spellImmune[op].end(); ++itr)
+ {
+ if (itr->spellId == spellId)
+ {
+ m_spellImmune[op].erase(itr);
+ break;
+ }
+ }
+ }
+
+}
+
+void Unit::ApplySpellDispelImmunity(const SpellEntry * spellProto, DispelType type, bool apply)
+{
+ ApplySpellImmune(spellProto->Id,IMMUNITY_DISPEL, type, apply);
+
+ if (apply && spellProto->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)
+ {
+ // Create dispel mask by dispel type
+ uint32 dispelMask = GetDispellMask(type);
+ // Dispel all existing auras vs current dispel type
+ AuraApplicationMap& auras = GetAppliedAuras();
+ for (AuraApplicationMap::iterator itr = auras.begin(); itr != auras.end();)
+ {
+ SpellEntry const* spell = itr->second->GetBase()->GetSpellProto();
+ if ((1<<spell->Dispel) & dispelMask )
+ {
+ // Dispel aura
+ RemoveAura(itr);
+ }
+ else
+ ++itr;
+ }
+ }
+}
+
+float Unit::GetWeaponProcChance() const
+{
+ // normalized proc chance for weapon attack speed
+ // (odd formula...)
+ if (isAttackReady(BASE_ATTACK))
+ return (GetAttackTime(BASE_ATTACK) * 1.8f / 1000.0f);
+ else if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
+ return (GetAttackTime(OFF_ATTACK) * 1.6f / 1000.0f);
+ return 0;
+}
+
+float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM, const SpellEntry * spellProto) const
+{
+ // proc per minute chance calculation
+ if (PPM <= 0) return 0.0f;
+ // Apply chance modifer aura
+ if (spellProto)
+ if (Player* modOwner = GetSpellModOwner())
+ modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_PROC_PER_MINUTE,PPM);
+
+ return uint32((WeaponSpeed * PPM) / 600.0f); // result is chance in percents (probability = Speed_in_sec * (PPM / 60))
+}
+
+void Unit::Mount(uint32 mount, uint32 VehicleId)
+{
+ RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNT);
+
+ if (mount)
+ SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount);
+
+ SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
+
+ // unsummon pet
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ Pet* pet = ((Player*)this)->GetPet();
+ if (pet)
+ {
+ BattleGround *bg = ((Player *)this)->GetBattleGround();
+ // don't unsummon pet in arena but SetFlag UNIT_FLAG_STUNNED to disable pet's interface
+ if (bg && bg->isArena())
+ pet->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
+ else
+ ((Player*)this)->UnsummonPetTemporaryIfAny();
+ }
+
+ if(VehicleId !=0)
+ {
+ if(VehicleEntry const *ve = sVehicleStore.LookupEntry(VehicleId))
+ {
+
+ if (CreateVehicleKit(VehicleId))
+ {
+ GetVehicleKit()->Reset();
+
+ // Send others that we now have a vehicle
+ WorldPacket data( SMSG_PLAYER_VEHICLE_DATA, GetPackGUID().size()+4);
+ data.appendPackGUID(GetGUID());
+ data << uint32(VehicleId);
+ SendMessageToSet( &data,true );
+
+ data.Initialize(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
+ ((Player*)this)->GetSession()->SendPacket( &data );
+ }
+ }
+ }
+ }
+
+}
+
+void Unit::Unmount()
+{
+ if (!IsMounted())
+ return;
+
+ RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED);
+
+ SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
+ RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
+
+ // only resummon old pet if the player is already added to a map
+ // this prevents adding a pet to a not created map which would otherwise cause a crash
+ // (it could probably happen when logging in after a previous crash)
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ if (Pet *pPet = ((Player*)this)->GetPet())
+ {
+ if (pPet && pPet->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED) && !pPet->hasUnitState(UNIT_STAT_STUNNED))
+ pPet->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
+ }
+ else
+ ((Player*)this)->ResummonPetTemporaryUnSummonedIfAny();
+ }
+ if(GetTypeId()==TYPEID_PLAYER && GetVehicleKit())
+ {
+ // Send other players that we are no longer a vehicle
+ WorldPacket data( SMSG_PLAYER_VEHICLE_DATA, 8+4 );
+ data.appendPackGUID(GetGUID());
+ data << uint32(0);
+ ((Player*)this)->SendMessageToSet(&data, true);
+ // Remove vehicle class from player
+ RemoveVehicleKit();
+ }
+}
+
+void Unit::SetInCombatWith(Unit* enemy)
+{
+ Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf();
+ if (eOwner->IsPvP())
+ {
+ SetInCombatState(true,enemy);
+ return;
+ }
+
+ //check for duel
+ if (eOwner->GetTypeId() == TYPEID_PLAYER && ((Player*)eOwner)->duel)
+ {
+ Unit const* myOwner = GetCharmerOrOwnerOrSelf();
+ if (((Player const*)eOwner)->duel->opponent == myOwner)
+ {
+ SetInCombatState(true,enemy);
+ return;
+ }
+ }
+ SetInCombatState(false,enemy);
+}
+
+void Unit::CombatStart(Unit* target, bool initialAggro)
+{
+ if (initialAggro)
+ {
+ if (!target->IsStandState()/* && !target->hasUnitState(UNIT_STAT_STUNNED)*/)
+ target->SetStandState(UNIT_STAND_STATE_STAND);
+
+ if (!target->isInCombat() && target->GetTypeId() != TYPEID_PLAYER
+ && !((Creature*)target)->HasReactState(REACT_PASSIVE) && ((Creature*)target)->IsAIEnabled)
+ {
+ ((Creature*)target)->AI()->AttackStart(this);
+ }
+
+ SetInCombatWith(target);
+ target->SetInCombatWith(this);
+ }
+ Unit *who = target->GetCharmerOrOwnerOrSelf();
+ if (who->GetTypeId() == TYPEID_PLAYER)
+ SetContestedPvP((Player*)who);
+
+ Player *me = GetCharmerOrOwnerPlayerOrPlayerItself();
+ if (me && who->IsPvP()
+ && (who->GetTypeId() != TYPEID_PLAYER
+ || !me->duel || me->duel->opponent != who))
+ {
+ me->UpdatePvP(true);
+ me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
+ }
+}
+
+void Unit::SetInCombatState(bool PvP, Unit* enemy)
+{
+ // only alive units can be in combat
+ if (!isAlive())
+ return;
+
+ if (PvP)
+ m_CombatTimer = 5000;
+
+ if (isInCombat() || hasUnitState(UNIT_STAT_EVADE))
+ return;
+
+ SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
+
+ if (GetTypeId() != TYPEID_PLAYER)
+ {
+ // Set home position at place of engaging combat for escorted creatures
+ if (( IsAIEnabled && ((Creature*)this)->AI()->IsEscorted() ) ||
+ GetMotionMaster()->GetCurrentMovementGeneratorType() == WAYPOINT_MOTION_TYPE ||
+ GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE)
+ ((Creature*)this)->SetHomePosition(GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
+
+ if (enemy)
+ {
+ if (IsAIEnabled)
+ ((Creature*)this)->AI()->EnterCombat(enemy);
+ if (((Creature*)this)->GetFormation())
+ ((Creature*)this)->GetFormation()->MemberAttackStart((Creature*)this, enemy);
+ }
+
+ if (isPet())
+ {
+ UpdateSpeed(MOVE_RUN, true);
+ UpdateSpeed(MOVE_SWIM, true);
+ UpdateSpeed(MOVE_FLIGHT, true);
+ }
+ }
+
+ for (Unit::ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
+ {
+ (*itr)->SetInCombatState(PvP, enemy);
+ (*itr)->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
+ }
+}
+
+void Unit::ClearInCombat()
+{
+ m_CombatTimer = 0;
+ RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
+
+ // Player's state will be cleared in Player::UpdateContestedPvP
+ if (GetTypeId() != TYPEID_PLAYER)
+ {
+ clearUnitState(UNIT_STAT_ATTACK_PLAYER);
+ if (HasFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TAPPED))
+ SetUInt32Value(UNIT_DYNAMIC_FLAGS, ((Creature*)this)->GetCreatureInfo()->dynamicflags);
+ }
+ else
+ ((Player*)this)->UpdatePotionCooldown();
+
+ if (GetTypeId() != TYPEID_PLAYER && ((Creature*)this)->isPet())
+ {
+ if (Unit *owner = GetOwner())
+ for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i)
+ if (owner->GetSpeedRate(UnitMoveType(i)) > GetSpeedRate(UnitMoveType(i)))
+ SetSpeed(UnitMoveType(i), owner->GetSpeedRate(UnitMoveType(i)), true);
+ }
+ else if (!isCharmed())
+ return;
+
+ RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
+}
+
+//TODO: remove this function
+bool Unit::isTargetableForAttack() const
+{
+ return isAttackableByAOE() && !hasUnitState(UNIT_STAT_DIED);
+}
+
+bool Unit::canAttack(Unit const* target, bool force) const
+{
+ assert(target);
+
+ if (force)
+ {
+ if (IsFriendlyTo(target))
+ return false;
+ }
+ else if (!IsHostileTo(target))
+ return false;
+
+ //if(m_Vehicle && m_Vehicle == target->m_Vehicle)
+ // return true;
+
+ if (!target->isAttackableByAOE() || target->hasUnitState(UNIT_STAT_DIED))
+ return false;
+
+ // shaman totem quests: spell 8898, shaman can detect elementals but elementals cannot see shaman
+ if (m_invisibilityMask || target->m_invisibilityMask)
+ if (!canDetectInvisibilityOf(target) && !target->canDetectInvisibilityOf(this))
+ return false;
+
+ if (target->GetVisibility() == VISIBILITY_GROUP_STEALTH && !canDetectStealthOf(target, GetDistance(target)))
+ return false;
+
+ if (m_vehicle)
+ if (IsOnVehicle(target) || m_vehicle->GetBase()->IsOnVehicle(target))
+ return false;
+
+ return true;
+}
+
+bool Unit::isAttackableByAOE() const
+{
+ if (!isAlive())
+ return false;
+
+ if (HasFlag(UNIT_FIELD_FLAGS,
+ UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_OOC_NOT_ATTACKABLE))
+ return false;
+
+ if (GetTypeId() == TYPEID_PLAYER && ((Player *)this)->isGameMaster())
+ return false;
+
+ return !hasUnitState(UNIT_STAT_UNATTACKABLE);
+}
+
+int32 Unit::ModifyHealth(int32 dVal)
+{
+ int32 gain = 0;
+
+ if (dVal==0)
+ return 0;
+
+ int32 curHealth = (int32)GetHealth();
+
+ int32 val = dVal + curHealth;
+ if (val <= 0)
+ {
+ SetHealth(0);
+ return -curHealth;
+ }
+
+ int32 maxHealth = (int32)GetMaxHealth();
+
+ if (val < maxHealth)
+ {
+ SetHealth(val);
+ gain = val - curHealth;
+ }
+ else if (curHealth != maxHealth)
+ {
+ SetHealth(maxHealth);
+ gain = maxHealth - curHealth;
+ }
+
+ return gain;
+}
+
+int32 Unit::GetHealthGain(int32 dVal)
+{
+ int32 gain = 0;
+
+ if (dVal==0)
+ return 0;
+
+ int32 curHealth = (int32)GetHealth();
+
+ int32 val = dVal + curHealth;
+ if (val <= 0)
+ {
+ return -curHealth;
+ }
+
+ int32 maxHealth = (int32)GetMaxHealth();
+
+ if (val < maxHealth)
+ gain = dVal;
+ else if (curHealth != maxHealth)
+ gain = maxHealth - curHealth;
+
+ return gain;
+}
+
+int32 Unit::ModifyPower(Powers power, int32 dVal)
+{
+ int32 gain = 0;
+
+ if (dVal==0)
+ return 0;
+
+ int32 curPower = (int32)GetPower(power);
+
+ int32 val = dVal + curPower;
+ if (val <= 0)
+ {
+ SetPower(power,0);
+ return -curPower;
+ }
+
+ int32 maxPower = (int32)GetMaxPower(power);
+
+ if (val < maxPower)
+ {
+ SetPower(power,val);
+ gain = val - curPower;
+ }
+ else if (curPower != maxPower)
+ {
+ SetPower(power,maxPower);
+ gain = maxPower - curPower;
+ }
+
+ return gain;
+}
+
+bool Unit::isVisibleForOrDetect(Unit const* u, bool detect, bool inVisibleList, bool is3dDistance) const
+{
+ if (!u || !IsInMap(u))
+ return false;
+
+ return u->canSeeOrDetect(this, detect, inVisibleList, is3dDistance);
+}
+
+bool Unit::canSeeOrDetect(Unit const* u, bool detect, bool inVisibleList, bool is3dDistance) const
+{
+ return true;
+}
+
+bool Unit::canDetectInvisibilityOf(Unit const* u) const
+{
+ if (m_invisibilityMask & u->m_invisibilityMask) // same group
+ return true;
+ AuraEffectList const& auras = u->GetAuraEffectsByType(SPELL_AURA_MOD_STALKED); // Hunter mark
+ for (AuraEffectList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
+ if ((*iter)->GetCasterGUID()==GetGUID())
+ return true;
+
+ if (uint32 mask = (m_detectInvisibilityMask & u->m_invisibilityMask))
+ {
+ for (uint32 i = 0; i < 10; ++i)
+ {
+ if (((1 << i) & mask)==0)
+ continue;
+
+ // find invisibility level
+ uint32 invLevel = 0;
+ Unit::AuraEffectList const& iAuras = u->GetAuraEffectsByType(SPELL_AURA_MOD_INVISIBILITY);
+ for (Unit::AuraEffectList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr)
+ if (((*itr)->GetMiscValue())==i && invLevel < (*itr)->GetAmount())
+ invLevel = (*itr)->GetAmount();
+
+ // find invisibility detect level
+ uint32 detectLevel = 0;
+ if (i==6 && GetTypeId() == TYPEID_PLAYER) // special drunk detection case
+ {
+ detectLevel = ((Player*)this)->GetDrunkValue();
+ }
+ else
+ {
+ Unit::AuraEffectList const& dAuras = GetAuraEffectsByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION);
+ for (Unit::AuraEffectList::const_iterator itr = dAuras.begin(); itr != dAuras.end(); ++itr)
+ if (((*itr)->GetMiscValue())==i && detectLevel < (*itr)->GetAmount())
+ detectLevel = (*itr)->GetAmount();
+ }
+
+ if (invLevel <= detectLevel)
+ return true;
+ }
+ }
+
+ return false;
+}
+
+bool Unit::canDetectStealthOf(Unit const* target, float distance) const
+{
+ if (hasUnitState(UNIT_STAT_STUNNED))
+ return false;
+ if (distance < 0.24f) //collision
+ return true;
+ if (!HasInArc(M_PI, target)) //behind
+ return false;
+ if (HasAuraType(SPELL_AURA_DETECT_STEALTH))
+ return true;
+
+ AuraEffectList const &auras = target->GetAuraEffectsByType(SPELL_AURA_MOD_STALKED); // Hunter mark
+ for (AuraEffectList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
+ if ((*iter)->GetCasterGUID() == GetGUID())
+ return true;
+
+ //Visible distance based on stealth value (stealth rank 4 300MOD, 10.5 - 3 = 7.5)
+ float visibleDistance = 7.5f;
+ //Visible distance is modified by -Level Diff (every level diff = 1.0f in visible distance)
+ visibleDistance += float(getLevelForTarget(target)) - target->GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH)/5.0f;
+ //-Stealth Mod(positive like Master of Deception) and Stealth Detection(negative like paranoia)
+ //based on wowwiki every 5 mod we have 1 more level diff in calculation
+ visibleDistance += (float)(GetTotalAuraModifier(SPELL_AURA_MOD_DETECT) - target->GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_LEVEL)) / 5.0f;
+ visibleDistance = visibleDistance > MAX_PLAYER_STEALTH_DETECT_RANGE ? MAX_PLAYER_STEALTH_DETECT_RANGE : visibleDistance;
+
+ return distance < visibleDistance;
+}
+
+void Unit::SetVisibility(UnitVisibility x)
+{
+ m_Visibility = x;
+
+ if(IsInWorld())
+ {
+ Map *m = GetMap();
+ CellPair p(Trinity::ComputeCellPair(GetPositionX(), GetPositionY()));
+ Cell cell(p);
+
+ if(GetTypeId() == TYPEID_PLAYER)
+ {
+ m->UpdatePlayerVisibility((Player*)this, cell, p);
+ m->UpdateObjectsVisibilityFor((Player*)this, cell, p);
+ }
+ else
+ m->UpdateObjectVisibility(this, cell, p);
+
+ AddToNotify(NOTIFY_AI_RELOCATION);
+ }
+
+ if (x == VISIBILITY_GROUP_STEALTH)
+ DestroyForNearbyPlayers();
+}
+
+void Unit::UpdateSpeed(UnitMoveType mtype, bool forced)
+{
+ int32 main_speed_mod = 0;
+ float stack_bonus = 1.0f;
+ float non_stack_bonus = 1.0f;
+
+ switch(mtype)
+ {
+ // Only apply debuffs
+ case MOVE_FLIGHT_BACK:
+ case MOVE_RUN_BACK:
+ case MOVE_SWIM_BACK:
+ break;
+ case MOVE_WALK:
+ return;
+ case MOVE_RUN:
+ {
+ if (IsMounted()) // Use on mount auras
+ {
+ main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED);
+ stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS);
+ non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK))/100.0f;
+ }
+ else
+ {
+ main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED);
+ stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS);
+ non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK))/100.0f;
+ }
+ break;
+ }
+ case MOVE_SWIM:
+ {
+ main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SWIM_SPEED);
+ break;
+ }
+ case MOVE_FLIGHT:
+ {
+ if (GetTypeId() == TYPEID_UNIT && IsControlledByPlayer()) // not sure if good for pet
+ {
+ main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED);
+ stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_VEHICLE_SPEED_ALWAYS);
+
+ // for some spells this mod is applied on vehicle owner
+ uint32 owner_speed_mod = 0;
+
+ if (Unit * owner = GetCharmer())
+ uint32 owner_speed_mod = owner->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED);
+
+ main_speed_mod = main_speed_mod>owner_speed_mod ? main_speed_mod : owner_speed_mod;
+ }
+ else if (IsMounted())
+ {
+ main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED);
+ stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_FLIGHT_SPEED_ALWAYS);
+ }
+ else // Use not mount (shapeshift for example) auras (should stack)
+ main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) + GetTotalAuraModifier(SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED);
+
+ non_stack_bonus = (100.0 + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK))/100.0f;
+
+ // Update speed for vehicle if available
+ if (GetTypeId() == TYPEID_PLAYER && GetVehicle())
+ GetVehicleBase()->UpdateSpeed(MOVE_FLIGHT, true);
+ break;
+ }
+ default:
+ sLog.outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype);
+ return;
+ }
+
+ float bonus = non_stack_bonus > stack_bonus ? non_stack_bonus : stack_bonus;
+
+ // now we ready for speed calculation
+ float speed = main_speed_mod ? bonus*(100.0f + main_speed_mod)/100.0f : bonus;
+
+ switch(mtype)
+ {
+ case MOVE_RUN:
+ case MOVE_SWIM:
+ case MOVE_FLIGHT:
+ {
+ // Set creature speed rate from CreatureInfo
+ if (GetTypeId() == TYPEID_UNIT)
+ speed *= ((Creature*)this)->GetCreatureInfo()->speed;
+
+ // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need
+ // TODO: possible affect only on MOVE_RUN
+ if (int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED))
+ {
+ // Use speed from aura
+ float max_speed = normalization / (IsControlledByPlayer() ? playerBaseMoveSpeed[mtype] : baseMoveSpeed[mtype]);
+ if (speed > max_speed)
+ speed = max_speed;
+ }
+ break;
+ }
+ default:
+ break;
+ }
+
+ // for creature case, we check explicit if mob searched for assistance
+ if (GetTypeId() == TYPEID_UNIT)
+ {
+ if (((Creature*)this)->HasSearchedAssistance())
+ speed *= 0.66f; // best guessed value, so this will be 33% reduction. Based off initial speed, mob can then "run", "walk fast" or "walk".
+ }
+
+ // Apply strongest slow aura mod to speed
+ int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED);
+ if (slow)
+ {
+ speed *=(100.0f + slow)/100.0f;
+ float min_speed = (float)GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MINIMUM_SPEED) / 100.0f;
+ if (speed < min_speed)
+ speed = min_speed;
+ }
+ SetSpeed(mtype, speed, forced);
+}
+
+float Unit::GetSpeed( UnitMoveType mtype ) const
+{
+ return m_speed_rate[mtype]*(IsControlledByPlayer() ? playerBaseMoveSpeed[mtype] : baseMoveSpeed[mtype]);
+}
+
+void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced)
+{
+ if (rate < 0)
+ rate = 0.0f;
+
+ // Update speed only on change
+ if (m_speed_rate[mtype] == rate)
+ return;
+
+ m_speed_rate[mtype] = rate;
+
+ propagateSpeedChange();
+
+ WorldPacket data;
+ if (!forced)
+ {
+ switch(mtype)
+ {
+ case MOVE_WALK:
+ data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8+4+2+4+4+4+4+4+4+4);
+ break;
+ case MOVE_RUN:
+ data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8+4+2+4+4+4+4+4+4+4);
+ break;
+ case MOVE_RUN_BACK:
+ data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
+ break;
+ case MOVE_SWIM:
+ data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8+4+2+4+4+4+4+4+4+4);
+ break;
+ case MOVE_SWIM_BACK:
+ data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
+ break;
+ case MOVE_TURN_RATE:
+ data.Initialize(MSG_MOVE_SET_TURN_RATE, 8+4+2+4+4+4+4+4+4+4);
+ break;
+ case MOVE_FLIGHT:
+ data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8+4+2+4+4+4+4+4+4+4);
+ break;
+ case MOVE_FLIGHT_BACK:
+ data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
+ break;
+ case MOVE_PITCH_RATE:
+ data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8+4+2+4+4+4+4+4+4+4);
+ break;
+ default:
+ sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
+ return;
+ }
+
+ data.append(GetPackGUID());
+ data << uint32(0); // movement flags
+ data << uint16(0); // unk flags
+ data << uint32(getMSTime());
+ data << float(GetPositionX());
+ data << float(GetPositionY());
+ data << float(GetPositionZ());
+ data << float(GetOrientation());
+ data << uint32(0); // fall time
+ data << float(GetSpeed(mtype));
+ SendMessageToSet( &data, true );
+ }
+ else
+ {
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ // register forced speed changes for WorldSession::HandleForceSpeedChangeAck
+ // and do it only for real sent packets and use run for run/mounted as client expected
+ ++((Player*)this)->m_forced_speed_changes[mtype];
+
+ if (!isInCombat())
+ if (Pet* pet = ((Player*)this)->GetPet())
+ pet->SetSpeed(mtype, m_speed_rate[mtype], forced);
+ }
+
+ switch(mtype)
+ {
+ case MOVE_WALK:
+ data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE, 16);
+ break;
+ case MOVE_RUN:
+ data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE, 17);
+ break;
+ case MOVE_RUN_BACK:
+ data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE, 16);
+ break;
+ case MOVE_SWIM:
+ data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE, 16);
+ break;
+ case MOVE_SWIM_BACK:
+ data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, 16);
+ break;
+ case MOVE_TURN_RATE:
+ data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE, 16);
+ break;
+ case MOVE_FLIGHT:
+ data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE, 16);
+ break;
+ case MOVE_FLIGHT_BACK:
+ data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, 16);
+ break;
+ case MOVE_PITCH_RATE:
+ data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE, 16);
+ break;
+ default:
+ sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
+ return;
+ }
+ data.append(GetPackGUID());
+ data << (uint32)0; // moveEvent, NUM_PMOVE_EVTS = 0x39
+ if (mtype == MOVE_RUN)
+ data << uint8(0); // new 2.1.0
+ data << float(GetSpeed(mtype));
+ SendMessageToSet( &data, true );
+ }
+}
+
+void Unit::SetHover(bool on)
+{
+ if (on)
+ CastSpell(this, 11010, true);
+ else
+ RemoveAurasDueToSpell(11010);
+}
+
+void Unit::setDeathState(DeathState s)
+{
+ if (s != ALIVE && s != JUST_ALIVED)
+ {
+ CombatStop();
+ DeleteThreatList();
+ getHostilRefManager().deleteReferences();
+ ClearComboPointHolders(); // any combo points pointed to unit lost at it death
+
+ if (IsNonMeleeSpellCasted(false))
+ InterruptNonMeleeSpells(false);
+
+ UnsummonAllTotems();
+ RemoveAllControlled();
+ RemoveAllAurasOnDeath();
+ ExitVehicle();
+ }
+
+ if (s == JUST_DIED)
+ {
+ ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false);
+ ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, false);
+ // remove aurastates allowing special moves
+ ClearAllReactives();
+ ClearDiminishings();
+ GetMotionMaster()->Clear(false);
+ GetMotionMaster()->MoveIdle();
+ if (m_vehicleKit)
+ m_vehicleKit->Die();
+ StopMoving();
+ //without this when removing IncreaseMaxHealth aura player may stuck with 1 hp
+ //do not why since in IncreaseMaxHealth currenthealth is checked
+ SetHealth(0);
+ }
+ else if (s == JUST_ALIVED)
+ RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground)
+
+ if (m_deathState != ALIVE && s == ALIVE)
+ {
+ //_ApplyAllAuraMods();
+ // Reset display id on resurection - needed by corpse explosion to cleanup after display change
+ SetDisplayId(GetNativeDisplayId());
+ }
+ m_deathState = s;
+}
+
+/*########################################
+######## ########
+######## AGGRO SYSTEM ########
+######## ########
+########################################*/
+bool Unit::CanHaveThreatList() const
+{
+ // only creatures can have threat list
+ if (GetTypeId() != TYPEID_UNIT)
+ return false;
+
+ // only alive units can have threat list
+ if (!isAlive())
+ return false;
+
+ // totems can not have threat list
+ if (((Creature*)this)->isTotem())
+ return false;
+
+ // vehicles can not have threat list
+ //if (((Creature*)this)->IsVehicle())
+ // return false;
+
+ // summons can not have a threat list, unless they are controlled by a creature
+ if (HasUnitTypeMask(UNIT_MASK_MINION | UNIT_MASK_GUARDIAN | UNIT_MASK_CONTROLABLE_GUARDIAN) && IS_PLAYER_GUID(((Pet*)this)->GetOwnerGUID()))
+ return false;
+
+ return true;
+}
+
+//======================================================================
+
+float Unit::ApplyTotalThreatModifier(float fThreat, SpellSchoolMask schoolMask)
+{
+ if (!HasAuraType(SPELL_AURA_MOD_THREAT) || fThreat < 0)
+ return fThreat;
+
+ SpellSchools school = GetFirstSchoolInMask(schoolMask);
+
+ return fThreat * m_threatModifier[school];
+}
+
+//======================================================================
+
+void Unit::AddThreat(Unit* pVictim, float fThreat, SpellSchoolMask schoolMask, SpellEntry const *threatSpell)
+{
+ // Only mobs can manage threat lists
+ if (CanHaveThreatList())
+ m_ThreatManager.addThreat(pVictim, fThreat, schoolMask, threatSpell);
+}
+
+//======================================================================
+
+void Unit::DeleteThreatList()
+{
+ if (CanHaveThreatList() && !m_ThreatManager.isThreatListEmpty())
+ SendClearThreatListOpcode();
+ m_ThreatManager.clearReferences();
+}
+
+//======================================================================
+
+void Unit::TauntApply(Unit* taunter)
+{
+ assert(GetTypeId() == TYPEID_UNIT);
+
+ if (!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
+ return;
+
+ if (!CanHaveThreatList())
+ return;
+
+ if (((Creature*)this)->HasReactState(REACT_PASSIVE))
+ return;
+
+ Unit *target = getVictim();
+ if (target && target == taunter)
+ return;
+
+ SetInFront(taunter);
+ if (((Creature*)this)->IsAIEnabled)
+ ((Creature*)this)->AI()->AttackStart(taunter);
+
+ //m_ThreatManager.tauntApply(taunter);
+}
+
+//======================================================================
+
+void Unit::TauntFadeOut(Unit *taunter)
+{
+ assert(GetTypeId() == TYPEID_UNIT);
+
+ if (!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
+ return;
+
+ if (!CanHaveThreatList())
+ return;
+
+ if (((Creature*)this)->HasReactState(REACT_PASSIVE))
+ return;
+
+ Unit *target = getVictim();
+ if (!target || target != taunter)
+ return;
+
+ if (m_ThreatManager.isThreatListEmpty())
+ {
+ if (((Creature*)this)->IsAIEnabled)
+ ((Creature*)this)->AI()->EnterEvadeMode();
+ return;
+ }
+
+ //m_ThreatManager.tauntFadeOut(taunter);
+ target = m_ThreatManager.getHostilTarget();
+
+ if (target && target != taunter)
+ {
+ SetInFront(target);
+ if (((Creature*)this)->IsAIEnabled)
+ ((Creature*)this)->AI()->AttackStart(target);
+ }
+}
+
+//======================================================================
+
+Unit* Creature::SelectVictim()
+{
+ //function provides main threat functionality
+ //next-victim-selection algorithm and evade mode are called
+ //threat list sorting etc.
+
+ Unit* target = NULL;
+ // First checking if we have some taunt on us
+ const AuraEffectList& tauntAuras = GetAuraEffectsByType(SPELL_AURA_MOD_TAUNT);
+ if (!tauntAuras.empty())
+ {
+ Unit* caster;
+
+ // The last taunt aura caster is alive an we are happy to attack him
+ if ((caster = tauntAuras.back()->GetCaster()) && caster->isAlive())
+ return getVictim();
+ else if (tauntAuras.size() > 1)
+ {
+ // We do not have last taunt aura caster but we have more taunt auras,
+ // so find first available target
+
+ // Auras are pushed_back, last caster will be on the end
+ AuraEffectList::const_iterator aura = --tauntAuras.end();
+ do
+ {
+ --aura;
+ if ((caster = (*aura)->GetCaster()) &&
+ caster->IsInMap(this) && canAttack(caster) && caster->isInAccessiblePlaceFor((Creature*)this))
+ {
+ target = caster;
+ break;
+ }
+ } while (aura != tauntAuras.begin());
+ }
+ else
+ target = getVictim();
+ }
+
+ if (CanHaveThreatList())
+ {
+ if (!target && !m_ThreatManager.isThreatListEmpty())
+ // No taunt aura or taunt aura caster is dead standard target selection
+ target = m_ThreatManager.getHostilTarget();
+ }
+ else if (!HasReactState(REACT_PASSIVE))
+ {
+ // We have player pet probably
+ target = getAttackerForHelper();
+ if (!target && isSummon())
+ {
+ if (Unit * owner = ((TempSummon*)this)->GetOwner())
+ {
+ if (owner->isInCombat())
+ target = owner->getAttackerForHelper();
+ if (!target)
+ {
+ for (ControlList::const_iterator itr = owner->m_Controlled.begin(); itr != owner->m_Controlled.end(); ++itr)
+ {
+ if ((*itr)->isInCombat())
+ {
+ target = (*itr)->getAttackerForHelper();
+ if (target) break;
+ }
+ }
+ }
+ }
+ }
+ }
+ else
+ return NULL;
+
+ if (target && _IsTargetAcceptable(target))
+ {
+ SetInFront(target);
+ return target;
+ }
+
+ // last case when creature don't must go to evade mode:
+ // it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list
+ // for example at owner command to pet attack some far away creature
+ // Note: creature not have targeted movement generator but have attacker in this case
+ for (AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr)
+ {
+ if ((*itr) && !canCreatureAttack(*itr) && (*itr)->GetTypeId() != TYPEID_PLAYER
+ && !((Creature*)(*itr))->HasUnitTypeMask(UNIT_MASK_CONTROLABLE_GUARDIAN))
+ return NULL;
+ }
+
+ // TODO: a vehicle may eat some mob, so mob should not evade
+ if (GetVehicle())
+ return NULL;
+
+ // search nearby enemy before enter evade mode
+ if (HasReactState(REACT_AGGRESSIVE))
+ if (target = SelectNearestTarget())
+ if (_IsTargetAcceptable(target))
+ return target;
+
+ if (m_invisibilityMask)
+ {
+ Unit::AuraEffectList const& iAuras = GetAuraEffectsByType(SPELL_AURA_MOD_INVISIBILITY);
+ for (Unit::AuraEffectList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr)
+ if ((*itr)->GetBase()->IsPermanent())
+ {
+ AI()->EnterEvadeMode();
+ break;
+ }
+ return NULL;
+ }
+
+ // enter in evade mode in other case
+ AI()->EnterEvadeMode();
+
+ return NULL;
+}
+
+//======================================================================
+//======================================================================
+//======================================================================
+
+int32 Unit::CalculateSpellDamage(SpellEntry const* spellProto, uint8 effect_index, int32 effBasePoints, Unit const* /*target*/)
+{
+ int32 level = int32(getLevel());
+ if (level > int32(spellProto->maxLevel) && spellProto->maxLevel > 0)
+ level = int32(spellProto->maxLevel);
+ else if (level < int32(spellProto->baseLevel))
+ level = int32(spellProto->baseLevel);
+ level -= int32(spellProto->spellLevel);
+
+ float basePointsPerLevel = spellProto->EffectRealPointsPerLevel[effect_index];
+ float randomPointsPerLevel = spellProto->EffectDicePerLevel[effect_index];
+ int32 basePoints = int32(effBasePoints + level * basePointsPerLevel);
+ int32 randomPoints = int32(spellProto->EffectDieSides[effect_index] + level * randomPointsPerLevel);
+
+ // range can have possitive and negative values, so order its for irand
+ int32 randvalue = int32(spellProto->EffectBaseDice[effect_index]) >= randomPoints
+ ? irand(randomPoints, int32(spellProto->EffectBaseDice[effect_index]))
+ : irand(int32(spellProto->EffectBaseDice[effect_index]), randomPoints);
+
+ int32 value = basePoints + randvalue;
+ //random damage
+ //if (comboDamage != 0 && unitPlayer /*&& target && (target->GetGUID() == unitPlayer->GetComboTarget())*/)
+ if (m_movedPlayer)
+ if (uint8 comboPoints = m_movedPlayer->GetComboPoints())
+ if (float comboDamage = spellProto->EffectPointsPerComboPoint[effect_index])
+ value += int32(comboDamage * comboPoints);
+
+ if (Player* modOwner = GetSpellModOwner())
+ {
+ modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_ALL_EFFECTS, value);
+ switch (effect_index)
+ {
+ case 0:
+ modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT1, value);
+ break;
+ case 1:
+ modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT2, value);
+ break;
+ case 2:
+ modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT3, value);
+ break;
+ }
+ }
+
+ if (!basePointsPerLevel && (spellProto->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION && spellProto->spellLevel) &&
+ spellProto->Effect[effect_index] != SPELL_EFFECT_WEAPON_PERCENT_DAMAGE &&
+ spellProto->Effect[effect_index] != SPELL_EFFECT_KNOCK_BACK &&
+ spellProto->EffectApplyAuraName[effect_index] != SPELL_AURA_MOD_SPEED_ALWAYS &&
+ spellProto->EffectApplyAuraName[effect_index] != SPELL_AURA_MOD_SPEED_NOT_STACK &&
+ spellProto->EffectApplyAuraName[effect_index] != SPELL_AURA_MOD_INCREASE_SPEED &&
+ spellProto->EffectApplyAuraName[effect_index] != SPELL_AURA_MOD_DECREASE_SPEED)
+ //there are many more: slow speed, -healing pct
+ value = int32(value*0.25f*exp(getLevel()*(70-spellProto->spellLevel)/1000.0f));
+ //value = int32(value * (int32)getLevel() / (int32)(spellProto->spellLevel ? spellProto->spellLevel : 1));
+
+ return value;
+}
+
+int32 Unit::CalcSpellDuration(SpellEntry const* spellProto)
+{
+ uint8 comboPoints = m_movedPlayer ? m_movedPlayer->GetComboPoints() : 0;
+
+ int32 minduration = GetSpellDuration(spellProto);
+ int32 maxduration = GetSpellMaxDuration(spellProto);
+
+ int32 duration;
+
+ if (comboPoints && minduration != -1 && minduration != maxduration)
+ duration = minduration + int32((maxduration - minduration) * comboPoints / 5);
+ else
+ duration = minduration;
+
+ return duration;
+}
+
+int32 Unit::ModSpellDuration(SpellEntry const* spellProto, Unit const* target, int32 duration, bool positive)
+{
+ //don't mod permament auras duration
+ if (duration < 0)
+ return duration;
+
+ //cut duration only of negative effects
+ if (!positive)
+ {
+ int32 mechanic = GetAllSpellMechanicMask(spellProto);
+
+ int32 durationMod;
+ int32 durationMod_always = 0;
+ int32 durationMod_not_stack = 0;
+
+ for (uint8 i = 1; i <= MECHANIC_ENRAGED; ++i)
+ {
+ if (!(mechanic & 1<<i))
+ continue;
+ // Find total mod value (negative bonus)
+ int32 new_durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD, i);
+ // Find max mod (negative bonus)
+ int32 new_durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK, i);
+ // Check if mods applied before were weaker
+ if (new_durationMod_always < durationMod_always)
+ durationMod_always = new_durationMod_always;
+ if (new_durationMod_not_stack < durationMod_not_stack)
+ durationMod_not_stack = new_durationMod_not_stack;
+ }
+
+ // Select strongest negative mod
+ if (durationMod_always > durationMod_not_stack)
+ durationMod = durationMod_not_stack;
+ else
+ durationMod = durationMod_always;
+
+ if (durationMod != 0)
+ duration = int32(float(duration) * float(100.0f+durationMod) / 100.0f);
+
+ // there are only negative mods currently
+ durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_AURA_DURATION_BY_DISPEL, spellProto->Dispel);
+ durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MOD_AURA_DURATION_BY_DISPEL_NOT_STACK, spellProto->Dispel);
+
+ durationMod = 0;
+ if (durationMod_always > durationMod_not_stack)
+ durationMod += durationMod_not_stack;
+ else
+ durationMod += durationMod_always;
+
+ if (durationMod != 0)
+ duration = int32(float(duration) * float(100.0f+durationMod) / 100.0f);
+ }
+ //else positive mods here, there are no currently
+ //when there will be, change GetTotalAuraModifierByMiscValue to GetTotalPositiveAuraModifierByMiscValue
+
+ // Glyphs which increase duration of selfcasted buffs
+ if (target == this)
+ {
+ switch (spellProto->SpellFamilyName)
+ {
+ case SPELLFAMILY_DRUID:
+ if (spellProto->SpellFamilyFlags[0] & 0x100)
+ {
+ // Glyph of Thorns
+ if (AuraEffect * aurEff = GetAuraEffect(57862, 0))
+ duration += aurEff->GetAmount() * MINUTE * IN_MILISECONDS;
+ }
+ break;
+ case SPELLFAMILY_PALADIN:
+ if (spellProto->SpellFamilyFlags[0] & 0x00000002)
+ {
+ // Glyph of Blessing of Might
+ if (AuraEffect * aurEff = GetAuraEffect(57958, 0))
+ duration += aurEff->GetAmount() * MINUTE * IN_MILISECONDS;
+ }
+ else if (spellProto->SpellFamilyFlags[0] & 0x00010000)
+ {
+ // Glyph of Blessing of Wisdom
+ if (AuraEffect * aurEff = GetAuraEffect(57979, 0))
+ duration += aurEff->GetAmount() * MINUTE * IN_MILISECONDS;
+ }
+ break;
+ }
+ }
+ return duration > 0 ? duration : 0;
+}
+
+void Unit::ModSpellCastTime(SpellEntry const* spellProto, int32 & castTime, Spell * spell)
+{
+ if (!spellProto || castTime < 0)
+ return;
+ //called from caster
+ if (Player* modOwner = GetSpellModOwner())
+ modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CASTING_TIME, castTime, spell);
+
+ if (!(spellProto->Attributes & (SPELL_ATTR_UNK4|SPELL_ATTR_TRADESPELL)) && spellProto->SpellFamilyName)
+ castTime = int32(float(castTime) * GetFloatValue(UNIT_MOD_CAST_SPEED));
+ else
+ {
+ if (spellProto->Attributes & SPELL_ATTR_REQ_AMMO && !(spellProto->AttributesEx2 & SPELL_ATTR_EX2_AUTOREPEAT_FLAG))
+ castTime = int32(float(castTime) * m_modAttackSpeedPct[RANGED_ATTACK]);
+ }
+}
+
+DiminishingLevels Unit::GetDiminishing(DiminishingGroup group)
+{
+ for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
+ {
+ if (i->DRGroup != group)
+ continue;
+
+ if (!i->hitCount)
+ return DIMINISHING_LEVEL_1;
+
+ if (!i->hitTime)
+ return DIMINISHING_LEVEL_1;
+
+ // If last spell was casted more than 15 seconds ago - reset the count.
+ if (i->stack==0 && getMSTimeDiff(i->hitTime,getMSTime()) > 15000)
+ {
+ i->hitCount = DIMINISHING_LEVEL_1;
+ return DIMINISHING_LEVEL_1;
+ }
+ // or else increase the count.
+ else
+ return DiminishingLevels(i->hitCount);
+ }
+ return DIMINISHING_LEVEL_1;
+}
+
+void Unit::IncrDiminishing(DiminishingGroup group)
+{
+ // Checking for existing in the table
+ for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
+ {
+ if (i->DRGroup != group)
+ continue;
+ if (i->hitCount < GetDiminishingReturnsMaxLevel(group))
+ i->hitCount += 1;
+ return;
+ }
+ m_Diminishing.push_back(DiminishingReturn(group,getMSTime(),DIMINISHING_LEVEL_2));
+}
+
+void Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration,Unit* caster,DiminishingLevels Level, int32 limitduration)
+{
+ if (duration == -1 || group == DIMINISHING_NONE || caster->IsFriendlyTo(this))
+ return;
+
+ // test pet/charm masters instead pets/charmeds
+ Unit const* targetOwner = GetCharmerOrOwner();
+ Unit const* casterOwner = caster->GetCharmerOrOwner();
+
+ // Duration of crowd control abilities on pvp target is limited by 10 sec. (2.2.0)
+ if (limitduration > 0 && duration > limitduration)
+ {
+ Unit const* target = targetOwner ? targetOwner : this;
+ Unit const* source = casterOwner ? casterOwner : caster;
+
+ if ((target->GetTypeId() == TYPEID_PLAYER
+ || ((Creature*)target)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_ALL_DIMINISH)
+ && source->GetTypeId() == TYPEID_PLAYER)
+ duration = limitduration;
+ }
+
+ float mod = 1.0f;
+
+ if (group == DIMINISHING_TAUNT)
+ {
+ if(GetTypeId() == TYPEID_UNIT && (((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_TAUNT_DIMINISH))
+ {
+ DiminishingLevels diminish = Level;
+ switch(diminish)
+ {
+ case DIMINISHING_LEVEL_1: break;
+ case DIMINISHING_LEVEL_2: mod = 0.65f; break;
+ case DIMINISHING_LEVEL_3: mod = 0.4225f; break;
+ case DIMINISHING_LEVEL_4: mod = 0.274625f; break;
+ case DIMINISHING_LEVEL_TAUNT_IMMUNE: mod = 0.0f; break;
+ default: break;
+ }
+ }
+ }
+ // Some diminishings applies to mobs too (for example, Stun)
+ else if ((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER
+ && ((targetOwner ? (targetOwner->GetTypeId() == TYPEID_PLAYER) : (GetTypeId() == TYPEID_PLAYER))
+ || (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_ALL_DIMINISH)))
+ || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL)
+ {
+ DiminishingLevels diminish = Level;
+ switch(diminish)
+ {
+ case DIMINISHING_LEVEL_1: break;
+ case DIMINISHING_LEVEL_2: mod = 0.5f; break;
+ case DIMINISHING_LEVEL_3: mod = 0.25f; break;
+ case DIMINISHING_LEVEL_IMMUNE: mod = 0.0f; break;
+ default: break;
+ }
+ }
+
+ duration = int32(duration * mod);
+}
+
+void Unit::ApplyDiminishingAura( DiminishingGroup group, bool apply )
+{
+ // Checking for existing in the table
+ for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
+ {
+ if (i->DRGroup != group)
+ continue;
+
+ if (apply)
+ i->stack += 1;
+ else if (i->stack)
+ {
+ i->stack -= 1;
+ // Remember time after last aura from group removed
+ if (i->stack == 0)
+ i->hitTime = getMSTime();
+ }
+ break;
+ }
+}
+
+uint32 Unit::GetSpellMaxRangeForTarget(Unit* target,const SpellRangeEntry * rangeEntry)
+{
+ if (!rangeEntry)
+ return 0;
+ if (rangeEntry->maxRangeHostile == rangeEntry->maxRangeFriend)
+ return rangeEntry->maxRangeFriend;
+ if (IsHostileTo(target))
+ return rangeEntry->maxRangeHostile;
+ return rangeEntry->maxRangeFriend;
+};
+uint32 Unit::GetSpellMinRangeForTarget(Unit* target,const SpellRangeEntry * rangeEntry)
+{
+ if (!rangeEntry)
+ return 0;
+ if (rangeEntry->minRangeHostile == rangeEntry->minRangeFriend)
+ return rangeEntry->minRangeFriend;
+ if (IsHostileTo(target))
+ return rangeEntry->minRangeHostile;
+ return rangeEntry->minRangeFriend;
+};
+uint32 Unit::GetSpellRadiusForTarget(Unit* target,const SpellRadiusEntry * radiusEntry)
+{
+ if (!radiusEntry)
+ return 0;
+ if (radiusEntry->radiusHostile == radiusEntry->radiusFriend)
+ return radiusEntry->radiusFriend;
+ if (IsHostileTo(target))
+ return radiusEntry->radiusHostile;
+ return radiusEntry->radiusFriend;
+};
+
+Unit* Unit::GetUnit(WorldObject& object, uint64 guid)
+{
+ return ObjectAccessor::GetUnit(object,guid);
+}
+
+Player* Unit::GetPlayer(uint64 guid)
+{
+ return ObjectAccessor::FindPlayer(guid);
+}
+
+Creature* Unit::GetCreature(WorldObject& object, uint64 guid)
+{
+ return object.GetMap()->GetCreature(guid);
+}
+
+bool Unit::isVisibleForInState( Player const* u, bool inVisibleList ) const
+{
+ return u->canSeeOrDetect(this, false, inVisibleList, false);
+}
+
+uint32 Unit::GetCreatureType() const
+{
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
+ if (ssEntry && ssEntry->creatureType > 0)
+ return ssEntry->creatureType;
+ else
+ return CREATURE_TYPE_HUMANOID;
+ }
+ else
+ return ((Creature*)this)->GetCreatureInfo()->type;
+}
+
+/*#######################################
+######## ########
+######## STAT SYSTEM ########
+######## ########
+#######################################*/
+
+bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply)
+{
+ if (unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
+ {
+ sLog.outError("ERROR in HandleStatModifier(): non existed UnitMods or wrong UnitModifierType!");
+ return false;
+ }
+
+ float val = 1.0f;
+
+ switch (modifierType)
+ {
+ case BASE_VALUE:
+ case TOTAL_VALUE:
+ m_auraModifiersGroup[unitMod][modifierType] += apply ? amount : -amount;
+ break;
+ case BASE_PCT:
+ case TOTAL_PCT:
+ if (amount <= -100.0f) //small hack-fix for -100% modifiers
+ amount = -200.0f;
+
+ val = (100.0f + amount) / 100.0f;
+ m_auraModifiersGroup[unitMod][modifierType] *= apply ? val : (1.0f/val);
+ break;
+
+ default:
+ break;
+ }
+
+ if (!CanModifyStats())
+ return false;
+
+ switch(unitMod)
+ {
+ case UNIT_MOD_STAT_STRENGTH:
+ case UNIT_MOD_STAT_AGILITY:
+ case UNIT_MOD_STAT_STAMINA:
+ case UNIT_MOD_STAT_INTELLECT:
+ case UNIT_MOD_STAT_SPIRIT: UpdateStats(GetStatByAuraGroup(unitMod)); break;
+
+ case UNIT_MOD_ARMOR: UpdateArmor(); break;
+ case UNIT_MOD_HEALTH: UpdateMaxHealth(); break;
+
+ case UNIT_MOD_MANA:
+ case UNIT_MOD_RAGE:
+ case UNIT_MOD_FOCUS:
+ case UNIT_MOD_ENERGY:
+ case UNIT_MOD_HAPPINESS:
+ case UNIT_MOD_RUNE:
+ case UNIT_MOD_RUNIC_POWER: UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); break;
+
+ case UNIT_MOD_RESISTANCE_HOLY:
+ case UNIT_MOD_RESISTANCE_FIRE:
+ case UNIT_MOD_RESISTANCE_NATURE:
+ case UNIT_MOD_RESISTANCE_FROST:
+ case UNIT_MOD_RESISTANCE_SHADOW:
+ case UNIT_MOD_RESISTANCE_ARCANE: UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); break;
+
+ case UNIT_MOD_ATTACK_POWER: UpdateAttackPowerAndDamage(); break;
+ case UNIT_MOD_ATTACK_POWER_RANGED: UpdateAttackPowerAndDamage(true); break;
+
+ case UNIT_MOD_DAMAGE_MAINHAND: UpdateDamagePhysical(BASE_ATTACK); break;
+ case UNIT_MOD_DAMAGE_OFFHAND: UpdateDamagePhysical(OFF_ATTACK); break;
+ case UNIT_MOD_DAMAGE_RANGED: UpdateDamagePhysical(RANGED_ATTACK); break;
+
+ default:
+ break;
+ }
+
+ return true;
+}
+
+float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const
+{
+ if (unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
+ {
+ sLog.outError("trial to access non existed modifier value from UnitMods!");
+ return 0.0f;
+ }
+
+ if (modifierType == TOTAL_PCT && m_auraModifiersGroup[unitMod][modifierType] <= 0.0f)
+ return 0.0f;
+
+ return m_auraModifiersGroup[unitMod][modifierType];
+}
+
+float Unit::GetTotalStatValue(Stats stat) const
+{
+ UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat);
+
+ if (m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
+ return 0.0f;
+
+ // value = ((base_value * base_pct) + total_value) * total_pct
+ float value = m_auraModifiersGroup[unitMod][BASE_VALUE] + GetCreateStat(stat);
+ value *= m_auraModifiersGroup[unitMod][BASE_PCT];
+ value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
+ value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
+
+ return value;
+}
+
+float Unit::GetTotalAuraModValue(UnitMods unitMod) const
+{
+ if (unitMod >= UNIT_MOD_END)
+ {
+ sLog.outError("trial to access non existed UnitMods in GetTotalAuraModValue()!");
+ return 0.0f;
+ }
+
+ if (m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
+ return 0.0f;
+
+ float value = m_auraModifiersGroup[unitMod][BASE_VALUE];
+ value *= m_auraModifiersGroup[unitMod][BASE_PCT];
+ value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
+ value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
+
+ return value;
+}
+
+SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const
+{
+ SpellSchools school = SPELL_SCHOOL_NORMAL;
+
+ switch(unitMod)
+ {
+ case UNIT_MOD_RESISTANCE_HOLY: school = SPELL_SCHOOL_HOLY; break;
+ case UNIT_MOD_RESISTANCE_FIRE: school = SPELL_SCHOOL_FIRE; break;
+ case UNIT_MOD_RESISTANCE_NATURE: school = SPELL_SCHOOL_NATURE; break;
+ case UNIT_MOD_RESISTANCE_FROST: school = SPELL_SCHOOL_FROST; break;
+ case UNIT_MOD_RESISTANCE_SHADOW: school = SPELL_SCHOOL_SHADOW; break;
+ case UNIT_MOD_RESISTANCE_ARCANE: school = SPELL_SCHOOL_ARCANE; break;
+
+ default:
+ break;
+ }
+
+ return school;
+}
+
+Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const
+{
+ Stats stat = STAT_STRENGTH;
+
+ switch(unitMod)
+ {
+ case UNIT_MOD_STAT_STRENGTH: stat = STAT_STRENGTH; break;
+ case UNIT_MOD_STAT_AGILITY: stat = STAT_AGILITY; break;
+ case UNIT_MOD_STAT_STAMINA: stat = STAT_STAMINA; break;
+ case UNIT_MOD_STAT_INTELLECT: stat = STAT_INTELLECT; break;
+ case UNIT_MOD_STAT_SPIRIT: stat = STAT_SPIRIT; break;
+
+ default:
+ break;
+ }
+
+ return stat;
+}
+
+Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const
+{
+ switch (unitMod)
+ {
+ case UNIT_MOD_RAGE: return POWER_RAGE;
+ case UNIT_MOD_FOCUS: return POWER_FOCUS;
+ case UNIT_MOD_ENERGY: return POWER_ENERGY;
+ case UNIT_MOD_HAPPINESS: return POWER_HAPPINESS;
+ case UNIT_MOD_RUNE: return POWER_RUNE;
+ case UNIT_MOD_RUNIC_POWER: return POWER_RUNIC_POWER;
+ default:
+ case UNIT_MOD_MANA: return POWER_MANA;
+ }
+}
+
+float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const
+{
+ if (attType == RANGED_ATTACK)
+ {
+ int32 ap = GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS);
+ if (ap < 0)
+ return 0.0f;
+ return ap * (1.0f + GetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER));
+ }
+ else
+ {
+ int32 ap = GetInt32Value(UNIT_FIELD_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS);
+ if (ap < 0)
+ return 0.0f;
+ return ap * (1.0f + GetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER));
+ }
+}
+
+float Unit::GetWeaponDamageRange(WeaponAttackType attType ,WeaponDamageRange type) const
+{
+ if (attType == OFF_ATTACK && !haveOffhandWeapon())
+ return 0.0f;
+
+ return m_weaponDamage[attType][type];
+}
+
+void Unit::SetLevel(uint8 lvl)
+{
+ SetUInt32Value(UNIT_FIELD_LEVEL, lvl);
+
+ // group update
+ if (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->GetGroup())
+ ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL);
+}
+
+void Unit::SetHealth(uint32 val)
+{
+ if (getDeathState() == JUST_DIED)
+ val = 0;
+ else if (GetTypeId() == TYPEID_PLAYER && (getDeathState() == DEAD || getDeathState() == DEAD_FALLING))
+ val = 1;
+ else
+ {
+ uint32 maxHealth = GetMaxHealth();
+ if (maxHealth < val)
+ val = maxHealth;
+ }
+
+ SetUInt32Value(UNIT_FIELD_HEALTH, val);
+
+ // group update
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ if (((Player*)this)->GetGroup())
+ ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP);
+ }
+ else if (((Creature*)this)->isPet())
+ {
+ Pet *pet = ((Pet*)this);
+ if (pet->isControlled())
+ {
+ Unit *owner = GetOwner();
+ if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
+ ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP);
+ }
+ }
+}
+
+void Unit::SetMaxHealth(uint32 val)
+{
+ if (!val)
+ val = 1;
+
+ uint32 health = GetHealth();
+ SetUInt32Value(UNIT_FIELD_MAXHEALTH, val);
+
+ // group update
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ if (((Player*)this)->GetGroup())
+ ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP);
+ }
+ else if (((Creature*)this)->isPet())
+ {
+ Pet *pet = ((Pet*)this);
+ if (pet->isControlled())
+ {
+ Unit *owner = GetOwner();
+ if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
+ ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP);
+ }
+ }
+
+ if (val < health)
+ SetHealth(val);
+}
+
+void Unit::SetPower(Powers power, uint32 val)
+{
+ if (GetPower(power) == val)
+ return;
+
+ uint32 maxPower = GetMaxPower(power);
+ if (maxPower < val)
+ val = maxPower;
+
+ SetStatInt32Value(UNIT_FIELD_POWER1 + power, val);
+
+ WorldPacket data(SMSG_POWER_UPDATE);
+ data.append(GetPackGUID());
+ data << uint8(power);
+ data << uint32(val);
+ SendMessageToSet(&data, GetTypeId() == TYPEID_PLAYER ? true : false);
+
+ // group update
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ if (((Player*)this)->GetGroup())
+ ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
+ }
+ else if (((Creature*)this)->isPet())
+ {
+ Pet *pet = ((Pet*)this);
+ if (pet->isControlled())
+ {
+ Unit *owner = GetOwner();
+ if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
+ ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
+ }
+
+ // Update the pet's character sheet with happiness damage bonus
+ if (pet->getPetType() == HUNTER_PET && power == POWER_HAPPINESS)
+ pet->UpdateDamagePhysical(BASE_ATTACK);
+ }
+}
+
+void Unit::SetMaxPower(Powers power, uint32 val)
+{
+ uint32 cur_power = GetPower(power);
+ SetStatInt32Value(UNIT_FIELD_MAXPOWER1 + power, val);
+
+ // group update
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ if (((Player*)this)->GetGroup())
+ ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
+ }
+ else if (((Creature*)this)->isPet())
+ {
+ Pet *pet = ((Pet*)this);
+ if (pet->isControlled())
+ {
+ Unit *owner = GetOwner();
+ if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
+ ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
+ }
+ }
+
+ if (val < cur_power)
+ SetPower(power, val);
+}
+
+void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply)
+{
+ ApplyModUInt32Value(UNIT_FIELD_POWER1+power, val, apply);
+
+ // group update
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ if (((Player*)this)->GetGroup())
+ ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
+ }
+ else if (((Creature*)this)->isPet())
+ {
+ Pet *pet = ((Pet*)this);
+ if (pet->isControlled())
+ {
+ Unit *owner = GetOwner();
+ if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
+ ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
+ }
+ }
+}
+
+void Unit::ApplyMaxPowerMod(Powers power, uint32 val, bool apply)
+{
+ ApplyModUInt32Value(UNIT_FIELD_MAXPOWER1+power, val, apply);
+
+ // group update
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ if (((Player*)this)->GetGroup())
+ ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
+ }
+ else if (((Creature*)this)->isPet())
+ {
+ Pet *pet = ((Pet*)this);
+ if (pet->isControlled())
+ {
+ Unit *owner = GetOwner();
+ if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
+ ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
+ }
+ }
+}
+
+uint32 Unit::GetCreatePowers( Powers power ) const
+{
+ // POWER_FOCUS and POWER_HAPPINESS only have hunter pet
+ switch (power)
+ {
+ case POWER_MANA: return GetCreateMana();
+ case POWER_RAGE: return 1000;
+ case POWER_FOCUS: return (GetTypeId() == TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 100);
+ case POWER_ENERGY: return 100;
+ case POWER_HAPPINESS: return (GetTypeId() == TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 1050000);
+ case POWER_RUNIC_POWER: return 1000;
+ case POWER_RUNE: return 0;
+ case POWER_HEALTH: return 0;
+ }
+
+ return 0;
+}
+
+void Unit::AddToWorld()
+{
+ if (!IsInWorld())
+ {
+ WorldObject::AddToWorld();
+ SetToNotify();
+ }
+}
+
+void Unit::RemoveFromWorld()
+{
+ // cleanup
+ assert(GetGUID());
+
+ if (IsInWorld())
+ {
+ if (IsVehicle())
+ GetVehicleKit()->Uninstall();
+
+ RemoveCharmAuras();
+ RemoveBindSightAuras();
+ RemoveNotOwnSingleTargetAuras();
+
+ RemoveAllGameObjects();
+ RemoveAllDynObjects();
+
+ ExitVehicle();
+ UnsummonAllTotems();
+ RemoveAllControlled();
+
+ RemoveAreaAurasDueToLeaveWorld();
+
+ if (GetCharmerGUID())
+ {
+ sLog.outCrash("Unit %u has charmer guid when removed from world", GetEntry());
+ assert(false);
+ }
+
+ if (Unit *owner = GetOwner())
+ {
+ if (owner->m_Controlled.find(this) != owner->m_Controlled.end())
+ {
+ sLog.outCrash("Unit %u is in controlled list of %u when removed from world", GetEntry(), owner->GetEntry());
+ assert(false);
+ }
+ }
+
+ WorldObject::RemoveFromWorld();
+ }
+}
+
+void Unit::CleanupsBeforeDelete(bool finalCleanup)
+{
+ if (IsInWorld())
+ RemoveFromWorld();
+
+ assert(GetGUID());
+
+ //A unit may be in removelist and not in world, but it is still in grid
+ //and may have some references during delete
+ RemoveAllAuras();
+
+ if (finalCleanup)
+ m_cleanupDone = true;
+
+ InterruptNonMeleeSpells(true);
+ m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList
+ CombatStop();
+ ClearComboPointHolders();
+ DeleteThreatList();
+ getHostilRefManager().setOnlineOfflineState(false);
+ GetMotionMaster()->Clear(false); // remove different non-standard movement generators.
+}
+
+void Unit::UpdateCharmAI()
+{
+ if (GetTypeId() == TYPEID_PLAYER)
+ return;
+
+ if (i_disabledAI) // disabled AI must be primary AI
+ {
+ if (!isCharmed())
+ {
+ if (i_AI)
+ delete i_AI;
+ i_AI = i_disabledAI;
+ i_disabledAI = NULL;
+ }
+ }
+ else
+ {
+ if (isCharmed())
+ {
+ i_disabledAI = i_AI;
+ if (isPossessed() || IsVehicle())
+ i_AI = new PossessedAI((Creature*)this);
+ else
+ i_AI = new PetAI((Creature*)this);
+ }
+ }
+}
+
+CharmInfo* Unit::InitCharmInfo()
+{
+ if (!m_charmInfo)
+ m_charmInfo = new CharmInfo(this);
+
+ return m_charmInfo;
+}
+
+void Unit::DeleteCharmInfo()
+{
+ if (!m_charmInfo)
+ return;
+
+ delete m_charmInfo;
+ m_charmInfo = NULL;
+}
+
+CharmInfo::CharmInfo(Unit* unit)
+: m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_petnumber(0), m_barInit(false)
+{
+ for (uint8 i = 0; i < MAX_SPELL_CHARM; ++i)
+ m_charmspells[i].SetActionAndType(0,ACT_DISABLED);
+
+ if (m_unit->GetTypeId() == TYPEID_UNIT)
+ {
+ m_oldReactState = ((Creature*)m_unit)->GetReactState();
+ ((Creature*)m_unit)->SetReactState(REACT_PASSIVE);
+ }
+
+}
+
+CharmInfo::~CharmInfo()
+{
+ if (m_unit->GetTypeId() == TYPEID_UNIT)
+ {
+ ((Creature*)m_unit)->SetReactState(m_oldReactState);
+ }
+}
+
+void CharmInfo::InitPetActionBar()
+{
+ // the first 3 SpellOrActions are attack, follow and stay
+ for (uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_START - ACTION_BAR_INDEX_START; ++i)
+ SetActionBar(ACTION_BAR_INDEX_START + i,COMMAND_ATTACK - i,ACT_COMMAND);
+
+ // middle 4 SpellOrActions are spells/special attacks/abilities
+ for (uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_END-ACTION_BAR_INDEX_PET_SPELL_START; ++i)
+ SetActionBar(ACTION_BAR_INDEX_PET_SPELL_START + i,0,ACT_PASSIVE);
+
+ // last 3 SpellOrActions are reactions
+ for (uint32 i = 0; i < ACTION_BAR_INDEX_END - ACTION_BAR_INDEX_PET_SPELL_END; ++i)
+ SetActionBar(ACTION_BAR_INDEX_PET_SPELL_END + i,COMMAND_ATTACK - i,ACT_REACTION);
+}
+
+void CharmInfo::InitEmptyActionBar(bool withAttack)
+{
+ if (withAttack)
+ SetActionBar(ACTION_BAR_INDEX_START,COMMAND_ATTACK,ACT_COMMAND);
+ else
+ SetActionBar(ACTION_BAR_INDEX_START,0,ACT_PASSIVE);
+ for (uint32 x = ACTION_BAR_INDEX_START+1; x < ACTION_BAR_INDEX_END; ++x)
+ SetActionBar(x,0,ACT_PASSIVE);
+}
+
+void CharmInfo::InitPossessCreateSpells()
+{
+ InitEmptyActionBar();
+ if (m_unit->GetTypeId() == TYPEID_UNIT)
+ {
+ for (uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
+ {
+ uint32 spellId = ((Creature*)m_unit)->m_spells[i];
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
+ if (spellInfo && spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_DEAD)
+ spellId = 0;
+ if (IsPassiveSpell(spellId))
+ m_unit->CastSpell(m_unit, spellId, true);
+ else
+ AddSpellToActionBar(((Creature*)m_unit)->m_spells[i], ACT_PASSIVE);
+ }
+ }
+}
+
+void CharmInfo::InitCharmCreateSpells()
+{
+ if (m_unit->GetTypeId() == TYPEID_PLAYER) //charmed players don't have spells
+ {
+ InitEmptyActionBar();
+ return;
+ }
+
+ InitPetActionBar();
+
+ for (uint32 x = 0; x < MAX_SPELL_CHARM; ++x)
+ {
+ uint32 spellId = ((Creature*)m_unit)->m_spells[x];
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
+ if (spellInfo && spellInfo->Attributes & SPELL_ATTR_CASTABLE_WHILE_DEAD)
+ spellId = 0;
+
+ if (!spellId)
+ {
+ m_charmspells[x].SetActionAndType(spellId,ACT_DISABLED);
+ continue;
+ }
+
+ if (IsPassiveSpell(spellId))
+ {
+ m_unit->CastSpell(m_unit, spellId, true);
+ m_charmspells[x].SetActionAndType(spellId,ACT_PASSIVE);
+ }
+ else
+ {
+ m_charmspells[x].SetActionAndType(spellId,ACT_DISABLED);
+
+ ActiveStates newstate;
+ if (spellInfo)
+ {
+ if (!IsAutocastableSpell(spellId))
+ newstate = ACT_PASSIVE;
+ else
+ {
+ bool autocast = false;
+ for (uint32 i = 0; i < MAX_SPELL_EFFECTS && !autocast; ++i)
+ if (SpellTargetType[spellInfo->EffectImplicitTargetA[i]] == TARGET_TYPE_UNIT_TARGET)
+ autocast = true;
+
+ if (autocast)
+ {
+ newstate = ACT_ENABLED;
+ ToggleCreatureAutocast(spellId, true);
+ }
+ else
+ newstate = ACT_DISABLED;
+ }
+ }
+
+ AddSpellToActionBar(spellId, newstate);
+ }
+ }
+}
+
+bool CharmInfo::AddSpellToActionBar(uint32 spell_id, ActiveStates newstate)
+{
+ uint32 first_id = spellmgr.GetFirstSpellInChain(spell_id);
+
+ // new spell rank can be already listed
+ for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
+ {
+ if (uint32 action = PetActionBar[i].GetAction())
+ {
+ if (PetActionBar[i].IsActionBarForSpell() && spellmgr.GetFirstSpellInChain(action) == first_id)
+ {
+ PetActionBar[i].SetAction(spell_id);
+ return true;
+ }
+ }
+ }
+
+ // or use empty slot in other case
+ for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
+ {
+ if (!PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell())
+ {
+ SetActionBar(i,spell_id,newstate == ACT_DECIDE ? IsAutocastableSpell(spell_id) ? ACT_DISABLED : ACT_PASSIVE : newstate);
+ return true;
+ }
+ }
+ return false;
+}
+
+bool CharmInfo::RemoveSpellFromActionBar(uint32 spell_id)
+{
+ uint32 first_id = spellmgr.GetFirstSpellInChain(spell_id);
+
+ for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
+ {
+ if (uint32 action = PetActionBar[i].GetAction())
+ {
+ if (PetActionBar[i].IsActionBarForSpell() && spellmgr.GetFirstSpellInChain(action) == first_id)
+ {
+ SetActionBar(i,0,ACT_PASSIVE);
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
+
+void CharmInfo::ToggleCreatureAutocast(uint32 spellid, bool apply)
+{
+ if (IsPassiveSpell(spellid))
+ return;
+
+ for (uint32 x = 0; x < MAX_SPELL_CHARM; ++x)
+ if (spellid == m_charmspells[x].GetAction())
+ m_charmspells[x].SetType(apply ? ACT_ENABLED : ACT_DISABLED);
+}
+
+void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow)
+{
+ m_petnumber = petnumber;
+ if (statwindow)
+ m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber);
+ else
+ m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0);
+}
+
+void CharmInfo::LoadPetActionBar(const std::string& data )
+{
+ InitPetActionBar();
+
+ Tokens tokens = StrSplit(data, " ");
+
+ if (tokens.size() != (ACTION_BAR_INDEX_END-ACTION_BAR_INDEX_START)*2)
+ return; // non critical, will reset to default
+
+ uint8 index;
+ Tokens::iterator iter;
+ for (iter = tokens.begin(), index = ACTION_BAR_INDEX_START; index < ACTION_BAR_INDEX_END; ++iter, ++index)
+ {
+ // use unsigned cast to avoid sign negative format use at long-> ActiveStates (int) conversion
+ uint8 type = atol((*iter).c_str());
+ ++iter;
+ uint32 action = atol((*iter).c_str());
+
+ PetActionBar[index].SetActionAndType(action,ActiveStates(type));
+
+ // check correctness
+ if (PetActionBar[index].IsActionBarForSpell())
+ {
+ if (!sSpellStore.LookupEntry(PetActionBar[index].GetAction()))
+ SetActionBar(index,0,ACT_PASSIVE);
+ else if (!IsAutocastableSpell(PetActionBar[index].GetAction()))
+ SetActionBar(index,PetActionBar[index].GetAction(),ACT_PASSIVE);
+ }
+ }
+}
+
+void CharmInfo::BuildActionBar( WorldPacket* data )
+{
+ for (uint32 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
+ *data << uint32(PetActionBar[i].packedData);
+}
+
+void CharmInfo::SetSpellAutocast( uint32 spell_id, bool state )
+{
+ for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
+ {
+ if (spell_id == PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell())
+ {
+ PetActionBar[i].SetType(state ? ACT_ENABLED : ACT_DISABLED);
+ break;
+ }
+ }
+}
+
+bool Unit::isFrozen() const
+{
+ return HasAuraState(AURA_STATE_FROZEN);
+}
+
+struct ProcTriggeredData
+{
+ ProcTriggeredData(Aura* _aura)
+ : aura(_aura)
+ {
+ effMask = 0;
+ spellProcEvent = NULL;
+ }
+ SpellProcEventEntry const *spellProcEvent;
+ Aura * aura;
+ uint32 effMask;
+};
+
+typedef std::list< ProcTriggeredData > ProcTriggeredList;
+
+// List of auras that CAN be trigger but may not exist in spell_proc_event
+// in most case need for drop charges
+// in some types of aura need do additional check
+// for example SPELL_AURA_MECHANIC_IMMUNITY - need check for mechanic
+bool InitTriggerAuraData()
+{
+ for (uint16 i = 0; i < TOTAL_AURAS; ++i)
+ {
+ isTriggerAura[i]=false;
+ isNonTriggerAura[i] = false;
+ }
+ isTriggerAura[SPELL_AURA_DUMMY] = true;
+ isTriggerAura[SPELL_AURA_MOD_CONFUSE] = true;
+ isTriggerAura[SPELL_AURA_MOD_THREAT] = true;
+ isTriggerAura[SPELL_AURA_MOD_STUN] = true; // Aura not have charges but need remove him on trigger
+ isTriggerAura[SPELL_AURA_MOD_DAMAGE_DONE] = true;
+ isTriggerAura[SPELL_AURA_MOD_DAMAGE_TAKEN] = true;
+ isTriggerAura[SPELL_AURA_MOD_RESISTANCE] = true;
+ isTriggerAura[SPELL_AURA_MOD_STEALTH] = true;
+ isTriggerAura[SPELL_AURA_MOD_FEAR] = true; // Aura not have charges but need remove him on trigger
+ isTriggerAura[SPELL_AURA_MOD_ROOT] = true;
+ isTriggerAura[SPELL_AURA_TRANSFORM] = true;
+ isTriggerAura[SPELL_AURA_REFLECT_SPELLS] = true;
+ isTriggerAura[SPELL_AURA_DAMAGE_IMMUNITY] = true;
+ isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL] = true;
+ isTriggerAura[SPELL_AURA_PROC_TRIGGER_DAMAGE] = true;
+ isTriggerAura[SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK] = true;
+ isTriggerAura[SPELL_AURA_SCHOOL_ABSORB] = true; // Savage Defense untested
+ isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT] = true;
+ isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL] = true;
+ isTriggerAura[SPELL_AURA_REFLECT_SPELLS_SCHOOL] = true;
+ isTriggerAura[SPELL_AURA_MECHANIC_IMMUNITY] = true;
+ isTriggerAura[SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN] = true;
+ isTriggerAura[SPELL_AURA_SPELL_MAGNET] = true;
+ isTriggerAura[SPELL_AURA_MOD_ATTACK_POWER] = true;
+ isTriggerAura[SPELL_AURA_ADD_CASTER_HIT_TRIGGER] = true;
+ isTriggerAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true;
+ isTriggerAura[SPELL_AURA_MOD_MECHANIC_RESISTANCE] = true;
+ isTriggerAura[SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS] = true;
+ isTriggerAura[SPELL_AURA_MOD_HASTE] = true;
+ isTriggerAura[SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE]=true;
+ isTriggerAura[SPELL_AURA_RAID_PROC_FROM_CHARGE] = true;
+ isTriggerAura[SPELL_AURA_RAID_PROC_FROM_CHARGE_WITH_VALUE] = true;
+ isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE] = true;
+ isTriggerAura[SPELL_AURA_MOD_DAMAGE_FROM_CASTER] = true;
+ isTriggerAura[SPELL_AURA_MOD_SPELL_CRIT_CHANCE] = true;
+
+ isNonTriggerAura[SPELL_AURA_MOD_POWER_REGEN]=true;
+ isNonTriggerAura[SPELL_AURA_REDUCE_PUSHBACK]=true;
+ isTriggerAura[SPELL_AURA_RANGED_AP_ATTACKER_CREATURES_BONUS] = true;
+
+ return true;
+}
+
+uint32 createProcExtendMask(SpellNonMeleeDamage *damageInfo, SpellMissInfo missCondition)
+{
+ uint32 procEx = PROC_EX_NONE;
+ // Check victim state
+ if (missCondition != SPELL_MISS_NONE)
+ switch (missCondition)
+ {
+ case SPELL_MISS_MISS: procEx|=PROC_EX_MISS; break;
+ case SPELL_MISS_RESIST: procEx|=PROC_EX_RESIST; break;
+ case SPELL_MISS_DODGE: procEx|=PROC_EX_DODGE; break;
+ case SPELL_MISS_PARRY: procEx|=PROC_EX_PARRY; break;
+ case SPELL_MISS_BLOCK: procEx|=PROC_EX_BLOCK; break;
+ case SPELL_MISS_EVADE: procEx|=PROC_EX_EVADE; break;
+ case SPELL_MISS_IMMUNE: procEx|=PROC_EX_IMMUNE; break;
+ case SPELL_MISS_IMMUNE2: procEx|=PROC_EX_IMMUNE; break;
+ case SPELL_MISS_DEFLECT: procEx|=PROC_EX_DEFLECT;break;
+ case SPELL_MISS_ABSORB: procEx|=PROC_EX_ABSORB; break;
+ case SPELL_MISS_REFLECT: procEx|=PROC_EX_REFLECT;break;
+ default:
+ break;
+ }
+ else
+ {
+ // On block
+ if (damageInfo->blocked)
+ procEx|=PROC_EX_BLOCK;
+ // On absorb
+ if (damageInfo->absorb)
+ procEx|=PROC_EX_ABSORB;
+ // On crit
+ if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT)
+ procEx|=PROC_EX_CRITICAL_HIT;
+ else
+ procEx|=PROC_EX_NORMAL_HIT;
+ }
+ return procEx;
+}
+
+void Unit::ProcDamageAndSpellFor(bool isVictim, Unit * pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const * procSpell, uint32 damage, SpellEntry const * procAura)
+{
+ // Player is loaded now - do not allow passive spell casts to proc
+ if (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->GetSession()->PlayerLoading())
+ return;
+ // For melee/ranged based attack need update skills and set some Aura states if victim present
+ if (procFlag & MELEE_BASED_TRIGGER_MASK && pTarget)
+ {
+ // Update skills here for players
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ // On melee based hit/miss/resist need update skill (for victim and attacker)
+ if (procExtra&(PROC_EX_NORMAL_HIT|PROC_EX_MISS|PROC_EX_RESIST))
+ {
+ if (pTarget->GetTypeId() != TYPEID_PLAYER && pTarget->GetCreatureType() != CREATURE_TYPE_CRITTER)
+ ((Player*)this)->UpdateCombatSkills(pTarget, attType, isVictim);
+ }
+ // Update defence if player is victim and parry/dodge/block
+ else if (isVictim && procExtra&(PROC_EX_DODGE|PROC_EX_PARRY|PROC_EX_BLOCK))
+ ((Player*)this)->UpdateCombatSkills(pTarget, attType, MELEE_HIT_DODGE);
+ }
+ // If exist crit/parry/dodge/block need update aura state (for victim and attacker)
+ if (procExtra & (PROC_EX_CRITICAL_HIT|PROC_EX_PARRY|PROC_EX_DODGE|PROC_EX_BLOCK))
+ {
+ // for victim
+ if (isVictim)
+ {
+ // if victim and dodge attack
+ if (procExtra&PROC_EX_DODGE)
+ {
+ //Update AURA_STATE on dodge
+ if (getClass() != CLASS_ROGUE) // skip Rogue Riposte
+ {
+ ModifyAuraState(AURA_STATE_DEFENSE, true);
+ StartReactiveTimer( REACTIVE_DEFENSE );
+ }
+ }
+ // if victim and parry attack
+ if (procExtra & PROC_EX_PARRY)
+ {
+ // For Hunters only Counterattack (skip Mongoose bite)
+ if (getClass() == CLASS_HUNTER)
+ {
+ ModifyAuraState(AURA_STATE_HUNTER_PARRY, true);
+ StartReactiveTimer( REACTIVE_HUNTER_PARRY );
+ }
+ else
+ {
+ ModifyAuraState(AURA_STATE_DEFENSE, true);
+ StartReactiveTimer( REACTIVE_DEFENSE );
+ }
+ }
+ // if and victim block attack
+ if (procExtra & PROC_EX_BLOCK)
+ {
+ ModifyAuraState(AURA_STATE_DEFENSE,true);
+ StartReactiveTimer( REACTIVE_DEFENSE );
+ }
+ }
+ else //For attacker
+ {
+ // Overpower on victim dodge
+ if (procExtra&PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR)
+ {
+ ((Player*)this)->AddComboPoints(pTarget, 1);
+ StartReactiveTimer( REACTIVE_OVERPOWER );
+ }
+ }
+ }
+ }
+
+ ProcTriggeredList procTriggered;
+ // Fill procTriggered list
+ for (AuraApplicationMap::const_iterator itr = GetAppliedAuras().begin(); itr!= GetAppliedAuras().end(); ++itr)
+ {
+ // Do not allow auras to proc from effect triggered by itself
+ if (procAura && procAura->Id == itr->first)
+ continue;
+ ProcTriggeredData triggerData(itr->second->GetBase());
+ // Defensive procs are active on absorbs (so absorption effects are not a hindrance)
+ bool active = (damage > 0) || ((procExtra & PROC_EX_ABSORB) && isVictim);
+ if (!IsTriggeredAtSpellProcEvent(pTarget, triggerData.aura, procSpell, procFlag, procExtra, attType, isVictim, active, triggerData.spellProcEvent))
+ continue;
+
+ for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
+ {
+ if (itr->second->HasEffect(i))
+ {
+ AuraEffect * aurEff = itr->second->GetBase()->GetEffect(i);
+ // Skip this auras
+ if (isNonTriggerAura[aurEff->GetAuraType()])
+ continue;
+ // If not trigger by default and spellProcEvent==NULL - skip
+ if (!isTriggerAura[aurEff->GetAuraType()] && triggerData.spellProcEvent==NULL)
+ continue;
+ uint32 triggered_spell_id = aurEff->GetSpellProto()->EffectTriggerSpell[i];
+ // check for positive auras that proc with charge drop
+ bool positive = (!triggered_spell_id && IsPositiveSpell(aurEff->GetId()) && aurEff->GetBase()->GetCharges()) ||
+ // check for positive auras that triggers unknown spells (Blessing Recovery, etc...)
+ (!sSpellStore.LookupEntry(triggered_spell_id) && IsPositiveSpell(aurEff->GetId())) ||
+ // final check for positive triggered spell
+ IsPositiveSpell(triggered_spell_id);
+ if (!damage && (procExtra & PROC_EX_ABSORB) && isVictim && positive)
+ continue;
+ triggerData.effMask |= 1<<i;
+ }
+ }
+ if (triggerData.effMask)
+ procTriggered.push_front(triggerData);
+ }
+
+ // Nothing found
+ if (procTriggered.empty())
+ return;
+
+ if (procExtra & (PROC_EX_INTERNAL_TRIGGERED | PROC_EX_INTERNAL_CANT_PROC))
+ SetCantProc(true);
+
+ // Handle effects proceed this time
+ for (ProcTriggeredList::const_iterator i = procTriggered.begin(); i != procTriggered.end(); ++i)
+ {
+ // look for aura in auras list, it may be removed while proc event processing
+ if (i->aura->IsRemoved())
+ continue;
+
+ bool useCharges= i->aura->GetCharges()>0;
+ bool takeCharges = false;
+ SpellEntry const *spellInfo = i->aura->GetSpellProto();
+ uint32 Id = i->aura->GetId();
+
+ // For players set spell cooldown if need
+ uint32 cooldown = 0;
+ if (GetTypeId() == TYPEID_PLAYER && i->spellProcEvent && i->spellProcEvent->cooldown)
+ cooldown = i->spellProcEvent->cooldown;
+
+ if (spellInfo->AttributesEx3 & SPELL_ATTR_EX3_DISABLE_PROC)
+ SetCantProc(true);
+
+ // This bool is needed till separate aura effect procs are still here
+ bool handled = false;
+ if (HandleAuraProc(pTarget, damage, i->aura, procSpell, procFlag, procExtra, cooldown, &handled))
+ {
+ sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), Id);
+ takeCharges = true;
+ }
+
+ if (!handled)
+ for (uint8 effIndex = 0; effIndex<MAX_SPELL_EFFECTS; ++effIndex)
+ {
+ if (!(i->effMask & (1<<effIndex)))
+ continue;
+
+ AuraEffect *triggeredByAura = i->aura->GetEffect(effIndex);
+ assert(triggeredByAura);
+
+ switch(triggeredByAura->GetAuraType())
+ {
+ case SPELL_AURA_PROC_TRIGGER_SPELL:
+ {
+ sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
+ // Don`t drop charge or add cooldown for not started trigger
+ if (HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
+ takeCharges = true;
+ break;
+ }
+ case SPELL_AURA_PROC_TRIGGER_DAMAGE:
+ {
+ sLog.outDebug("ProcDamageAndSpell: doing %u damage from spell id %u (triggered by %s aura of spell %u)", triggeredByAura->GetAmount() , spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
+ SpellNonMeleeDamage damageInfo(this, pTarget, spellInfo->Id, spellInfo->SchoolMask);
+ uint32 damage = SpellDamageBonus(pTarget, spellInfo, triggeredByAura->GetAmount(), SPELL_DIRECT_DAMAGE);
+ CalculateSpellDamageTaken(&damageInfo, damage, spellInfo);
+ DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb);
+ SendSpellNonMeleeDamageLog(&damageInfo);
+ DealSpellDamage(&damageInfo, true);
+ takeCharges = true;
+ break;
+ }
+ case SPELL_AURA_MANA_SHIELD:
+ case SPELL_AURA_DUMMY:
+ {
+ sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s dummy aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
+ if (HandleDummyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
+ takeCharges = true;
+ break;
+ }
+ case SPELL_AURA_OBS_MOD_POWER:
+ sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
+ if (HandleObsModEnergyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
+ takeCharges = true;
+ break;
+ case SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN:
+ sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
+ if (HandleModDamagePctTakenAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
+ takeCharges = true;
+ break;
+ case SPELL_AURA_MOD_HASTE:
+ {
+ sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s haste aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
+ if (HandleHasteAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
+ takeCharges = true;
+ break;
+ }
+ case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
+ {
+ sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
+ if (HandleOverrideClassScriptAuraProc(pTarget, damage, triggeredByAura, procSpell, cooldown))
+ takeCharges = true;
+ break;
+ }
+ case SPELL_AURA_RAID_PROC_FROM_CHARGE_WITH_VALUE:
+ {
+ sLog.outDebug("ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
+ (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
+
+ HandleAuraRaidProcFromChargeWithValue(triggeredByAura);
+ takeCharges = true;
+ break;
+ }
+ case SPELL_AURA_RAID_PROC_FROM_CHARGE:
+ {
+ sLog.outDebug("ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
+ (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
+
+ HandleAuraRaidProcFromCharge(triggeredByAura);
+ takeCharges = true;
+ break;
+ }
+ case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE:
+ {
+ sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
+
+ if (HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
+ takeCharges = true;
+ break;
+ }
+ case SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK:
+ // Skip melee hits or instant cast spells
+ if (procSpell && GetSpellCastTime(procSpell) != 0)
+ takeCharges = true;
+ break;
+ case SPELL_AURA_REFLECT_SPELLS_SCHOOL:
+ // Skip Melee hits and spells ws wrong school
+ if (procSpell && (triggeredByAura->GetMiscValue() & procSpell->SchoolMask)) // School check
+ takeCharges = true;
+ break;
+ case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT:
+ case SPELL_AURA_MOD_POWER_COST_SCHOOL:
+ // Skip melee hits and spells ws wrong school or zero cost
+ if (procSpell &&
+ (procSpell->manaCost != 0 || procSpell->ManaCostPercentage != 0) && // Cost check
+ (triggeredByAura->GetMiscValue() & procSpell->SchoolMask) == 0) // School check
+ takeCharges = true;
+ break;
+ case SPELL_AURA_MECHANIC_IMMUNITY:
+ // Compare mechanic
+ if (procSpell && procSpell->Mechanic == triggeredByAura->GetMiscValue())
+ takeCharges = true;
+ break;
+ case SPELL_AURA_MOD_MECHANIC_RESISTANCE:
+ // Compare mechanic
+ if (procSpell && procSpell->Mechanic == triggeredByAura->GetMiscValue())
+ takeCharges = true;
+ break;
+ case SPELL_AURA_MOD_DAMAGE_FROM_CASTER:
+ // Compare casters
+ if (triggeredByAura->GetCasterGUID() == pTarget->GetGUID())
+ takeCharges = true;
+ break;
+ case SPELL_AURA_MOD_SPELL_CRIT_CHANCE:
+ sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s spell crit chance aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
+ if (procSpell && HandleSpellCritChanceAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
+ takeCharges = true;
+ break;
+ // CC Auras which use their amount amount to drop
+ // Are there any more auras which need this?
+ case SPELL_AURA_MOD_CONFUSE:
+ case SPELL_AURA_MOD_FEAR:
+ case SPELL_AURA_MOD_STUN:
+ case SPELL_AURA_MOD_ROOT:
+ case SPELL_AURA_TRANSFORM:
+ if (isVictim && damage)
+ {
+ // Damage is dealt after proc system - lets ignore auras which wasn't updated yet
+ // to make spell not remove its own aura
+ if (i->aura->GetDuration() == i->aura->GetMaxDuration())
+ break;
+ int32 damageLeft = triggeredByAura->GetAmount();
+ // No damage left
+ if (damageLeft < damage )
+ i->aura->Remove();
+ else
+ triggeredByAura->SetAmount(damageLeft-damage);
+ }
+ break;
+ //case SPELL_AURA_ADD_FLAT_MODIFIER:
+ //case SPELL_AURA_ADD_PCT_MODIFIER:
+ // HandleSpellModAuraProc
+ //break;
+ default:
+ // nothing do, just charges counter
+ takeCharges = true;
+ break;
+ }
+ }
+ // Remove charge (aura can be removed by triggers)
+ if (useCharges && takeCharges)
+ i->aura->DropCharge();
+
+ if (spellInfo->AttributesEx3 & SPELL_ATTR_EX3_DISABLE_PROC)
+ SetCantProc(false);
+ }
+
+ // Cleanup proc requirements
+ if (procExtra & (PROC_EX_INTERNAL_TRIGGERED | PROC_EX_INTERNAL_CANT_PROC))
+ SetCantProc(false);
+}
+
+SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const
+{
+ return SPELL_SCHOOL_MASK_NORMAL;
+}
+
+Player* Unit::GetSpellModOwner() const
+{
+ if (GetTypeId() == TYPEID_PLAYER)
+ return (Player*)this;
+ if (((Creature*)this)->isPet() || ((Creature*)this)->isTotem())
+ {
+ Unit* owner = GetOwner();
+ if (owner && owner->GetTypeId() == TYPEID_PLAYER)
+ return (Player*)owner;
+ }
+ return NULL;
+}
+
+///----------Pet responses methods-----------------
+void Unit::SendPetCastFail(uint32 spellid, SpellCastResult msg)
+{
+ if (msg == SPELL_CAST_OK)
+ return;
+
+ Unit *owner = GetCharmerOrOwner();
+ if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
+ return;
+
+ WorldPacket data(SMSG_PET_CAST_FAILED, 1 + 4 + 1);
+ data << uint8(0); // cast count?
+ data << uint32(spellid);
+ data << uint8(msg);
+ // uint32 for some reason
+ // uint32 for some reason
+ ((Player*)owner)->GetSession()->SendPacket(&data);
+}
+
+void Unit::SendPetActionFeedback (uint8 msg)
+{
+ Unit* owner = GetOwner();
+ if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
+ return;
+
+ WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1);
+ data << uint8(msg);
+ ((Player*)owner)->GetSession()->SendPacket(&data);
+}
+
+void Unit::SendPetTalk (uint32 pettalk)
+{
+ Unit* owner = GetOwner();
+ if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
+ return;
+
+ WorldPacket data(SMSG_PET_ACTION_SOUND, 8 + 4);
+ data << uint64(GetGUID());
+ data << uint32(pettalk);
+ ((Player*)owner)->GetSession()->SendPacket(&data);
+}
+
+void Unit::SendPetAIReaction(uint64 guid)
+{
+ Unit* owner = GetOwner();
+ if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
+ return;
+
+ WorldPacket data(SMSG_AI_REACTION, 8 + 4);
+ data << uint64(guid);
+ data << uint32(AI_REACTION_AGGRO);
+ ((Player*)owner)->GetSession()->SendPacket(&data);
+}
+
+///----------End of Pet responses methods----------
+
+void Unit::StopMoving()
+{
+ clearUnitState(UNIT_STAT_MOVING);
+
+ // send explicit stop packet
+ // rely on vmaps here because for example stormwind is in air
+ //float z = MapManager::Instance().GetBaseMap(GetMapId())->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), true);
+ //if (fabs(GetPositionZ() - z) < 2.0f)
+ // Relocate(GetPositionX(), GetPositionY(), z);
+ //Relocate(GetPositionX(), GetPositionY(),GetPositionZ());
+
+ SendMonsterStop();
+
+ // update position and orientation;
+ WorldPacket data;
+ BuildHeartBeatMsg(&data);
+ SendMessageToSet(&data,false);
+}
+
+void Unit::SendMovementFlagUpdate()
+{
+ WorldPacket data;
+ BuildHeartBeatMsg(&data);
+ SendMessageToSet(&data, false);
+}
+
+bool Unit::IsSitState() const
+{
+ uint8 s = getStandState();
+ return
+ s == UNIT_STAND_STATE_SIT_CHAIR || s == UNIT_STAND_STATE_SIT_LOW_CHAIR ||
+ s == UNIT_STAND_STATE_SIT_MEDIUM_CHAIR || s == UNIT_STAND_STATE_SIT_HIGH_CHAIR ||
+ s == UNIT_STAND_STATE_SIT;
+}
+
+bool Unit::IsStandState() const
+{
+ uint8 s = getStandState();
+ return !IsSitState() && s != UNIT_STAND_STATE_SLEEP && s != UNIT_STAND_STATE_KNEEL;
+}
+
+void Unit::SetStandState(uint8 state)
+{
+ SetByteValue(UNIT_FIELD_BYTES_1, 0, state);
+
+ if (IsStandState())
+ RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED);
+
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ WorldPacket data(SMSG_STANDSTATE_UPDATE, 1);
+ data << (uint8)state;
+ ((Player*)this)->GetSession()->SendPacket(&data);
+ }
+}
+
+bool Unit::IsPolymorphed() const
+{
+ uint32 transformId = getTransForm();
+ if (!transformId)
+ return false;
+
+ const SpellEntry *spellInfo=sSpellStore.LookupEntry(transformId);
+ if (!spellInfo)
+ return false;
+
+ return GetSpellSpecific(spellInfo)==SPELL_SPECIFIC_MAGE_POLYMORPH;
+}
+
+void Unit::SetDisplayId(uint32 modelId)
+{
+ SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId);
+
+ if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
+ {
+ Pet *pet = ((Pet*)this);
+ if (!pet->isControlled())
+ return;
+ Unit *owner = GetOwner();
+ if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
+ ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID);
+ }
+}
+
+void Unit::ClearComboPointHolders()
+{
+ while(!m_ComboPointHolders.empty())
+ {
+ uint32 lowguid = *m_ComboPointHolders.begin();
+
+ Player* plr = objmgr.GetPlayer(MAKE_NEW_GUID(lowguid, 0, HIGHGUID_PLAYER));
+ if (plr && plr->GetComboTarget()==GetGUID()) // recheck for safe
+ plr->ClearComboPoints(); // remove also guid from m_ComboPointHolders;
+ else
+ m_ComboPointHolders.erase(lowguid); // or remove manually
+ }
+}
+
+void Unit::ClearAllReactives()
+{
+ for (uint8 i=0; i < MAX_REACTIVE; ++i)
+ m_reactiveTimer[i] = 0;
+
+ if (HasAuraState(AURA_STATE_DEFENSE))
+ ModifyAuraState(AURA_STATE_DEFENSE, false);
+ if (getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
+ ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
+ if (getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
+ ((Player*)this)->ClearComboPoints();
+}
+
+void Unit::UpdateReactives( uint32 p_time )
+{
+ for (uint8 i = 0; i < MAX_REACTIVE; ++i)
+ {
+ ReactiveType reactive = ReactiveType(i);
+
+ if (!m_reactiveTimer[reactive])
+ continue;
+
+ if ( m_reactiveTimer[reactive] <= p_time)
+ {
+ m_reactiveTimer[reactive] = 0;
+
+ switch ( reactive )
+ {
+ case REACTIVE_DEFENSE:
+ if (HasAuraState(AURA_STATE_DEFENSE))
+ ModifyAuraState(AURA_STATE_DEFENSE, false);
+ break;
+ case REACTIVE_HUNTER_PARRY:
+ if ( getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
+ ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
+ break;
+ case REACTIVE_OVERPOWER:
+ if (getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
+ ((Player*)this)->ClearComboPoints();
+ break;
+ default:
+ break;
+ }
+ }
+ else
+ {
+ m_reactiveTimer[reactive] -= p_time;
+ }
+ }
+}
+
+Unit* Unit::SelectNearbyTarget(float dist) const
+{
+ std::list<Unit *> targets;
+ Trinity::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, dist);
+ Trinity::UnitListSearcher<Trinity::AnyUnfriendlyUnitInObjectRangeCheck> searcher(this, targets, u_check);
+ VisitNearbyObject(dist, searcher);
+
+ // remove current target
+ if (getVictim())
+ targets.remove(getVictim());
+
+ // remove not LoS targets
+ for (std::list<Unit *>::iterator tIter = targets.begin(); tIter != targets.end();)
+ {
+ if (!IsWithinLOSInMap(*tIter))
+ {
+ std::list<Unit *>::iterator tIter2 = tIter;
+ ++tIter;
+ targets.erase(tIter2);
+ }
+ else
+ ++tIter;
+ }
+
+ // no appropriate targets
+ if (targets.empty())
+ return NULL;
+
+ // select random
+ uint32 rIdx = urand(0,targets.size()-1);
+ std::list<Unit *>::const_iterator tcIter = targets.begin();
+ for (uint32 i = 0; i < rIdx; ++i)
+ ++tcIter;
+
+ return *tcIter;
+}
+
+void Unit::ApplyAttackTimePercentMod( WeaponAttackType att,float val, bool apply )
+{
+ float remainingTimePct = (float)m_attackTimer[att] / (GetAttackTime(att) * m_modAttackSpeedPct[att]);
+ if (val > 0)
+ {
+ ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply);
+ ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,val,!apply);
+ }
+ else
+ {
+ ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply);
+ ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,-val,apply);
+ }
+ m_attackTimer[att] = uint32(GetAttackTime(att) * m_modAttackSpeedPct[att] * remainingTimePct);
+}
+
+void Unit::ApplyCastTimePercentMod(float val, bool apply )
+{
+ if (val > 0)
+ ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,val,!apply);
+ else
+ ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,-val,apply);
+}
+
+uint32 Unit::GetCastingTimeForBonus( SpellEntry const *spellProto, DamageEffectType damagetype, uint32 CastingTime )
+{
+ // Not apply this to creature casted spells with casttime==0
+ if (CastingTime==0 && GetTypeId() == TYPEID_UNIT && !((Creature*)this)->isPet())
+ return 3500;
+
+ if (CastingTime > 7000) CastingTime = 7000;
+ if (CastingTime < 1500) CastingTime = 1500;
+
+ if (damagetype == DOT && !IsChanneledSpell(spellProto))
+ CastingTime = 3500;
+
+ int32 overTime = 0;
+ uint8 effects = 0;
+ bool DirectDamage = false;
+ bool AreaEffect = false;
+
+ for (uint32 i=0; i<MAX_SPELL_EFFECTS; i++)
+ {
+ switch ( spellProto->Effect[i] )
+ {
+ case SPELL_EFFECT_SCHOOL_DAMAGE:
+ case SPELL_EFFECT_POWER_DRAIN:
+ case SPELL_EFFECT_HEALTH_LEECH:
+ case SPELL_EFFECT_ENVIRONMENTAL_DAMAGE:
+ case SPELL_EFFECT_POWER_BURN:
+ case SPELL_EFFECT_HEAL:
+ DirectDamage = true;
+ break;
+ case SPELL_EFFECT_APPLY_AURA:
+ switch ( spellProto->EffectApplyAuraName[i] )
+ {
+ case SPELL_AURA_PERIODIC_DAMAGE:
+ case SPELL_AURA_PERIODIC_HEAL:
+ case SPELL_AURA_PERIODIC_LEECH:
+ if ( GetSpellDuration(spellProto) )
+ overTime = GetSpellDuration(spellProto);
+ break;
+ default:
+ // -5% per additional effect
+ ++effects;
+ break;
+ }
+ default:
+ break;
+ }
+
+ if (IsAreaEffectTarget[spellProto->EffectImplicitTargetA[i]] || IsAreaEffectTarget[spellProto->EffectImplicitTargetB[i]])
+ AreaEffect = true;
+ }
+
+ // Combined Spells with Both Over Time and Direct Damage
+ if ( overTime > 0 && CastingTime > 0 && DirectDamage )
+ {
+ // mainly for DoTs which are 3500 here otherwise
+ uint32 OriginalCastTime = GetSpellCastTime(spellProto);
+ if (OriginalCastTime > 7000) OriginalCastTime = 7000;
+ if (OriginalCastTime < 1500) OriginalCastTime = 1500;
+ // Portion to Over Time
+ float PtOT = (overTime / 15000.0f) / ((overTime / 15000.0f) + (OriginalCastTime / 3500.0f));
+
+ if ( damagetype == DOT )
+ CastingTime = uint32(CastingTime * PtOT);
+ else if ( PtOT < 1.0f )
+ CastingTime = uint32(CastingTime * (1 - PtOT));
+ else
+ CastingTime = 0;
+ }
+
+ // Area Effect Spells receive only half of bonus
+ if ( AreaEffect )
+ CastingTime /= 2;
+
+ // -5% of total per any additional effect
+ for (uint8 i=0; i<effects; ++i)
+ {
+ if ( CastingTime > 175 )
+ {
+ CastingTime -= 175;
+ }
+ else
+ {
+ CastingTime = 0;
+ break;
+ }
+ }
+
+ return CastingTime;
+}
+
+void Unit::UpdateAuraForGroup(uint8 slot)
+{
+ if (slot >= MAX_AURAS) // slot not found, return
+ return;
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ Player* player = (Player*)this;
+ if (player->GetGroup())
+ {
+ player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_AURAS);
+ player->SetAuraUpdateMaskForRaid(slot);
+ }
+ }
+ else if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
+ {
+ Pet *pet = ((Pet*)this);
+ if (pet->isControlled())
+ {
+ Unit *owner = GetOwner();
+ if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
+ {
+ ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_AURAS);
+ pet->SetAuraUpdateMaskForRaid(slot);
+ }
+ }
+ }
+}
+
+float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized)
+{
+ if (!normalized || GetTypeId() != TYPEID_PLAYER)
+ return float(GetAttackTime(attType))/1000.0f;
+
+ Item *Weapon = ((Player*)this)->GetWeaponForAttack(attType);
+ if (!Weapon)
+ return 2.4; // fist attack
+
+ switch (Weapon->GetProto()->InventoryType)
+ {
+ case INVTYPE_2HWEAPON:
+ return 3.3;
+ case INVTYPE_RANGED:
+ case INVTYPE_RANGEDRIGHT:
+ case INVTYPE_THROWN:
+ return 2.8;
+ case INVTYPE_WEAPON:
+ case INVTYPE_WEAPONMAINHAND:
+ case INVTYPE_WEAPONOFFHAND:
+ default:
+ return Weapon->GetProto()->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7 : 2.4;
+ }
+}
+
+bool Unit::IsUnderLastManaUseEffect() const
+{
+ return getMSTimeDiff(m_lastManaUse,getMSTime()) < 5000;
+}
+
+void Unit::SetContestedPvP(Player *attackedPlayer)
+{
+ Player* player = GetCharmerOrOwnerPlayerOrPlayerItself();
+
+ if (!player || attackedPlayer && (attackedPlayer == player || player->duel && player->duel->opponent == attackedPlayer))
+ return;
+
+ player->SetContestedPvPTimer(30000);
+ if (!player->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
+ {
+ player->addUnitState(UNIT_STAT_ATTACK_PLAYER);
+ player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
+ // call MoveInLineOfSight for nearby contested guards
+ player->SetVisibility(player->GetVisibility());
+ }
+ if (!hasUnitState(UNIT_STAT_ATTACK_PLAYER))
+ {
+ addUnitState(UNIT_STAT_ATTACK_PLAYER);
+ // call MoveInLineOfSight for nearby contested guards
+ SetVisibility(GetVisibility());
+ }
+}
+
+void Unit::AddPetAura(PetAura const* petSpell)
+{
+ if (GetTypeId() != TYPEID_PLAYER)
+ return;
+
+ m_petAuras.insert(petSpell);
+ if (Pet* pet = ((Player*)this)->GetPet())
+ pet->CastPetAura(petSpell);
+}
+
+void Unit::RemovePetAura(PetAura const* petSpell)
+{
+ if (GetTypeId() != TYPEID_PLAYER)
+ return;
+
+ m_petAuras.erase(petSpell);
+ if (Pet* pet = ((Player*)this)->GetPet())
+ pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry()));
+}
+
+Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget,uint32 spell_id)
+{
+ if (GetTypeId() != TYPEID_PLAYER)
+ return NULL;
+
+ Pet* pet = new Pet((Player*)this, HUNTER_PET);
+
+ if (!pet->CreateBaseAtCreature(creatureTarget))
+ {
+ delete pet;
+ return NULL;
+ }
+
+ pet->SetCreatorGUID(GetGUID());
+ pet->setFaction(getFaction());
+ pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id);
+
+ if (GetTypeId() == TYPEID_PLAYER)
+ pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
+
+ uint8 level = (creatureTarget->getLevel() < (getLevel() - 5)) ? (getLevel() - 5) : creatureTarget->getLevel();
+
+ if (!pet->InitStatsForLevel(level))
+ {
+ sLog.outError("Pet::InitStatsForLevel() failed for creature (Entry: %u)!",creatureTarget->GetEntry());
+ delete pet;
+ return NULL;
+ }
+
+ pet->GetCharmInfo()->SetPetNumber(objmgr.GeneratePetNumber(), true);
+ // this enables pet details window (Shift+P)
+ pet->InitPetCreateSpells();
+ //pet->InitLevelupSpellsForLevel();
+ pet->SetHealth(pet->GetMaxHealth());
+
+ return pet;
+}
+
+bool Unit::IsTriggeredAtSpellProcEvent(Unit *pVictim, Aura * aura, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const *& spellProcEvent )
+{
+ SpellEntry const *spellProto = aura->GetSpellProto();
+
+ // Get proc Event Entry
+ spellProcEvent = spellmgr.GetSpellProcEvent(spellProto->Id);
+
+ // Get EventProcFlag
+ uint32 EventProcFlag;
+ if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags
+ EventProcFlag = spellProcEvent->procFlags;
+ else
+ EventProcFlag = spellProto->procFlags; // else get from spell proto
+ // Continue if no trigger exist
+ if (!EventProcFlag)
+ return false;
+
+ // Additional checks for triggered spells (ignore trap casts)
+ if (procExtra & PROC_EX_INTERNAL_TRIGGERED && !(procFlag & PROC_FLAG_ON_TRAP_ACTIVATION))
+ {
+ if (!(spellProto->AttributesEx3 & SPELL_ATTR_EX3_CAN_PROC_TRIGGERED))
+ return false;
+ }
+
+ // Check spellProcEvent data requirements
+ if (!spellmgr.IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active))
+ return false;
+ // In most cases req get honor or XP from kill
+ if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER)
+ {
+ bool allow = ((Player*)this)->isHonorOrXPTarget(pVictim);
+ // Shadow Word: Death - can trigger from every kill
+ if (aura->GetId() == 32409)
+ allow = true;
+ if (!allow)
+ return false;
+ }
+ // Aura added by spell can`t trigger from self (prevent drop charges/do triggers)
+ // But except periodic and kill triggers (can triggered from self)
+ if (procSpell && procSpell->Id == spellProto->Id
+ && !(spellProto->procFlags&(PROC_FLAG_ON_TAKE_PERIODIC | PROC_FLAG_KILL)))
+ return false;
+
+ // Check if current equipment allows aura to proc
+ if (!isVictim && GetTypeId() == TYPEID_PLAYER)
+ {
+ if (spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
+ {
+ Item *item = NULL;
+ if (attType == BASE_ATTACK)
+ item = ((Player*)this)->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
+ else if (attType == OFF_ATTACK)
+ item = ((Player*)this)->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
+ else
+ item = ((Player*)this)->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
+
+ if (((Player*)this)->IsInFeralForm())
+ return false;
+
+ if (!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
+ return false;
+ }
+ else if (spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
+ {
+ // Check if player is wearing shield
+ Item *item = ((Player*)this)->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
+ if (!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
+ return false;
+ }
+ }
+ // Get chance from spell
+ float chance = float(spellProto->procChance);
+ // If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance;
+ if (spellProcEvent && spellProcEvent->customChance)
+ chance = spellProcEvent->customChance;
+ // If PPM exist calculate chance from PPM
+ if (spellProcEvent && spellProcEvent->ppmRate != 0)
+ {
+ if (!isVictim)
+ {
+ uint32 WeaponSpeed = GetAttackTime(attType);
+ chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate, spellProto);
+ }
+ else
+ {
+ uint32 WeaponSpeed = pVictim->GetAttackTime(attType);
+ chance = pVictim->GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate, spellProto);
+ }
+ }
+ // Apply chance modifer aura
+ if (Player* modOwner = GetSpellModOwner())
+ {
+ modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
+ }
+ return roll_chance_f(chance);
+}
+
+bool Unit::HandleAuraRaidProcFromChargeWithValue(AuraEffect *triggeredByAura)
+{
+ // aura can be deleted at casts
+ SpellEntry const *spellProto = triggeredByAura->GetSpellProto();
+ uint32 effIdx = triggeredByAura->GetEffIndex();
+ int32 heal = triggeredByAura->GetAmount();
+ uint64 caster_guid = triggeredByAura->GetCasterGUID();
+
+ //Currently only Prayer of Mending
+ if (!(spellProto->SpellFamilyName == SPELLFAMILY_PRIEST && spellProto->SpellFamilyFlags[1] & 0x20))
+ {
+ sLog.outDebug("Unit::HandleAuraRaidProcFromChargeWithValue, received not handled spell: %u", spellProto->Id);
+ return false;
+ }
+
+ // jumps
+ int32 jumps = triggeredByAura->GetBase()->GetCharges()-1;
+
+ // current aura expire
+ triggeredByAura->GetBase()->SetCharges(1); // will removed at next charges decrease
+
+ // next target selection
+ if (jumps > 0)
+ {
+ float radius;
+ if (spellProto->EffectRadiusIndex[effIdx])
+ radius = GetSpellRadiusForTarget(triggeredByAura->GetCaster(), sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
+ else
+ radius = GetSpellMaxRangeForTarget(triggeredByAura->GetCaster(), sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
+
+ if (Unit * caster = triggeredByAura->GetCaster())
+ {
+ if (Player * modOwner = caster->GetSpellModOwner())
+ modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius, NULL);
+
+ if (Unit *target = GetNextRandomRaidMemberOrPet(radius))
+ {
+ CastCustomSpell(target, spellProto->Id, &heal, NULL, NULL, true, NULL, triggeredByAura, caster_guid);
+ if (Aura * aura = target->GetAura(spellProto->Id, caster->GetGUID()))
+ aura->SetCharges(jumps);
+ heal = caster->SpellHealingBonus(this, spellProto, heal, HEAL);
+ }
+ }
+ }
+
+ // heal
+ CastCustomSpell(this, 33110, &heal, NULL, NULL, true, NULL, NULL, caster_guid);
+ return true;
+
+}
+bool Unit::HandleAuraRaidProcFromCharge(AuraEffect* triggeredByAura)
+{
+ // aura can be deleted at casts
+ SpellEntry const* spellProto = triggeredByAura->GetSpellProto();
+
+ uint32 damageSpellId;
+ switch (spellProto->Id)
+ {
+ case 57949: //shiver
+ damageSpellId = 57952;
+ //animationSpellId = 57951; dummy effects for jump spell have unknown use (see also 41637)
+ break;
+ case 59978: //shiver
+ damageSpellId = 59979;
+ break;
+ case 43593: //Cold Stare
+ damageSpellId = 43594;
+ break;
+ default:
+ sLog.outError("Unit::HandleAuraRaidProcFromCharge, received not handled spell: %u", spellProto->Id);
+ return false;
+ }
+
+ uint64 caster_guid = triggeredByAura->GetCasterGUID();
+ uint32 effIdx = triggeredByAura->GetEffIndex();
+
+ // jumps
+ int32 jumps = triggeredByAura->GetBase()->GetCharges()-1;
+
+ // current aura expire
+ triggeredByAura->GetBase()->SetCharges(1); // will removed at next charges decrease
+
+ // next target selection
+ if (jumps > 0)
+ {
+ float radius;
+ if (spellProto->EffectRadiusIndex[effIdx])
+ radius = GetSpellRadiusForTarget(triggeredByAura->GetCaster(), sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
+ else
+ radius = GetSpellMaxRangeForTarget(triggeredByAura->GetCaster() ,sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
+
+ if (Unit * caster = triggeredByAura->GetCaster())
+ {
+ if (Player * modOwner = caster->GetSpellModOwner())
+ modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius, NULL);
+
+ if (Unit* target= GetNextRandomRaidMemberOrPet(radius))
+ {
+ CastSpell(target, spellProto, true,NULL,triggeredByAura,caster_guid);
+ if (Aura * aura = target->GetAura(spellProto->Id, caster->GetGUID()))
+ aura->SetCharges(jumps);
+ }
+ }
+ }
+
+ CastSpell(this, damageSpellId, true,NULL,triggeredByAura,caster_guid);
+
+ return true;
+}
+/*-----------------------TRINITY-----------------------------*/
+
+void Unit::SetToNotify()
+{
+ if (GetTypeId() == TYPEID_PLAYER)
+ AddToNotify(NOTIFY_VISIBILITY_CHANGED | NOTIFY_AI_RELOCATION | NOTIFY_PLAYER_VISIBILITY);
+ else
+ AddToNotify(NOTIFY_VISIBILITY_CHANGED | NOTIFY_AI_RELOCATION);
+}
+
+void Unit::Kill(Unit *pVictim, bool durabilityLoss)
+{
+ // Prevent killing unit twice (and giving reward from kill twice)
+ if (!pVictim->GetHealth())
+ return;
+
+ // Inform pets (if any) when player kills target)
+ if (this->GetTypeId() == TYPEID_PLAYER && ((Player*)this)->GetPet())
+ {
+ Pet *pPet = ((Player*)this)->GetPet();
+
+ if (pPet && pPet->isAlive() && pPet->isControlled())
+ pPet->AI()->KilledUnit(pVictim);
+ }
+
+ //sLog.outError("%u kill %u", GetEntry(), pVictim->GetEntry());
+
+ pVictim->SetHealth(0);
+
+ // find player: owner of controlled `this` or `this` itself maybe
+ Player *player = GetCharmerOrOwnerPlayerOrPlayerItself();
+
+ bool bRewardIsAllowed = true;
+ if (pVictim->GetTypeId() == TYPEID_UNIT)
+ {
+ bRewardIsAllowed = ((Creature*)pVictim)->IsDamageEnoughForLootingAndReward();
+ if (!bRewardIsAllowed)
+ ((Creature*)pVictim)->SetLootRecipient(NULL);
+ }
+
+ if (bRewardIsAllowed && pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->GetLootRecipient())
+ player = ((Creature*)pVictim)->GetLootRecipient();
+ // Reward player, his pets, and group/raid members
+ // call kill spell proc event (before real die and combat stop to triggering auras removed at death/combat stop)
+ if (bRewardIsAllowed && player && player!=pVictim)
+ {
+ WorldPacket data(SMSG_PARTYKILLLOG, (8+8)); //send event PARTY_KILL
+ data << uint64(player->GetGUID()); //player with killing blow
+ data << uint64(pVictim->GetGUID()); //victim
+ if (Group *group = player->GetGroup())
+ group->BroadcastPacket(&data, group->GetMemberGroup(player->GetGUID()));
+ else
+ player->SendDirectMessage(&data);
+
+ if (player->RewardPlayerAndGroupAtKill(pVictim))
+ player->ProcDamageAndSpell(pVictim, PROC_FLAG_KILL, PROC_FLAG_KILLED, PROC_EX_NONE, 0);
+ else
+ player->ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_KILLED, PROC_EX_NONE, 0);
+ }
+
+ // Proc auras on death - must be before aura/combat remove
+ pVictim->ProcDamageAndSpell(NULL, PROC_FLAG_DEATH, PROC_FLAG_NONE, PROC_EX_NONE, 0, BASE_ATTACK, 0);
+
+ // if talent known but not triggered (check priest class for speedup check)
+ bool SpiritOfRedemption = false;
+ if (pVictim->GetTypeId() == TYPEID_PLAYER && pVictim->getClass() == CLASS_PRIEST)
+ {
+ AuraEffectList const& vDummyAuras = pVictim->GetAuraEffectsByType(SPELL_AURA_DUMMY);
+ for (AuraEffectList::const_iterator itr = vDummyAuras.begin(); itr != vDummyAuras.end(); ++itr)
+ {
+ if ((*itr)->GetSpellProto()->SpellIconID==1654)
+ {
+ // save value before aura remove
+ uint32 ressSpellId = pVictim->GetUInt32Value(PLAYER_SELF_RES_SPELL);
+ if (!ressSpellId)
+ ressSpellId = ((Player*)pVictim)->GetResurrectionSpellId();
+ //Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers)
+ pVictim->RemoveAllAurasOnDeath();
+ // restore for use at real death
+ pVictim->SetUInt32Value(PLAYER_SELF_RES_SPELL,ressSpellId);
+
+ // FORM_SPIRITOFREDEMPTION and related auras
+ pVictim->CastSpell(pVictim,27827,true,NULL,*itr);
+ SpiritOfRedemption = true;
+ break;
+ }
+ }
+ }
+
+ if (!SpiritOfRedemption)
+ {
+ DEBUG_LOG("SET JUST_DIED");
+ pVictim->setDeathState(JUST_DIED);
+ }
+
+ // 10% durability loss on death
+ // clean InHateListOf
+ if (pVictim->GetTypeId() == TYPEID_PLAYER)
+ {
+ // remember victim PvP death for corpse type and corpse reclaim delay
+ // at original death (not at SpiritOfRedemtionTalent timeout)
+ ((Player*)pVictim)->SetPvPDeath(player != NULL);
+
+ // only if not player and not controlled by player pet. And not at BG
+ if ((durabilityLoss && !player && !((Player*)pVictim)->InBattleGround()) || (player && sWorld.getConfig(CONFIG_DURABILITY_LOSS_IN_PVP)))
+ {
+ DEBUG_LOG("We are dead, losing %u percent durability", sWorld.getRate(RATE_DURABILITY_LOSS_ON_DEATH));
+ ((Player*)pVictim)->DurabilityLossAll(sWorld.getRate(RATE_DURABILITY_LOSS_ON_DEATH),false);
+ // durability lost message
+ WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
+ ((Player*)pVictim)->GetSession()->SendPacket(&data);
+ }
+ // Call KilledUnit for creatures
+ if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsAIEnabled)
+ ((Creature*)this)->AI()->KilledUnit(pVictim);
+
+ // last damage from non duel opponent or opponent controlled creature
+ if (((Player*)pVictim)->duel)
+ {
+ ((Player*)pVictim)->duel->opponent->CombatStopWithPets(true);
+ ((Player*)pVictim)->CombatStopWithPets(true);
+ ((Player*)pVictim)->DuelComplete(DUEL_INTERUPTED);
+ }
+ }
+ else // creature died
+ {
+ DEBUG_LOG("DealDamageNotPlayer");
+ Creature *cVictim = (Creature*)pVictim;
+
+ if (!cVictim->isPet())
+ {
+ cVictim->DeleteThreatList();
+ CreatureInfo const* cInfo = cVictim->GetCreatureInfo();
+ if (cInfo && (cInfo->lootid || cInfo->maxgold > 0))
+ cVictim->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
+ }
+
+ // Call KilledUnit for creatures, this needs to be called after the lootable flag is set
+ if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsAIEnabled)
+ ((Creature*)this)->AI()->KilledUnit(pVictim);
+
+ // Call creature just died function
+ if (cVictim->IsAIEnabled)
+ cVictim->AI()->JustDied(this);
+
+ // Dungeon specific stuff, only applies to players killing creatures
+ if (cVictim->GetInstanceId())
+ {
+ Map *m = cVictim->GetMap();
+ Player *creditedPlayer = GetCharmerOrOwnerPlayerOrPlayerItself();
+ // TODO: do instance binding anyway if the charmer/owner is offline
+
+ if (m->IsDungeon() && creditedPlayer)
+ {
+ if (m->IsRaidOrHeroicDungeon())
+ {
+ if (cVictim->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
+ ((InstanceMap *)m)->PermBindAllPlayers(creditedPlayer);
+ }
+ else
+ {
+ // the reset time is set but not added to the scheduler
+ // until the players leave the instance
+ time_t resettime = cVictim->GetRespawnTimeEx() + 2 * HOUR;
+ if (InstanceSave *save = sInstanceSaveManager.GetInstanceSave(cVictim->GetInstanceId()))
+ if (save->GetResetTime() < resettime) save->SetResetTime(resettime);
+ }
+ }
+ }
+ }
+
+ // outdoor pvp things, do these after setting the death state, else the player activity notify won't work... doh...
+ // handle player kill only if not suicide (spirit of redemption for example)
+ if (player && this != pVictim)
+ if (OutdoorPvP * pvp = player->GetOutdoorPvP())
+ pvp->HandleKill(player, pVictim);
+
+ //if (pVictim->GetTypeId() == TYPEID_PLAYER)
+ // if (OutdoorPvP * pvp = ((Player*)pVictim)->GetOutdoorPvP())
+ // pvp->HandlePlayerActivityChanged((Player*)pVictim);
+
+ // battleground things (do this at the end, so the death state flag will be properly set to handle in the bg->handlekill)
+ if (player && player->InBattleGround())
+ {
+ if (BattleGround *bg = player->GetBattleGround())
+ {
+ if (pVictim->GetTypeId() == TYPEID_PLAYER)
+ bg->HandleKillPlayer((Player*)pVictim, player);
+ else
+ bg->HandleKillUnit((Creature*)pVictim, player);
+ }
+ }
+
+ // achievement stuff
+ if (pVictim->GetTypeId() == TYPEID_PLAYER)
+ {
+ if (GetTypeId() == TYPEID_UNIT)
+ ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE, GetEntry());
+ else if (GetTypeId() == TYPEID_PLAYER && pVictim != this)
+ ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER, 1, ((Player*)this)->GetTeam());
+ }
+}
+
+void Unit::SetControlled(bool apply, UnitState state)
+{
+ if (apply)
+ {
+ if (hasUnitState(state))
+ return;
+
+ addUnitState(state);
+
+ switch(state)
+ {
+ case UNIT_STAT_STUNNED:
+ SetStunned(true);
+ break;
+ case UNIT_STAT_ROOT:
+ if (!hasUnitState(UNIT_STAT_STUNNED))
+ SetRooted(true);
+ break;
+ case UNIT_STAT_CONFUSED:
+ if (!hasUnitState(UNIT_STAT_STUNNED))
+ SetConfused(true);
+ break;
+ case UNIT_STAT_FLEEING:
+ if (!hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_CONFUSED))
+ SetFeared(true);
+ break;
+ default:
+ break;
+ }
+ }
+ else
+ {
+ switch(state)
+ {
+ case UNIT_STAT_STUNNED: if (HasAuraType(SPELL_AURA_MOD_STUN)) return;
+ else SetStunned(false); break;
+ case UNIT_STAT_ROOT: if (HasAuraType(SPELL_AURA_MOD_ROOT) || GetVehicle()) return;
+ else SetRooted(false); break;
+ case UNIT_STAT_CONFUSED:if (HasAuraType(SPELL_AURA_MOD_CONFUSE)) return;
+ else SetConfused(false); break;
+ case UNIT_STAT_FLEEING: if (HasAuraType(SPELL_AURA_MOD_FEAR)) return;
+ else SetFeared(false); break;
+ default: return;
+ }
+
+ clearUnitState(state);
+
+ if (hasUnitState(UNIT_STAT_STUNNED))
+ SetStunned(true);
+ else
+ {
+ if (hasUnitState(UNIT_STAT_ROOT))
+ SetRooted(true);
+
+ if (hasUnitState(UNIT_STAT_CONFUSED))
+ SetConfused(true);
+ else if (hasUnitState(UNIT_STAT_FLEEING))
+ SetFeared(true);
+ }
+ }
+}
+
+void Unit::SetStunned(bool apply)
+{
+ if (apply)
+ {
+ SetUInt64Value(UNIT_FIELD_TARGET, 0);
+ SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
+ CastStop();
+ AddUnitMovementFlag(MOVEMENTFLAG_ROOT);
+
+ // Creature specific
+ if (GetTypeId() != TYPEID_PLAYER)
+ ((Creature*)this)->StopMoving();
+ else
+ SetStandState(UNIT_STAND_STATE_STAND);
+
+ WorldPacket data(SMSG_FORCE_MOVE_ROOT, 8);
+ data.append(GetPackGUID());
+ data << uint32(0);
+ SendMessageToSet(&data,true);
+ }
+ else
+ {
+ if (isAlive() && getVictim())
+ SetUInt64Value(UNIT_FIELD_TARGET, getVictim()->GetGUID());
+
+ // don't remove UNIT_FLAG_STUNNED for pet when owner is mounted (disabled pet's interface)
+ Unit *pOwner = GetOwner();
+ if (!pOwner || (pOwner->GetTypeId() == TYPEID_PLAYER && !((Player *)pOwner)->IsMounted()))
+ RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
+
+ if (!hasUnitState(UNIT_STAT_ROOT)) // prevent allow move if have also root effect
+ {
+ WorldPacket data(SMSG_FORCE_MOVE_UNROOT, 8+4);
+ data.append(GetPackGUID());
+ data << uint32(0);
+ SendMessageToSet(&data,true);
+
+ RemoveUnitMovementFlag(MOVEMENTFLAG_ROOT);
+ }
+ }
+}
+
+void Unit::SetRooted(bool apply)
+{
+ if (apply)
+ {
+ AddUnitMovementFlag(MOVEMENTFLAG_ROOT);
+
+ WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
+ data.append(GetPackGUID());
+ data << (uint32)2;
+ SendMessageToSet(&data,true);
+
+ if (GetTypeId() != TYPEID_PLAYER)
+ ((Creature *)this)->StopMoving();
+ }
+ else
+ {
+ if (!hasUnitState(UNIT_STAT_STUNNED)) // prevent allow move if have also stun effect
+ {
+ WorldPacket data(SMSG_FORCE_MOVE_UNROOT, 10);
+ data.append(GetPackGUID());
+ data << (uint32)2;
+ SendMessageToSet(&data,true);
+
+ RemoveUnitMovementFlag(MOVEMENTFLAG_ROOT);
+ }
+ }
+}
+
+void Unit::SetFeared(bool apply)
+{
+ if (apply)
+ {
+ SetUInt64Value(UNIT_FIELD_TARGET, 0);
+
+ Unit *caster = NULL;
+ Unit::AuraEffectList const& fearAuras = GetAuraEffectsByType(SPELL_AURA_MOD_FEAR);
+ if (!fearAuras.empty())
+ caster = ObjectAccessor::GetUnit(*this, fearAuras.front()->GetCasterGUID());
+ if (!caster)
+ caster = getAttackerForHelper();
+ GetMotionMaster()->MoveFleeing(caster, fearAuras.empty() ? sWorld.getConfig(CONFIG_CREATURE_FAMILY_FLEE_DELAY) : 0); // caster==NULL processed in MoveFleeing
+ }
+ else
+ {
+ if (isAlive())
+ {
+ if (GetMotionMaster()->GetCurrentMovementGeneratorType() == FLEEING_MOTION_TYPE)
+ GetMotionMaster()->MovementExpired();
+ if (getVictim())
+ SetUInt64Value(UNIT_FIELD_TARGET, getVictim()->GetGUID());
+ }
+ }
+
+ if (GetTypeId() == TYPEID_PLAYER)
+ ((Player*)this)->SetClientControl(this, !apply);
+}
+
+void Unit::SetConfused(bool apply)
+{
+ if (apply)
+ {
+ SetUInt64Value(UNIT_FIELD_TARGET, 0);
+ GetMotionMaster()->MoveConfused();
+ }
+ else
+ {
+ if (isAlive())
+ {
+ if (GetMotionMaster()->GetCurrentMovementGeneratorType() == CONFUSED_MOTION_TYPE)
+ GetMotionMaster()->MovementExpired();
+ if (getVictim())
+ SetUInt64Value(UNIT_FIELD_TARGET, getVictim()->GetGUID());
+ }
+ }
+
+ if (GetTypeId() == TYPEID_PLAYER)
+ ((Player*)this)->SetClientControl(this, !apply);
+}
+
+bool Unit::SetCharmedBy(Unit* charmer, CharmType type)
+{
+ if (!charmer)
+ return false;
+
+ assert(type != CHARM_TYPE_POSSESS || charmer->GetTypeId() == TYPEID_PLAYER);
+ assert((type == CHARM_TYPE_VEHICLE) == IsVehicle());
+
+ sLog.outDebug("SetCharmedBy: charmer %u, charmed %u, type %u.", charmer->GetEntry(), GetEntry(), (uint32)type);
+
+ if (this == charmer)
+ {
+ sLog.outCrash("Unit::SetCharmedBy: Unit %u is trying to charm itself!", GetEntry());
+ return false;
+ }
+
+ //if (hasUnitState(UNIT_STAT_UNATTACKABLE))
+ // return false;
+
+ if (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->GetTransport())
+ {
+ sLog.outCrash("Unit::SetCharmedBy: Player on transport is trying to charm %u", GetEntry());
+ return false;
+ }
+
+ // Already charmed
+ if (GetCharmerGUID())
+ {
+ sLog.outCrash("Unit::SetCharmedBy: %u has already been charmed but %u is trying to charm it!", GetEntry(), charmer->GetEntry());
+ return false;
+ }
+
+ CastStop();
+ CombatStop(); //TODO: CombatStop(true) may cause crash (interrupt spells)
+ DeleteThreatList();
+
+ // Charmer stop charming
+ if (charmer->GetTypeId() == TYPEID_PLAYER)
+ {
+ ((Player*)charmer)->StopCastingCharm();
+ ((Player*)charmer)->StopCastingBindSight();
+ }
+
+ // Charmed stop charming
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ ((Player*)this)->StopCastingCharm();
+ ((Player*)this)->StopCastingBindSight();
+ }
+
+ // StopCastingCharm may remove a possessed pet?
+ if (!IsInWorld())
+ {
+ sLog.outCrash("Unit::SetCharmedBy: %u is not in world but %u is trying to charm it!", GetEntry(), charmer->GetEntry());
+ return false;
+ }
+
+ // Set charmed
+ setFaction(charmer->getFaction());
+ charmer->SetCharm(this, true);
+
+ if (GetTypeId() == TYPEID_UNIT)
+ {
+ ((Creature*)this)->AI()->OnCharmed(true);
+ GetMotionMaster()->MoveIdle();
+ }
+ else
+ {
+ if (((Player*)this)->isAFK())
+ ((Player*)this)->ToggleAFK();
+ ((Player*)this)->SetClientControl(this, 0);
+ }
+
+ // Pets already have a properly initialized CharmInfo, don't overwrite it.
+ if (type != CHARM_TYPE_VEHICLE && !GetCharmInfo())
+ {
+ CharmInfo *charmInfo = InitCharmInfo();
+ if (type == CHARM_TYPE_POSSESS)
+ charmInfo->InitPossessCreateSpells();
+ else
+ charmInfo->InitCharmCreateSpells();
+ }
+
+ if (charmer->GetTypeId() == TYPEID_PLAYER)
+ {
+ switch(type)
+ {
+ case CHARM_TYPE_VEHICLE:
+ SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
+ ((Player*)charmer)->SetClientControl(this, 1);
+ ((Player*)charmer)->SetViewpoint(this, true);
+ ((Player*)charmer)->VehicleSpellInitialize();
+ break;
+ case CHARM_TYPE_POSSESS:
+ addUnitState(UNIT_STAT_POSSESSED);
+ SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
+ charmer->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE);
+ ((Player*)charmer)->SetClientControl(this, 1);
+ ((Player*)charmer)->SetViewpoint(this, true);
+ ((Player*)charmer)->PossessSpellInitialize();
+ break;
+ case CHARM_TYPE_CHARM:
+ if (GetTypeId() == TYPEID_UNIT && charmer->getClass() == CLASS_WARLOCK)
+ {
+ CreatureInfo const *cinfo = ((Creature*)this)->GetCreatureInfo();
+ if (cinfo && cinfo->type == CREATURE_TYPE_DEMON)
+ {
+ //to prevent client crash
+ SetByteValue(UNIT_FIELD_BYTES_0, 1, (uint8)CLASS_MAGE);
+
+ //just to enable stat window
+ if (GetCharmInfo())
+ GetCharmInfo()->SetPetNumber(objmgr.GeneratePetNumber(), true);
+
+ //if charmed two demons the same session, the 2nd gets the 1st one's name
+ SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, time(NULL));
+ }
+ }
+ ((Player*)charmer)->CharmSpellInitialize();
+ break;
+ default:
+ case CHARM_TYPE_CONVERT:
+ break;
+ }
+ }
+ return true;
+}
+
+void Unit::RemoveCharmedBy(Unit *charmer)
+{
+ if (!isCharmed())
+ return;
+
+ if (!charmer)
+ charmer = GetCharmer();
+ if (charmer != GetCharmer()) // one aura overrides another?
+ {
+// sLog.outCrash("Unit::RemoveCharmedBy: this: " UI64FMTD " true charmer: " UI64FMTD " false charmer: " UI64FMTD,
+// GetGUID(), GetCharmerGUID(), charmer->GetGUID());
+// assert(false);
+ return;
+ }
+
+ CharmType type;
+ if (hasUnitState(UNIT_STAT_POSSESSED))
+ type = CHARM_TYPE_POSSESS;
+ else if (charmer->IsOnVehicle(this))
+ type = CHARM_TYPE_VEHICLE;
+ else
+ type = CHARM_TYPE_CHARM;
+
+ CastStop();
+ CombatStop(); //TODO: CombatStop(true) may cause crash (interrupt spells)
+ getHostilRefManager().deleteReferences();
+ DeleteThreatList();
+ RestoreFaction();
+ GetMotionMaster()->InitDefault();
+
+ if (type == CHARM_TYPE_POSSESS)
+ {
+ clearUnitState(UNIT_STAT_POSSESSED);
+ RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
+ }
+
+ if (GetTypeId() == TYPEID_UNIT)
+ {
+ ((Creature*)this)->AI()->OnCharmed(false);
+ ((Creature*)this)->AIM_Initialize();
+
+ if (((Creature*)this)->AI() && charmer && charmer->isAlive())
+ ((Creature*)this)->AI()->AttackStart(charmer);
+ /*if (isAlive() && ((Creature*)this)->IsAIEnabled)
+ {
+ if (charmer && !IsFriendlyTo(charmer))
+ ((Creature*)this)->AI()->AttackStart(charmer);
+ else
+ ((Creature*)this)->AI()->EnterEvadeMode();
+ }*/
+ }
+ else
+ ((Player*)this)->SetClientControl(this, 1);
+
+ // If charmer still exists
+ if (!charmer)
+ return;
+
+ assert(type != CHARM_TYPE_POSSESS || charmer->GetTypeId() == TYPEID_PLAYER);
+ assert(type != CHARM_TYPE_VEHICLE || GetTypeId() == TYPEID_UNIT && IsVehicle());
+
+ charmer->SetCharm(this, false);
+
+ if (charmer->GetTypeId() == TYPEID_PLAYER)
+ {
+ switch(type)
+ {
+ case CHARM_TYPE_VEHICLE:
+ ((Player*)charmer)->SetClientControl(charmer, 1);
+ ((Player*)charmer)->SetViewpoint(this, false);
+ break;
+ case CHARM_TYPE_POSSESS:
+ ((Player*)charmer)->SetClientControl(charmer, 1);
+ ((Player*)charmer)->SetViewpoint(this, false);
+ charmer->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE);
+ break;
+ case CHARM_TYPE_CHARM:
+ if (GetTypeId() == TYPEID_UNIT && charmer->getClass() == CLASS_WARLOCK)
+ {
+ CreatureInfo const *cinfo = ((Creature*)this)->GetCreatureInfo();
+ if (cinfo && cinfo->type == CREATURE_TYPE_DEMON)
+ {
+ SetByteValue(UNIT_FIELD_BYTES_0, 1, uint8(cinfo->unit_class));
+ if (GetCharmInfo())
+ GetCharmInfo()->SetPetNumber(0, true);
+ else
+ sLog.outError("Aura::HandleModCharm: target="UI64FMTD" with typeid=%d has a charm aura but no charm info!", GetGUID(), GetTypeId());
+ }
+ }
+ break;
+ default:
+ case CHARM_TYPE_CONVERT:
+ break;
+ }
+ }
+
+ //a guardian should always have charminfo
+ if (charmer->GetTypeId() == TYPEID_PLAYER && this != charmer->GetFirstControlled())
+ ((Player*)charmer)->SendRemoveControlBar();
+ else if (GetTypeId() == TYPEID_PLAYER || GetTypeId() == TYPEID_UNIT && !((Creature*)this)->isGuardian())
+ DeleteCharmInfo();
+}
+
+void Unit::RestoreFaction()
+{
+ if (GetTypeId() == TYPEID_PLAYER)
+ ((Player*)this)->setFactionForRace(getRace());
+ else
+ {
+ if (HasUnitTypeMask(UNIT_MASK_MINION))
+ {
+ if (Unit* owner = GetOwner())
+ {
+ setFaction(owner->getFaction());
+ return;
+ }
+ }
+
+ if (CreatureInfo const *cinfo = ((Creature*)this)->GetCreatureInfo()) // normal creature
+ {
+ FactionTemplateEntry const *faction = getFactionTemplateEntry();
+ setFaction((faction && faction->friendlyMask & 0x004) ? cinfo->faction_H : cinfo->faction_A);
+ }
+ }
+}
+
+bool Unit::CreateVehicleKit(uint32 id)
+{
+ VehicleEntry const *vehInfo = sVehicleStore.LookupEntry(id);
+ if (!vehInfo)
+ return false;
+
+ m_vehicleKit = new Vehicle(this, vehInfo);
+ m_updateFlag |= UPDATEFLAG_VEHICLE;
+ m_unitTypeMask |= UNIT_MASK_VEHICLE;
+ return true;
+}
+
+void Unit::RemoveVehicleKit()
+{
+ if (!m_vehicleKit)
+ return;
+
+ m_vehicleKit->Uninstall();
+ delete m_vehicleKit;
+
+ m_vehicleKit = NULL;
+
+ m_updateFlag &= ~UPDATEFLAG_VEHICLE;
+ m_unitTypeMask &= ~UNIT_MASK_VEHICLE;
+ RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
+ RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_PLAYER_VEHICLE);
+}
+
+Unit *Unit::GetVehicleBase() const
+{
+ return m_vehicle ? m_vehicle->GetBase() : NULL;
+}
+
+Creature *Unit::GetVehicleCreatureBase() const
+{
+ Unit *veh = GetVehicleBase();
+ if (veh->GetTypeId() == TYPEID_UNIT)
+ return (Creature*)veh;
+ return NULL;
+}
+
+bool Unit::IsInPartyWith(Unit const *unit) const
+{
+ if (this == unit)
+ return true;
+
+ const Unit *u1 = GetCharmerOrOwnerOrSelf();
+ const Unit *u2 = unit->GetCharmerOrOwnerOrSelf();
+ if (u1 == u2)
+ return true;
+
+ if (u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_PLAYER)
+ return ((Player*)u1)->IsInSameGroupWith((Player*)u2);
+ else
+ return false;
+}
+
+bool Unit::IsInRaidWith(Unit const *unit) const
+{
+ if (this == unit)
+ return true;
+
+ const Unit *u1 = GetCharmerOrOwnerOrSelf();
+ const Unit *u2 = unit->GetCharmerOrOwnerOrSelf();
+ if (u1 == u2)
+ return true;
+
+ if (u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_PLAYER)
+ return ((Player*)u1)->IsInSameRaidWith((Player*)u2);
+ else
+ return false;
+}
+
+void Unit::GetRaidMember(std::list<Unit*> &nearMembers, float radius)
+{
+ Player *owner = GetCharmerOrOwnerPlayerOrPlayerItself();
+ if (!owner)
+ return;
+
+ Group *pGroup = owner->GetGroup();
+ if (pGroup)
+ {
+ for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
+ {
+ Player* Target = itr->getSource();
+
+ if (Target && !IsHostileTo(Target))
+ {
+ if (Target->isAlive() && IsWithinDistInMap(Target, radius))
+ nearMembers.push_back(Target);
+
+ if (Guardian* pet = Target->GetGuardianPet())
+ if (pet->isAlive() && IsWithinDistInMap(pet, radius))
+ nearMembers.push_back(pet);
+ }
+ }
+ }
+ else
+ {
+ if (owner->isAlive() && (owner == this || IsWithinDistInMap(owner, radius)))
+ nearMembers.push_back(owner);
+ if (Guardian* pet = owner->GetGuardianPet())
+ if (pet->isAlive() && (pet == this && IsWithinDistInMap(pet, radius)))
+ nearMembers.push_back(pet);
+ }
+}
+
+void Unit::GetPartyMemberInDist(std::list<Unit*> &TagUnitMap, float radius)
+{
+ Unit *owner = GetCharmerOrOwnerOrSelf();
+ Group *pGroup = NULL;
+ if (owner->GetTypeId() == TYPEID_PLAYER)
+ pGroup = ((Player*)owner)->GetGroup();
+
+ if (pGroup)
+ {
+ uint8 subgroup = ((Player*)owner)->GetSubGroup();
+
+ for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
+ {
+ Player* Target = itr->getSource();
+
+ // IsHostileTo check duel and controlled by enemy
+ if (Target && Target->GetSubGroup()==subgroup && !IsHostileTo(Target))
+ {
+ if (Target->isAlive() && IsWithinDistInMap(Target, radius))
+ TagUnitMap.push_back(Target);
+
+ if (Guardian* pet = Target->GetGuardianPet())
+ if (pet->isAlive() && IsWithinDistInMap(pet, radius))
+ TagUnitMap.push_back(pet);
+ }
+ }
+ }
+ else
+ {
+ if (owner->isAlive() && (owner == this || IsWithinDistInMap(owner, radius)))
+ TagUnitMap.push_back(owner);
+ if (Guardian* pet = owner->GetGuardianPet())
+ if (pet->isAlive() && (pet == this && IsWithinDistInMap(pet, radius)))
+ TagUnitMap.push_back(pet);
+ }
+}
+
+void Unit::GetPartyMembers(std::list<Unit*> &TagUnitMap)
+{
+ Unit *owner = GetCharmerOrOwnerOrSelf();
+ Group *pGroup = NULL;
+ if (owner->GetTypeId() == TYPEID_PLAYER)
+ pGroup = ((Player*)owner)->GetGroup();
+
+ if (pGroup)
+ {
+ uint8 subgroup = ((Player*)owner)->GetSubGroup();
+
+ for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
+ {
+ Player* Target = itr->getSource();
+
+ // IsHostileTo check duel and controlled by enemy
+ if (Target && Target->GetSubGroup()==subgroup && !IsHostileTo(Target))
+ {
+ if (Target->isAlive() && IsInMap(Target))
+ TagUnitMap.push_back(Target);
+
+ if (Guardian* pet = Target->GetGuardianPet())
+ if (pet->isAlive() && IsInMap(Target))
+ TagUnitMap.push_back(pet);
+ }
+ }
+ }
+ else
+ {
+ if (owner->isAlive() && (owner == this || IsInMap(owner)))
+ TagUnitMap.push_back(owner);
+ if (Guardian* pet = owner->GetGuardianPet())
+ if (pet->isAlive() && (pet == this || IsInMap(pet)))
+ TagUnitMap.push_back(pet);
+ }
+}
+
+Aura * Unit::AddAura(uint32 spellId, Unit *target)
+{
+ if (!target || !target->isAlive())
+ return NULL;
+
+ SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
+ if (!spellInfo)
+ return NULL;
+
+ return AddAura(spellInfo, MAX_EFFECT_MASK, target);
+}
+
+Aura * Unit::AddAura(SpellEntry const *spellInfo, uint8 effMask, Unit *target)
+{
+ if (!spellInfo)
+ return NULL;
+
+ if (target->IsImmunedToSpell(spellInfo))
+ return NULL;
+
+ for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
+ {
+ if (!(effMask & (1<<i)))
+ continue;
+ if (target->IsImmunedToSpellEffect(spellInfo, i))
+ effMask &= ~(1<<i);
+ }
+
+ if (Aura * aura = Aura::TryCreate(spellInfo, effMask, target, this))
+ {
+ aura->ApplyForTargets();
+ return aura;
+ }
+ return NULL;
+}
+
+void Unit::SetAuraStack(uint32 spellId, Unit *target, uint32 stack)
+{
+ Aura *aura = target->GetAura(spellId, GetGUID());
+ if (!aura)
+ aura = AddAura(spellId, target);
+ if (aura && stack)
+ aura->SetStackAmount(stack);
+}
+
+// Melee based spells can be miss, parry or dodge on this step
+// Crit or block - determined on damage calculation phase! (and can be both in some time)
+float Unit::MeleeSpellMissChance(const Unit *pVictim, WeaponAttackType attType, int32 skillDiff, uint32 spellId) const
+{
+ // Calculate hit chance (more correct for chance mod)
+ int32 HitChance;
+
+ // PvP - PvE melee chances
+ /*int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
+ int32 leveldif = pVictim->getLevelForTarget(this) - getLevelForTarget(pVictim);
+ if (leveldif < 3)
+ HitChance = 95 - leveldif;
+ else
+ HitChance = 93 - (leveldif - 2) * lchance;*/
+ if (spellId || attType == RANGED_ATTACK || !haveOffhandWeapon())
+ HitChance = 95.0f;
+ else
+ HitChance = 76.0f;
+
+ // Hit chance depends from victim auras
+ if (attType == RANGED_ATTACK)
+ HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
+ else
+ HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
+
+ // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
+ if (spellId)
+ {
+ if (Player *modOwner = GetSpellModOwner())
+ modOwner->ApplySpellMod(spellId, SPELLMOD_RESIST_MISS_CHANCE, HitChance);
+ }
+
+ // Miss = 100 - hit
+ float miss_chance = 100.0f - HitChance;
+
+ // Bonuses from attacker aura and ratings
+ if (attType == RANGED_ATTACK)
+ miss_chance -= m_modRangedHitChance;
+ else
+ miss_chance -= m_modMeleeHitChance;
+
+ // bonus from skills is 0.04%
+ //miss_chance -= skillDiff * 0.04f;
+ int32 diff = -skillDiff;
+ if (pVictim->GetTypeId() == TYPEID_PLAYER)
+ miss_chance += diff > 0 ? diff * 0.04 : diff * 0.02;
+ else
+ miss_chance += diff > 10 ? 2 + (diff - 10) * 0.4 : diff * 0.1;
+
+ // Limit miss chance from 0 to 60%
+ if (miss_chance < 0.0f)
+ return 0.0f;
+ if (miss_chance > 60.0f)
+ return 60.0f;
+ return miss_chance;
+}
+
+void Unit::SetPhaseMask(uint32 newPhaseMask, bool update)
+{
+ if (newPhaseMask == GetPhaseMask())
+ return;
+
+ if (IsInWorld())
+ RemoveNotOwnSingleTargetAuras(newPhaseMask); // we can lost access to caster or target
+
+ WorldObject::SetPhaseMask(newPhaseMask,update);
+
+ if (!IsInWorld())
+ return;
+
+ for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
+ if ((*itr)->GetTypeId() == TYPEID_UNIT)
+ (*itr)->SetPhaseMask(newPhaseMask,true);
+
+ for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i)
+ if (m_SummonSlot[i])
+ if (Creature *summon = GetMap()->GetCreature(m_SummonSlot[i]))
+ summon->SetPhaseMask(newPhaseMask,true);
+}
+
+void Unit::KnockbackFrom(float x, float y, float speedXY, float speedZ)
+{
+ Player *player = NULL;
+ if (GetTypeId() == TYPEID_PLAYER)
+ player = (Player*)this;
+ else
+ {
+ player = dynamic_cast<Player*>(GetCharmer());
+ if (player && player->m_mover != this)
+ player = NULL;
+ }
+
+ if (!player)
+ {
+ GetMotionMaster()->MoveKnockbackFrom(x, y, speedXY, speedZ);
+ }
+ else
+ {
+ float vcos, vsin;
+ GetSinCos(x, y, vsin, vcos);
+
+ WorldPacket data(SMSG_MOVE_KNOCK_BACK, (8+4+4+4+4+4));
+ data.append(GetPackGUID());
+ data << uint32(0); // Sequence
+ data << float(vcos); // x direction
+ data << float(vsin); // y direction
+ data << float(speedXY); // Horizontal speed
+ data << float(-speedZ); // Z Movement speed (vertical)
+
+ player->GetSession()->SendPacket(&data);
+ }
+}
+
+float Unit::GetCombatRatingReduction(CombatRating cr) const
+{
+ if (GetTypeId() == TYPEID_PLAYER)
+ return ((Player const*)this)->GetRatingBonusValue(cr);
+ else if (((Creature const*)this)->isPet())
+ {
+ // Player's pet get resilience from owner
+ if (Unit* owner = GetOwner())
+ if(owner->GetTypeId() == TYPEID_PLAYER)
+ return ((Player*)owner)->GetRatingBonusValue(cr);
+ }
+
+ return 0.0f;
+}
+
+uint32 Unit::GetCombatRatingDamageReduction(CombatRating cr, float rate, float cap, uint32 damage) const
+{
+ float percent = GetCombatRatingReduction(cr) * rate;
+ if (percent > cap)
+ percent = cap;
+ return uint32 (percent * damage / 100.0f);
+}
+
+uint32 Unit::GetModelForForm(ShapeshiftForm form)
+{
+ switch(form)
+ {
+ case FORM_CAT:
+ // Based on Hair color
+ if (getRace() == RACE_NIGHTELF)
+ {
+ uint8 hairColor = GetByteValue(PLAYER_BYTES, 3);
+ switch (hairColor)
+ {
+ case 7: // Violet
+ case 8:
+ return 29405;
+ case 3: // Light Blue
+ return 29406;
+ case 0: // Green
+ case 1: // Light Green
+ case 2: // Dark Green
+ return 29407;
+ case 4: // White
+ return 29408;
+ default: // original - Dark Blue
+ return 892;
+ }
+ }
+ // Based on Skin color
+ else if (getRace() == RACE_TAUREN)
+ {
+ uint8 skinColor = GetByteValue(PLAYER_BYTES, 0);
+ // Male
+ if (getGender() == GENDER_MALE)
+ {
+ switch(skinColor)
+ {
+ case 12: // White
+ case 13:
+ case 14:
+ case 18: // Completly White
+ return 29409;
+ case 9: // Light Brown
+ case 10:
+ case 11:
+ return 29410;
+ case 6: // Brown
+ case 7:
+ case 8:
+ return 29411;
+ case 0: // Dark
+ case 1:
+ case 2:
+ case 3: // Dark Grey
+ case 4:
+ case 5:
+ return 29412;
+ default: // original - Grey
+ return 8571;
+ }
+ }
+ // Female
+ else switch (skinColor)
+ {
+ case 10: // White
+ return 29409;
+ case 6: // Light Brown
+ case 7:
+ return 29410;
+ case 4: // Brown
+ case 5:
+ return 29411;
+ case 0: // Dark
+ case 1:
+ case 2:
+ case 3:
+ return 29412;
+ default: // original - Grey
+ return 8571;
+ }
+ }
+ else if(Player::TeamForRace(getRace())==ALLIANCE)
+ return 892;
+ else
+ return 8571;
+ case FORM_DIREBEAR:
+ case FORM_BEAR:
+ // Based on Hair color
+ if (getRace() == RACE_NIGHTELF)
+ {
+ uint8 hairColor = GetByteValue(PLAYER_BYTES, 3);
+ switch (hairColor)
+ {
+ case 0: // Green
+ case 1: // Light Green
+ case 2: // Dark Green
+ return 29413; // 29415?
+ case 6: // Dark Blue
+ return 29414;
+ case 4: // White
+ return 29416;
+ case 3: // Light Blue
+ return 29417;
+ default: // original - Violet
+ return 2281;
+ }
+ }
+ // Based on Skin color
+ else if (getRace() == RACE_TAUREN)
+ {
+ uint8 skinColor = GetByteValue(PLAYER_BYTES, 0);
+ // Male
+ if (getGender() == GENDER_MALE)
+ {
+ switch (skinColor)
+ {
+ case 0: // Dark (Black)
+ case 1:
+ case 2:
+ return 29418;
+ case 3: // White
+ case 4:
+ case 5:
+ case 12:
+ case 13:
+ case 14:
+ return 29419;
+ case 9: // Light Brown/Grey
+ case 10:
+ case 11:
+ case 15:
+ case 16:
+ case 17:
+ return 29420;
+ case 18: // Completly White
+ return 29421;
+ default: // original - Brown
+ return 2289;
+ }
+ }
+ // Female
+ else switch (skinColor)
+ {
+ case 0: // Dark (Black)
+ case 1:
+ return 29418;
+ case 2: // White
+ case 3:
+ return 29419;
+ case 6: // Light Brown/Grey
+ case 7:
+ case 8:
+ case 9:
+ return 29420;
+ case 10: // Completly White
+ return 29421;
+ default: // original - Brown
+ return 2289;
+ }
+ }
+ else if(Player::TeamForRace(getRace())==ALLIANCE)
+ return 2281;
+ else
+ return 2289;
+ case FORM_TRAVEL:
+ return 632;
+ case FORM_AQUA:
+ if(Player::TeamForRace(getRace())==ALLIANCE)
+ return 2428;
+ else
+ return 2428;
+ case FORM_GHOUL:
+ return 24994;
+ case FORM_CREATUREBEAR:
+ return 902;
+ case FORM_GHOSTWOLF:
+ return 4613;
+ case FORM_FLIGHT:
+ if(Player::TeamForRace(getRace())==ALLIANCE)
+ return 20857;
+ else
+ return 20872;
+ case FORM_MOONKIN:
+ if(Player::TeamForRace(getRace())==ALLIANCE)
+ return 15374;
+ else
+ return 15375;
+ case FORM_FLIGHT_EPIC:
+ if(Player::TeamForRace(getRace())==ALLIANCE)
+ return 21243;
+ else
+ return 21244;
+ case FORM_METAMORPHOSIS:
+ return 25277;
+ case FORM_MASTER_ANGLER:
+ return 15234;
+ case FORM_TREE:
+ return 864;
+ case FORM_SPIRITOFREDEMPTION:
+ return 16031;
+ }
+ return 0;
+}
+
+void Unit::JumpTo(float speedXY, float speedZ, bool forward)
+{
+ float angle = forward ? 0 : M_PI;
+ if (GetTypeId() == TYPEID_UNIT)
+ GetMotionMaster()->MoveJumpTo(angle, speedXY, speedZ);
+ else
+ {
+ float vcos = cos(angle+GetOrientation());
+ float vsin = sin(angle+GetOrientation());
+
+ WorldPacket data(SMSG_MOVE_KNOCK_BACK, (8+4+4+4+4+4));
+ data.append(GetPackGUID());
+ data << uint32(0); // Sequence
+ data << float(vcos); // x direction
+ data << float(vsin); // y direction
+ data << float(speedXY); // Horizontal speed
+ data << float(-speedZ); // Z Movement speed (vertical)
+
+ ((Player*)this)->GetSession()->SendPacket(&data);
+ }
+}
+
+void Unit::JumpTo(WorldObject *obj, float speedZ)
+{
+ float x, y, z;
+ obj->GetContactPoint(this, x, y, z);
+ float speedXY = GetExactDist2d(x, y) * 10.0f / speedZ;
+ GetMotionMaster()->MoveJump(x, y, z, speedXY, speedZ);
+}
+
+bool Unit::CheckPlayerCondition(Player* pPlayer)
+{
+ switch(GetEntry())
+ {
+ case 35644: //Argent Warhorse
+ case 36558: //Argent Battleworg
+ if (!pPlayer->HasItemOrGemWithIdEquipped(46106,1)) //Check item Argent Lance
+ return false;
+ default:
+ return true;
+ }
+}
+
+void Unit::EnterVehicle(Vehicle *vehicle, int8 seatId)
+{
+ if (!isAlive() || GetVehicleKit() == vehicle)
+ return;
+
+ if (m_vehicle)
+ {
+ if (m_vehicle == vehicle)
+ {
+ if (seatId >= 0)
+ {
+ sLog.outDebug("EnterVehicle: %u leave vehicle %u seat %d and enter %d.", GetEntry(), m_vehicle->GetBase()->GetEntry(), GetTransSeat(), seatId);
+ ChangeSeat(seatId);
+ }
+ return;
+ }
+ else
+ {
+ sLog.outDebug("EnterVehicle: %u exit %u and enter %u.", GetEntry(), m_vehicle->GetBase()->GetEntry(), vehicle->GetBase()->GetEntry());
+ ExitVehicle();
+ }
+ }
+
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ ((Player*)this)->StopCastingCharm();
+ ((Player*)this)->StopCastingBindSight();
+ ((Player*)this)->Unmount();
+ ((Player*)this)->RemoveAurasByType(SPELL_AURA_MOUNTED);
+
+ // drop flag at invisible in bg
+ if(((Player*)this)->InBattleGround())
+ if(BattleGround *bg = ((Player*)this)->GetBattleGround())
+ bg->EventPlayerDroppedFlag((Player*)this);
+ }
+
+ assert(!m_vehicle);
+ m_vehicle = vehicle;
+ if (!m_vehicle->AddPassenger(this, seatId))
+ {
+ m_vehicle = NULL;
+ return;
+ }
+
+ SetControlled(true, UNIT_STAT_ROOT);
+ //movementInfo is set in AddPassenger
+ //packets are sent in AddPassenger
+
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ //((Player*)this)->SetClientControl(vehicle, 1);
+ WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
+ ((Player*)this)->GetSession()->SendPacket(&data);
+ }
+}
+
+void Unit::ChangeSeat(int8 seatId, bool next)
+{
+ if (!m_vehicle)
+ return;
+
+ if (seatId < 0)
+ {
+ seatId = m_vehicle->GetNextEmptySeat(GetTransSeat(), next);
+ if (seatId < 0)
+ return;
+ }
+ else if (seatId == GetTransSeat() || !m_vehicle->HasEmptySeat(seatId))
+ return;
+
+ m_vehicle->RemovePassenger(this);
+ if (!m_vehicle->AddPassenger(this, seatId))
+ assert(false);
+}
+
+void Unit::ExitVehicle()
+{
+ if (!m_vehicle)
+ return;
+
+ Unit *vehicleBase = m_vehicle->GetBase();
+ const AuraEffectList &modAuras = vehicleBase->GetAuraEffectsByType(SPELL_AURA_CONTROL_VEHICLE);
+ for (AuraEffectList::const_iterator itr = modAuras.begin(); itr != modAuras.end(); ++itr)
+ {
+ if ((*itr)->GetBase()->GetOwner() == this)
+ {
+ vehicleBase->RemoveAura((*itr)->GetBase());
+ break; // there should be no case that a vehicle has two auras for one owner
+ }
+ }
+
+ if (!m_vehicle)
+ return;
+
+ //sLog.outError("exit vehicle");
+
+ m_vehicle->RemovePassenger(this);
+
+ // This should be done before dismiss, because there may be some aura removal
+ Vehicle *vehicle = m_vehicle;
+ m_vehicle = NULL;
+
+ SetControlled(false, UNIT_STAT_ROOT);
+
+ RemoveUnitMovementFlag(MOVEMENTFLAG_ONTRANSPORT);
+ m_movementInfo.t_x = 0;
+ m_movementInfo.t_y = 0;
+ m_movementInfo.t_z = 0;
+ m_movementInfo.t_o = 0;
+ m_movementInfo.t_time = 0;
+ m_movementInfo.t_seat = 0;
+
+ Relocate(vehicle->GetBase());
+
+ //Send leave vehicle, not correct
+ if (GetTypeId() == TYPEID_PLAYER)
+ {
+ //((Player*)this)->SetClientControl(this, 1);
+ ((Player*)this)->SendTeleportAckMsg();
+ ((Player*)this)->SetFallInformation(0, GetPositionZ());
+ }
+ WorldPacket data;
+ BuildHeartBeatMsg(&data);
+ SendMessageToSet(&data, false);
+
+ if (vehicle->GetBase()->HasUnitTypeMask(UNIT_MASK_MINION))
+ if (((Minion*)vehicle->GetBase())->GetOwner() == this)
+ vehicle->Dismiss();
+}
+
+void Unit::BuildMovementPacket(ByteBuffer *data) const
+{
+ switch (GetTypeId())
+ {
+ case TYPEID_UNIT:
+ if (canFly())
+ const_cast<Unit*>(this)->AddUnitMovementFlag(MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_LEVITATING);
+ break;
+ case TYPEID_PLAYER:
+ // remove unknown, unused etc flags for now
+ const_cast<Unit*>(this)->RemoveUnitMovementFlag(MOVEMENTFLAG_SPLINE2);
+ if (isInFlight())
+ {
+ WPAssert(const_cast<Unit*>(this)->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE);
+ const_cast<Unit*>(this)->AddUnitMovementFlag(MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_SPLINE2);
+ }
+ break;
+ }
+
+ *data << uint32(GetUnitMovementFlags()); // movement flags
+ *data << uint16(m_movementInfo.unk1); // 2.3.0
+ *data << uint32(getMSTime()); // time
+ *data << GetPositionX();
+ *data << GetPositionY();
+ *data << GetPositionZ();
+ *data << GetOrientation();
+
+ // 0x00000200
+ if (GetUnitMovementFlags() & MOVEMENTFLAG_ONTRANSPORT)
+ {
+ if (m_vehicle)
+ data->append(m_vehicle->GetBase()->GetPackGUID());
+ else if (GetTransport())
+ data->append(GetTransport()->GetPackGUID());
+ else
+ {
+ sLog.outError("Unit %u does not have transport!", GetEntry());
+ *data << (uint8)0;
+ }
+ *data << float (GetTransOffsetX());
+ *data << float (GetTransOffsetY());
+ *data << float (GetTransOffsetZ());
+ *data << float (GetTransOffsetO());
+ *data << uint32(GetTransTime());
+ *data << uint8 (GetTransSeat());
+ }
+
+ // 0x02200000
+ if ((GetUnitMovementFlags() & (MOVEMENTFLAG_SWIMMING | MOVEMENTFLAG_FLYING))
+ || (m_movementInfo.unk1 & 0x20))
+ *data << (float)m_movementInfo.s_pitch;
+
+ *data << (uint32)m_movementInfo.fallTime;
+
+ // 0x00001000
+ if (GetUnitMovementFlags() & MOVEMENTFLAG_JUMPING)
+ {
+ *data << (float)m_movementInfo.j_zspeed;
+ *data << (float)m_movementInfo.j_sinAngle;
+ *data << (float)m_movementInfo.j_cosAngle;
+ *data << (float)m_movementInfo.j_xyspeed;
+ }
+
+ // 0x04000000
+ if (GetUnitMovementFlags() & MOVEMENTFLAG_SPLINE)
+ *data << (float)m_movementInfo.u_unk1;
+
+ /*if (GetTypeId() == TYPEID_PLAYER)
+ {
+ sLog.outString("Send MovementInfo:");
+ OutMovementInfo();
+ }*/
+}
+
+void Unit::OutMovementInfo() const
+{
+ sLog.outString("MovementInfo for %u: Flag %u, Unk1 %u, Time %u, Pos %f %f %f %f, Fall %u", GetEntry(), m_movementInfo.flags, (uint32)m_movementInfo.unk1, m_movementInfo.time, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation(), m_movementInfo.fallTime);
+ if (m_movementInfo.flags & MOVEMENTFLAG_ONTRANSPORT)
+ sLog.outString("Transport: GUID " UI64FMTD ", Pos %f %f %f %f, Time %u, Seat %d", m_movementInfo.t_guid, m_movementInfo.t_x, m_movementInfo.t_y, m_movementInfo.t_z, m_movementInfo.t_o, m_movementInfo.t_time, (int32)m_movementInfo.t_seat);
+ if ((m_movementInfo.flags & (MOVEMENTFLAG_SWIMMING | MOVEMENTFLAG_FLYING)) || (m_movementInfo.unk1 & 0x20))
+ sLog.outString("Pitch: %f", m_movementInfo.s_pitch);
+ if (m_movementInfo.flags & MOVEMENTFLAG_JUMPING)
+ sLog.outString("Jump: speedz %f, sin %f, cos %f, speedxy %f", m_movementInfo.j_zspeed, m_movementInfo.j_sinAngle, m_movementInfo.j_cosAngle, m_movementInfo.j_xyspeed);
+ if (m_movementInfo.flags & MOVEMENTFLAG_SPLINE)
+ sLog.outString("Spline: %f", m_movementInfo.u_unk1);
+}
+
+void Unit::SetFlying(bool apply)
+{
+ if (apply)
+ {
+ SetByteFlag(UNIT_FIELD_BYTES_1, 3, 0x02);
+ AddUnitMovementFlag(MOVEMENTFLAG_FLY_MODE | MOVEMENTFLAG_FLYING);
+ }
+ else
+ {
+ RemoveByteFlag(UNIT_FIELD_BYTES_1, 3, 0x02);
+ RemoveUnitMovementFlag(MOVEMENTFLAG_FLY_MODE | MOVEMENTFLAG_FLYING);
+ }
+}
+
+void Unit::NearTeleportTo( float x, float y, float z, float orientation, bool casting /*= false*/ )
+{
+ if (GetTypeId() == TYPEID_PLAYER)
+ ((Player*)this)->TeleportTo(GetMapId(), x, y, z, orientation, TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET | (casting ? TELE_TO_SPELL : 0));
+ else
+ {
+ WorldPacket data;
+ /*data.Initialize(MSG_MOVE_TELEPORT, 30);
+ data.append(GetPackGUID());
+ data << uint32(GetUnitMovementFlags());
+ data << uint16(0); // Probably walk flags here
+ data << getMSTime(); // time
+ data << x; // destination coords
+ data << y;
+ data << z;
+ data << orientation;
+ data << uint32 (0);
+ // Other information here: jumping angle etc
+ SendMessageToSet(&data, false);*/
+
+ // FIXME: this interrupts spell visual
+ DestroyForNearbyPlayers();
+
+ SetPosition(x, y, z, orientation, true);
+ //ObjectAccessor::UpdateObjectVisibility(this);
+
+ //WorldPacket data;
+ // Work strange for many spells: triggered active mover set for targeted player to creature
+ //BuildTeleportAckMsg(&data, x, y, z, orientation);
+ //BuildHeartBeatMsg(&data);
+ //SendMessageToSet(&data, false);
+ }
+}
+
+bool Unit::SetPosition(float x, float y, float z, float orientation, bool teleport)
+{
+ // prevent crash when a bad coord is sent by the client
+ if (!Trinity::IsValidMapCoord(x,y))
+ {
+ sLog.outDebug("Unit::SetPosition(%f, %f, %f) .. bad coordinates!",x,y,z);
+ return false;
+ }
+
+ bool turn = (GetOrientation() != orientation);
+ bool relocated = (teleport || GetPositionX() != x || GetPositionY() != y || GetPositionZ() != z);
+
+ if (turn)
+ RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
+
+ if (relocated)
+ {
+ RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE);
+
+ // move and update visible state if need
+ if(GetTypeId() == TYPEID_PLAYER)
+ GetMap()->PlayerRelocation((Player*)this, x, y, z, orientation);
+ else
+ GetMap()->CreatureRelocation((Creature*)this, x, y, z, orientation);
+ }
+ else if(turn)
+ SetOrientation(orientation);
+
+ if ((relocated || turn) && IsVehicle())
+ GetVehicleKit()->RelocatePassengers(x,y,z,orientation);
+
+ return (relocated || turn);
+}
+
+void Unit::SendThreatListUpdate()
+{
+ if (uint32 count = getThreatManager().getThreatList().size())
+ {
+ //sLog.outDebug( "WORLD: Send SMSG_THREAT_UPDATE Message" );
+ WorldPacket data(SMSG_THREAT_UPDATE, 8 + count * 8);
+ data.append(GetPackGUID());
+ data << uint32(count);
+ std::list<HostilReference*>& tlist = getThreatManager().getThreatList();
+ for (std::list<HostilReference*>::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr)
+ {
+ data.appendPackGUID((*itr)->getUnitGuid());
+ data << uint32((*itr)->getThreat());
+ }
+ SendMessageToSet(&data, false);
+ }
+}
+
+void Unit::SendChangeCurrentVictimOpcode(HostilReference* pHostilReference)
+{
+ if (uint32 count = getThreatManager().getThreatList().size())
+ {
+ sLog.outDebug( "WORLD: Send SMSG_HIGHEST_THREAT_UPDATE Message" );
+ WorldPacket data(SMSG_HIGHEST_THREAT_UPDATE, 8 + 8 + count * 8);
+ data.append(GetPackGUID());
+ data.appendPackGUID(pHostilReference->getUnitGuid());
+ data << uint32(count);
+ std::list<HostilReference*>& tlist = getThreatManager().getThreatList();
+ for (std::list<HostilReference*>::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr)
+ {
+ data.appendPackGUID((*itr)->getUnitGuid());
+ data << uint32((*itr)->getThreat());
+ }
+ SendMessageToSet(&data, false);
+ }
+}
+
+void Unit::SendClearThreatListOpcode()
+{
+ sLog.outDebug( "WORLD: Send SMSG_THREAT_CLEAR Message" );
+ WorldPacket data(SMSG_THREAT_CLEAR, 8);
+ data.append(GetPackGUID());
+ SendMessageToSet(&data, false);
+}
+
+void Unit::SendRemoveFromThreatListOpcode(HostilReference* pHostilReference)
+{
+ sLog.outDebug( "WORLD: Send SMSG_THREAT_REMOVE Message" );
+ WorldPacket data(SMSG_THREAT_REMOVE, 8 + 8);
+ data.append(GetPackGUID());
+ data.appendPackGUID(pHostilReference->getUnitGuid());
+ SendMessageToSet(&data, false);
+}
+
+void Unit::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
+{
+ float addRage;
+
+ float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
+
+ // Unknown if correct, but lineary adjust rage conversion above level 70
+ if (getLevel() > 70)
+ rageconversion += 13.27f*(getLevel()-70);
+
+ if (attacker)
+ {
+ addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
+
+ // talent who gave more rage on attack
+ addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
+ }
+ else
+ {
+ addRage = damage/rageconversion*2.5;
+
+ // Berserker Rage effect
+ if (HasAura(18499))
+ addRage *= 2.0;
+ }
+
+ addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
+
+ ModifyPower(POWER_RAGE, uint32(addRage*10));
+}
+
+void Unit::StopAttackFaction(uint32 faction_id)
+{
+ if (Unit* victim = getVictim())
+ {
+ if (victim->getFactionTemplateEntry()->faction==faction_id)
+ {
+ AttackStop();
+ if (IsNonMeleeSpellCasted(false))
+ InterruptNonMeleeSpells(false);
+
+ // melee and ranged forced attack cancel
+ if (GetTypeId() == TYPEID_PLAYER)
+ ((Player*)this)->SendAttackSwingCancelAttack();
+ }
+ }
+
+ AttackerSet const& attackers = getAttackers();
+ for(AttackerSet::const_iterator itr = attackers.begin(); itr != attackers.end();)
+ {
+ if ((*itr)->getFactionTemplateEntry()->faction==faction_id)
+ {
+ (*itr)->AttackStop();
+ itr = attackers.begin();
+ }
+ else
+ ++itr;
+ }
+
+ getHostilRefManager().deleteReferencesForFaction(faction_id);
+
+ for(ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
+ (*itr)->StopAttackFaction(faction_id);
+}
+
+void Unit::OutDebugInfo() const
+{
+ sLog.outError("Unit::OutDebugInfo");
+ sLog.outString("GUID "UI64FMTD", entry %u, type %u, name %s", GetGUID(), GetEntry(), (uint32)GetTypeId(), GetName());
+ sLog.outString("OwnerGUID "UI64FMTD", MinionGUID "UI64FMTD", CharmerGUID "UI64FMTD", CharmedGUID "UI64FMTD, GetOwnerGUID(), GetMinionGUID(), GetCharmerGUID(), GetCharmGUID());
+ sLog.outString("In world %u, unit type mask %u", (uint32)(IsInWorld() ? 1 : 0), m_unitTypeMask);
+
+ sLog.outStringInLine("Summon Slot: ");
+ for (uint32 i = 0; i < MAX_SUMMON_SLOT; ++i)
+ sLog.outStringInLine(UI64FMTD", ", m_SummonSlot[i]);
+ sLog.outString();
+
+ sLog.outStringInLine("Controlled List: ");
+ for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
+ sLog.outStringInLine(UI64FMTD", ", (*itr)->GetGUID());
+ sLog.outString();
+
+ sLog.outStringInLine("Aura List: ");
+ for (AuraApplicationMap::const_iterator itr = m_appliedAuras.begin(); itr != m_appliedAuras.end(); ++itr)
+ sLog.outStringInLine("%u, ", itr->first);
+ sLog.outString();
+
+ if (IsVehicle())
+ {
+ sLog.outStringInLine("Passenger List: ");
+ for (SeatMap::iterator itr = GetVehicleKit()->m_Seats.begin(); itr != GetVehicleKit()->m_Seats.end(); ++itr)
+ if (Unit *passenger = itr->second.passenger)
+ sLog.outStringInLine(UI64FMTD", ", passenger->GetGUID());
+ sLog.outString();
+ }
+
+ if (GetVehicle())
+ sLog.outString("On vehicle %u.", GetVehicleBase()->GetEntry());
+}
+
+void CharmInfo::SetIsCommandAttack(bool val)
+{
+ m_isCommandAttack = val;
+}
+
+bool CharmInfo::IsCommandAttack()
+{
+ return m_isCommandAttack;
+}
+
+void CharmInfo::SaveStayPosition()
+{
+ m_unit->GetPosition(m_stayX, m_stayY, m_stayZ);
+}
+
+void CharmInfo::GetStayPosition(float &x, float &y, float &z)
+{
+ x = m_stayX;
+ y = m_stayY;
+ z = m_stayZ;
+}
+
+void CharmInfo::SetIsAtStay(bool val)
+{
+ m_isAtStay = val;
+}
+
+bool CharmInfo::IsAtStay()
+{
+ return m_isAtStay;
+}
+
+void CharmInfo::SetIsFollowing(bool val)
+{
+ m_isFollowing = val;
+}
+
+bool CharmInfo::IsFollowing()
+{
+ return m_isFollowing;
+}
+
+void CharmInfo::SetIsReturning(bool val)
+{
+ m_isReturning = val;
+}
+
+bool CharmInfo::IsReturning()
+{
+ return m_isReturning;
+}