[9187] Fixed problem with non-attackable pes/totems at arenas
[getmangos.git] / src / game / Unit.cpp
blob916a697aed4c1895e9cbc0dfdbeec710ba12cef5
1 /*
2 * Copyright (C) 2005-2010 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Log.h"
21 #include "Opcodes.h"
22 #include "WorldPacket.h"
23 #include "WorldSession.h"
24 #include "World.h"
25 #include "ObjectMgr.h"
26 #include "ObjectDefines.h"
27 #include "SpellMgr.h"
28 #include "Unit.h"
29 #include "QuestDef.h"
30 #include "Player.h"
31 #include "Creature.h"
32 #include "Spell.h"
33 #include "Group.h"
34 #include "SpellAuras.h"
35 #include "MapManager.h"
36 #include "ObjectAccessor.h"
37 #include "CreatureAI.h"
38 #include "Formulas.h"
39 #include "Pet.h"
40 #include "Util.h"
41 #include "Totem.h"
42 #include "BattleGround.h"
43 #include "InstanceSaveMgr.h"
44 #include "GridNotifiersImpl.h"
45 #include "CellImpl.h"
46 #include "Path.h"
47 #include "Traveller.h"
48 #include "VMapFactory.h"
50 #include <math.h>
52 float baseMoveSpeed[MAX_MOVE_TYPE] =
54 2.5f, // MOVE_WALK
55 7.0f, // MOVE_RUN
56 1.25f, // MOVE_RUN_BACK
57 4.722222f, // MOVE_SWIM
58 4.5f, // MOVE_SWIM_BACK
59 3.141594f, // MOVE_TURN_RATE
60 7.0f, // MOVE_FLIGHT
61 4.5f, // MOVE_FLIGHT_BACK
62 3.14f // MOVE_PITCH_RATE
65 // Used for prepare can/can`t triggr aura
66 static bool InitTriggerAuraData();
67 // Define can trigger auras
68 static bool isTriggerAura[TOTAL_AURAS];
69 // Define can`t trigger auras (need for disable second trigger)
70 static bool isNonTriggerAura[TOTAL_AURAS];
71 // Prepare lists
72 static bool procPrepared = InitTriggerAuraData();
74 Unit::Unit()
75 : WorldObject(), i_motionMaster(this), m_ThreatManager(this), m_HostileRefManager(this)
77 m_objectType |= TYPEMASK_UNIT;
78 m_objectTypeId = TYPEID_UNIT;
80 m_updateFlag = (UPDATEFLAG_HIGHGUID | UPDATEFLAG_LIVING | UPDATEFLAG_HAS_POSITION);
82 m_attackTimer[BASE_ATTACK] = 0;
83 m_attackTimer[OFF_ATTACK] = 0;
84 m_attackTimer[RANGED_ATTACK] = 0;
85 m_modAttackSpeedPct[BASE_ATTACK] = 1.0f;
86 m_modAttackSpeedPct[OFF_ATTACK] = 1.0f;
87 m_modAttackSpeedPct[RANGED_ATTACK] = 1.0f;
89 m_extraAttacks = 0;
91 m_state = 0;
92 m_form = FORM_NONE;
93 m_deathState = ALIVE;
95 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
96 m_currentSpells[i] = NULL;
98 m_addDmgOnce = 0;
100 for(int i = 0; i < MAX_TOTEM; ++i)
101 m_TotemSlot[i] = 0;
103 m_ObjectSlot[0] = m_ObjectSlot[1] = m_ObjectSlot[2] = m_ObjectSlot[3] = 0;
104 //m_Aura = NULL;
105 //m_AurasCheck = 2000;
106 //m_removeAuraTimer = 4;
107 m_AurasUpdateIterator = m_Auras.end();
108 m_AuraFlags = 0;
110 m_Visibility = VISIBILITY_ON;
112 m_detectInvisibilityMask = 0;
113 m_invisibilityMask = 0;
114 m_transform = 0;
115 m_ShapeShiftFormSpellId = 0;
116 m_canModifyStats = false;
118 for (int i = 0; i < MAX_SPELL_IMMUNITY; ++i)
119 m_spellImmune[i].clear();
120 for (int i = 0; i < UNIT_MOD_END; ++i)
122 m_auraModifiersGroup[i][BASE_VALUE] = 0.0f;
123 m_auraModifiersGroup[i][BASE_PCT] = 1.0f;
124 m_auraModifiersGroup[i][TOTAL_VALUE] = 0.0f;
125 m_auraModifiersGroup[i][TOTAL_PCT] = 1.0f;
127 // implement 50% base damage from offhand
128 m_auraModifiersGroup[UNIT_MOD_DAMAGE_OFFHAND][TOTAL_PCT] = 0.5f;
130 for (int i = 0; i < MAX_ATTACK; ++i)
132 m_weaponDamage[i][MINDAMAGE] = BASE_MINDAMAGE;
133 m_weaponDamage[i][MAXDAMAGE] = BASE_MAXDAMAGE;
135 for (int i = 0; i < MAX_STATS; ++i)
136 m_createStats[i] = 0.0f;
138 m_attacking = NULL;
139 m_modMeleeHitChance = 0.0f;
140 m_modRangedHitChance = 0.0f;
141 m_modSpellHitChance = 0.0f;
142 m_baseSpellCritChance = 5;
144 m_CombatTimer = 0;
145 m_lastManaUseTimer = 0;
147 //m_victimThreat = 0.0f;
148 for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
149 m_threatModifier[i] = 1.0f;
150 m_isSorted = true;
151 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
152 m_speed_rate[i] = 1.0f;
154 m_charmInfo = NULL;
156 // remove aurastates allowing special moves
157 for(int i=0; i < MAX_REACTIVE; ++i)
158 m_reactiveTimer[i] = 0;
161 Unit::~Unit()
163 // set current spells as deletable
164 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
166 if (m_currentSpells[i])
168 m_currentSpells[i]->SetReferencedFromCurrent(false);
169 m_currentSpells[i] = NULL;
173 if (m_charmInfo)
174 delete m_charmInfo;
176 // those should be already removed at "RemoveFromWorld()" call
177 assert(m_gameObj.size() == 0);
178 assert(m_dynObjGUIDs.size() == 0);
179 assert(m_deletedAuras.size() == 0);
182 void Unit::Update( uint32 p_time )
184 if(!IsInWorld())
185 return;
187 /*if(p_time > m_AurasCheck)
189 m_AurasCheck = 2000;
190 _UpdateAura();
191 }else
192 m_AurasCheck -= p_time;*/
194 // WARNING! Order of execution here is important, do not change.
195 // Spells must be processed with event system BEFORE they go to _UpdateSpells.
196 // Or else we may have some SPELL_STATE_FINISHED spells stalled in pointers, that is bad.
197 m_Events.Update( p_time );
198 _UpdateSpells( p_time );
200 CleanupDeletedAuras();
202 if (m_lastManaUseTimer)
204 if (p_time >= m_lastManaUseTimer)
205 m_lastManaUseTimer = 0;
206 else
207 m_lastManaUseTimer -= p_time;
210 if (CanHaveThreatList())
211 getThreatManager().UpdateForClient(p_time);
213 // update combat timer only for players and pets
214 if (isInCombat() && (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet() || ((Creature*)this)->isCharmed()))
216 // Check UNIT_STAT_MELEE_ATTACKING or UNIT_STAT_CHASE (without UNIT_STAT_FOLLOW in this case) so pets can reach far away
217 // targets without stopping half way there and running off.
218 // These flags are reset after target dies or another command is given.
219 if (m_HostileRefManager.isEmpty())
221 // m_CombatTimer set at aura start and it will be freeze until aura removing
222 if (m_CombatTimer <= p_time)
223 CombatStop();
224 else
225 m_CombatTimer -= p_time;
229 if (uint32 base_att = getAttackTimer(BASE_ATTACK))
231 setAttackTimer(BASE_ATTACK, (p_time >= base_att ? 0 : base_att - p_time) );
234 // update abilities available only for fraction of time
235 UpdateReactives( p_time );
237 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, GetHealth() < GetMaxHealth()*0.20f);
238 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, GetHealth() < GetMaxHealth()*0.35f);
239 ModifyAuraState(AURA_STATE_HEALTH_ABOVE_75_PERCENT, GetHealth() > GetMaxHealth()*0.75f);
241 i_motionMaster.UpdateMotion(p_time);
244 bool Unit::haveOffhandWeapon() const
246 if(GetTypeId() == TYPEID_PLAYER)
247 return ((Player*)this)->GetWeaponForAttack(OFF_ATTACK,true,true);
248 else
249 return false;
252 void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint8 type, MonsterMovementFlags flags, uint32 Time, Player* player)
254 float moveTime = Time;
256 WorldPacket data( SMSG_MONSTER_MOVE, (41 + GetPackGUID().size()) );
257 data.append(GetPackGUID());
258 data << uint8(0); // new in 3.1
259 data << GetPositionX() << GetPositionY() << GetPositionZ();
260 data << uint32(getMSTime());
262 data << uint8(type); // unknown
263 switch(type)
265 case 0: // normal packet
266 break;
267 case 1: // stop packet (raw pos?)
268 SendMessageToSet( &data, true );
269 return;
270 case 2: // facing spot, not used currently
271 data << float(0);
272 data << float(0);
273 data << float(0);
274 break;
275 case 3: // not used currently
276 data << uint64(0); // probably target guid (facing target?)
277 break;
278 case 4: // not used currently
279 data << float(0); // facing angle
280 break;
283 data << uint32(flags);
285 if(flags & MONSTER_MOVE_WALK)
286 moveTime *= 1.05f;
288 data << uint32(moveTime); // Time in between points
289 data << uint32(1); // 1 single waypoint
290 data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B
292 if(player)
293 player->GetSession()->SendPacket(&data);
294 else
295 SendMessageToSet( &data, true );
298 void Unit::SendMonsterMoveByPath(Path const& path, uint32 start, uint32 end, MonsterMovementFlags flags)
300 uint32 traveltime = uint32(path.GetTotalLength(start, end) * 32);
302 uint32 pathSize = end - start;
304 WorldPacket data( SMSG_MONSTER_MOVE, (GetPackGUID().size()+1+4+4+4+4+1+4+4+4+pathSize*4*3) );
305 data.append(GetPackGUID());
306 data << uint8(0);
307 data << GetPositionX();
308 data << GetPositionY();
309 data << GetPositionZ();
310 data << uint32(getMSTime());
311 data << uint8(0);
312 data << uint32(flags);
313 data << uint32(traveltime);
314 data << uint32(pathSize);
315 data.append((char*)path.GetNodes(start), pathSize * 4 * 3);
316 SendMessageToSet(&data, true);
319 void Unit::BuildHeartBeatMsg(WorldPacket *data) const
321 MovementFlags move_flags = GetTypeId()==TYPEID_PLAYER
322 ? ((Player const*)this)->m_movementInfo.GetMovementFlags()
323 : MOVEMENTFLAG_NONE;
325 data->Initialize(MSG_MOVE_HEARTBEAT, 32);
326 data->append(GetPackGUID());
327 *data << uint32(move_flags); // movement flags
328 *data << uint16(0); // 2.3.0
329 *data << uint32(getMSTime()); // time
330 *data << float(GetPositionX());
331 *data << float(GetPositionY());
332 *data << float(GetPositionZ());
333 *data << float(GetOrientation());
334 *data << uint32(0);
337 void Unit::resetAttackTimer(WeaponAttackType type)
339 m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]);
342 bool Unit::canReachWithAttack(Unit *pVictim) const
344 assert(pVictim);
345 float reach = GetFloatValue(UNIT_FIELD_COMBATREACH);
346 if( reach <= 0.0f )
347 reach = 1.0f;
348 return IsWithinDistInMap(pVictim, reach);
351 void Unit::RemoveSpellsCausingAura(AuraType auraType)
353 if (auraType >= TOTAL_AURAS) return;
354 AuraList::const_iterator iter, next;
355 for (iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end(); iter = next)
357 next = iter;
358 ++next;
360 if (*iter)
362 RemoveAurasDueToSpell((*iter)->GetId());
363 if (!m_modAuras[auraType].empty())
364 next = m_modAuras[auraType].begin();
365 else
366 return;
371 bool Unit::HasAuraType(AuraType auraType) const
373 return (!m_modAuras[auraType].empty());
376 /* Called by DealDamage for auras that have a chance to be dispelled on damage taken. */
377 void Unit::RemoveSpellbyDamageTaken(AuraType auraType, uint32 damage)
379 if(!HasAuraType(auraType))
380 return;
382 // The chance to dispel an aura depends on the damage taken with respect to the casters level.
383 uint32 max_dmg = getLevel() > 8 ? 25 * getLevel() - 150 : 50;
384 float chance = float(damage) / max_dmg * 100.0f;
385 if (roll_chance_f(chance))
386 RemoveSpellsCausingAura(auraType);
389 void Unit::DealDamageMods(Unit *pVictim, uint32 &damage, uint32* absorb)
391 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
393 if(absorb)
394 absorb += damage;
395 damage = 0;
396 return;
399 //You don't lose health from damage taken from another player while in a sanctuary
400 //You still see it in the combat log though
401 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
403 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
404 if(area && area->flags & AREA_FLAG_SANCTUARY) //sanctuary
406 if(absorb)
407 absorb += damage;
408 damage = 0;
412 uint32 originalDamage = damage;
414 //Script Event damage Deal
415 if( GetTypeId()== TYPEID_UNIT && ((Creature *)this)->AI())
416 ((Creature *)this)->AI()->DamageDeal(pVictim, damage);
417 //Script Event damage taken
418 if( pVictim->GetTypeId()== TYPEID_UNIT && ((Creature *)pVictim)->AI() )
419 ((Creature *)pVictim)->AI()->DamageTaken(this, damage);
421 if(absorb && originalDamage > damage)
422 absorb += (originalDamage - damage);
425 uint32 Unit::DealDamage(Unit *pVictim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellEntry const *spellProto, bool durabilityLoss)
427 // remove affects from victim (including from 0 damage and DoTs)
428 if(pVictim != this)
429 pVictim->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
431 // remove affects from attacker at any non-DoT damage (including 0 damage)
432 if( damagetype != DOT)
434 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
435 RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
437 if(pVictim != this)
438 RemoveSpellsCausingAura(SPELL_AURA_MOD_INVISIBILITY);
440 if(pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->IsStandState() && !pVictim->hasUnitState(UNIT_STAT_STUNNED))
441 pVictim->SetStandState(UNIT_STAND_STATE_STAND);
444 if(!damage)
446 // Rage from physical damage received .
447 if(cleanDamage && cleanDamage->damage && (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL) && pVictim->GetTypeId() == TYPEID_PLAYER && (pVictim->getPowerType() == POWER_RAGE))
448 ((Player*)pVictim)->RewardRage(cleanDamage->damage, 0, false);
450 return 0;
452 if (!spellProto || !IsSpellHaveAura(spellProto,SPELL_AURA_MOD_FEAR))
453 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_FEAR, damage);
454 // root type spells do not dispel the root effect
455 if (!spellProto || !(spellProto->Mechanic == MECHANIC_ROOT || IsSpellHaveAura(spellProto,SPELL_AURA_MOD_ROOT)))
456 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_ROOT, damage);
458 // no xp,health if type 8 /critters/
459 if(pVictim->GetTypeId() != TYPEID_PLAYER && pVictim->GetCreatureType() == CREATURE_TYPE_CRITTER)
461 pVictim->setDeathState(JUST_DIED);
462 pVictim->SetHealth(0);
464 // allow loot only if has loot_id in creature_template
465 CreatureInfo const* cInfo = ((Creature*)pVictim)->GetCreatureInfo();
466 if(cInfo && cInfo->lootid)
467 pVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
469 // some critters required for quests (need normal entry instead possible heroic in any cases)
470 if(GetTypeId() == TYPEID_PLAYER)
471 if(CreatureInfo const* normalInfo = ObjectMgr::GetCreatureTemplate(pVictim->GetEntry()))
472 ((Player*)this)->KilledMonster(normalInfo,pVictim->GetGUID());
474 return damage;
477 DEBUG_LOG("DealDamageStart");
479 uint32 health = pVictim->GetHealth();
480 sLog.outDetail("deal dmg:%d to health:%d ",damage,health);
482 // duel ends when player has 1 or less hp
483 bool duel_hasEnded = false;
484 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->duel && damage >= (health-1))
486 // prevent kill only if killed in duel and killed by opponent or opponent controlled creature
487 if(((Player*)pVictim)->duel->opponent==this || ((Player*)pVictim)->duel->opponent->GetGUID() == GetOwnerGUID())
488 damage = health-1;
490 duel_hasEnded = true;
492 //Get in CombatState
493 if(pVictim != this && damagetype != DOT)
495 SetInCombatWith(pVictim);
496 pVictim->SetInCombatWith(this);
498 if(Player* attackedPlayer = pVictim->GetCharmerOrOwnerPlayerOrPlayerItself())
499 SetContestedPvP(attackedPlayer);
502 // Rage from Damage made (only from direct weapon damage)
503 if( cleanDamage && damagetype==DIRECT_DAMAGE && this != pVictim && GetTypeId() == TYPEID_PLAYER && (getPowerType() == POWER_RAGE))
505 uint32 weaponSpeedHitFactor;
507 switch(cleanDamage->attackType)
509 case BASE_ATTACK:
511 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
512 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 7);
513 else
514 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
516 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
518 break;
520 case OFF_ATTACK:
522 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
523 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
524 else
525 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 1.75f);
527 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
529 break;
531 case RANGED_ATTACK:
532 break;
536 if (GetTypeId() == TYPEID_PLAYER && this != pVictim)
538 Player *killer = ((Player*)this);
540 // in bg, count dmg if victim is also a player
541 if (pVictim->GetTypeId()==TYPEID_PLAYER)
543 if (BattleGround *bg = killer->GetBattleGround())
545 // FIXME: kept by compatibility. don't know in BG if the restriction apply.
546 bg->UpdatePlayerScore(killer, SCORE_DAMAGE_DONE, damage);
550 killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE, damage, 0, pVictim);
551 killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT, damage);
554 if (pVictim->GetTypeId() == TYPEID_PLAYER)
555 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED, damage);
557 if (pVictim->GetTypeId() == TYPEID_UNIT && !((Creature*)pVictim)->isPet() && !((Creature*)pVictim)->hasLootRecipient())
558 ((Creature*)pVictim)->SetLootRecipient(this);
560 if (health <= damage)
562 DEBUG_LOG("DealDamage: victim just died");
564 if (pVictim->GetTypeId() == TYPEID_PLAYER)
565 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, health);
567 // find player: owner of controlled `this` or `this` itself maybe
568 Player *player = GetCharmerOrOwnerPlayerOrPlayerItself();
570 if(pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->GetLootRecipient())
571 player = ((Creature*)pVictim)->GetLootRecipient();
572 // Reward player, his pets, and group/raid members
573 // call kill spell proc event (before real die and combat stop to triggering auras removed at death/combat stop)
574 if(player && player!=pVictim)
576 player->RewardPlayerAndGroupAtKill(pVictim);
577 player->ProcDamageAndSpell(pVictim, PROC_FLAG_KILL, PROC_FLAG_KILLED, PROC_EX_NONE, 0);
579 WorldPacket data(SMSG_PARTYKILLLOG, (8+8)); //send event PARTY_KILL
580 data << uint64(player->GetGUID()); //player with killing blow
581 data << uint64(pVictim->GetGUID()); //victim
582 if (Group *group = player->GetGroup())
583 group->BroadcastPacket(&data, group->GetMemberGroup(player->GetGUID()));
584 else
585 player->SendDirectMessage(&data);
588 DEBUG_LOG("DealDamageAttackStop");
590 // stop combat
591 pVictim->CombatStop();
592 pVictim->getHostileRefManager().deleteReferences();
594 bool damageFromSpiritOfRedemtionTalent = spellProto && spellProto->Id == 27795;
596 // if talent known but not triggered (check priest class for speedup check)
597 Aura* spiritOfRedemtionTalentReady = NULL;
598 if( !damageFromSpiritOfRedemtionTalent && // not called from SPELL_AURA_SPIRIT_OF_REDEMPTION
599 pVictim->GetTypeId()==TYPEID_PLAYER && pVictim->getClass()==CLASS_PRIEST )
601 AuraList const& vDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
602 for(AuraList::const_iterator itr = vDummyAuras.begin(); itr != vDummyAuras.end(); ++itr)
604 if((*itr)->GetSpellProto()->SpellIconID==1654)
606 spiritOfRedemtionTalentReady = *itr;
607 break;
612 DEBUG_LOG("SET JUST_DIED");
613 if(!spiritOfRedemtionTalentReady)
614 pVictim->setDeathState(JUST_DIED);
616 DEBUG_LOG("DealDamageHealth1");
618 if(spiritOfRedemtionTalentReady)
620 // save value before aura remove
621 uint32 ressSpellId = pVictim->GetUInt32Value(PLAYER_SELF_RES_SPELL);
622 if(!ressSpellId)
623 ressSpellId = ((Player*)pVictim)->GetResurrectionSpellId();
625 //Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers)
626 pVictim->RemoveAllAurasOnDeath();
628 // restore for use at real death
629 pVictim->SetUInt32Value(PLAYER_SELF_RES_SPELL,ressSpellId);
631 // FORM_SPIRITOFREDEMPTION and related auras
632 pVictim->CastSpell(pVictim,27827,true,NULL,spiritOfRedemtionTalentReady);
634 else
635 pVictim->SetHealth(0);
637 // remember victim PvP death for corpse type and corpse reclaim delay
638 // at original death (not at SpiritOfRedemtionTalent timeout)
639 if( pVictim->GetTypeId()==TYPEID_PLAYER && !damageFromSpiritOfRedemtionTalent )
640 ((Player*)pVictim)->SetPvPDeath(player!=NULL);
642 // Call KilledUnit for creatures
643 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->AI())
644 ((Creature*)this)->AI()->KilledUnit(pVictim);
646 // achievement stuff
647 if (pVictim->GetTypeId() == TYPEID_PLAYER)
649 if (GetTypeId() == TYPEID_UNIT)
650 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE, GetEntry());
651 else if(GetTypeId() == TYPEID_PLAYER && pVictim != this)
652 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER, 1, ((Player*)this)->GetTeam());
655 // 10% durability loss on death
656 // clean InHateListOf
657 if (pVictim->GetTypeId() == TYPEID_PLAYER)
659 // only if not player and not controlled by player pet. And not at BG
660 if (durabilityLoss && !player && !((Player*)pVictim)->InBattleGround())
662 DEBUG_LOG("We are dead, loosing 10 percents durability");
663 ((Player*)pVictim)->DurabilityLossAll(0.10f,false);
664 // durability lost message
665 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
666 ((Player*)pVictim)->GetSession()->SendPacket(&data);
669 else // creature died
671 DEBUG_LOG("DealDamageNotPlayer");
672 Creature *cVictim = (Creature*)pVictim;
674 if(!cVictim->isPet())
676 cVictim->DeleteThreatList();
677 // only lootable if it has loot or can drop gold
678 if(cVictim->GetCreatureInfo()->lootid || cVictim->GetCreatureInfo()->maxgold > 0)
679 cVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
680 else
681 cVictim->lootForBody = true; // needed for skinning
683 // Call creature just died function
684 if (cVictim->AI())
685 cVictim->AI()->JustDied(this);
687 // Dungeon specific stuff, only applies to players killing creatures
688 if(cVictim->GetInstanceId())
690 Map *m = cVictim->GetMap();
691 Player *creditedPlayer = GetCharmerOrOwnerPlayerOrPlayerItself();
692 // TODO: do instance binding anyway if the charmer/owner is offline
694 if(m->IsDungeon() && creditedPlayer)
696 if (m->IsRaidOrHeroicDungeon())
698 if(cVictim->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
699 ((InstanceMap *)m)->PermBindAllPlayers(creditedPlayer);
701 else
703 // the reset time is set but not added to the scheduler
704 // until the players leave the instance
705 time_t resettime = cVictim->GetRespawnTimeEx() + 2 * HOUR;
706 if(InstanceSave *save = sInstanceSaveMgr.GetInstanceSave(cVictim->GetInstanceId()))
707 if(save->GetResetTime() < resettime) save->SetResetTime(resettime);
713 // last damage from non duel opponent or opponent controlled creature
714 if(duel_hasEnded)
716 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
717 Player *he = (Player*)pVictim;
719 assert(he->duel);
721 he->duel->opponent->CombatStopWithPets(true);
722 he->CombatStopWithPets(true);
724 he->DuelComplete(DUEL_INTERUPTED);
727 // battleground things (do this at the end, so the death state flag will be properly set to handle in the bg->handlekill)
728 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->InBattleGround())
730 Player *killed = ((Player*)pVictim);
731 if(BattleGround *bg = killed->GetBattleGround())
732 if(player)
733 bg->HandleKillPlayer(killed, player);
735 else if(pVictim->GetTypeId() == TYPEID_UNIT)
737 if (player)
738 if (BattleGround *bg = player->GetBattleGround())
739 bg->HandleKillUnit((Creature*)pVictim, player);
742 else // if (health <= damage)
744 DEBUG_LOG("DealDamageAlive");
746 if (pVictim->GetTypeId() == TYPEID_PLAYER)
747 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, damage);
749 pVictim->ModifyHealth(- (int32)damage);
751 if(damagetype != DOT)
753 if(!getVictim())
755 // if not have main target then attack state with target (including AI call)
756 //start melee attacks only after melee hit
757 Attack(pVictim,(damagetype == DIRECT_DAMAGE));
760 // if damage pVictim call AI reaction
761 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
762 ((Creature*)pVictim)->AI()->AttackedBy(this);
765 // polymorphed, hex and other negative transformed cases
766 uint32 morphSpell = pVictim->getTransForm();
767 if (morphSpell && !IsPositiveSpell(morphSpell))
769 if (SpellEntry const* morphEntry = sSpellStore.LookupEntry(morphSpell))
771 if (IsSpellHaveAura(morphEntry, SPELL_AURA_MOD_CONFUSE))
772 pVictim->RemoveAurasDueToSpell(morphSpell);
773 else if (IsSpellHaveAura(morphEntry, SPELL_AURA_MOD_PACIFY_SILENCE))
774 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_PACIFY_SILENCE, damage);
778 if(damagetype == DIRECT_DAMAGE || damagetype == SPELL_DIRECT_DAMAGE)
780 if (!spellProto || !(spellProto->AuraInterruptFlags&AURA_INTERRUPT_FLAG_DIRECT_DAMAGE))
781 pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DIRECT_DAMAGE);
783 if (pVictim->GetTypeId() != TYPEID_PLAYER)
785 if(spellProto && IsDamageToThreatSpell(spellProto))
786 pVictim->AddThreat(this, damage*2, (cleanDamage && cleanDamage->hitOutCome == MELEE_HIT_CRIT), damageSchoolMask, spellProto);
787 else
788 pVictim->AddThreat(this, damage, (cleanDamage && cleanDamage->hitOutCome == MELEE_HIT_CRIT), damageSchoolMask, spellProto);
790 else // victim is a player
792 // Rage from damage received
793 if(this != pVictim && pVictim->getPowerType() == POWER_RAGE)
795 uint32 rage_damage = damage + (cleanDamage ? cleanDamage->damage : 0);
796 ((Player*)pVictim)->RewardRage(rage_damage, 0, false);
799 // random durability for items (HIT TAKEN)
800 if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
802 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
803 ((Player*)pVictim)->DurabilityPointLossForEquipSlot(slot);
807 if(GetTypeId()==TYPEID_PLAYER)
809 // random durability for items (HIT DONE)
810 if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
812 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
813 ((Player*)this)->DurabilityPointLossForEquipSlot(slot);
817 // TODO: Store auras by interrupt flag to speed this up.
818 AuraMap& vAuras = pVictim->GetAuras();
819 for (AuraMap::const_iterator i = vAuras.begin(), next; i != vAuras.end(); i = next)
821 const SpellEntry *se = i->second->GetSpellProto();
822 next = i; ++next;
823 if (spellProto && spellProto->Id == se->Id) // Not drop auras added by self
824 continue;
825 if( se->AuraInterruptFlags & AURA_INTERRUPT_FLAG_DAMAGE )
827 bool remove = true;
828 if (se->procFlags & (1<<3))
830 if (!roll_chance_i(se->procChance))
831 remove = false;
833 if (remove)
835 pVictim->RemoveAurasDueToSpell(i->second->GetId());
836 // FIXME: this may cause the auras with proc chance to be rerolled several times
837 next = vAuras.begin();
842 if (damagetype != NODAMAGE && damage && pVictim->GetTypeId() == TYPEID_PLAYER)
844 if( damagetype != DOT )
846 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
848 // skip channeled spell (processed differently below)
849 if (i == CURRENT_CHANNELED_SPELL)
850 continue;
852 if(Spell* spell = pVictim->GetCurrentSpell(CurrentSpellTypes(i)))
854 if(spell->getState() == SPELL_STATE_PREPARING)
856 if(spell->m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_ABORT_ON_DMG)
857 pVictim->InterruptSpell(CurrentSpellTypes(i));
858 else
859 spell->Delayed();
865 if(Spell* spell = pVictim->m_currentSpells[CURRENT_CHANNELED_SPELL])
867 if (spell->getState() == SPELL_STATE_CASTING)
869 uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags;
870 if( channelInterruptFlags & CHANNEL_FLAG_DELAY )
872 if(pVictim!=this) //don't shorten the duration of channeling if you damage yourself
873 spell->DelayedChannel();
875 else if( (channelInterruptFlags & (CHANNEL_FLAG_DAMAGE | CHANNEL_FLAG_DAMAGE2)) )
877 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
878 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
881 else if (spell->getState() == SPELL_STATE_DELAYED)
882 // break channeled spell in delayed state on damage
884 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
885 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
890 // last damage from duel opponent
891 if(duel_hasEnded)
893 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
894 Player *he = (Player*)pVictim;
896 assert(he->duel);
898 he->SetHealth(1);
900 he->duel->opponent->CombatStopWithPets(true);
901 he->CombatStopWithPets(true);
903 he->CastSpell(he, 7267, true); // beg
904 he->DuelComplete(DUEL_WON);
908 DEBUG_LOG("DealDamageEnd returned %d damage", damage);
910 return damage;
913 void Unit::CastStop(uint32 except_spellid)
915 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
916 if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id!=except_spellid)
917 InterruptSpell(CurrentSpellTypes(i),false);
920 void Unit::CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
922 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
924 if(!spellInfo)
926 sLog.outError("CastSpell: unknown spell id %i by caster: %s %u)", spellId,(GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
927 return;
930 CastSpell(Victim,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
933 void Unit::CastSpell(Unit* Victim,SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
935 if(!spellInfo)
937 sLog.outError("CastSpell: unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
938 return;
941 if (castItem)
942 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
944 if(!originalCaster && triggeredByAura)
945 originalCaster = triggeredByAura->GetCasterGUID();
947 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
949 SpellCastTargets targets;
950 targets.setUnitTarget( Victim );
951 spell->m_CastItem = castItem;
952 spell->prepare(&targets, triggeredByAura);
955 void Unit::CastCustomSpell(Unit* Victim,uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
957 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
959 if(!spellInfo)
961 sLog.outError("CastCustomSpell: unknown spell id %i", spellId);
962 return;
965 CastCustomSpell(Victim,spellInfo,bp0,bp1,bp2,triggered,castItem,triggeredByAura, originalCaster);
968 void Unit::CastCustomSpell(Unit* Victim,SpellEntry const *spellInfo, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
970 if(!spellInfo)
972 sLog.outError("CastCustomSpell: unknown spell");
973 return;
976 if (castItem)
977 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
979 if(!originalCaster && triggeredByAura)
980 originalCaster = triggeredByAura->GetCasterGUID();
982 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster);
984 if(bp0)
985 spell->m_currentBasePoints[0] = *bp0-int32(spellInfo->EffectBaseDice[0]);
987 if(bp1)
988 spell->m_currentBasePoints[1] = *bp1-int32(spellInfo->EffectBaseDice[1]);
990 if(bp2)
991 spell->m_currentBasePoints[2] = *bp2-int32(spellInfo->EffectBaseDice[2]);
993 SpellCastTargets targets;
994 targets.setUnitTarget( Victim );
995 spell->m_CastItem = castItem;
996 spell->prepare(&targets, triggeredByAura);
999 // used for scripting
1000 void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
1002 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
1004 if(!spellInfo)
1006 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()));
1007 return;
1010 CastSpell(x, y, z,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
1013 // used for scripting
1014 void Unit::CastSpell(float x, float y, float z, SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
1016 if(!spellInfo)
1018 sLog.outError("CastSpell(x,y,z): unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
1019 return;
1022 if (castItem)
1023 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
1025 if(!originalCaster && triggeredByAura)
1026 originalCaster = triggeredByAura->GetCasterGUID();
1028 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
1030 SpellCastTargets targets;
1031 targets.setDestination(x, y, z);
1032 spell->m_CastItem = castItem;
1033 spell->prepare(&targets, triggeredByAura);
1036 // Obsolete func need remove, here only for comotability vs another patches
1037 uint32 Unit::SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage)
1039 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellID);
1040 SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, spellInfo->SchoolMask);
1041 CalculateSpellDamage(&damageInfo, damage, spellInfo);
1042 DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb);
1043 SendSpellNonMeleeDamageLog(&damageInfo);
1044 DealSpellDamage(&damageInfo, true);
1045 return damageInfo.damage;
1048 void Unit::CalculateSpellDamage(SpellNonMeleeDamage *damageInfo, int32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType)
1050 SpellSchoolMask damageSchoolMask = SpellSchoolMask(damageInfo->schoolMask);
1051 Unit *pVictim = damageInfo->target;
1053 if (damage < 0)
1054 return;
1056 if(!this || !pVictim)
1057 return;
1058 if(!this->isAlive() || !pVictim->isAlive())
1059 return;
1061 uint32 crTypeMask = pVictim->GetCreatureTypeMask();
1062 // Check spell crit chance
1063 bool crit = isSpellCrit(pVictim, spellInfo, damageSchoolMask, attackType);
1064 bool blocked = false;
1066 // damage bonus (per damage class)
1067 switch (spellInfo->DmgClass)
1069 // Melee and Ranged Spells
1070 case SPELL_DAMAGE_CLASS_RANGED:
1071 case SPELL_DAMAGE_CLASS_MELEE:
1073 //Calculate damage bonus
1074 damage = MeleeDamageBonus(pVictim, damage, attackType, spellInfo, SPELL_DIRECT_DAMAGE);
1075 // Get blocked status
1076 blocked = isSpellBlocked(pVictim, spellInfo, attackType);
1078 // if crit add critical bonus
1079 if (crit)
1081 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1082 damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim);
1083 // Resilience - reduce crit damage
1084 uint32 redunction_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageSchoolMask);
1085 if (attackType != RANGED_ATTACK)
1086 damage -= pVictim->GetMeleeCritDamageReduction(redunction_affected_damage);
1087 else
1088 damage -= pVictim->GetRangedCritDamageReduction(redunction_affected_damage);
1091 break;
1092 // Magical Attacks
1093 case SPELL_DAMAGE_CLASS_NONE:
1094 case SPELL_DAMAGE_CLASS_MAGIC:
1096 // Calculate damage bonus
1097 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1098 // If crit add critical bonus
1099 if (crit)
1101 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1102 damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim);
1103 // Resilience - reduce crit damage
1104 uint32 redunction_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageSchoolMask);
1105 damage -= pVictim->GetSpellCritDamageReduction(redunction_affected_damage);
1108 break;
1111 // only from players
1112 if (GetTypeId() == TYPEID_PLAYER)
1114 uint32 redunction_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageSchoolMask);
1115 damage -= pVictim->GetSpellDamageReduction(redunction_affected_damage);
1118 // damage mitigation
1119 if (damage > 0)
1121 // physical damage => armor
1122 if (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL)
1124 uint32 armor_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageSchoolMask);
1125 damage = damage - armor_affected_damage + CalcArmorReducedDamage(pVictim, armor_affected_damage);
1128 // block (only for damage class ranged and -melee, also non-physical damage possible)
1129 if (blocked)
1131 damageInfo->blocked = uint32(pVictim->GetShieldBlockValue());
1132 if (damage < damageInfo->blocked)
1133 damageInfo->blocked = damage;
1134 damage-=damageInfo->blocked;
1137 uint32 absorb_affected_damage = CalcNotIgnoreAbsorbDamage(damage,damageSchoolMask,spellInfo);
1138 CalcAbsorbResist(pVictim, damageSchoolMask, SPELL_DIRECT_DAMAGE, absorb_affected_damage, &damageInfo->absorb, &damageInfo->resist, !(spellInfo->AttributesEx2 & SPELL_ATTR_EX2_CANT_REFLECTED));
1139 damage-= damageInfo->absorb + damageInfo->resist;
1141 else
1142 damage = 0;
1143 damageInfo->damage = damage;
1146 void Unit::DealSpellDamage(SpellNonMeleeDamage *damageInfo, bool durabilityLoss)
1148 if (!damageInfo)
1149 return;
1151 Unit *pVictim = damageInfo->target;
1153 if(!this || !pVictim)
1154 return;
1156 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1157 return;
1159 SpellEntry const *spellProto = sSpellStore.LookupEntry(damageInfo->SpellID);
1160 if (spellProto == NULL)
1162 sLog.outDebug("Unit::DealSpellDamage have wrong damageInfo->SpellID: %u", damageInfo->SpellID);
1163 return;
1166 //You don't lose health from damage taken from another player while in a sanctuary
1167 //You still see it in the combat log though
1168 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1170 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1171 if(area && area->flags & AREA_FLAG_SANCTUARY) // sanctuary
1172 return;
1175 // Call default DealDamage (send critical in hit info for threat calculation)
1176 CleanDamage cleanDamage(damageInfo->cleanDamage, BASE_ATTACK, damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT ? MELEE_HIT_CRIT : MELEE_HIT_NORMAL);
1177 DealDamage(pVictim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, SpellSchoolMask(damageInfo->schoolMask), spellProto, durabilityLoss);
1180 //TODO for melee need create structure as in
1181 void Unit::CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType)
1183 damageInfo->attacker = this;
1184 damageInfo->target = pVictim;
1185 damageInfo->damageSchoolMask = GetMeleeDamageSchoolMask();
1186 damageInfo->attackType = attackType;
1187 damageInfo->damage = 0;
1188 damageInfo->cleanDamage = 0;
1189 damageInfo->absorb = 0;
1190 damageInfo->resist = 0;
1191 damageInfo->blocked_amount = 0;
1193 damageInfo->TargetState = 0;
1194 damageInfo->HitInfo = 0;
1195 damageInfo->procAttacker = PROC_FLAG_NONE;
1196 damageInfo->procVictim = PROC_FLAG_NONE;
1197 damageInfo->procEx = PROC_EX_NONE;
1198 damageInfo->hitOutCome = MELEE_HIT_EVADE;
1200 if(!this || !pVictim)
1201 return;
1202 if(!this->isAlive() || !pVictim->isAlive())
1203 return;
1205 // Select HitInfo/procAttacker/procVictim flag based on attack type
1206 switch (attackType)
1208 case BASE_ATTACK:
1209 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_HIT;
1210 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;
1211 damageInfo->HitInfo = HITINFO_NORMALSWING2;
1212 break;
1213 case OFF_ATTACK:
1214 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_HIT | PROC_FLAG_SUCCESSFUL_OFFHAND_HIT;
1215 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;//|PROC_FLAG_TAKEN_OFFHAND_HIT // not used
1216 damageInfo->HitInfo = HITINFO_LEFTSWING;
1217 break;
1218 case RANGED_ATTACK:
1219 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
1220 damageInfo->procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
1221 damageInfo->HitInfo = 0x08;// test
1222 break;
1223 default:
1224 break;
1227 // Physical Immune check
1228 if (damageInfo->target->IsImmunedToDamage(damageInfo->damageSchoolMask))
1230 damageInfo->HitInfo |= HITINFO_NORMALSWING;
1231 damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE;
1233 damageInfo->procEx |=PROC_EX_IMMUNE;
1234 damageInfo->damage = 0;
1235 damageInfo->cleanDamage = 0;
1236 return;
1238 damage += CalculateDamage (damageInfo->attackType, false);
1239 // Add melee damage bonus
1240 damage = MeleeDamageBonus(damageInfo->target, damage, damageInfo->attackType);
1241 // Calculate armor reduction
1243 uint32 armor_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageInfo->damageSchoolMask);
1244 damageInfo->damage = damage - armor_affected_damage + CalcArmorReducedDamage(damageInfo->target, armor_affected_damage);
1245 damageInfo->cleanDamage += damage - damageInfo->damage;
1247 damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType);
1249 // Disable parry or dodge for ranged attack
1250 if (damageInfo->attackType == RANGED_ATTACK)
1252 if (damageInfo->hitOutCome == MELEE_HIT_PARRY) damageInfo->hitOutCome = MELEE_HIT_NORMAL;
1253 if (damageInfo->hitOutCome == MELEE_HIT_DODGE) damageInfo->hitOutCome = MELEE_HIT_MISS;
1256 switch(damageInfo->hitOutCome)
1258 case MELEE_HIT_EVADE:
1260 damageInfo->HitInfo |= HITINFO_MISS|HITINFO_SWINGNOHITSOUND;
1261 damageInfo->TargetState = VICTIMSTATE_EVADES;
1263 damageInfo->procEx|=PROC_EX_EVADE;
1264 damageInfo->damage = 0;
1265 damageInfo->cleanDamage = 0;
1266 return;
1268 case MELEE_HIT_MISS:
1270 damageInfo->HitInfo |= HITINFO_MISS;
1271 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1273 damageInfo->procEx|=PROC_EX_MISS;
1274 damageInfo->damage = 0;
1275 damageInfo->cleanDamage = 0;
1276 break;
1278 case MELEE_HIT_NORMAL:
1279 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1280 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1281 break;
1282 case MELEE_HIT_CRIT:
1284 damageInfo->HitInfo |= HITINFO_CRITICALHIT;
1285 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1287 damageInfo->procEx|=PROC_EX_CRITICAL_HIT;
1288 // Crit bonus calc
1289 damageInfo->damage += damageInfo->damage;
1290 int32 mod=0;
1291 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1292 if(damageInfo->attackType == RANGED_ATTACK)
1293 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1294 else
1295 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1297 mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS, SPELL_SCHOOL_MASK_NORMAL);
1299 uint32 crTypeMask = damageInfo->target->GetCreatureTypeMask();
1301 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1302 mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1303 if (mod!=0)
1304 damageInfo->damage = int32((damageInfo->damage) * float((100.0f + mod)/100.0f));
1306 // Resilience - reduce crit damage
1307 uint32 redunction_affected_damage = CalcNotIgnoreDamageRedunction(damageInfo->damage,damageInfo->damageSchoolMask);
1308 uint32 resilienceReduction;
1309 if (attackType != RANGED_ATTACK)
1310 resilienceReduction = pVictim->GetMeleeCritDamageReduction(redunction_affected_damage);
1311 else
1312 resilienceReduction = pVictim->GetRangedCritDamageReduction(redunction_affected_damage);
1314 damageInfo->damage -= resilienceReduction;
1315 damageInfo->cleanDamage += resilienceReduction;
1316 break;
1318 case MELEE_HIT_PARRY:
1319 damageInfo->TargetState = VICTIMSTATE_PARRY;
1320 damageInfo->procEx |= PROC_EX_PARRY;
1321 damageInfo->cleanDamage += damageInfo->damage;
1322 damageInfo->damage = 0;
1323 break;
1325 case MELEE_HIT_DODGE:
1326 damageInfo->TargetState = VICTIMSTATE_DODGE;
1327 damageInfo->procEx|=PROC_EX_DODGE;
1328 damageInfo->cleanDamage += damageInfo->damage;
1329 damageInfo->damage = 0;
1330 break;
1331 case MELEE_HIT_BLOCK:
1333 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1334 damageInfo->HitInfo |= HITINFO_BLOCK;
1335 damageInfo->procEx |= PROC_EX_BLOCK;
1336 damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue();
1337 if (damageInfo->blocked_amount >= damageInfo->damage)
1339 damageInfo->TargetState = VICTIMSTATE_BLOCKS;
1340 damageInfo->blocked_amount = damageInfo->damage;
1341 damageInfo->procEx |= PROC_EX_FULL_BLOCK;
1343 damageInfo->damage -= damageInfo->blocked_amount;
1344 damageInfo->cleanDamage += damageInfo->blocked_amount;
1345 break;
1347 case MELEE_HIT_GLANCING:
1349 damageInfo->HitInfo |= HITINFO_GLANCING;
1350 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1351 damageInfo->procEx |= PROC_EX_NORMAL_HIT;
1352 float reducePercent = 1.0f; //damage factor
1353 // calculate base values and mods
1354 float baseLowEnd = 1.3f;
1355 float baseHighEnd = 1.2f;
1356 switch(getClass()) // lowering base values for casters
1358 case CLASS_SHAMAN:
1359 case CLASS_PRIEST:
1360 case CLASS_MAGE:
1361 case CLASS_WARLOCK:
1362 case CLASS_DRUID:
1363 baseLowEnd -= 0.7f;
1364 baseHighEnd -= 0.3f;
1365 break;
1368 float maxLowEnd = 0.6f;
1369 switch(getClass()) // upper for melee classes
1371 case CLASS_WARRIOR:
1372 case CLASS_ROGUE:
1373 maxLowEnd = 0.91f; //If the attacker is a melee class then instead the lower value of 0.91
1376 // calculate values
1377 int32 diff = damageInfo->target->GetDefenseSkillValue() - GetWeaponSkillValue(damageInfo->attackType);
1378 float lowEnd = baseLowEnd - ( 0.05f * diff );
1379 float highEnd = baseHighEnd - ( 0.03f * diff );
1381 // apply max/min bounds
1382 if ( lowEnd < 0.01f ) //the low end must not go bellow 0.01f
1383 lowEnd = 0.01f;
1384 else if ( lowEnd > maxLowEnd ) //the smaller value of this and 0.6 is kept as the low end
1385 lowEnd = maxLowEnd;
1387 if ( highEnd < 0.2f ) //high end limits
1388 highEnd = 0.2f;
1389 if ( highEnd > 0.99f )
1390 highEnd = 0.99f;
1392 if(lowEnd > highEnd) // prevent negative range size
1393 lowEnd = highEnd;
1395 reducePercent = lowEnd + rand_norm() * ( highEnd - lowEnd );
1397 damageInfo->cleanDamage += damageInfo->damage-uint32(reducePercent * damageInfo->damage);
1398 damageInfo->damage = uint32(reducePercent * damageInfo->damage);
1399 break;
1401 case MELEE_HIT_CRUSHING:
1403 damageInfo->HitInfo |= HITINFO_CRUSHING;
1404 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1405 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1406 // 150% normal damage
1407 damageInfo->damage += (damageInfo->damage / 2);
1408 break;
1410 default:
1412 break;
1415 // only from players
1416 if (GetTypeId() == TYPEID_PLAYER)
1418 uint32 redunction_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageInfo->damageSchoolMask);
1419 if (attackType != RANGED_ATTACK)
1420 damage -= pVictim->GetMeleeDamageReduction(redunction_affected_damage);
1421 else
1422 damage -= pVictim->GetRangedDamageReduction(redunction_affected_damage);
1425 // Calculate absorb resist
1426 if(int32(damageInfo->damage) > 0)
1428 damageInfo->procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1430 // Calculate absorb & resists
1431 uint32 absorb_affected_damage = CalcNotIgnoreAbsorbDamage(damageInfo->damage,damageInfo->damageSchoolMask);
1432 CalcAbsorbResist(damageInfo->target, damageInfo->damageSchoolMask, DIRECT_DAMAGE, absorb_affected_damage, &damageInfo->absorb, &damageInfo->resist, true);
1433 damageInfo->damage-=damageInfo->absorb + damageInfo->resist;
1434 if (damageInfo->absorb)
1436 damageInfo->HitInfo|=HITINFO_ABSORB;
1437 damageInfo->procEx|=PROC_EX_ABSORB;
1439 if (damageInfo->resist)
1440 damageInfo->HitInfo|=HITINFO_RESIST;
1443 else // Umpossible get negative result but....
1444 damageInfo->damage = 0;
1447 void Unit::DealMeleeDamage(CalcDamageInfo *damageInfo, bool durabilityLoss)
1449 if (damageInfo==0) return;
1450 Unit *pVictim = damageInfo->target;
1452 if(!this || !pVictim)
1453 return;
1455 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1456 return;
1458 //You don't lose health from damage taken from another player while in a sanctuary
1459 //You still see it in the combat log though
1460 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1462 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1463 if(area && area->flags & AREA_FLAG_SANCTUARY) // sanctuary
1464 return;
1467 // Hmmmm dont like this emotes client must by self do all animations
1468 if (damageInfo->HitInfo&HITINFO_CRITICALHIT)
1469 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_WOUNDCRITICAL);
1470 if(damageInfo->blocked_amount && damageInfo->TargetState!=VICTIMSTATE_BLOCKS)
1471 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_PARRYSHIELD);
1473 if(damageInfo->TargetState == VICTIMSTATE_PARRY)
1475 // Get attack timers
1476 float offtime = float(pVictim->getAttackTimer(OFF_ATTACK));
1477 float basetime = float(pVictim->getAttackTimer(BASE_ATTACK));
1478 // Reduce attack time
1479 if (pVictim->haveOffhandWeapon() && offtime < basetime)
1481 float percent20 = pVictim->GetAttackTime(OFF_ATTACK) * 0.20f;
1482 float percent60 = 3.0f * percent20;
1483 if(offtime > percent20 && offtime <= percent60)
1485 pVictim->setAttackTimer(OFF_ATTACK, uint32(percent20));
1487 else if(offtime > percent60)
1489 offtime -= 2.0f * percent20;
1490 pVictim->setAttackTimer(OFF_ATTACK, uint32(offtime));
1493 else
1495 float percent20 = pVictim->GetAttackTime(BASE_ATTACK) * 0.20;
1496 float percent60 = 3.0f * percent20;
1497 if(basetime > percent20 && basetime <= percent60)
1499 pVictim->setAttackTimer(BASE_ATTACK, uint32(percent20));
1501 else if(basetime > percent60)
1503 basetime -= 2.0f * percent20;
1504 pVictim->setAttackTimer(BASE_ATTACK, uint32(basetime));
1509 // Call default DealDamage
1510 CleanDamage cleanDamage(damageInfo->cleanDamage,damageInfo->attackType,damageInfo->hitOutCome);
1511 DealDamage(pVictim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, damageInfo->damageSchoolMask, NULL, durabilityLoss);
1513 // If this is a creature and it attacks from behind it has a probability to daze it's victim
1514 if( (damageInfo->hitOutCome==MELEE_HIT_CRIT || damageInfo->hitOutCome==MELEE_HIT_CRUSHING || damageInfo->hitOutCome==MELEE_HIT_NORMAL || damageInfo->hitOutCome==MELEE_HIT_GLANCING) &&
1515 GetTypeId() != TYPEID_PLAYER && !((Creature*)this)->GetCharmerOrOwnerGUID() && !pVictim->HasInArc(M_PI, this) )
1517 // -probability is between 0% and 40%
1518 // 20% base chance
1519 float Probability = 20.0f;
1521 //there is a newbie protection, at level 10 just 7% base chance; assuming linear function
1522 if( pVictim->getLevel() < 30 )
1523 Probability = 0.65f*pVictim->getLevel()+0.5f;
1525 uint32 VictimDefense=pVictim->GetDefenseSkillValue();
1526 uint32 AttackerMeleeSkill=GetUnitMeleeSkill();
1528 Probability *= AttackerMeleeSkill/(float)VictimDefense;
1530 if(Probability > 40.0f)
1531 Probability = 40.0f;
1533 if(roll_chance_f(Probability))
1534 CastSpell(pVictim, 1604, true);
1537 // If not miss
1538 if (!(damageInfo->HitInfo & HITINFO_MISS))
1540 // on weapon hit casts
1541 if(GetTypeId() == TYPEID_PLAYER && pVictim->isAlive())
1542 ((Player*)this)->CastItemCombatSpell(pVictim, damageInfo->attackType);
1544 // victim's damage shield
1545 std::set<Aura*> alreadyDone;
1546 AuraList const& vDamageShields = pVictim->GetAurasByType(SPELL_AURA_DAMAGE_SHIELD);
1547 for(AuraList::const_iterator i = vDamageShields.begin(); i != vDamageShields.end();)
1549 if (alreadyDone.find(*i) == alreadyDone.end())
1551 alreadyDone.insert(*i);
1552 uint32 damage=(*i)->GetModifier()->m_amount;
1553 SpellEntry const *i_spellProto = (*i)->GetSpellProto();
1554 //Calculate absorb resist ??? no data in opcode for this possibly unable to absorb or resist?
1555 //uint32 absorb;
1556 //uint32 resist;
1557 //CalcAbsorbResist(pVictim, SpellSchools(spellProto->School), SPELL_DIRECT_DAMAGE, damage, &absorb, &resist);
1558 //damage-=absorb + resist;
1560 pVictim->DealDamageMods(this,damage,NULL);
1562 WorldPacket data(SMSG_SPELLDAMAGESHIELD,(8+8+4+4+4+4));
1563 data << uint64(pVictim->GetGUID());
1564 data << uint64(GetGUID());
1565 data << uint32(i_spellProto->Id);
1566 data << uint32(damage); // Damage
1567 data << uint32(0); // Overkill
1568 data << uint32(i_spellProto->SchoolMask);
1569 pVictim->SendMessageToSet(&data, true );
1571 pVictim->DealDamage(this, damage, 0, SPELL_DIRECT_DAMAGE, GetSpellSchoolMask(i_spellProto), i_spellProto, true);
1573 i = vDamageShields.begin();
1575 else
1576 ++i;
1582 void Unit::HandleEmoteCommand(uint32 anim_id)
1584 WorldPacket data( SMSG_EMOTE, 4 + 8 );
1585 data << uint32(anim_id);
1586 data << uint64(GetGUID());
1587 SendMessageToSet(&data, true);
1590 uint32 Unit::CalcNotIgnoreAbsorbDamage( uint32 damage, SpellSchoolMask damageSchoolMask, SpellEntry const* spellInfo /*= NULL*/)
1592 float absorb_affected_rate = 1.0f;
1593 Unit::AuraList const& ignoreAbsorbSchool = GetAurasByType(SPELL_AURA_MOD_IGNORE_ABSORB_SCHOOL);
1594 for(Unit::AuraList::const_iterator i = ignoreAbsorbSchool.begin(); i != ignoreAbsorbSchool.end(); ++i)
1595 if ((*i)->GetMiscValue() & damageSchoolMask)
1596 absorb_affected_rate *= (100.0f - (*i)->GetModifier()->m_amount)/100.0f;
1598 if(spellInfo)
1600 Unit::AuraList const& ignoreAbsorbForSpell = GetAurasByType(SPELL_AURA_MOD_IGNORE_ABSORB_FOR_SPELL);
1601 for(Unit::AuraList::const_iterator citr = ignoreAbsorbForSpell.begin(); citr != ignoreAbsorbForSpell.end(); ++citr)
1602 if ((*citr)->isAffectedOnSpell(spellInfo))
1603 absorb_affected_rate *= (100.0f - (*citr)->GetModifier()->m_amount)/100.0f;
1606 return absorb_affected_rate <= 0.0f ? 0 : (absorb_affected_rate < 1.0f ? uint32(damage * absorb_affected_rate) : damage);
1609 uint32 Unit::CalcNotIgnoreDamageRedunction( uint32 damage, SpellSchoolMask damageSchoolMask)
1611 float absorb_affected_rate = 1.0f;
1612 Unit::AuraList const& ignoreAbsorb = GetAurasByType(SPELL_AURA_MOD_IGNORE_DAMAGE_REDUCTION_SCHOOL);
1613 for(Unit::AuraList::const_iterator i = ignoreAbsorb.begin(); i != ignoreAbsorb.end(); ++i)
1614 if ((*i)->GetMiscValue() & damageSchoolMask)
1615 absorb_affected_rate *= (100.0f - (*i)->GetModifier()->m_amount)/100.0f;
1617 return absorb_affected_rate <= 0.0f ? 0 : (absorb_affected_rate < 1.0f ? uint32(damage * absorb_affected_rate) : damage);
1620 uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage)
1622 uint32 newdamage = 0;
1623 float armor = pVictim->GetArmor();
1625 // Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura
1626 armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL);
1628 // Apply Player CR_ARMOR_PENETRATION rating and percent talents
1629 if (GetTypeId()==TYPEID_PLAYER)
1630 armor *= 1.0f - ((Player*)this)->GetArmorPenetrationPct() / 100.0f;
1632 if (armor < 0.0f)
1633 armor = 0.0f;
1635 float levelModifier = getLevel();
1636 if (levelModifier > 59)
1637 levelModifier = levelModifier + (4.5f * (levelModifier-59));
1639 float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40);
1640 tmpvalue = tmpvalue/(1.0f + tmpvalue);
1642 if (tmpvalue < 0.0f)
1643 tmpvalue = 0.0f;
1644 if (tmpvalue > 0.75f)
1645 tmpvalue = 0.75f;
1647 newdamage = uint32(damage - (damage * tmpvalue));
1649 return (newdamage > 1) ? newdamage : 1;
1652 void Unit::CalcAbsorbResist(Unit *pVictim,SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist, bool canReflect)
1654 if(!pVictim || !pVictim->isAlive() || !damage)
1655 return;
1657 // Magic damage, check for resists
1658 if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL)==0)
1660 // Get base victim resistance for school
1661 float tmpvalue2 = (float)pVictim->GetResistance(GetFirstSchoolInMask(schoolMask));
1662 // Ignore resistance by self SPELL_AURA_MOD_TARGET_RESISTANCE aura
1663 tmpvalue2 += (float)GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask);
1665 tmpvalue2 *= (float)(0.15f / getLevel());
1666 if (tmpvalue2 < 0.0f)
1667 tmpvalue2 = 0.0f;
1668 if (tmpvalue2 > 0.75f)
1669 tmpvalue2 = 0.75f;
1670 uint32 ran = urand(0, 100);
1671 uint32 faq[4] = {24,6,4,6};
1672 uint8 m = 0;
1673 float Binom = 0.0f;
1674 for (uint8 i = 0; i < 4; ++i)
1676 Binom += 2400 *( powf(tmpvalue2, i) * powf( (1-tmpvalue2), (4-i)))/faq[i];
1677 if (ran > Binom )
1678 ++m;
1679 else
1680 break;
1682 if (damagetype == DOT && m == 4)
1683 *resist += uint32(damage - 1);
1684 else
1685 *resist += uint32(damage * m / 4);
1686 if(*resist > damage)
1687 *resist = damage;
1689 else
1690 *resist = 0;
1692 int32 RemainingDamage = damage - *resist;
1694 // Get unit state (need for some absorb check)
1695 uint32 unitflag = pVictim->GetUInt32Value(UNIT_FIELD_FLAGS);
1696 // Reflect damage spells (not cast any damage spell in aura lookup)
1697 uint32 reflectSpell = 0;
1698 int32 reflectDamage = 0;
1699 Aura* reflectTriggeredBy = NULL; // expected as not expired at reflect as in current cases
1700 // Death Prevention Aura
1701 SpellEntry const* preventDeathSpell = NULL;
1702 int32 preventDeathAmount = 0;
1704 // full absorb cases (by chance)
1705 AuraList const& vAbsorb = pVictim->GetAurasByType(SPELL_AURA_SCHOOL_ABSORB);
1706 for(AuraList::const_iterator i = vAbsorb.begin(); i != vAbsorb.end() && RemainingDamage > 0; ++i)
1708 // only work with proper school mask damage
1709 Modifier* i_mod = (*i)->GetModifier();
1710 if (!(i_mod->m_miscvalue & schoolMask))
1711 continue;
1713 SpellEntry const* i_spellProto = (*i)->GetSpellProto();
1714 // Fire Ward or Frost Ward
1715 if(i_spellProto->SpellFamilyName == SPELLFAMILY_MAGE && i_spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000108))
1717 int chance = 0;
1718 Unit::AuraList const& auras = pVictim->GetAurasByType(SPELL_AURA_ADD_PCT_MODIFIER);
1719 for (Unit::AuraList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
1721 SpellEntry const* itr_spellProto = (*itr)->GetSpellProto();
1722 // Frost Warding (chance full absorb)
1723 if (itr_spellProto->SpellFamilyName == SPELLFAMILY_MAGE && itr_spellProto->SpellIconID == 501)
1725 // chance stored in next dummy effect
1726 chance = itr_spellProto->CalculateSimpleValue(1);
1727 break;
1730 if(roll_chance_i(chance))
1732 int32 amount = RemainingDamage;
1733 RemainingDamage = 0;
1734 // Frost Warding (mana regen)
1735 pVictim->CastCustomSpell(pVictim, 57776, &amount, NULL, NULL, true, NULL, *i);
1736 break;
1741 // Need remove expired auras after
1742 bool existExpired = false;
1744 // absorb without mana cost
1745 AuraList const& vSchoolAbsorb = pVictim->GetAurasByType(SPELL_AURA_SCHOOL_ABSORB);
1746 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end() && RemainingDamage > 0; ++i)
1748 Modifier* mod = (*i)->GetModifier();
1749 if (!(mod->m_miscvalue & schoolMask))
1750 continue;
1752 SpellEntry const* spellProto = (*i)->GetSpellProto();
1754 // Max Amount can be absorbed by this aura
1755 int32 currentAbsorb = mod->m_amount;
1757 // Found empty aura (impossible but..)
1758 if (currentAbsorb <=0)
1760 existExpired = true;
1761 continue;
1763 // Handle custom absorb auras
1764 // TODO: try find better way
1765 switch(spellProto->SpellFamilyName)
1767 case SPELLFAMILY_GENERIC:
1769 // Astral Shift
1770 if (spellProto->SpellIconID == 3066)
1772 //reduces all damage taken while stun, fear or silence
1773 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1774 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1775 continue;
1777 // Nerves of Steel
1778 if (spellProto->SpellIconID == 2115)
1780 // while affected by Stun and Fear
1781 if (unitflag&(UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING))
1782 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1783 continue;
1785 // Spell Deflection
1786 if (spellProto->SpellIconID == 3006)
1788 // You have a chance equal to your Parry chance
1789 if (damagetype == DIRECT_DAMAGE && // Only for direct damage
1790 roll_chance_f(pVictim->GetUnitParryChance())) // Roll chance
1791 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1792 continue;
1794 // Reflective Shield (Lady Malande boss)
1795 if (spellProto->Id == 41475 && canReflect)
1797 if(RemainingDamage < currentAbsorb)
1798 reflectDamage = RemainingDamage / 2;
1799 else
1800 reflectDamage = currentAbsorb / 2;
1801 reflectSpell = 33619;
1802 reflectTriggeredBy = *i;
1803 break;
1805 if (spellProto->Id == 39228 || // Argussian Compass
1806 spellProto->Id == 60218) // Essence of Gossamer
1808 // Max absorb stored in 1 dummy effect
1809 if (spellProto->EffectBasePoints[1] < currentAbsorb)
1810 currentAbsorb = spellProto->EffectBasePoints[1];
1811 break;
1813 break;
1815 case SPELLFAMILY_DRUID:
1817 // Primal Tenacity
1818 if (spellProto->SpellIconID == 2253)
1820 //reduces all damage taken while Stunned
1821 if (unitflag & UNIT_FLAG_STUNNED)
1822 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1823 continue;
1825 break;
1827 case SPELLFAMILY_ROGUE:
1829 // Cheat Death (make less prio with Guardian Spirit case)
1830 if (!preventDeathSpell && spellProto->SpellIconID == 2109 &&
1831 pVictim->GetTypeId()==TYPEID_PLAYER && // Only players
1832 !((Player*)pVictim)->HasSpellCooldown(31231) &&
1833 // Only if no cooldown
1834 roll_chance_i((*i)->GetModifier()->m_amount))
1835 // Only if roll
1837 preventDeathSpell = (*i)->GetSpellProto();
1838 continue;
1840 break;
1842 case SPELLFAMILY_PRIEST:
1844 // Guardian Spirit
1845 if (spellProto->SpellIconID == 2873)
1847 preventDeathSpell = (*i)->GetSpellProto();
1848 preventDeathAmount = (*i)->GetModifier()->m_amount;
1849 continue;
1851 // Power Word: Shield
1852 if (spellProto->SpellFamilyFlags & UI64LIT(00000001) && spellProto->Mechanic == MECHANIC_SHIELD)
1854 // Glyph of Power Word: Shield
1855 if (Aura *glyph = pVictim->GetAura(55672,0))
1857 int32 heal = int32(glyph->GetModifier()->m_amount *
1858 (RemainingDamage >= currentAbsorb ? currentAbsorb : RemainingDamage) / 100);
1859 pVictim->CastCustomSpell(pVictim, 56160, &heal, NULL, NULL, true, 0, *i);
1862 // Reflective Shield
1863 if (spellProto->SpellFamilyFlags == 0x1 && canReflect)
1865 if (pVictim == this)
1866 break;
1867 Unit* caster = (*i)->GetCaster();
1868 if (!caster)
1869 break;
1870 AuraList const& vOverRideCS = caster->GetAurasByType(SPELL_AURA_DUMMY);
1871 for(AuraList::const_iterator k = vOverRideCS.begin(); k != vOverRideCS.end(); ++k)
1873 switch((*k)->GetModifier()->m_miscvalue)
1875 case 5065: // Rank 1
1876 case 5064: // Rank 2
1878 if(RemainingDamage >= currentAbsorb)
1879 reflectDamage = (*k)->GetModifier()->m_amount * currentAbsorb/100;
1880 else
1881 reflectDamage = (*k)->GetModifier()->m_amount * RemainingDamage/100;
1882 reflectSpell = 33619;
1883 reflectTriggeredBy = *i;
1884 } break;
1885 default: break;
1888 break;
1890 break;
1892 case SPELLFAMILY_SHAMAN:
1894 // Astral Shift
1895 if (spellProto->SpellIconID == 3066)
1897 //reduces all damage taken while stun, fear or silence
1898 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1899 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1900 continue;
1902 break;
1904 case SPELLFAMILY_DEATHKNIGHT:
1906 // Shadow of Death
1907 if (spellProto->SpellIconID == 1958)
1909 // TODO: absorb only while transform
1910 continue;
1912 // Anti-Magic Shell (on self)
1913 if (spellProto->Id == 48707)
1915 // damage absorbed by Anti-Magic Shell energizes the DK with additional runic power.
1916 // This, if I'm not mistaken, shows that we get back ~2% of the absorbed damage as runic power.
1917 int32 absorbed = RemainingDamage * currentAbsorb / 100;
1918 int32 regen = absorbed * 2 / 10;
1919 pVictim->CastCustomSpell(pVictim, 49088, &regen, NULL, NULL, true, NULL, *i);
1920 RemainingDamage -= absorbed;
1921 continue;
1923 // Anti-Magic Shell (on single party/raid member)
1924 if (spellProto->Id == 50462)
1926 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1927 continue;
1929 // Anti-Magic Zone
1930 if (spellProto->Id == 50461)
1932 Unit* caster = (*i)->GetCaster();
1933 if (!caster)
1934 continue;
1935 int32 absorbed = RemainingDamage * currentAbsorb / 100;
1936 int32 canabsorb = caster->GetHealth();
1937 if (canabsorb < absorbed)
1938 absorbed = canabsorb;
1940 RemainingDamage -= absorbed;
1942 uint32 ab_damage = absorbed;
1943 DealDamageMods(caster,ab_damage,NULL);
1944 DealDamage(caster, ab_damage, NULL, damagetype, schoolMask, 0, false);
1945 continue;
1947 break;
1949 default:
1950 break;
1953 // currentAbsorb - damage can be absorbed by shield
1954 // If need absorb less damage
1955 if (RemainingDamage < currentAbsorb)
1956 currentAbsorb = RemainingDamage;
1958 RemainingDamage -= currentAbsorb;
1960 // Reduce shield amount
1961 mod->m_amount-=currentAbsorb;
1962 if((*i)->DropAuraCharge())
1963 mod->m_amount = 0;
1964 // Need remove it later
1965 if (mod->m_amount<=0)
1966 existExpired = true;
1969 // Remove all expired absorb auras
1970 if (existExpired)
1972 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end();)
1974 if ((*i)->GetModifier()->m_amount<=0)
1976 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1977 i = vSchoolAbsorb.begin();
1979 else
1980 ++i;
1984 // Cast back reflect damage spell
1985 if (canReflect && reflectSpell)
1986 pVictim->CastCustomSpell(this, reflectSpell, &reflectDamage, NULL, NULL, true, NULL, reflectTriggeredBy);
1988 // absorb by mana cost
1989 AuraList const& vManaShield = pVictim->GetAurasByType(SPELL_AURA_MANA_SHIELD);
1990 for(AuraList::const_iterator i = vManaShield.begin(), next; i != vManaShield.end() && RemainingDamage > 0; i = next)
1992 next = i; ++next;
1994 // check damage school mask
1995 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1996 continue;
1998 int32 currentAbsorb;
1999 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
2000 currentAbsorb = (*i)->GetModifier()->m_amount;
2001 else
2002 currentAbsorb = RemainingDamage;
2004 if (float manaMultiplier = (*i)->GetSpellProto()->EffectMultipleValue[(*i)->GetEffIndex()])
2006 if(Player *modOwner = pVictim->GetSpellModOwner())
2007 modOwner->ApplySpellMod((*i)->GetId(), SPELLMOD_MULTIPLE_VALUE, manaMultiplier);
2009 int32 maxAbsorb = int32(pVictim->GetPower(POWER_MANA) / manaMultiplier);
2010 if (currentAbsorb > maxAbsorb)
2011 currentAbsorb = maxAbsorb;
2013 int32 manaReduction = int32(currentAbsorb * manaMultiplier);
2014 pVictim->ApplyPowerMod(POWER_MANA, manaReduction, false);
2017 (*i)->GetModifier()->m_amount -= currentAbsorb;
2018 if((*i)->GetModifier()->m_amount <= 0)
2020 pVictim->RemoveAurasDueToSpell((*i)->GetId());
2021 next = vManaShield.begin();
2024 RemainingDamage -= currentAbsorb;
2027 // effects dependent from full absorb amount
2028 if (int32 full_absorb = damage - RemainingDamage - *resist)
2030 Unit::AuraList const& auras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
2031 for (Unit::AuraList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
2033 SpellEntry const* itr_spellProto = (*itr)->GetSpellProto();
2035 // Incanter's Absorption
2036 if (itr_spellProto->SpellFamilyName == SPELLFAMILY_GENERIC &&
2037 itr_spellProto->SpellIconID == 2941)
2040 int32 amount = int32(full_absorb * (*itr)->GetModifier()->m_amount / 100);
2042 // apply normalized part of already accumulated amount in aura
2043 if (Aura* spdAura = pVictim->GetAura(44413,0))
2044 amount += spdAura->GetModifier()->m_amount * spdAura->GetAuraDuration() / spdAura->GetAuraMaxDuration();
2046 // limit 5 health percents
2047 int32 health_5percent = pVictim->GetMaxHealth()*5/100;
2048 if(amount > health_5percent)
2049 amount = health_5percent;
2051 // Incanter's Absorption (triggered absorb based spell power, will replace existed if any)
2052 pVictim->CastCustomSpell(pVictim, 44413, &amount, NULL, NULL, true);
2053 break;
2058 // only split damage if not damaging yourself
2059 if(pVictim != this)
2061 AuraList const& vSplitDamageFlat = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_FLAT);
2062 for(AuraList::const_iterator i = vSplitDamageFlat.begin(), next; i != vSplitDamageFlat.end() && RemainingDamage >= 0; i = next)
2064 next = i; ++next;
2066 // check damage school mask
2067 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
2068 continue;
2070 // Damage can be splitted only if aura has an alive caster
2071 Unit *caster = (*i)->GetCaster();
2072 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
2073 continue;
2075 int32 currentAbsorb;
2076 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
2077 currentAbsorb = (*i)->GetModifier()->m_amount;
2078 else
2079 currentAbsorb = RemainingDamage;
2081 RemainingDamage -= currentAbsorb;
2084 uint32 splitted = currentAbsorb;
2085 uint32 splitted_absorb = 0;
2086 DealDamageMods(caster,splitted,&splitted_absorb);
2088 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, splitted_absorb, 0, false, 0, false);
2090 CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL);
2091 DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
2094 AuraList const& vSplitDamagePct = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_PCT);
2095 for(AuraList::const_iterator i = vSplitDamagePct.begin(), next; i != vSplitDamagePct.end() && RemainingDamage >= 0; i = next)
2097 next = i; ++next;
2099 // check damage school mask
2100 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
2101 continue;
2103 // Damage can be splitted only if aura has an alive caster
2104 Unit *caster = (*i)->GetCaster();
2105 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
2106 continue;
2108 uint32 splitted = uint32(RemainingDamage * (*i)->GetModifier()->m_amount / 100.0f);
2110 RemainingDamage -= int32(splitted);
2112 uint32 split_absorb = 0;
2113 DealDamageMods(caster,splitted,&split_absorb);
2115 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, split_absorb, 0, false, 0, false);
2117 CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL);
2118 DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
2122 // Apply death prevention spells effects
2123 if (preventDeathSpell && RemainingDamage >= pVictim->GetHealth())
2125 switch(preventDeathSpell->SpellFamilyName)
2127 // Cheat Death
2128 case SPELLFAMILY_ROGUE:
2130 // Cheat Death
2131 if (preventDeathSpell->SpellIconID == 2109)
2133 pVictim->CastSpell(pVictim,31231,true);
2134 ((Player*)pVictim)->AddSpellCooldown(31231,0,time(NULL)+60);
2135 // with health > 10% lost health until health==10%, in other case no losses
2136 uint32 health10 = pVictim->GetMaxHealth()/10;
2137 RemainingDamage = pVictim->GetHealth() > health10 ? pVictim->GetHealth() - health10 : 0;
2139 break;
2141 // Guardian Spirit
2142 case SPELLFAMILY_PRIEST:
2144 // Guardian Spirit
2145 if (preventDeathSpell->SpellIconID == 2873)
2147 int32 healAmount = pVictim->GetMaxHealth() * preventDeathAmount / 100;
2148 pVictim->CastCustomSpell(pVictim, 48153, &healAmount, NULL, NULL, true);
2149 pVictim->RemoveAurasDueToSpell(preventDeathSpell->Id);
2150 RemainingDamage = 0;
2152 break;
2157 *absorb = damage - RemainingDamage - *resist;
2160 void Unit::AttackerStateUpdate (Unit *pVictim, WeaponAttackType attType, bool extra )
2162 if(hasUnitState(UNIT_STAT_CONFUSED | UNIT_STAT_STUNNED | UNIT_STAT_FLEEING | UNIT_STAT_DIED) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) )
2163 return;
2165 if (!pVictim->isAlive())
2166 return;
2168 if(IsNonMeleeSpellCasted(false))
2169 return;
2171 uint32 hitInfo;
2172 if (attType == BASE_ATTACK)
2173 hitInfo = HITINFO_NORMALSWING2;
2174 else if (attType == OFF_ATTACK)
2175 hitInfo = HITINFO_LEFTSWING;
2176 else
2177 return; // ignore ranged case
2179 uint32 extraAttacks = m_extraAttacks;
2181 // melee attack spell casted at main hand attack only
2182 if (attType == BASE_ATTACK && m_currentSpells[CURRENT_MELEE_SPELL])
2184 m_currentSpells[CURRENT_MELEE_SPELL]->cast();
2186 // not recent extra attack only at any non extra attack (melee spell case)
2187 if(!extra && extraAttacks)
2189 while(m_extraAttacks)
2191 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
2192 if(m_extraAttacks > 0)
2193 --m_extraAttacks;
2196 return;
2199 // attack can be redirected to another target
2200 pVictim = SelectMagnetTarget(pVictim);
2202 CalcDamageInfo damageInfo;
2203 CalculateMeleeDamage(pVictim, 0, &damageInfo, attType);
2204 // Send log damage message to client
2205 DealDamageMods(pVictim,damageInfo.damage,&damageInfo.absorb);
2206 SendAttackStateUpdate(&damageInfo);
2207 ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.damage, damageInfo.attackType);
2208 DealMeleeDamage(&damageInfo,true);
2210 if (GetTypeId() == TYPEID_PLAYER)
2211 DEBUG_LOG("AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
2212 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
2213 else
2214 DEBUG_LOG("AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
2215 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
2217 // if damage pVictim call AI reaction
2218 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
2219 ((Creature*)pVictim)->AI()->AttackedBy(this);
2221 // extra attack only at any non extra attack (normal case)
2222 if(!extra && extraAttacks)
2224 while(m_extraAttacks)
2226 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
2227 if(m_extraAttacks > 0)
2228 --m_extraAttacks;
2233 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType) const
2235 // This is only wrapper
2237 // Miss chance based on melee
2238 float miss_chance = MeleeMissChanceCalc(pVictim, attType);
2240 // Critical hit chance
2241 float crit_chance = GetUnitCriticalChance(attType, pVictim);
2243 // stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case)
2244 float dodge_chance = pVictim->GetUnitDodgeChance();
2245 float block_chance = pVictim->GetUnitBlockChance();
2246 float parry_chance = pVictim->GetUnitParryChance();
2248 // Useful if want to specify crit & miss chances for melee, else it could be removed
2249 DEBUG_LOG("MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance,crit_chance,dodge_chance,parry_chance,block_chance);
2251 return RollMeleeOutcomeAgainst(pVictim, attType, int32(crit_chance*100), int32(miss_chance*100), int32(dodge_chance*100),int32(parry_chance*100),int32(block_chance*100));
2254 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst (const Unit *pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const
2256 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2257 return MELEE_HIT_EVADE;
2259 int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(pVictim);
2260 int32 victimMaxSkillValueForLevel = pVictim->GetMaxSkillValueForLevel(this);
2262 int32 attackerWeaponSkill = GetWeaponSkillValue(attType,pVictim);
2263 int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this);
2265 // bonus from skills is 0.04%
2266 int32 skillBonus = 4 * ( attackerWeaponSkill - victimMaxSkillValueForLevel );
2267 int32 sum = 0, tmp = 0;
2268 int32 roll = urand (0, 10000);
2270 DEBUG_LOG ("RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus);
2271 DEBUG_LOG ("RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d",
2272 roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance);
2274 tmp = miss_chance;
2276 if (tmp > 0 && roll < (sum += tmp ))
2278 DEBUG_LOG ("RollMeleeOutcomeAgainst: MISS");
2279 return MELEE_HIT_MISS;
2282 // always crit against a sitting target (except 0 crit chance)
2283 if( pVictim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !pVictim->IsStandState() )
2285 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT (sitting victim)");
2286 return MELEE_HIT_CRIT;
2289 // Dodge chance
2291 // only players can't dodge if attacker is behind
2292 if (pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->HasInArc(M_PI,this))
2294 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind and victim was a player.");
2296 else
2298 // Reduce dodge chance by attacker expertise rating
2299 if (GetTypeId() == TYPEID_PLAYER)
2300 dodge_chance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2301 else
2302 dodge_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
2304 // Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2305 dodge_chance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE);
2307 tmp = dodge_chance;
2308 if ( (tmp > 0) // check if unit _can_ dodge
2309 && ((tmp -= skillBonus) > 0)
2310 && roll < (sum += tmp))
2312 DEBUG_LOG ("RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum-tmp, sum);
2313 return MELEE_HIT_DODGE;
2317 // parry & block chances
2319 // check if attack comes from behind, nobody can parry or block if attacker is behind
2320 if (!pVictim->HasInArc(M_PI,this))
2322 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind.");
2324 else
2326 // Reduce parry chance by attacker expertise rating
2327 if (GetTypeId() == TYPEID_PLAYER)
2328 parry_chance-= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2329 else
2330 parry_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
2332 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY) )
2334 int32 tmp2 = int32(parry_chance);
2335 if ( (tmp2 > 0) // check if unit _can_ parry
2336 && ((tmp2 -= skillBonus) > 0)
2337 && (roll < (sum += tmp2)))
2339 DEBUG_LOG ("RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum-tmp2, sum);
2340 return MELEE_HIT_PARRY;
2344 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) )
2346 tmp = block_chance;
2347 if ( (tmp > 0) // check if unit _can_ block
2348 && ((tmp -= skillBonus) > 0)
2349 && (roll < (sum += tmp)))
2351 DEBUG_LOG ("RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum-tmp, sum);
2352 return MELEE_HIT_BLOCK;
2357 // Critical chance
2358 tmp = crit_chance;
2360 if (tmp > 0 && roll < (sum += tmp))
2362 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum-tmp, sum);
2363 return MELEE_HIT_CRIT;
2366 // 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)
2367 if( attType != RANGED_ATTACK &&
2368 (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet()) &&
2369 pVictim->GetTypeId() != TYPEID_PLAYER && !((Creature*)pVictim)->isPet() &&
2370 getLevel() < pVictim->getLevelForTarget(this) )
2372 // cap possible value (with bonuses > max skill)
2373 int32 skill = attackerWeaponSkill;
2374 int32 maxskill = attackerMaxSkillValueForLevel;
2375 skill = (skill > maxskill) ? maxskill : skill;
2377 tmp = (10 + (victimDefenseSkill - skill)) * 100;
2378 tmp = tmp > 4000 ? 4000 : tmp;
2379 if (roll < (sum += tmp))
2381 DEBUG_LOG ("RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum-4000, sum);
2382 return MELEE_HIT_GLANCING;
2386 // mobs can score crushing blows if they're 4 or more levels above victim
2387 if (getLevelForTarget(pVictim) >= pVictim->getLevelForTarget(this) + 4 &&
2388 // can be from by creature (if can) or from controlled player that considered as creature
2389 (GetTypeId()!=TYPEID_PLAYER && !((Creature*)this)->isPet() &&
2390 !(((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH) ||
2391 GetTypeId()==TYPEID_PLAYER && GetCharmerOrOwnerGUID()))
2393 // when their weapon skill is 15 or more above victim's defense skill
2394 tmp = victimDefenseSkill;
2395 int32 tmpmax = victimMaxSkillValueForLevel;
2396 // having defense above your maximum (from items, talents etc.) has no effect
2397 tmp = tmp > tmpmax ? tmpmax : tmp;
2398 // tmp = mob's level * 5 - player's current defense skill
2399 tmp = attackerMaxSkillValueForLevel - tmp;
2400 if(tmp >= 15)
2402 // add 2% chance per lacking skill point, min. is 15%
2403 tmp = tmp * 200 - 1500;
2404 if (roll < (sum += tmp))
2406 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum-tmp, sum);
2407 return MELEE_HIT_CRUSHING;
2412 DEBUG_LOG ("RollMeleeOutcomeAgainst: NORMAL");
2413 return MELEE_HIT_NORMAL;
2416 uint32 Unit::CalculateDamage (WeaponAttackType attType, bool normalized)
2418 float min_damage, max_damage;
2420 if (normalized && GetTypeId()==TYPEID_PLAYER)
2421 ((Player*)this)->CalculateMinMaxDamage(attType,normalized,min_damage, max_damage);
2422 else
2424 switch (attType)
2426 case RANGED_ATTACK:
2427 min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE);
2428 max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE);
2429 break;
2430 case BASE_ATTACK:
2431 min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE);
2432 max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE);
2433 break;
2434 case OFF_ATTACK:
2435 min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE);
2436 max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE);
2437 break;
2438 // Just for good manner
2439 default:
2440 min_damage = 0.0f;
2441 max_damage = 0.0f;
2442 break;
2446 if (min_damage > max_damage)
2448 std::swap(min_damage,max_damage);
2451 if(max_damage == 0.0f)
2452 max_damage = 5.0f;
2454 return urand((uint32)min_damage, (uint32)max_damage);
2457 float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const
2459 if(spellProto->spellLevel <= 0)
2460 return 1.0f;
2462 float LvlPenalty = 0.0f;
2464 if(spellProto->spellLevel < 20)
2465 LvlPenalty = 20.0f - spellProto->spellLevel * 3.75f;
2466 float LvlFactor = (float(spellProto->spellLevel) + 6.0f) / float(getLevel());
2467 if(LvlFactor > 1.0f)
2468 LvlFactor = 1.0f;
2470 return (100.0f - LvlPenalty) * LvlFactor / 100.0f;
2473 void Unit::SendMeleeAttackStart(Unit* pVictim)
2475 WorldPacket data( SMSG_ATTACKSTART, 8 + 8 );
2476 data << uint64(GetGUID());
2477 data << uint64(pVictim->GetGUID());
2479 SendMessageToSet(&data, true);
2480 DEBUG_LOG( "WORLD: Sent SMSG_ATTACKSTART" );
2483 void Unit::SendMeleeAttackStop(Unit* victim)
2485 if(!victim)
2486 return;
2488 WorldPacket data( SMSG_ATTACKSTOP, (4+16) ); // we guess size
2489 data.append(GetPackGUID());
2490 data.append(victim->GetPackGUID()); // can be 0x00...
2491 data << uint32(0); // can be 0x1
2492 SendMessageToSet(&data, true);
2493 sLog.outDetail("%s %u stopped attacking %s %u", (GetTypeId()==TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), (victim->GetTypeId()==TYPEID_PLAYER ? "player" : "creature"),victim->GetGUIDLow());
2495 /*if(victim->GetTypeId() == TYPEID_UNIT)
2496 ((Creature*)victim)->AI().EnterEvadeMode(this);*/
2499 bool Unit::isSpellBlocked(Unit *pVictim, SpellEntry const * /*spellProto*/, WeaponAttackType attackType)
2501 if (pVictim->HasInArc(M_PI,this))
2503 /* Currently not exist spells with ignore block
2504 // Ignore combat result aura (parry/dodge check on prepare)
2505 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2506 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2508 if (!(*i)->isAffectedOnSpell(spellProto))
2509 continue;
2510 if ((*i)->GetModifier()->m_miscvalue == )
2511 return false;
2515 // Check creatures flags_extra for disable block
2516 if(pVictim->GetTypeId()==TYPEID_UNIT &&
2517 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK )
2518 return false;
2520 float blockChance = pVictim->GetUnitBlockChance();
2521 blockChance += (int32(GetWeaponSkillValue(attackType)) - int32(pVictim->GetMaxSkillValueForLevel()))*0.04f;
2522 if (roll_chance_f(blockChance))
2523 return true;
2525 return false;
2528 // Melee based spells can be miss, parry or dodge on this step
2529 // Crit or block - determined on damage calculation phase! (and can be both in some time)
2530 float Unit::MeleeSpellMissChance(Unit *pVictim, WeaponAttackType attType, int32 skillDiff, SpellEntry const *spell)
2532 // Calculate hit chance (more correct for chance mod)
2533 int32 HitChance;
2535 // PvP - PvE melee chances
2536 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2537 int32 leveldif = pVictim->getLevelForTarget(this) - getLevelForTarget(pVictim);
2538 if(leveldif < 3)
2539 HitChance = 95 - leveldif;
2540 else
2541 HitChance = 93 - (leveldif - 2) * lchance;
2543 // Hit chance depends from victim auras
2544 if(attType == RANGED_ATTACK)
2545 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2546 else
2547 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2549 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2550 if(Player *modOwner = GetSpellModOwner())
2551 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, HitChance);
2553 // Miss = 100 - hit
2554 float miss_chance= 100.0f - HitChance;
2556 // Bonuses from attacker aura and ratings
2557 if (attType == RANGED_ATTACK)
2558 miss_chance -= m_modRangedHitChance;
2559 else
2560 miss_chance -= m_modMeleeHitChance;
2562 // bonus from skills is 0.04%
2563 miss_chance -= skillDiff * 0.04f;
2565 // Limit miss chance from 0 to 60%
2566 if (miss_chance < 0.0f)
2567 return 0.0f;
2568 if (miss_chance > 60.0f)
2569 return 60.0f;
2570 return miss_chance;
2573 // Melee based spells hit result calculations
2574 SpellMissInfo Unit::MeleeSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2576 WeaponAttackType attType = BASE_ATTACK;
2578 if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED)
2579 attType = RANGED_ATTACK;
2581 // bonus from skills is 0.04% per skill Diff
2582 int32 attackerWeaponSkill = int32(GetWeaponSkillValue(attType,pVictim));
2583 int32 skillDiff = attackerWeaponSkill - int32(pVictim->GetMaxSkillValueForLevel(this));
2584 int32 fullSkillDiff = attackerWeaponSkill - int32(pVictim->GetDefenseSkillValue(this));
2586 uint32 roll = urand (0, 10000);
2588 uint32 missChance = uint32(MeleeSpellMissChance(pVictim, attType, fullSkillDiff, spell)*100.0f);
2589 // Roll miss
2590 uint32 tmp = missChance;
2591 if (roll < tmp)
2592 return SPELL_MISS_MISS;
2594 // Chance resist mechanic (select max value from every mechanic spell effect)
2595 int32 resist_mech = 0;
2596 // Get effects mechanic and chance
2597 for(int eff = 0; eff < 3; ++eff)
2599 int32 effect_mech = GetEffectMechanic(spell, eff);
2600 if (effect_mech)
2602 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2603 if (resist_mech < temp*100)
2604 resist_mech = temp*100;
2607 // Roll chance
2608 tmp += resist_mech;
2609 if (roll < tmp)
2610 return SPELL_MISS_RESIST;
2612 bool canDodge = true;
2613 bool canParry = true;
2615 // Same spells cannot be parry/dodge
2616 if (spell->Attributes & SPELL_ATTR_IMPOSSIBLE_DODGE_PARRY_BLOCK)
2617 return SPELL_MISS_NONE;
2619 // Ranged attack cannot be parry/dodge only deflect
2620 if (attType == RANGED_ATTACK)
2622 // only if in front
2623 if (pVictim->HasInArc(M_PI,this))
2625 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2626 tmp+=deflect_chance;
2627 if (roll < tmp)
2628 return SPELL_MISS_DEFLECT;
2630 return SPELL_MISS_NONE;
2633 // Check for attack from behind
2634 if (!pVictim->HasInArc(M_PI,this))
2636 // Can`t dodge from behind in PvP (but its possible in PvE)
2637 if (GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
2638 canDodge = false;
2639 // Can`t parry
2640 canParry = false;
2642 // Check creatures flags_extra for disable parry
2643 if(pVictim->GetTypeId()==TYPEID_UNIT)
2645 uint32 flagEx = ((Creature*)pVictim)->GetCreatureInfo()->flags_extra;
2646 if( flagEx & CREATURE_FLAG_EXTRA_NO_PARRY )
2647 canParry = false;
2649 // Ignore combat result aura
2650 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2651 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2653 if (!(*i)->isAffectedOnSpell(spell))
2654 continue;
2655 switch((*i)->GetModifier()->m_miscvalue)
2657 case MELEE_HIT_DODGE: canDodge = false; break;
2658 case MELEE_HIT_BLOCK: break; // Block check in hit step
2659 case MELEE_HIT_PARRY: canParry = false; break;
2660 default:
2661 DEBUG_LOG("Spell %u SPELL_AURA_IGNORE_COMBAT_RESULT have unhandled state %d", (*i)->GetId(), (*i)->GetModifier()->m_miscvalue);
2662 break;
2666 if (canDodge)
2668 // Roll dodge
2669 int32 dodgeChance = int32(pVictim->GetUnitDodgeChance()*100.0f) - skillDiff * 4;
2670 // Reduce enemy dodge chance by SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2671 dodgeChance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE)*100;
2672 // Reduce dodge chance by attacker expertise rating
2673 if (GetTypeId() == TYPEID_PLAYER)
2674 dodgeChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2675 else
2676 dodgeChance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
2677 if (dodgeChance < 0)
2678 dodgeChance = 0;
2680 tmp += dodgeChance;
2681 if (roll < tmp)
2682 return SPELL_MISS_DODGE;
2685 if (canParry)
2687 // Roll parry
2688 int32 parryChance = int32(pVictim->GetUnitParryChance()*100.0f) - skillDiff * 4;
2689 // Reduce parry chance by attacker expertise rating
2690 if (GetTypeId() == TYPEID_PLAYER)
2691 parryChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2692 else
2693 parryChance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
2694 if (parryChance < 0)
2695 parryChance = 0;
2697 tmp += parryChance;
2698 if (roll < tmp)
2699 return SPELL_MISS_PARRY;
2702 return SPELL_MISS_NONE;
2705 // TODO need use unit spell resistances in calculations
2706 SpellMissInfo Unit::MagicSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2708 // Can`t miss on dead target (on skinning for example)
2709 if (!pVictim->isAlive())
2710 return SPELL_MISS_NONE;
2712 SpellSchoolMask schoolMask = GetSpellSchoolMask(spell);
2713 // PvP - PvE spell misschances per leveldif > 2
2714 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 7 : 11;
2715 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2717 // Base hit chance from attacker and victim levels
2718 int32 modHitChance;
2719 if(leveldif < 3)
2720 modHitChance = 96 - leveldif;
2721 else
2722 modHitChance = 94 - (leveldif - 2) * lchance;
2724 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2725 if(Player *modOwner = GetSpellModOwner())
2726 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance);
2727 // Increase from attacker SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT auras
2728 modHitChance+=GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT, schoolMask);
2729 // Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras
2730 modHitChance+= pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask);
2731 // Reduce spell hit chance for Area of effect spells from victim SPELL_AURA_MOD_AOE_AVOIDANCE aura
2732 if (IsAreaOfEffectSpell(spell))
2733 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE);
2734 // Reduce spell hit chance for dispel mechanic spells from victim SPELL_AURA_MOD_DISPEL_RESIST
2735 if (IsDispelSpell(spell))
2736 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_DISPEL_RESIST);
2737 // Chance resist mechanic (select max value from every mechanic spell effect)
2738 int32 resist_mech = 0;
2739 // Get effects mechanic and chance
2740 for(int eff = 0; eff < 3; ++eff)
2742 int32 effect_mech = GetEffectMechanic(spell, eff);
2743 if (effect_mech)
2745 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2746 if (resist_mech < temp)
2747 resist_mech = temp;
2750 // Apply mod
2751 modHitChance-=resist_mech;
2753 // Chance resist debuff
2754 modHitChance-=pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel));
2756 int32 HitChance = modHitChance * 100;
2757 // Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings
2758 HitChance += int32(m_modSpellHitChance*100.0f);
2760 // Decrease hit chance from victim rating bonus
2761 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2762 HitChance -= int32(((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_SPELL)*100.0f);
2764 if (HitChance < 100) HitChance = 100;
2765 if (HitChance > 10000) HitChance = 10000;
2767 int32 tmp = 10000 - HitChance;
2769 uint32 rand = urand(0,10000);
2771 if (rand < tmp)
2772 return SPELL_MISS_MISS;
2774 // cast by caster in front of victim
2775 if (pVictim->HasInArc(M_PI,this))
2777 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2778 tmp+=deflect_chance;
2779 if (rand < tmp)
2780 return SPELL_MISS_DEFLECT;
2783 return SPELL_MISS_NONE;
2786 // Calculate spell hit result can be:
2787 // Every spell can: Evade/Immune/Reflect/Sucesful hit
2788 // For melee based spells:
2789 // Miss
2790 // Dodge
2791 // Parry
2792 // For spells
2793 // Resist
2794 SpellMissInfo Unit::SpellHitResult(Unit *pVictim, SpellEntry const *spell, bool CanReflect)
2796 // Return evade for units in evade mode
2797 if (pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2798 return SPELL_MISS_EVADE;
2800 // Check for immune
2801 if (pVictim->IsImmunedToSpell(spell))
2802 return SPELL_MISS_IMMUNE;
2804 // All positive spells can`t miss
2805 // TODO: client not show miss log for this spells - so need find info for this in dbc and use it!
2806 if (IsPositiveSpell(spell->Id))
2807 return SPELL_MISS_NONE;
2809 // Check for immune
2810 if (pVictim->IsImmunedToDamage(GetSpellSchoolMask(spell)))
2811 return SPELL_MISS_IMMUNE;
2813 // Try victim reflect spell
2814 if (CanReflect)
2816 int32 reflectchance = pVictim->GetTotalAuraModifier(SPELL_AURA_REFLECT_SPELLS);
2817 Unit::AuraList const& mReflectSpellsSchool = pVictim->GetAurasByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL);
2818 for(Unit::AuraList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i)
2819 if((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spell))
2820 reflectchance += (*i)->GetModifier()->m_amount;
2821 if (reflectchance > 0 && roll_chance_i(reflectchance))
2823 // Start triggers for remove charges if need (trigger only for victim, and mark as active spell)
2824 ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT, PROC_EX_REFLECT, 1, BASE_ATTACK, spell);
2825 return SPELL_MISS_REFLECT;
2829 switch (spell->DmgClass)
2831 case SPELL_DAMAGE_CLASS_RANGED:
2832 case SPELL_DAMAGE_CLASS_MELEE:
2833 return MeleeSpellHitResult(pVictim, spell);
2834 case SPELL_DAMAGE_CLASS_NONE:
2835 case SPELL_DAMAGE_CLASS_MAGIC:
2836 return MagicSpellHitResult(pVictim, spell);
2838 return SPELL_MISS_NONE;
2841 float Unit::MeleeMissChanceCalc(const Unit *pVictim, WeaponAttackType attType) const
2843 if(!pVictim)
2844 return 0.0f;
2846 // Base misschance 5%
2847 float misschance = 5.0f;
2849 // DualWield - Melee spells and physical dmg spells - 5% , white damage 24%
2850 if (haveOffhandWeapon() && attType != RANGED_ATTACK)
2852 bool isNormal = false;
2853 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
2855 if( m_currentSpells[i] && (GetSpellSchoolMask(m_currentSpells[i]->m_spellInfo) & SPELL_SCHOOL_MASK_NORMAL) )
2857 isNormal = true;
2858 break;
2861 if (isNormal || m_currentSpells[CURRENT_MELEE_SPELL])
2862 misschance = 5.0f;
2863 else
2864 misschance = 24.0f;
2867 // PvP : PvE melee misschances per leveldif > 2
2868 int32 chance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2870 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2871 if(leveldif < 0)
2872 leveldif = 0;
2874 // Hit chance from attacker based on ratings and auras
2875 float m_modHitChance;
2876 if (attType == RANGED_ATTACK)
2877 m_modHitChance = m_modRangedHitChance;
2878 else
2879 m_modHitChance = m_modMeleeHitChance;
2881 if(leveldif < 3)
2882 misschance += (leveldif - m_modHitChance);
2883 else
2884 misschance += ((leveldif - 2) * chance - m_modHitChance);
2886 // Hit chance for victim based on ratings
2887 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2889 if (attType == RANGED_ATTACK)
2890 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_RANGED);
2891 else
2892 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_MELEE);
2895 // Modify miss chance by victim auras
2896 if(attType == RANGED_ATTACK)
2897 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2898 else
2899 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2901 // Modify miss chance from skill difference ( bonus from skills is 0.04% )
2902 int32 skillBonus = int32(GetWeaponSkillValue(attType,pVictim)) - int32(pVictim->GetDefenseSkillValue(this));
2903 misschance -= skillBonus * 0.04f;
2905 // Limit miss chance from 0 to 60%
2906 if ( misschance < 0.0f)
2907 return 0.0f;
2908 if ( misschance > 60.0f)
2909 return 60.0f;
2911 return misschance;
2914 uint32 Unit::GetDefenseSkillValue(Unit const* target) const
2916 if(GetTypeId() == TYPEID_PLAYER)
2918 // in PvP use full skill instead current skill value
2919 uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2920 ? ((Player*)this)->GetMaxSkillValue(SKILL_DEFENSE)
2921 : ((Player*)this)->GetSkillValue(SKILL_DEFENSE);
2922 value += uint32(((Player*)this)->GetRatingBonusValue(CR_DEFENSE_SKILL));
2923 return value;
2925 else
2926 return GetUnitMeleeSkill(target);
2929 float Unit::GetUnitDodgeChance() const
2931 if(hasUnitState(UNIT_STAT_STUNNED))
2932 return 0.0f;
2933 if( GetTypeId() == TYPEID_PLAYER )
2934 return GetFloatValue(PLAYER_DODGE_PERCENTAGE);
2935 else
2937 if(((Creature const*)this)->isTotem())
2938 return 0.0f;
2939 else
2941 float dodge = 5.0f;
2942 dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT);
2943 return dodge > 0.0f ? dodge : 0.0f;
2948 float Unit::GetUnitParryChance() const
2950 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2951 return 0.0f;
2953 float chance = 0.0f;
2955 if(GetTypeId() == TYPEID_PLAYER)
2957 Player const* player = (Player const*)this;
2958 if(player->CanParry() )
2960 Item *tmpitem = player->GetWeaponForAttack(BASE_ATTACK,true,true);
2961 if(!tmpitem)
2962 tmpitem = player->GetWeaponForAttack(OFF_ATTACK,true,true);
2964 if(tmpitem)
2965 chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE);
2968 else if(GetTypeId() == TYPEID_UNIT)
2970 if(GetCreatureType() == CREATURE_TYPE_HUMANOID)
2972 chance = 5.0f;
2973 chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT);
2977 return chance > 0.0f ? chance : 0.0f;
2980 float Unit::GetUnitBlockChance() const
2982 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2983 return 0.0f;
2985 if(GetTypeId() == TYPEID_PLAYER)
2987 Player const* player = (Player const*)this;
2988 if(player->CanBlock() )
2990 Item *tmpitem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
2991 if(tmpitem && !tmpitem->IsBroken() && tmpitem->GetProto()->Block)
2992 return GetFloatValue(PLAYER_BLOCK_PERCENTAGE);
2994 // is player but has no block ability or no not broken shield equipped
2995 return 0.0f;
2997 else
2999 if(((Creature const*)this)->isTotem())
3000 return 0.0f;
3001 else
3003 float block = 5.0f;
3004 block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT);
3005 return block > 0.0f ? block : 0.0f;
3010 float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit *pVictim) const
3012 float crit;
3014 if(GetTypeId() == TYPEID_PLAYER)
3016 switch(attackType)
3018 case BASE_ATTACK:
3019 crit = GetFloatValue( PLAYER_CRIT_PERCENTAGE );
3020 break;
3021 case OFF_ATTACK:
3022 crit = GetFloatValue( PLAYER_OFFHAND_CRIT_PERCENTAGE );
3023 break;
3024 case RANGED_ATTACK:
3025 crit = GetFloatValue( PLAYER_RANGED_CRIT_PERCENTAGE );
3026 break;
3027 // Just for good manner
3028 default:
3029 crit = 0.0f;
3030 break;
3033 else
3035 crit = 5.0f;
3036 crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PERCENT);
3039 // flat aura mods
3040 if(attackType == RANGED_ATTACK)
3041 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE);
3042 else
3043 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE);
3045 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
3047 // reduce crit chance from Rating for players
3048 if (attackType != RANGED_ATTACK)
3049 crit -= pVictim->GetMeleeCritChanceReduction();
3050 else
3051 crit -= pVictim->GetRangedCritChanceReduction();
3053 // Apply crit chance from defence skill
3054 crit += (int32(GetMaxSkillValueForLevel(pVictim)) - int32(pVictim->GetDefenseSkillValue(this))) * 0.04f;
3056 if (crit < 0.0f)
3057 crit = 0.0f;
3058 return crit;
3061 uint32 Unit::GetWeaponSkillValue (WeaponAttackType attType, Unit const* target) const
3063 uint32 value = 0;
3064 if(GetTypeId() == TYPEID_PLAYER)
3066 Item* item = ((Player*)this)->GetWeaponForAttack(attType,true,true);
3068 // feral or unarmed skill only for base attack
3069 if(attType != BASE_ATTACK && !item )
3070 return 0;
3072 if(IsInFeralForm())
3073 return GetMaxSkillValueForLevel(); // always maximized SKILL_FERAL_COMBAT in fact
3075 // weapon skill or (unarmed for base attack)
3076 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
3078 // in PvP use full skill instead current skill value
3079 value = (target && target->GetTypeId() == TYPEID_PLAYER)
3080 ? ((Player*)this)->GetMaxSkillValue(skill)
3081 : ((Player*)this)->GetSkillValue(skill);
3082 // Modify value from ratings
3083 value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL));
3084 switch (attType)
3086 case BASE_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_MAINHAND));break;
3087 case OFF_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_OFFHAND));break;
3088 case RANGED_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_RANGED));break;
3091 else
3092 value = GetUnitMeleeSkill(target);
3093 return value;
3096 void Unit::_UpdateSpells( uint32 time )
3098 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
3099 _UpdateAutoRepeatSpell();
3101 // remove finished spells from current pointers
3102 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
3104 if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED)
3106 m_currentSpells[i]->SetReferencedFromCurrent(false);
3107 m_currentSpells[i] = NULL; // remove pointer
3111 // update auras
3112 // m_AurasUpdateIterator can be updated in inderect called code at aura remove to skip next planned to update but removed auras
3113 for (m_AurasUpdateIterator = m_Auras.begin(); m_AurasUpdateIterator != m_Auras.end();)
3115 Aura* i_aura = m_AurasUpdateIterator->second;
3116 ++m_AurasUpdateIterator; // need shift to next for allow update if need into aura update
3117 i_aura->UpdateAura(time);
3120 // remove expired auras
3121 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end();)
3123 if ((*i).second)
3125 if ( !(*i).second->GetAuraDuration() && !((*i).second->IsPermanent() || ((*i).second->IsPassive())) )
3126 RemoveAura(i);
3127 else
3128 ++i;
3130 else
3131 ++i;
3134 if(!m_gameObj.empty())
3136 GameObjectList::iterator ite1, dnext1;
3137 for (ite1 = m_gameObj.begin(); ite1 != m_gameObj.end(); ite1 = dnext1)
3139 dnext1 = ite1;
3140 //(*i)->Update( difftime );
3141 if( !(*ite1)->isSpawned() )
3143 (*ite1)->SetOwnerGUID(0);
3144 (*ite1)->SetRespawnTime(0);
3145 (*ite1)->Delete();
3146 dnext1 = m_gameObj.erase(ite1);
3148 else
3149 ++dnext1;
3154 void Unit::_UpdateAutoRepeatSpell()
3156 //check "realtime" interrupts
3157 if ( (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->isMoving()) || IsNonMeleeSpellCasted(false,false,true) )
3159 // cancel wand shoot
3160 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3161 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3162 m_AutoRepeatFirstCast = true;
3163 return;
3166 //apply delay
3167 if ( m_AutoRepeatFirstCast && getAttackTimer(RANGED_ATTACK) < 500 )
3168 setAttackTimer(RANGED_ATTACK,500);
3169 m_AutoRepeatFirstCast = false;
3171 //castroutine
3172 if (isAttackReady(RANGED_ATTACK))
3174 // Check if able to cast
3175 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->CheckCast(true) != SPELL_CAST_OK)
3177 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3178 return;
3181 // we want to shoot
3182 Spell* spell = new Spell(this, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, true, 0);
3183 spell->prepare(&(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_targets));
3185 // all went good, reset attack
3186 resetAttackTimer(RANGED_ATTACK);
3190 void Unit::SetCurrentCastedSpell( Spell * pSpell )
3192 assert(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells
3194 CurrentSpellTypes CSpellType = pSpell->GetCurrentContainer();
3196 if (pSpell == m_currentSpells[CSpellType]) return; // avoid breaking self
3198 // break same type spell if it is not delayed
3199 InterruptSpell(CSpellType,false);
3201 // special breakage effects:
3202 switch (CSpellType)
3204 case CURRENT_GENERIC_SPELL:
3206 // generic spells always break channeled not delayed spells
3207 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3209 // autorepeat breaking
3210 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3212 // break autorepeat if not Auto Shot
3213 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3214 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3215 m_AutoRepeatFirstCast = true;
3217 } break;
3219 case CURRENT_CHANNELED_SPELL:
3221 // channel spells always break generic non-delayed and any channeled spells
3222 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3223 InterruptSpell(CURRENT_CHANNELED_SPELL);
3225 // it also does break autorepeat if not Auto Shot
3226 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] &&
3227 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT )
3228 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3229 } break;
3231 case CURRENT_AUTOREPEAT_SPELL:
3233 // only Auto Shoot does not break anything
3234 if (pSpell->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3236 // generic autorepeats break generic non-delayed and channeled non-delayed spells
3237 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3238 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3240 // special action: set first cast flag
3241 m_AutoRepeatFirstCast = true;
3242 } break;
3244 default:
3246 // other spell types don't break anything now
3247 } break;
3250 // current spell (if it is still here) may be safely deleted now
3251 if (m_currentSpells[CSpellType])
3252 m_currentSpells[CSpellType]->SetReferencedFromCurrent(false);
3254 // set new current spell
3255 m_currentSpells[CSpellType] = pSpell;
3256 pSpell->SetReferencedFromCurrent(true);
3258 pSpell->m_selfContainer = &(m_currentSpells[pSpell->GetCurrentContainer()]);
3261 void Unit::InterruptSpell(CurrentSpellTypes spellType, bool withDelayed)
3263 assert(spellType < CURRENT_MAX_SPELL);
3265 if (m_currentSpells[spellType] && (withDelayed || m_currentSpells[spellType]->getState() != SPELL_STATE_DELAYED) )
3267 // send autorepeat cancel message for autorepeat spells
3268 if (spellType == CURRENT_AUTOREPEAT_SPELL)
3270 if(GetTypeId() == TYPEID_PLAYER)
3271 ((Player*)this)->SendAutoRepeatCancel(this);
3274 if (m_currentSpells[spellType]->getState() != SPELL_STATE_FINISHED)
3275 m_currentSpells[spellType]->cancel();
3277 // cancel can interrupt spell already (caster cancel ->target aura remove -> caster iterrupt)
3278 if (m_currentSpells[spellType])
3280 m_currentSpells[spellType]->SetReferencedFromCurrent(false);
3281 m_currentSpells[spellType] = NULL;
3286 void Unit::FinishSpell(CurrentSpellTypes spellType, bool ok /*= true*/)
3288 Spell* spell = m_currentSpells[spellType];
3289 if (!spell)
3290 return;
3292 if (spellType == CURRENT_CHANNELED_SPELL)
3293 spell->SendChannelUpdate(0);
3295 spell->finish(ok);
3299 bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat) const
3301 // We don't do loop here to explicitly show that melee spell is excluded.
3302 // Maybe later some special spells will be excluded too.
3304 // generic spells are casted when they are not finished and not delayed
3305 if ( m_currentSpells[CURRENT_GENERIC_SPELL] &&
3306 (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
3307 (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
3308 return(true);
3310 // channeled spells may be delayed, but they are still considered casted
3311 else if ( !skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] &&
3312 (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED) )
3313 return(true);
3315 // autorepeat spells may be finished or delayed, but they are still considered casted
3316 else if ( !skipAutorepeat && m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3317 return(true);
3319 return(false);
3322 void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id)
3324 // generic spells are interrupted if they are not finished or delayed
3325 if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id==spell_id))
3326 InterruptSpell(CURRENT_GENERIC_SPELL,withDelayed);
3328 // autorepeat spells are interrupted if they are not finished or delayed
3329 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id==spell_id))
3330 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,withDelayed);
3332 // channeled spells are interrupted if they are not finished, even if they are delayed
3333 if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id==spell_id))
3334 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
3337 Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const
3339 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
3340 if(m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id==spell_id)
3341 return m_currentSpells[i];
3342 return NULL;
3345 void Unit::SetInFront(Unit const* target)
3347 SetOrientation(GetAngle(target));
3350 void Unit::SetFacingToObject(WorldObject* pObject)
3352 // update orientation at server
3353 SetOrientation(GetAngle(pObject));
3355 // and client
3356 WorldPacket data;
3357 BuildHeartBeatMsg(&data);
3358 SendMessageToSet(&data, false);
3361 bool Unit::isInAccessablePlaceFor(Creature const* c) const
3363 if(IsInWater())
3364 return c->canSwim();
3365 else
3366 return c->canWalk() || c->canFly();
3369 bool Unit::IsInWater() const
3371 return GetBaseMap()->IsInWater(GetPositionX(),GetPositionY(), GetPositionZ());
3374 bool Unit::IsUnderWater() const
3376 return GetBaseMap()->IsUnderWater(GetPositionX(),GetPositionY(),GetPositionZ());
3379 void Unit::DeMorph()
3381 SetDisplayId(GetNativeDisplayId());
3384 int32 Unit::GetTotalAuraModifier(AuraType auratype) const
3386 int32 modifier = 0;
3388 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3389 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3390 modifier += (*i)->GetModifier()->m_amount;
3392 return modifier;
3395 float Unit::GetTotalAuraMultiplier(AuraType auratype) const
3397 float multiplier = 1.0f;
3399 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3400 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3401 multiplier *= (100.0f + (*i)->GetModifier()->m_amount)/100.0f;
3403 return multiplier;
3406 int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype) const
3408 int32 modifier = 0;
3410 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3411 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3412 if ((*i)->GetModifier()->m_amount > modifier)
3413 modifier = (*i)->GetModifier()->m_amount;
3415 return modifier;
3418 int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const
3420 int32 modifier = 0;
3422 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3423 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3424 if ((*i)->GetModifier()->m_amount < modifier)
3425 modifier = (*i)->GetModifier()->m_amount;
3427 return modifier;
3430 int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3432 if(!misc_mask)
3433 return 0;
3435 int32 modifier = 0;
3437 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3438 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3440 Modifier* mod = (*i)->GetModifier();
3441 if (mod->m_miscvalue & misc_mask)
3442 modifier += mod->m_amount;
3444 return modifier;
3447 float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const
3449 if(!misc_mask)
3450 return 1.0f;
3452 float multiplier = 1.0f;
3454 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3455 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3457 Modifier* mod = (*i)->GetModifier();
3458 if (mod->m_miscvalue & misc_mask)
3459 multiplier *= (100.0f + mod->m_amount)/100.0f;
3461 return multiplier;
3464 int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3466 if(!misc_mask)
3467 return 0;
3469 int32 modifier = 0;
3471 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3472 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3474 Modifier* mod = (*i)->GetModifier();
3475 if (mod->m_miscvalue & misc_mask && mod->m_amount > modifier)
3476 modifier = mod->m_amount;
3479 return modifier;
3482 int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3484 if(!misc_mask)
3485 return 0;
3487 int32 modifier = 0;
3489 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3490 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3492 Modifier* mod = (*i)->GetModifier();
3493 if (mod->m_miscvalue & misc_mask && mod->m_amount < modifier)
3494 modifier = mod->m_amount;
3497 return modifier;
3500 int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3502 int32 modifier = 0;
3504 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3505 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3507 Modifier* mod = (*i)->GetModifier();
3508 if (mod->m_miscvalue == misc_value)
3509 modifier += mod->m_amount;
3511 return modifier;
3514 float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const
3516 float multiplier = 1.0f;
3518 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3519 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3521 Modifier* mod = (*i)->GetModifier();
3522 if (mod->m_miscvalue == misc_value)
3523 multiplier *= (100.0f + mod->m_amount)/100.0f;
3525 return multiplier;
3528 int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3530 int32 modifier = 0;
3532 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3533 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3535 Modifier* mod = (*i)->GetModifier();
3536 if (mod->m_miscvalue == misc_value && mod->m_amount > modifier)
3537 modifier = mod->m_amount;
3540 return modifier;
3543 int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3545 int32 modifier = 0;
3547 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3548 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3550 Modifier* mod = (*i)->GetModifier();
3551 if (mod->m_miscvalue == misc_value && mod->m_amount < modifier)
3552 modifier = mod->m_amount;
3555 return modifier;
3558 float Unit::GetTotalAuraMultiplierByMiscValueForMask(AuraType auratype, uint32 mask) const
3560 if(!mask)
3561 return 1.0f;
3563 float multiplier = 1.0f;
3565 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3566 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3568 Modifier* mod = (*i)->GetModifier();
3569 if (mask & (1 << (mod->m_miscvalue -1)))
3570 multiplier *= (100.0f + mod->m_amount)/100.0f;
3572 return multiplier;
3575 bool Unit::AddAura(Aura *Aur)
3577 SpellEntry const* aurSpellInfo = Aur->GetSpellProto();
3579 // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load)
3580 if( !isAlive() && !IsDeathPersistentSpell(aurSpellInfo) &&
3581 !IsDeathOnlySpell(aurSpellInfo) &&
3582 (GetTypeId()!=TYPEID_PLAYER || !((Player*)this)->GetSession()->PlayerLoading()) )
3584 delete Aur;
3585 return false;
3588 if(Aur->GetTarget() != this)
3590 sLog.outError("Aura (spell %u eff %u) add to aura list of %s (lowguid: %u) but Aura target is %s (lowguid: %u)",
3591 Aur->GetId(),Aur->GetEffIndex(),(GetTypeId()==TYPEID_PLAYER?"player":"creature"),GetGUIDLow(),
3592 (Aur->GetTarget()->GetTypeId()==TYPEID_PLAYER?"player":"creature"),Aur->GetTarget()->GetGUIDLow());
3593 delete Aur;
3594 return false;
3597 // m_auraname can be modified to SPELL_AURA_NONE for area auras, this expected for this value
3598 AuraType aurName = Aur->GetModifier()->m_auraname;
3600 spellEffectPair spair = spellEffectPair(Aur->GetId(), Aur->GetEffIndex());
3601 AuraMap::iterator i = m_Auras.find( spair );
3603 // take out same spell
3604 if (i != m_Auras.end())
3606 // passive and persistent auras can stack with themselves any number of times
3607 if (!Aur->IsPassive() && !Aur->IsPersistent())
3609 for(AuraMap::iterator i2 = m_Auras.lower_bound(spair); i2 != m_Auras.upper_bound(spair); ++i2)
3611 Aura* aur2 = i2->second;
3612 if(aur2->GetCasterGUID()==Aur->GetCasterGUID())
3614 // Aura can stack on self -> Stack it;
3615 if(aurSpellInfo->StackAmount)
3617 // can be created with >1 stack by some spell mods
3618 aur2->modStackAmount(Aur->GetStackAmount());
3619 delete Aur;
3620 return false;
3622 // Carry over removed Aura's remaining damage if Aura still has ticks remaining
3623 else if (aur2->GetSpellProto()->AttributesEx4 & SPELL_ATTR_EX4_STACK_DOT_MODIFIER && aurName == SPELL_AURA_PERIODIC_DAMAGE && aur2->GetAuraDuration() > 0)
3625 int32 remainingTicks = aur2->GetAuraMaxTicks() - aur2->GetAuraTicks();
3626 int32 remainingDamage = aur2->GetModifier()->m_amount * remainingTicks;
3628 Aur->GetModifier()->m_amount += int32(remainingDamage / Aur->GetAuraMaxTicks());
3630 // can be only single (this check done at _each_ aura add
3631 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3632 break;
3635 bool stop = false;
3637 // m_auraname can be modified to SPELL_AURA_NONE for area auras, use original
3638 AuraType aurNameReal = AuraType(aurSpellInfo->EffectApplyAuraName[Aur->GetEffIndex()]);
3640 switch(aurNameReal)
3642 // DoT/HoT/etc
3643 case SPELL_AURA_DUMMY: // allow stack
3644 case SPELL_AURA_PERIODIC_DAMAGE:
3645 case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
3646 case SPELL_AURA_PERIODIC_LEECH:
3647 case SPELL_AURA_PERIODIC_HEAL:
3648 case SPELL_AURA_OBS_MOD_HEALTH:
3649 case SPELL_AURA_PERIODIC_MANA_LEECH:
3650 case SPELL_AURA_OBS_MOD_MANA:
3651 case SPELL_AURA_POWER_BURN_MANA:
3652 break;
3653 case SPELL_AURA_PERIODIC_ENERGIZE: // all or self or clear non-stackable
3654 default: // not allow
3655 // can be only single (this check done at _each_ aura add
3656 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3657 stop = true;
3658 break;
3661 if(stop)
3662 break;
3667 // passive auras not stacable with other ranks
3668 if (!IsPassiveSpellStackableWithRanks(aurSpellInfo))
3670 if (!RemoveNoStackAurasDueToAura(Aur))
3672 delete Aur;
3673 return false; // couldn't remove conflicting aura with higher rank
3677 // update single target auras list (before aura add to aura list, to prevent unexpected remove recently added aura)
3678 if (Aur->IsSingleTarget() && Aur->GetTarget())
3680 // caster pointer can be deleted in time aura remove, find it by guid at each iteration
3681 for(;;)
3683 Unit* caster = Aur->GetCaster();
3684 if(!caster) // caster deleted and not required adding scAura
3685 break;
3687 bool restart = false;
3688 AuraList& scAuras = caster->GetSingleCastAuras();
3689 for(AuraList::const_iterator itr = scAuras.begin(); itr != scAuras.end(); ++itr)
3691 if( (*itr)->GetTarget() != Aur->GetTarget() &&
3692 IsSingleTargetSpells((*itr)->GetSpellProto(),aurSpellInfo) )
3694 if ((*itr)->IsInUse())
3696 sLog.outError("Aura (Spell %u Effect %u) is in process but attempt removed at aura (Spell %u Effect %u) adding, need add stack rule for IsSingleTargetSpell", (*itr)->GetId(), (*itr)->GetEffIndex(),Aur->GetId(), Aur->GetEffIndex());
3697 continue;
3699 (*itr)->GetTarget()->RemoveAura((*itr)->GetId(), (*itr)->GetEffIndex());
3700 restart = true;
3701 break;
3705 if(!restart)
3707 // done
3708 scAuras.push_back(Aur);
3709 break;
3714 // add aura, register in lists and arrays
3715 Aur->_AddAura();
3716 m_Auras.insert(AuraMap::value_type(spellEffectPair(Aur->GetId(), Aur->GetEffIndex()), Aur));
3717 if (aurName < TOTAL_AURAS)
3719 m_modAuras[aurName].push_back(Aur);
3722 Aur->ApplyModifier(true,true);
3723 sLog.outDebug("Aura %u now is in use", aurName);
3725 // if aura deleted before boosts apply ignore
3726 // this can be possible it it removed indirectly by triggered spell effect at ApplyModifier
3727 if (Aur->IsDeleted())
3728 return false;
3730 if(IsSpellLastAuraEffect(aurSpellInfo,Aur->GetEffIndex()))
3731 Aur->HandleSpellSpecificBoosts(true);
3733 return true;
3736 void Unit::RemoveRankAurasDueToSpell(uint32 spellId)
3738 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
3739 if(!spellInfo)
3740 return;
3741 AuraMap::const_iterator i,next;
3742 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3744 next = i;
3745 ++next;
3746 uint32 i_spellId = (*i).second->GetId();
3747 if((*i).second && i_spellId && i_spellId != spellId)
3749 if(sSpellMgr.IsRankSpellDueToSpell(spellInfo,i_spellId))
3751 RemoveAurasDueToSpell(i_spellId);
3753 if( m_Auras.empty() )
3754 break;
3755 else
3756 next = m_Auras.begin();
3762 bool Unit::RemoveNoStackAurasDueToAura(Aura *Aur)
3764 if (!Aur)
3765 return false;
3767 SpellEntry const* spellProto = Aur->GetSpellProto();
3768 if (!spellProto)
3769 return false;
3771 uint32 spellId = Aur->GetId();
3772 uint32 effIndex = Aur->GetEffIndex();
3774 // passive spell special case (only non stackable with ranks)
3775 if(IsPassiveSpell(spellId))
3777 if(IsPassiveSpellStackableWithRanks(spellProto))
3778 return true;
3781 SpellSpecific spellId_spec = GetSpellSpecific(spellId);
3783 AuraMap::iterator i,next;
3784 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3786 next = i;
3787 ++next;
3788 if (!(*i).second) continue;
3790 SpellEntry const* i_spellProto = (*i).second->GetSpellProto();
3792 if (!i_spellProto)
3793 continue;
3795 uint32 i_spellId = i_spellProto->Id;
3797 // early checks that spellId is passive non stackable spell
3798 if(IsPassiveSpell(i_spellId))
3800 // passive non-stackable spells not stackable only for same caster
3801 if(Aur->GetCasterGUID()!=i->second->GetCasterGUID())
3802 continue;
3804 // passive non-stackable spells not stackable only with another rank of same spell
3805 if (!sSpellMgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3806 continue;
3809 uint32 i_effIndex = (*i).second->GetEffIndex();
3811 if(i_spellId == spellId) continue;
3813 bool is_triggered_by_spell = false;
3814 // prevent triggering aura of removing aura that triggered it
3815 for(int j = 0; j < 3; ++j)
3816 if (i_spellProto->EffectTriggerSpell[j] == spellId)
3817 is_triggered_by_spell = true;
3819 // prevent triggered aura of removing aura that triggering it (triggered effect early some aura of parent spell
3820 for(int j = 0; j < 3; ++j)
3821 if (spellProto->EffectTriggerSpell[j] == i_spellId)
3822 is_triggered_by_spell = true;
3824 if (is_triggered_by_spell)
3825 continue;
3827 SpellSpecific i_spellId_spec = GetSpellSpecific(i_spellId);
3829 // single allowed spell specific from same caster or from any caster at target
3830 bool is_spellSpecPerTargetPerCaster = IsSingleFromSpellSpecificPerTargetPerCaster(spellId_spec,i_spellId_spec);
3831 bool is_spellSpecPerTarget = IsSingleFromSpellSpecificPerTarget(spellId_spec,i_spellId_spec);
3832 if( is_spellSpecPerTarget || is_spellSpecPerTargetPerCaster && Aur->GetCasterGUID() == (*i).second->GetCasterGUID() )
3834 // cannot remove higher rank
3835 if (sSpellMgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3836 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3837 return false;
3839 // Its a parent aura (create this aura in ApplyModifier)
3840 if ((*i).second->IsInUse())
3842 sLog.outError("Aura (Spell %u Effect %u) is in process but attempt removed at aura (Spell %u Effect %u) adding, need add stack rule for Unit::RemoveNoStackAurasDueToAura", i->second->GetId(), i->second->GetEffIndex(),Aur->GetId(), Aur->GetEffIndex());
3843 continue;
3845 RemoveAurasDueToSpell(i_spellId);
3847 if( m_Auras.empty() )
3848 break;
3849 else
3850 next = m_Auras.begin();
3852 continue;
3855 // spell with spell specific that allow single ranks for spell from diff caster
3856 // same caster case processed or early or later
3857 bool is_spellPerTarget = IsSingleFromSpellSpecificSpellRanksPerTarget(spellId_spec,i_spellId_spec);
3858 if ( is_spellPerTarget && Aur->GetCasterGUID() != (*i).second->GetCasterGUID() && sSpellMgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3860 // cannot remove higher rank
3861 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3862 return false;
3864 // Its a parent aura (create this aura in ApplyModifier)
3865 if ((*i).second->IsInUse())
3867 sLog.outError("Aura (Spell %u Effect %u) is in process but attempt removed at aura (Spell %u Effect %u) adding, need add stack rule for Unit::RemoveNoStackAurasDueToAura", i->second->GetId(), i->second->GetEffIndex(),Aur->GetId(), Aur->GetEffIndex());
3868 continue;
3870 RemoveAurasDueToSpell(i_spellId);
3872 if( m_Auras.empty() )
3873 break;
3874 else
3875 next = m_Auras.begin();
3877 continue;
3880 // non single (per caster) per target spell specific (possible single spell per target at caster)
3881 if( !is_spellSpecPerTargetPerCaster && !is_spellSpecPerTarget && sSpellMgr.IsNoStackSpellDueToSpell(spellId, i_spellId) )
3883 // Its a parent aura (create this aura in ApplyModifier)
3884 if ((*i).second->IsInUse())
3886 sLog.outError("Aura (Spell %u Effect %u) is in process but attempt removed at aura (Spell %u Effect %u) adding, need add stack rule for Unit::RemoveNoStackAurasDueToAura", i->second->GetId(), i->second->GetEffIndex(),Aur->GetId(), Aur->GetEffIndex());
3887 continue;
3889 RemoveAurasDueToSpell(i_spellId);
3891 if( m_Auras.empty() )
3892 break;
3893 else
3894 next = m_Auras.begin();
3896 continue;
3899 // Potions stack aura by aura (elixirs/flask already checked)
3900 if( spellProto->SpellFamilyName == SPELLFAMILY_POTION && i_spellProto->SpellFamilyName == SPELLFAMILY_POTION )
3902 if (IsNoStackAuraDueToAura(spellId, effIndex, i_spellId, i_effIndex))
3904 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3905 return false; // cannot remove higher rank
3907 // Its a parent aura (create this aura in ApplyModifier)
3908 if ((*i).second->IsInUse())
3910 sLog.outError("Aura (Spell %u Effect %u) is in process but attempt removed at aura (Spell %u Effect %u) adding, need add stack rule for Unit::RemoveNoStackAurasDueToAura", i->second->GetId(), i->second->GetEffIndex(),Aur->GetId(), Aur->GetEffIndex());
3911 continue;
3913 RemoveAura(i);
3914 next = i;
3918 return true;
3921 void Unit::RemoveAura(uint32 spellId, uint32 effindex, Aura* except)
3923 spellEffectPair spair = spellEffectPair(spellId, effindex);
3924 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3926 if(iter->second!=except)
3928 RemoveAura(iter);
3929 iter = m_Auras.lower_bound(spair);
3931 else
3932 ++iter;
3936 void Unit::RemoveAurasByCasterSpell(uint32 spellId, uint64 casterGUID)
3938 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3940 Aura *aur = iter->second;
3941 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3942 RemoveAura(iter);
3943 else
3944 ++iter;
3948 void Unit::RemoveAurasByCasterSpell(uint32 spellId, uint32 effindex, uint64 casterGUID)
3950 spellEffectPair spair = spellEffectPair(spellId, effindex);
3951 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3953 Aura *aur = iter->second;
3954 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3956 RemoveAura(iter);
3957 iter = m_Auras.lower_bound(spair);
3959 else
3960 ++iter;
3964 void Unit::RemoveSingleAuraDueToSpellByDispel(uint32 spellId, uint64 casterGUID, Unit *dispeler)
3966 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellId);
3968 // Custom dispel cases
3969 // Unstable Affliction
3970 if(spellEntry->SpellFamilyName == SPELLFAMILY_WARLOCK && (spellEntry->SpellFamilyFlags & UI64LIT(0x010000000000)))
3972 if (Aura* dotAura = GetAura(SPELL_AURA_PERIODIC_DAMAGE,SPELLFAMILY_WARLOCK,UI64LIT(0x010000000000),0x00000000,casterGUID))
3974 int32 damage = dotAura->GetModifier()->m_amount*9;
3976 // Remove spell auras from stack
3977 RemoveSingleSpellAurasByCasterSpell(spellId, casterGUID, AURA_REMOVE_BY_DISPEL);
3979 // backfire damage and silence
3980 dispeler->CastCustomSpell(dispeler, 31117, &damage, NULL, NULL, true, NULL, NULL,casterGUID);
3981 return;
3984 // Flame Shock
3985 else if (spellEntry->SpellFamilyName == SPELLFAMILY_SHAMAN && (spellEntry->SpellFamilyFlags & UI64LIT(0x10000000)))
3987 Unit* caster = NULL;
3988 uint32 triggeredSpell = 0;
3990 if (Aura* dotAura = GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, UI64LIT(0x10000000), 0x00000000, casterGUID))
3991 caster = dotAura->GetCaster();
3993 if (caster && !caster->isDead())
3995 Unit::AuraList const& auras = caster->GetAurasByType(SPELL_AURA_DUMMY);
3996 for (Unit::AuraList::const_iterator i = auras.begin(); i != auras.end(); ++i)
3998 switch((*i)->GetId())
4000 case 51480: triggeredSpell=64694; break;// Lava Flows, Rank 1
4001 case 51481: triggeredSpell=65263; break;// Lava Flows, Rank 2
4002 case 51482: triggeredSpell=65264; break;// Lava Flows, Rank 3
4003 default: continue;
4005 break;
4009 // Remove spell auras from stack
4010 RemoveSingleSpellAurasByCasterSpell(spellId, casterGUID, AURA_REMOVE_BY_DISPEL);
4012 // Haste
4013 if (triggeredSpell)
4014 caster->CastSpell(caster, triggeredSpell, true);
4015 return;
4017 // Vampiric touch (first dummy aura)
4018 else if (spellEntry->SpellFamilyName == SPELLFAMILY_PRIEST && spellEntry->SpellFamilyFlags & UI64LIT(0x0000040000000000))
4020 if (Aura *dot = GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, UI64LIT(0x0000040000000000), 0x00000000, casterGUID))
4022 if(Unit* caster = dot->GetCaster())
4024 int32 bp0 = dot->GetModifier()->m_amount;
4025 bp0 = 8 * caster->SpellDamageBonus(this, spellEntry, bp0, DOT, 1);
4027 // Remove spell auras from stack
4028 RemoveSingleSpellAurasByCasterSpell(spellId, casterGUID, AURA_REMOVE_BY_DISPEL);
4030 CastCustomSpell(this, 64085, &bp0, NULL, NULL, true, NULL, NULL, casterGUID);
4031 return;
4036 RemoveSingleSpellAurasByCasterSpell(spellId, casterGUID, AURA_REMOVE_BY_DISPEL);
4039 void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit *stealer)
4041 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
4043 Aura *aur = iter->second;
4044 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
4046 int32 basePoints = aur->GetBasePoints();
4047 // construct the new aura for the attacker - will never return NULL, it's just a wrapper for
4048 // some different constructors
4049 Aura * new_aur = CreateAura(aur->GetSpellProto(), aur->GetEffIndex(), &basePoints, stealer, this);
4051 // set its duration and maximum duration
4052 // max duration 2 minutes (in msecs)
4053 int32 dur = aur->GetAuraDuration();
4054 int32 max_dur = 2*MINUTE*IN_MILISECONDS;
4055 int32 new_max_dur = max_dur > dur ? dur : max_dur;
4056 new_aur->SetAuraMaxDuration( new_max_dur );
4057 new_aur->SetAuraDuration( new_max_dur );
4059 // set periodic to do at least one tick (for case when original aura has been at last tick preparing)
4060 int32 periodic = aur->GetModifier()->periodictime;
4061 new_aur->GetModifier()->periodictime = periodic < new_max_dur ? periodic : new_max_dur;
4063 // Unregister _before_ adding to stealer
4064 aur->UnregisterSingleCastAura();
4066 // strange but intended behaviour: Stolen single target auras won't be treated as single targeted
4067 new_aur->SetIsSingleTarget(false);
4069 // add the new aura to stealer
4070 stealer->AddAura(new_aur);
4072 // Remove aura as dispel
4073 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
4075 else
4076 ++iter;
4080 void Unit::RemoveAurasDueToSpellByCancel(uint32 spellId)
4082 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
4084 if (iter->second->GetId() == spellId)
4085 RemoveAura(iter, AURA_REMOVE_BY_CANCEL);
4086 else
4087 ++iter;
4091 void Unit::RemoveAurasWithDispelType( DispelType type )
4093 // Create dispel mask by dispel type
4094 uint32 dispelMask = GetDispellMask(type);
4095 // Dispel all existing auras vs current dispel type
4096 AuraMap& auras = GetAuras();
4097 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
4099 SpellEntry const* spell = itr->second->GetSpellProto();
4100 if( (1<<spell->Dispel) & dispelMask )
4102 // Dispel aura
4103 RemoveAurasDueToSpell(spell->Id);
4104 itr = auras.begin();
4106 else
4107 ++itr;
4111 void Unit::RemoveSingleAuraFromStack(AuraMap::iterator &i, AuraRemoveMode mode)
4113 if (i->second->modStackAmount(-1))
4114 RemoveAura(i,mode);
4118 void Unit::RemoveSingleAuraFromStack(uint32 spellId, uint32 effindex, AuraRemoveMode mode)
4120 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
4121 if(iter != m_Auras.end())
4122 RemoveSingleAuraFromStack(iter,mode);
4125 void Unit::RemoveSingleSpellAurasFromStack(uint32 spellId, AuraRemoveMode mode)
4127 for (int i=0; i<3; ++i)
4128 RemoveSingleAuraFromStack(spellId, i, mode);
4131 void Unit::RemoveSingleSpellAurasByCasterSpell(uint32 spellId, uint64 casterGUID, AuraRemoveMode mode)
4133 for (int i=0; i<3; ++i)
4134 RemoveSingleAuraByCasterSpell(spellId, i, casterGUID, mode);
4137 void Unit::RemoveSingleAuraByCasterSpell(uint32 spellId, uint32 effindex, uint64 casterGUID, AuraRemoveMode mode)
4139 spellEffectPair spair = spellEffectPair(spellId, effindex);
4140 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
4142 Aura *aur = iter->second;
4143 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
4145 RemoveSingleAuraFromStack(iter,mode);
4146 break;
4152 void Unit::RemoveAurasDueToSpell(uint32 spellId, Aura* except)
4154 for (int i = 0; i < 3; ++i)
4155 RemoveAura(spellId,i,except);
4158 void Unit::RemoveAurasDueToItemSpell(Item* castItem,uint32 spellId)
4160 for (int k=0; k < 3; ++k)
4162 spellEffectPair spair = spellEffectPair(spellId, k);
4163 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
4165 if (iter->second->GetCastItemGUID() == castItem->GetGUID())
4167 RemoveAura(iter);
4168 iter = m_Auras.upper_bound(spair); // overwrite by more appropriate
4170 else
4171 ++iter;
4176 void Unit::RemoveAurasWithInterruptFlags(uint32 flags)
4178 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
4180 if (iter->second->GetSpellProto()->AuraInterruptFlags & flags)
4181 RemoveAura(iter);
4182 else
4183 ++iter;
4187 void Unit::RemoveNotOwnSingleTargetAuras(uint32 newPhase)
4189 // single target auras from other casters
4190 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
4192 if (iter->second->GetCasterGUID()!=GetGUID() && IsSingleTargetSpell(iter->second->GetSpellProto()))
4194 if(!newPhase)
4195 RemoveAura(iter);
4196 else
4198 Unit* caster = iter->second->GetCaster();
4199 if(!caster || !caster->InSamePhase(newPhase))
4200 RemoveAura(iter);
4201 else
4202 ++iter;
4205 else
4206 ++iter;
4209 // single target auras at other targets
4210 AuraList& scAuras = GetSingleCastAuras();
4211 for (AuraList::iterator iter = scAuras.begin(); iter != scAuras.end(); )
4213 Aura* aura = *iter;
4214 if (aura->GetTarget() != this && !aura->GetTarget()->InSamePhase(newPhase))
4216 scAuras.erase(iter); // explicitly remove, instead waiting remove in RemoveAura
4217 aura->GetTarget()->RemoveAura(aura);
4218 iter = scAuras.begin();
4220 else
4221 ++iter;
4226 void Unit::RemoveAura(Aura* aura, AuraRemoveMode mode /*= AURA_REMOVE_BY_DEFAULT*/)
4228 AuraMap::iterator i = m_Auras.lower_bound(spellEffectPair(aura->GetId(), aura->GetEffIndex()));
4229 AuraMap::iterator upperBound = m_Auras.upper_bound(spellEffectPair(aura->GetId(), aura->GetEffIndex()));
4230 for (; i != upperBound; ++i)
4232 if (i->second == aura)
4234 RemoveAura(i,mode);
4235 return;
4238 sLog.outDebug("Trying to remove aura id %u effect %u by pointer but aura not found on target", aura->GetId(), aura->GetEffIndex());
4241 void Unit::RemoveAura(AuraMap::iterator &i, AuraRemoveMode mode)
4243 Aura* Aur = i->second;
4244 SpellEntry const* AurSpellInfo = Aur->GetSpellProto();
4246 Aur->UnregisterSingleCastAura();
4248 // remove from list before mods removing (prevent cyclic calls, mods added before including to aura list - use reverse order)
4249 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
4251 m_modAuras[Aur->GetModifier()->m_auraname].remove(Aur);
4254 // Set remove mode
4255 Aur->SetRemoveMode(mode);
4257 // if unit currently update aura list then make safe update iterator shift to next
4258 if (m_AurasUpdateIterator == i)
4259 ++m_AurasUpdateIterator;
4261 // some ShapeshiftBoosts at remove trigger removing other auras including parent Shapeshift aura
4262 // remove aura from list before to prevent deleting it before
4263 m_Auras.erase(i);
4265 // now aura removed from from list and can't be deleted by indirect call but can be referenced from callers
4267 // Statue unsummoned at aura remove
4268 Totem* statue = NULL;
4269 if(IsChanneledSpell(AurSpellInfo))
4270 if(Unit* caster = Aur->GetCaster())
4271 if(caster->GetTypeId()==TYPEID_UNIT && ((Creature*)caster)->isTotem() && ((Totem*)caster)->GetTotemType()==TOTEM_STATUE)
4272 statue = ((Totem*)caster);
4274 sLog.outDebug("Aura %u now is remove mode %d",Aur->GetModifier()->m_auraname, mode);
4275 if (mode != AURA_REMOVE_BY_DELETE) // not unapply if target will deleted
4276 Aur->ApplyModifier(false,true);
4278 if (Aur->_RemoveAura())
4280 // last aura in stack removed
4281 if (mode != AURA_REMOVE_BY_DELETE && IsSpellLastAuraEffect(Aur->GetSpellProto(),Aur->GetEffIndex()))
4282 Aur->HandleSpellSpecificBoosts(false);
4285 // If aura in use (removed from code that plan access to it data after return)
4286 // store it in aura list with delayed deletion
4287 if (Aur->IsInUse())
4288 m_deletedAuras.push_back(Aur);
4289 else
4290 delete Aur;
4292 if(statue)
4293 statue->UnSummon();
4295 // only way correctly remove all auras from list
4296 if( m_Auras.empty() )
4297 i = m_Auras.end();
4298 else
4299 i = m_Auras.begin();
4303 void Unit::RemoveAllAuras(AuraRemoveMode mode /*= AURA_REMOVE_BY_DEFAULT*/)
4305 while (!m_Auras.empty())
4307 AuraMap::iterator iter = m_Auras.begin();
4308 RemoveAura(iter,mode);
4312 void Unit::RemoveArenaAuras(bool onleave)
4314 // in join, remove positive buffs, on end, remove negative
4315 // used to remove positive visible auras in arenas
4316 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
4318 if (!(iter->second->GetSpellProto()->AttributesEx4 & SPELL_ATTR_EX4_UNK21) &&
4319 // don't remove stances, shadowform, pally/hunter auras
4320 !iter->second->IsPassive() && // don't remove passive auras
4321 (!(iter->second->GetSpellProto()->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY) ||
4322 !(iter->second->GetSpellProto()->Attributes & SPELL_ATTR_UNK8)) &&
4323 // not unaffected by invulnerability auras or not having that unknown flag (that seemed the most probable)
4324 (iter->second->IsPositive() != onleave)) // remove positive buffs on enter, negative buffs on leave
4325 RemoveAura(iter);
4326 else
4327 ++iter;
4331 void Unit::RemoveAllAurasOnDeath()
4333 // used just after dieing to remove all visible auras
4334 // and disable the mods for the passive ones
4335 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
4337 if (!iter->second->IsPassive() && !iter->second->IsDeathPersistent())
4338 RemoveAura(iter, AURA_REMOVE_BY_DEATH);
4339 else
4340 ++iter;
4344 void Unit::DelayAura(uint32 spellId, uint32 effindex, int32 delaytime)
4346 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
4347 if (iter != m_Auras.end())
4349 if (iter->second->GetAuraDuration() < delaytime)
4350 iter->second->SetAuraDuration(0);
4351 else
4352 iter->second->SetAuraDuration(iter->second->GetAuraDuration() - delaytime);
4353 iter->second->SendAuraUpdate(false);
4354 sLog.outDebug("Aura %u partially interrupted on unit %u, new duration: %u ms",iter->second->GetModifier()->m_auraname, GetGUIDLow(), iter->second->GetAuraDuration());
4358 void Unit::_RemoveAllAuraMods()
4360 for (AuraMap::const_iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
4362 (*i).second->ApplyModifier(false);
4366 void Unit::_ApplyAllAuraMods()
4368 for (AuraMap::const_iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
4370 (*i).second->ApplyModifier(true);
4374 Aura* Unit::GetAura(uint32 spellId, uint32 effindex)
4376 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
4377 if (iter != m_Auras.end())
4378 return iter->second;
4379 return NULL;
4382 Aura* Unit::GetAura(AuraType type, uint32 family, uint64 familyFlag, uint32 familyFlag2, uint64 casterGUID)
4384 AuraList const& auras = GetAurasByType(type);
4385 for(AuraList::const_iterator i = auras.begin();i != auras.end(); ++i)
4387 SpellEntry const *spell = (*i)->GetSpellProto();
4388 if (spell->SpellFamilyName == family && (spell->SpellFamilyFlags & familyFlag || spell->SpellFamilyFlags2 & familyFlag2))
4390 if (casterGUID && (*i)->GetCasterGUID()!=casterGUID)
4391 continue;
4392 return (*i);
4395 return NULL;
4398 bool Unit::HasAura(uint32 spellId) const
4400 for (int i = 0; i < 3 ; ++i)
4402 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, i));
4403 if (iter != m_Auras.end())
4404 return true;
4406 return false;
4409 void Unit::AddDynObject(DynamicObject* dynObj)
4411 m_dynObjGUIDs.push_back(dynObj->GetGUID());
4414 void Unit::RemoveDynObject(uint32 spellid)
4416 if(m_dynObjGUIDs.empty())
4417 return;
4418 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4420 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4421 if(!dynObj)
4423 i = m_dynObjGUIDs.erase(i);
4425 else if(spellid == 0 || dynObj->GetSpellId() == spellid)
4427 dynObj->Delete();
4428 i = m_dynObjGUIDs.erase(i);
4430 else
4431 ++i;
4435 void Unit::RemoveAllDynObjects()
4437 while(!m_dynObjGUIDs.empty())
4439 DynamicObject* dynObj = GetMap()->GetDynamicObject(*m_dynObjGUIDs.begin());
4440 if(dynObj)
4441 dynObj->Delete();
4442 m_dynObjGUIDs.erase(m_dynObjGUIDs.begin());
4446 DynamicObject * Unit::GetDynObject(uint32 spellId, uint32 effIndex)
4448 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4450 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4451 if(!dynObj)
4453 i = m_dynObjGUIDs.erase(i);
4454 continue;
4457 if (dynObj->GetSpellId() == spellId && dynObj->GetEffIndex() == effIndex)
4458 return dynObj;
4459 ++i;
4461 return NULL;
4464 DynamicObject * Unit::GetDynObject(uint32 spellId)
4466 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4468 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4469 if(!dynObj)
4471 i = m_dynObjGUIDs.erase(i);
4472 continue;
4475 if (dynObj->GetSpellId() == spellId)
4476 return dynObj;
4477 ++i;
4479 return NULL;
4482 GameObject* Unit::GetGameObject(uint32 spellId) const
4484 for (GameObjectList::const_iterator i = m_gameObj.begin(); i != m_gameObj.end(); ++i)
4485 if ((*i)->GetSpellId() == spellId)
4486 return *i;
4488 return NULL;
4491 void Unit::AddGameObject(GameObject* gameObj)
4493 assert(gameObj && gameObj->GetOwnerGUID()==0);
4494 m_gameObj.push_back(gameObj);
4495 gameObj->SetOwnerGUID(GetGUID());
4497 if ( GetTypeId()==TYPEID_PLAYER && gameObj->GetSpellId() )
4499 SpellEntry const* createBySpell = sSpellStore.LookupEntry(gameObj->GetSpellId());
4500 // Need disable spell use for owner
4501 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4502 // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
4503 ((Player*)this)->AddSpellAndCategoryCooldowns(createBySpell,0,NULL,true);
4507 void Unit::RemoveGameObject(GameObject* gameObj, bool del)
4509 assert(gameObj && gameObj->GetOwnerGUID()==GetGUID());
4511 gameObj->SetOwnerGUID(0);
4513 // GO created by some spell
4514 if (uint32 spellid = gameObj->GetSpellId())
4516 RemoveAurasDueToSpell(spellid);
4518 if (GetTypeId()==TYPEID_PLAYER)
4520 SpellEntry const* createBySpell = sSpellStore.LookupEntry(spellid );
4521 // Need activate spell use for owner
4522 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4523 // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
4524 ((Player*)this)->SendCooldownEvent(createBySpell);
4528 m_gameObj.remove(gameObj);
4530 if(del)
4532 gameObj->SetRespawnTime(0);
4533 gameObj->Delete();
4537 void Unit::RemoveGameObject(uint32 spellid, bool del)
4539 if(m_gameObj.empty())
4540 return;
4541 GameObjectList::iterator i, next;
4542 for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next)
4544 next = i;
4545 if(spellid == 0 || (*i)->GetSpellId() == spellid)
4547 (*i)->SetOwnerGUID(0);
4548 if(del)
4550 (*i)->SetRespawnTime(0);
4551 (*i)->Delete();
4554 next = m_gameObj.erase(i);
4556 else
4557 ++next;
4561 void Unit::RemoveAllGameObjects()
4563 // remove references to unit
4564 for(GameObjectList::iterator i = m_gameObj.begin(); i != m_gameObj.end();)
4566 (*i)->SetOwnerGUID(0);
4567 (*i)->SetRespawnTime(0);
4568 (*i)->Delete();
4569 i = m_gameObj.erase(i);
4573 void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage *log)
4575 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+4+1+4+4+1+1+4+4+1)); // we guess size
4576 data.append(log->target->GetPackGUID());
4577 data.append(log->attacker->GetPackGUID());
4578 data << uint32(log->SpellID);
4579 data << uint32(log->damage); // damage amount
4580 data << uint32(log->overkill); // overkill
4581 data << uint8 (log->schoolMask); // damage school
4582 data << uint32(log->absorb); // AbsorbedDamage
4583 data << uint32(log->resist); // resist
4584 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
4585 data << uint8 (log->unused); // unused
4586 data << uint32(log->blocked); // blocked
4587 data << uint32(log->HitInfo);
4588 data << uint8 (0); // flag to use extend data
4589 SendMessageToSet( &data, true );
4592 void Unit::SendSpellNonMeleeDamageLog(Unit *target, uint32 SpellID, uint32 Damage, SpellSchoolMask damageSchoolMask, uint32 AbsorbedDamage, uint32 Resist, bool PhysicalDamage, uint32 Blocked, bool CriticalHit)
4594 SpellNonMeleeDamage log(this, target, SpellID, damageSchoolMask);
4595 log.damage = Damage - AbsorbedDamage - Resist - Blocked;
4596 log.absorb = AbsorbedDamage;
4597 log.resist = Resist;
4598 log.physicalLog = PhysicalDamage;
4599 log.blocked = Blocked;
4600 log.HitInfo = SPELL_HIT_TYPE_UNK1 | SPELL_HIT_TYPE_UNK3 | SPELL_HIT_TYPE_UNK6;
4601 if(CriticalHit)
4602 log.HitInfo |= SPELL_HIT_TYPE_CRIT;
4603 SendSpellNonMeleeDamageLog(&log);
4606 void Unit::SendPeriodicAuraLog(SpellPeriodicAuraLogInfo *pInfo)
4608 Aura *aura = pInfo->aura;
4609 Modifier *mod = aura->GetModifier();
4611 WorldPacket data(SMSG_PERIODICAURALOG, 30);
4612 data.append(aura->GetTarget()->GetPackGUID());
4613 data.appendPackGUID(aura->GetCasterGUID());
4614 data << uint32(aura->GetId()); // spellId
4615 data << uint32(1); // count
4616 data << uint32(mod->m_auraname); // auraId
4617 switch(mod->m_auraname)
4619 case SPELL_AURA_PERIODIC_DAMAGE:
4620 case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
4621 data << uint32(pInfo->damage); // damage
4622 data << uint32(pInfo->overDamage); // overkill?
4623 data << uint32(GetSpellSchoolMask(aura->GetSpellProto()));
4624 data << uint32(pInfo->absorb); // absorb
4625 data << uint32(pInfo->resist); // resist
4626 data << uint8(pInfo->critical ? 1 : 0); // new 3.1.2 critical flag
4627 break;
4628 case SPELL_AURA_PERIODIC_HEAL:
4629 case SPELL_AURA_OBS_MOD_HEALTH:
4630 data << uint32(pInfo->damage); // damage
4631 data << uint32(pInfo->overDamage); // overheal?
4632 data << uint8(pInfo->critical ? 1 : 0); // new 3.1.2 critical flag
4633 break;
4634 case SPELL_AURA_OBS_MOD_MANA:
4635 case SPELL_AURA_PERIODIC_ENERGIZE:
4636 data << uint32(mod->m_miscvalue); // power type
4637 data << uint32(pInfo->damage); // damage
4638 break;
4639 case SPELL_AURA_PERIODIC_MANA_LEECH:
4640 data << uint32(mod->m_miscvalue); // power type
4641 data << uint32(pInfo->damage); // amount
4642 data << float(pInfo->multiplier); // gain multiplier
4643 break;
4644 default:
4645 sLog.outError("Unit::SendPeriodicAuraLog: unknown aura %u", uint32(mod->m_auraname));
4646 return;
4649 aura->GetTarget()->SendMessageToSet(&data, true);
4652 void Unit::ProcDamageAndSpell(Unit *pVictim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellEntry const *procSpell)
4654 // Not much to do if no flags are set.
4655 if (procAttacker)
4656 ProcDamageAndSpellFor(false,pVictim,procAttacker, procExtra,attType, procSpell, amount);
4657 // Now go on with a victim's events'n'auras
4658 // Not much to do if no flags are set or there is no victim
4659 if(pVictim && pVictim->isAlive() && procVictim)
4660 pVictim->ProcDamageAndSpellFor(true,this,procVictim, procExtra, attType, procSpell, amount);
4663 void Unit::SendSpellMiss(Unit *target, uint32 spellID, SpellMissInfo missInfo)
4665 WorldPacket data(SMSG_SPELLLOGMISS, (4+8+1+4+8+1));
4666 data << uint32(spellID);
4667 data << uint64(GetGUID());
4668 data << uint8(0); // can be 0 or 1
4669 data << uint32(1); // target count
4670 // for(i = 0; i < target count; ++i)
4671 data << uint64(target->GetGUID()); // target GUID
4672 data << uint8(missInfo);
4673 // end loop
4674 SendMessageToSet(&data, true);
4677 void Unit::SendAttackStateUpdate(CalcDamageInfo *damageInfo)
4679 sLog.outDebug("WORLD: Sending SMSG_ATTACKERSTATEUPDATE");
4681 uint32 count = 1;
4682 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, 16 + 45); // we guess size
4683 data << uint32(damageInfo->HitInfo);
4684 data.append(damageInfo->attacker->GetPackGUID());
4685 data.append(damageInfo->target->GetPackGUID());
4686 data << uint32(damageInfo->damage); // Full damage
4687 data << uint32(0); // overkill value
4688 data << uint8(count); // Sub damage count
4690 for(int i = 0; i < count; ++i)
4692 data << uint32(damageInfo->damageSchoolMask); // School of sub damage
4693 data << float(damageInfo->damage); // sub damage
4694 data << uint32(damageInfo->damage); // Sub Damage
4697 if(damageInfo->HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4699 for(int i = 0; i < count; ++i)
4700 data << uint32(damageInfo->absorb); // Absorb
4703 if(damageInfo->HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4705 for(int i = 0; i < count; ++i)
4706 data << uint32(damageInfo->resist); // Resist
4709 data << uint8(damageInfo->TargetState);
4710 data << uint32(0);
4711 data << uint32(0);
4713 if(damageInfo->HitInfo & HITINFO_BLOCK)
4714 data << uint32(damageInfo->blocked_amount);
4716 if(damageInfo->HitInfo & HITINFO_UNK3)
4717 data << uint32(0);
4719 if(damageInfo->HitInfo & HITINFO_UNK1)
4721 data << uint32(0);
4722 data << float(0);
4723 data << float(0);
4724 data << float(0);
4725 data << float(0);
4726 data << float(0);
4727 data << float(0);
4728 data << float(0);
4729 data << float(0);
4730 for(uint8 i = 0; i < 5; ++i)
4732 data << float(0);
4733 data << float(0);
4735 data << uint32(0);
4738 SendMessageToSet( &data, true );
4741 void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit *target, uint8 SwingType, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount)
4743 CalcDamageInfo dmgInfo;
4744 dmgInfo.HitInfo = HitInfo;
4745 dmgInfo.attacker = this;
4746 dmgInfo.target = target;
4747 dmgInfo.damage = Damage - AbsorbDamage - Resist - BlockedAmount;
4748 dmgInfo.damageSchoolMask = damageSchoolMask;
4749 dmgInfo.absorb = AbsorbDamage;
4750 dmgInfo.resist = Resist;
4751 dmgInfo.TargetState = TargetState;
4752 dmgInfo.blocked_amount = BlockedAmount;
4753 SendAttackStateUpdate(&dmgInfo);
4756 bool Unit::HandleHasteAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
4758 SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto();
4760 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4761 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4763 uint32 triggered_spell_id = 0;
4764 Unit* target = pVictim;
4765 int32 basepoints0 = 0;
4767 switch(hasteSpell->SpellFamilyName)
4769 case SPELLFAMILY_ROGUE:
4771 switch(hasteSpell->Id)
4773 // Blade Flurry
4774 case 13877:
4775 case 33735:
4777 target = SelectNearbyTarget(pVictim);
4778 if(!target)
4779 return false;
4780 basepoints0 = damage;
4781 triggered_spell_id = 22482;
4782 break;
4785 break;
4789 // processed charge only counting case
4790 if(!triggered_spell_id)
4791 return true;
4793 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
4795 if(!triggerEntry)
4797 sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",hasteSpell->Id,triggered_spell_id);
4798 return false;
4801 // default case
4802 if(!target || target!=this && !target->isAlive())
4803 return false;
4805 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
4806 return false;
4808 if(basepoints0)
4809 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
4810 else
4811 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
4813 if( cooldown && GetTypeId()==TYPEID_PLAYER )
4814 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
4816 return true;
4819 bool Unit::HandleSpellCritChanceAuraProc(Unit *pVictim, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
4821 SpellEntry const *triggeredByAuraSpell = triggeredByAura->GetSpellProto();
4823 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4824 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4826 uint32 triggered_spell_id = 0;
4827 Unit* target = pVictim;
4828 int32 basepoints0 = 0;
4830 switch(triggeredByAuraSpell->SpellFamilyName)
4832 case SPELLFAMILY_MAGE:
4834 switch(triggeredByAuraSpell->Id)
4836 // Focus Magic
4837 case 54646:
4839 Unit* caster = triggeredByAura->GetCaster();
4840 if(!caster)
4841 return false;
4843 triggered_spell_id = 54648;
4844 target = caster;
4845 break;
4851 // processed charge only counting case
4852 if(!triggered_spell_id)
4853 return true;
4855 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
4857 if(!triggerEntry)
4859 sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",triggeredByAuraSpell->Id,triggered_spell_id);
4860 return false;
4863 // default case
4864 if(!target || target!=this && !target->isAlive())
4865 return false;
4867 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
4868 return false;
4870 if(basepoints0)
4871 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
4872 else
4873 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
4875 if( cooldown && GetTypeId()==TYPEID_PLAYER )
4876 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
4878 return true;
4881 bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
4883 SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
4884 uint32 effIndex = triggeredByAura->GetEffIndex();
4885 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
4887 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4888 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4890 uint32 triggered_spell_id = 0;
4891 Unit* target = pVictim;
4892 int32 basepoints0 = 0;
4894 switch(dummySpell->SpellFamilyName)
4896 case SPELLFAMILY_GENERIC:
4898 switch (dummySpell->Id)
4900 // Eye for an Eye
4901 case 9799:
4902 case 25988:
4904 // return damage % to attacker but < 50% own total health
4905 basepoints0 = triggerAmount*int32(damage)/100;
4906 if(basepoints0 > GetMaxHealth()/2)
4907 basepoints0 = GetMaxHealth()/2;
4909 triggered_spell_id = 25997;
4910 break;
4912 // Sweeping Strikes (NPC spells may be)
4913 case 18765:
4914 case 35429:
4916 // prevent chain of triggered spell from same triggered spell
4917 if(procSpell && procSpell->Id == 26654)
4918 return false;
4920 target = SelectNearbyTarget(pVictim);
4921 if(!target)
4922 return false;
4924 triggered_spell_id = 26654;
4925 break;
4927 // Twisted Reflection (boss spell)
4928 case 21063:
4929 triggered_spell_id = 21064;
4930 break;
4931 // Unstable Power
4932 case 24658:
4934 if (!procSpell || procSpell->Id == 24659)
4935 return false;
4936 // Need remove one 24659 aura
4937 RemoveSingleSpellAurasFromStack(24659);
4938 return true;
4940 // Restless Strength
4941 case 24661:
4943 // Need remove one 24662 aura
4944 RemoveSingleSpellAurasFromStack(24662);
4945 return true;
4947 // Adaptive Warding (Frostfire Regalia set)
4948 case 28764:
4950 if(!procSpell)
4951 return false;
4953 // find Mage Armor
4954 bool found = false;
4955 AuraList const& mRegenInterupt = GetAurasByType(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT);
4956 for(AuraList::const_iterator iter = mRegenInterupt.begin(); iter != mRegenInterupt.end(); ++iter)
4958 if(SpellEntry const* iterSpellProto = (*iter)->GetSpellProto())
4960 if(iterSpellProto->SpellFamilyName==SPELLFAMILY_MAGE && (iterSpellProto->SpellFamilyFlags & UI64LIT(0x10000000)))
4962 found=true;
4963 break;
4967 if(!found)
4968 return false;
4970 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4972 case SPELL_SCHOOL_NORMAL:
4973 case SPELL_SCHOOL_HOLY:
4974 return false; // ignored
4975 case SPELL_SCHOOL_FIRE: triggered_spell_id = 28765; break;
4976 case SPELL_SCHOOL_NATURE: triggered_spell_id = 28768; break;
4977 case SPELL_SCHOOL_FROST: triggered_spell_id = 28766; break;
4978 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 28769; break;
4979 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 28770; break;
4980 default:
4981 return false;
4984 target = this;
4985 break;
4987 // Obsidian Armor (Justice Bearer`s Pauldrons shoulder)
4988 case 27539:
4990 if(!procSpell)
4991 return false;
4993 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4995 case SPELL_SCHOOL_NORMAL:
4996 return false; // ignore
4997 case SPELL_SCHOOL_HOLY: triggered_spell_id = 27536; break;
4998 case SPELL_SCHOOL_FIRE: triggered_spell_id = 27533; break;
4999 case SPELL_SCHOOL_NATURE: triggered_spell_id = 27538; break;
5000 case SPELL_SCHOOL_FROST: triggered_spell_id = 27534; break;
5001 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 27535; break;
5002 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 27540; break;
5003 default:
5004 return false;
5007 target = this;
5008 break;
5010 // Mana Leech (Passive) (Priest Pet Aura)
5011 case 28305:
5013 // Cast on owner
5014 target = GetOwner();
5015 if(!target)
5016 return false;
5018 triggered_spell_id = 34650;
5019 break;
5021 // Divine purpose
5022 case 31871:
5023 case 31872:
5025 // Roll chane
5026 if (!roll_chance_i(triggerAmount))
5027 return false;
5029 // Remove any stun effect on target
5030 AuraMap& Auras = pVictim->GetAuras();
5031 for(AuraMap::const_iterator iter = Auras.begin(); iter != Auras.end();)
5033 SpellEntry const *spell = iter->second->GetSpellProto();
5034 if( spell->Mechanic == MECHANIC_STUN ||
5035 spell->EffectMechanic[iter->second->GetEffIndex()] == MECHANIC_STUN)
5037 pVictim->RemoveAurasDueToSpell(spell->Id);
5038 iter = Auras.begin();
5040 else
5041 ++iter;
5043 return true;
5045 // Mark of Malice
5046 case 33493:
5048 // Cast finish spell at last charge
5049 if (triggeredByAura->GetAuraCharges() > 1)
5050 return false;
5052 target = this;
5053 triggered_spell_id = 33494;
5054 break;
5056 // Vampiric Aura (boss spell)
5057 case 38196:
5059 basepoints0 = 3 * damage; // 300%
5060 if (basepoints0 < 0)
5061 return false;
5063 triggered_spell_id = 31285;
5064 target = this;
5065 break;
5067 // Aura of Madness (Darkmoon Card: Madness trinket)
5068 //=====================================================
5069 // 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior)
5070 // 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid)
5071 // 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid)
5072 // 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin)
5073 // 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes)
5074 // 41005 Manic: +35 haste (spell, melee and ranged) (All classes)
5075 // 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter)
5076 // 41011 Martyr Complex: +35 stamina (All classes)
5077 // 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
5078 // 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
5079 case 39446:
5081 if(GetTypeId() != TYPEID_PLAYER)
5082 return false;
5084 // Select class defined buff
5085 switch (getClass())
5087 case CLASS_PALADIN: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
5088 case CLASS_DRUID: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
5090 uint32 RandomSpell[]={39511,40997,40998,40999,41002,41005,41009,41011,41409};
5091 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
5092 break;
5094 case CLASS_ROGUE: // 39511,40997,40998,41002,41005,41011
5095 case CLASS_WARRIOR: // 39511,40997,40998,41002,41005,41011
5097 uint32 RandomSpell[]={39511,40997,40998,41002,41005,41011};
5098 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
5099 break;
5101 case CLASS_PRIEST: // 40999,41002,41005,41009,41011,41406,41409
5102 case CLASS_SHAMAN: // 40999,41002,41005,41009,41011,41406,41409
5103 case CLASS_MAGE: // 40999,41002,41005,41009,41011,41406,41409
5104 case CLASS_WARLOCK: // 40999,41002,41005,41009,41011,41406,41409
5106 uint32 RandomSpell[]={40999,41002,41005,41009,41011,41406,41409};
5107 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
5108 break;
5110 case CLASS_HUNTER: // 40997,40999,41002,41005,41009,41011,41406,41409
5112 uint32 RandomSpell[]={40997,40999,41002,41005,41009,41011,41406,41409};
5113 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
5114 break;
5116 default:
5117 return false;
5120 target = this;
5121 if (roll_chance_i(10))
5122 ((Player*)this)->Say("This is Madness!", LANG_UNIVERSAL);
5123 break;
5125 // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck)
5126 // cast 45479 Light's Wrath if Exalted by Aldor
5127 // cast 45429 Arcane Bolt if Exalted by Scryers
5128 case 45481:
5130 if(GetTypeId() != TYPEID_PLAYER)
5131 return false;
5133 // Get Aldor reputation rank
5134 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
5136 target = this;
5137 triggered_spell_id = 45479;
5138 break;
5140 // Get Scryers reputation rank
5141 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
5143 // triggered at positive/self casts also, current attack target used then
5144 if(IsFriendlyTo(target))
5146 target = getVictim();
5147 if(!target)
5149 uint64 selected_guid = ((Player *)this)->GetSelection();
5150 target = ObjectAccessor::GetUnit(*this,selected_guid);
5151 if(!target)
5152 return false;
5154 if(IsFriendlyTo(target))
5155 return false;
5158 triggered_spell_id = 45429;
5159 break;
5161 return false;
5163 // Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck)
5164 // cast 45480 Light's Strength if Exalted by Aldor
5165 // cast 45428 Arcane Strike if Exalted by Scryers
5166 case 45482:
5168 if(GetTypeId() != TYPEID_PLAYER)
5169 return false;
5171 // Get Aldor reputation rank
5172 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
5174 target = this;
5175 triggered_spell_id = 45480;
5176 break;
5178 // Get Scryers reputation rank
5179 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
5181 triggered_spell_id = 45428;
5182 break;
5184 return false;
5186 // Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck)
5187 // cast 45431 Arcane Insight if Exalted by Aldor
5188 // cast 45432 Light's Ward if Exalted by Scryers
5189 case 45483:
5191 if(GetTypeId() != TYPEID_PLAYER)
5192 return false;
5194 // Get Aldor reputation rank
5195 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
5197 target = this;
5198 triggered_spell_id = 45432;
5199 break;
5201 // Get Scryers reputation rank
5202 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
5204 target = this;
5205 triggered_spell_id = 45431;
5206 break;
5208 return false;
5210 // Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck)
5211 // cast 45478 Light's Salvation if Exalted by Aldor
5212 // cast 45430 Arcane Surge if Exalted by Scryers
5213 case 45484:
5215 if(GetTypeId() != TYPEID_PLAYER)
5216 return false;
5218 // Get Aldor reputation rank
5219 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
5221 target = this;
5222 triggered_spell_id = 45478;
5223 break;
5225 // Get Scryers reputation rank
5226 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
5228 triggered_spell_id = 45430;
5229 break;
5231 return false;
5234 // Sunwell Exalted Caster Neck (??? neck)
5235 // cast ??? Light's Wrath if Exalted by Aldor
5236 // cast ??? Arcane Bolt if Exalted by Scryers*/
5237 case 46569:
5238 return false; // old unused version
5239 // Living Seed
5240 case 48504:
5242 triggered_spell_id = 48503;
5243 basepoints0 = triggerAmount;
5244 target = this;
5245 break;
5247 // Vampiric Touch (generic, used by some boss)
5248 case 52723:
5249 case 60501:
5251 triggered_spell_id = 52724;
5252 basepoints0 = damage / 2;
5253 target = this;
5254 break;
5256 // Shadowfiend Death (Gain mana if pet dies with Glyph of Shadowfiend)
5257 case 57989:
5259 Unit *owner = GetOwner();
5260 if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
5261 return false;
5263 // Glyph of Shadowfiend (need cast as self cast for owner, no hidden cooldown)
5264 owner->CastSpell(owner,58227,true,castItem,triggeredByAura);
5265 return true;
5267 // Glyph of Life Tap
5268 case 63320:
5269 triggered_spell_id = 63321;
5270 break;
5272 break;
5274 case SPELLFAMILY_MAGE:
5276 // Magic Absorption
5277 if (dummySpell->SpellIconID == 459) // only this spell have SpellIconID == 459 and dummy aura
5279 if (getPowerType() != POWER_MANA)
5280 return false;
5282 // mana reward
5283 basepoints0 = (triggerAmount * GetMaxPower(POWER_MANA) / 100);
5284 target = this;
5285 triggered_spell_id = 29442;
5286 break;
5288 // Master of Elements
5289 if (dummySpell->SpellIconID == 1920)
5291 if(!procSpell)
5292 return false;
5294 // mana cost save
5295 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
5296 basepoints0 = cost * triggerAmount/100;
5297 if( basepoints0 <=0 )
5298 return false;
5300 target = this;
5301 triggered_spell_id = 29077;
5302 break;
5305 // Arcane Potency
5306 if (dummySpell->SpellIconID == 2120)
5308 if(!procSpell)
5309 return false;
5311 target = this;
5312 switch (dummySpell->Id)
5314 case 31571: triggered_spell_id = 57529; break;
5315 case 31572: triggered_spell_id = 57531; break;
5316 default:
5317 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u",dummySpell->Id);
5318 return false;
5320 break;
5323 // Hot Streak
5324 if (dummySpell->SpellIconID == 2999)
5326 if (effIndex!=0)
5327 return true;
5328 Aura *counter = GetAura(triggeredByAura->GetId(), 1);
5329 if (!counter)
5330 return true;
5332 // Count spell criticals in a row in second aura
5333 Modifier *mod = counter->GetModifier();
5334 if (procEx & PROC_EX_CRITICAL_HIT)
5336 mod->m_amount *=2;
5337 if (mod->m_amount < 100) // not enough
5338 return true;
5339 // Crititcal counted -> roll chance
5340 if (roll_chance_i(triggerAmount))
5341 CastSpell(this, 48108, true, castItem, triggeredByAura);
5343 mod->m_amount = 25;
5344 return true;
5346 // Burnout
5347 if (dummySpell->SpellIconID == 2998)
5349 if(!procSpell)
5350 return false;
5352 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
5353 basepoints0 = cost * triggerAmount/100;
5354 if( basepoints0 <=0 )
5355 return false;
5356 triggered_spell_id = 44450;
5357 target = this;
5358 break;
5360 // Incanter's Regalia set (add trigger chance to Mana Shield)
5361 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000000000008000))
5363 if(GetTypeId() != TYPEID_PLAYER)
5364 return false;
5366 target = this;
5367 triggered_spell_id = 37436;
5368 break;
5370 switch(dummySpell->Id)
5372 // Ignite
5373 case 11119:
5374 case 11120:
5375 case 12846:
5376 case 12847:
5377 case 12848:
5379 switch (dummySpell->Id)
5381 case 11119: basepoints0 = int32(0.04f*damage); break;
5382 case 11120: basepoints0 = int32(0.08f*damage); break;
5383 case 12846: basepoints0 = int32(0.12f*damage); break;
5384 case 12847: basepoints0 = int32(0.16f*damage); break;
5385 case 12848: basepoints0 = int32(0.20f*damage); break;
5386 default:
5387 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (IG)",dummySpell->Id);
5388 return false;
5391 triggered_spell_id = 12654;
5392 break;
5394 // Combustion
5395 case 11129:
5397 //last charge and crit
5398 if (triggeredByAura->GetAuraCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT) )
5399 return true; // charge counting (will removed)
5401 CastSpell(this, 28682, true, castItem, triggeredByAura);
5402 return (procEx & PROC_EX_CRITICAL_HIT); // charge update only at crit hits, no hidden cooldowns
5404 // Glyph of Ice Block
5405 case 56372:
5407 if (GetTypeId() != TYPEID_PLAYER)
5408 return false;
5410 // not 100% safe with client version switches but for 3.1.3 no spells with cooldown that can have mage player except Frost Nova.
5411 ((Player*)this)->RemoveSpellCategoryCooldown(35, true);
5412 return true;
5414 // Glyph of Polymorph
5415 case 56375:
5417 if (!pVictim || !pVictim->isAlive())
5418 return false;
5420 pVictim->RemoveSpellsCausingAura(SPELL_AURA_PERIODIC_DAMAGE);
5421 pVictim->RemoveSpellsCausingAura(SPELL_AURA_PERIODIC_DAMAGE_PERCENT);
5422 return true;
5425 break;
5427 case SPELLFAMILY_WARRIOR:
5429 // Retaliation
5430 if (dummySpell->SpellFamilyFlags == UI64LIT(0x0000000800000000))
5432 // check attack comes not from behind
5433 if (!HasInArc(M_PI, pVictim))
5434 return false;
5436 triggered_spell_id = 22858;
5437 break;
5439 // Second Wind
5440 if (dummySpell->SpellIconID == 1697)
5442 // only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example)
5443 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
5444 return false;
5445 // Need stun or root mechanic
5446 if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_ROOT_AND_STUN_MASK))
5447 return false;
5449 switch (dummySpell->Id)
5451 case 29838: triggered_spell_id=29842; break;
5452 case 29834: triggered_spell_id=29841; break;
5453 case 42770: triggered_spell_id=42771; break;
5454 default:
5455 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)",dummySpell->Id);
5456 return false;
5459 target = this;
5460 break;
5462 // Damage Shield
5463 if (dummySpell->SpellIconID == 3214)
5465 triggered_spell_id = 59653;
5466 basepoints0 = GetShieldBlockValue() * triggerAmount / 100;
5467 break;
5470 // Sweeping Strikes
5471 if (dummySpell->Id == 12328)
5473 // prevent chain of triggered spell from same triggered spell
5474 if(procSpell && procSpell->Id == 26654)
5475 return false;
5477 target = SelectNearbyTarget(pVictim);
5478 if(!target)
5479 return false;
5481 triggered_spell_id = 26654;
5482 break;
5484 break;
5486 case SPELLFAMILY_WARLOCK:
5488 // Seed of Corruption
5489 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000001000000000))
5491 Modifier* mod = triggeredByAura->GetModifier();
5492 // if damage is more than need or target die from damage deal finish spell
5493 if( mod->m_amount <= damage || GetHealth() <= damage )
5495 // remember guid before aura delete
5496 uint64 casterGuid = triggeredByAura->GetCasterGUID();
5498 // Remove aura (before cast for prevent infinite loop handlers)
5499 RemoveAurasDueToSpell(triggeredByAura->GetId());
5501 // Cast finish spell (triggeredByAura already not exist!)
5502 CastSpell(this, 27285, true, castItem, NULL, casterGuid);
5503 return true; // no hidden cooldown
5506 // Damage counting
5507 mod->m_amount-=damage;
5508 return true;
5510 // Seed of Corruption (Mobs cast) - no die req
5511 if (dummySpell->SpellFamilyFlags == UI64LIT(0x0) && dummySpell->SpellIconID == 1932)
5513 Modifier* mod = triggeredByAura->GetModifier();
5514 // if damage is more than need deal finish spell
5515 if( mod->m_amount <= damage )
5517 // remember guid before aura delete
5518 uint64 casterGuid = triggeredByAura->GetCasterGUID();
5520 // Remove aura (before cast for prevent infinite loop handlers)
5521 RemoveAurasDueToSpell(triggeredByAura->GetId());
5523 // Cast finish spell (triggeredByAura already not exist!)
5524 CastSpell(this, 32865, true, castItem, NULL, casterGuid);
5525 return true; // no hidden cooldown
5527 // Damage counting
5528 mod->m_amount-=damage;
5529 return true;
5531 // Fel Synergy
5532 if (dummySpell->SpellIconID == 3222)
5534 target = GetPet();
5535 if (!target)
5536 return false;
5537 basepoints0 = damage * triggerAmount / 100;
5538 triggered_spell_id = 54181;
5539 break;
5541 switch(dummySpell->Id)
5543 // Nightfall & Glyph of Corruption
5544 case 18094:
5545 case 18095:
5546 case 56218:
5548 target = this;
5549 triggered_spell_id = 17941;
5550 break;
5552 //Soul Leech
5553 case 30293:
5554 case 30295:
5555 case 30296:
5557 // health
5558 basepoints0 = int32(damage*triggerAmount/100);
5559 target = this;
5560 triggered_spell_id = 30294;
5561 break;
5563 // Shadowflame (Voidheart Raiment set bonus)
5564 case 37377:
5566 triggered_spell_id = 37379;
5567 break;
5569 // Pet Healing (Corruptor Raiment or Rift Stalker Armor)
5570 case 37381:
5572 target = GetPet();
5573 if(!target)
5574 return false;
5576 // heal amount
5577 basepoints0 = damage * triggerAmount/100;
5578 triggered_spell_id = 37382;
5579 break;
5581 // Shadowflame Hellfire (Voidheart Raiment set bonus)
5582 case 39437:
5584 triggered_spell_id = 37378;
5585 break;
5587 // Siphon Life
5588 case 63108:
5590 basepoints0 = int32(damage * triggerAmount / 100);
5591 triggered_spell_id = 63106;
5592 break;
5595 break;
5597 case SPELLFAMILY_PRIEST:
5599 // Vampiric Touch
5600 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000040000000000))
5602 if(!pVictim || !pVictim->isAlive())
5603 return false;
5605 // pVictim is caster of aura
5606 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5607 return false;
5609 // Energize 0.25% of max. mana
5610 pVictim->CastSpell(pVictim,57669,true,castItem,triggeredByAura);
5611 return true; // no hidden cooldown
5614 switch(dummySpell->SpellIconID)
5616 // Improved Shadowform
5617 case 217:
5619 if(!roll_chance_i(triggerAmount))
5620 return false;
5622 RemoveSpellsCausingAura(SPELL_AURA_MOD_ROOT);
5623 RemoveSpellsCausingAura(SPELL_AURA_MOD_DECREASE_SPEED);
5624 break;
5626 // Divine Aegis
5627 case 2820:
5629 basepoints0 = damage * triggerAmount/100;
5630 triggered_spell_id = 47753;
5631 break;
5633 // Empowered Renew
5634 case 3021:
5636 if (!procSpell)
5637 return false;
5639 Aura* healingAura = pVictim->GetAura(procSpell->Id,0);
5640 if (!healingAura)
5641 return false;
5643 int32 healingfromticks = SpellHealingBonus(pVictim, procSpell, (healingAura->GetModifier()->m_amount* GetSpellAuraMaxTicks(procSpell)), DOT);
5644 basepoints0 = healingfromticks * triggerAmount / 100;
5645 triggered_spell_id = 63544;
5646 break;
5648 // Improved Devouring Plague
5649 case 3790:
5651 if (!procSpell)
5652 return false;
5654 Aura* leachAura = pVictim->GetAura(procSpell->Id,0);
5655 if (!leachAura)
5656 return false;
5658 int32 damagefromticks = SpellDamageBonus(pVictim, procSpell, (leachAura->GetModifier()->m_amount* GetSpellAuraMaxTicks(procSpell)), DOT);
5659 basepoints0 = damagefromticks * triggerAmount / 100;
5660 triggered_spell_id = 63675;
5661 break;
5665 switch(dummySpell->Id)
5667 // Vampiric Embrace
5668 case 15286:
5670 if(!pVictim || !pVictim->isAlive())
5671 return false;
5673 // pVictim is caster of aura
5674 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5675 return false;
5677 // heal amount
5678 int32 team = triggerAmount*damage/500;
5679 int32 self = triggerAmount*damage/100 - team;
5680 pVictim->CastCustomSpell(pVictim,15290,&team,&self,NULL,true,castItem,triggeredByAura);
5681 return true; // no hidden cooldown
5683 // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen)
5684 case 40438:
5686 // Shadow Word: Pain
5687 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000008000))
5688 triggered_spell_id = 40441;
5689 // Renew
5690 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000010))
5691 triggered_spell_id = 40440;
5692 else
5693 return false;
5695 target = this;
5696 break;
5698 // Oracle Healing Bonus ("Garments of the Oracle" set)
5699 case 26169:
5701 // heal amount
5702 basepoints0 = int32(damage * 10/100);
5703 target = this;
5704 triggered_spell_id = 26170;
5705 break;
5707 // Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set
5708 case 39372:
5710 if(!procSpell || (GetSpellSchoolMask(procSpell) & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW))==0 )
5711 return false;
5713 // heal amount
5714 basepoints0 = damage * triggerAmount/100;
5715 target = this;
5716 triggered_spell_id = 39373;
5717 break;
5719 // Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus)
5720 case 28809:
5722 triggered_spell_id = 28810;
5723 break;
5725 // Glyph of Dispel Magic
5726 case 55677:
5728 if(!target->IsFriendlyTo(this))
5729 return false;
5731 basepoints0 = int32(target->GetMaxHealth() * triggerAmount / 100);
5732 triggered_spell_id = 56131;
5733 break;
5736 break;
5738 case SPELLFAMILY_DRUID:
5740 switch(dummySpell->Id)
5742 // Leader of the Pack
5743 case 24932:
5745 // dummy m_amount store health percent (!=0 if Improved Leader of the Pack applied)
5746 int32 heal_percent = triggeredByAura->GetModifier()->m_amount;
5747 if (!heal_percent)
5748 return false;
5750 // check explicitly only to prevent mana cast when halth cast cooldown
5751 if (cooldown && ((Player*)this)->HasSpellCooldown(34299))
5752 return false;
5754 // health
5755 triggered_spell_id = 34299;
5756 basepoints0 = GetMaxHealth() * heal_percent / 100;
5757 target = this;
5759 // mana to caster
5760 if (triggeredByAura->GetCasterGUID() == GetGUID())
5762 if (SpellEntry const* manaCastEntry = sSpellStore.LookupEntry(60889))
5764 int32 mana_percent = manaCastEntry->CalculateSimpleValue(0) * heal_percent;
5765 CastCustomSpell(this, manaCastEntry, &mana_percent, NULL, NULL, true, castItem, triggeredByAura);
5768 break;
5770 // Healing Touch (Dreamwalker Raiment set)
5771 case 28719:
5773 // mana back
5774 basepoints0 = int32(procSpell->manaCost * 30 / 100);
5775 target = this;
5776 triggered_spell_id = 28742;
5777 break;
5779 // Healing Touch Refund (Idol of Longevity trinket)
5780 case 28847:
5782 target = this;
5783 triggered_spell_id = 28848;
5784 break;
5786 // Mana Restore (Malorne Raiment set / Malorne Regalia set)
5787 case 37288:
5788 case 37295:
5790 target = this;
5791 triggered_spell_id = 37238;
5792 break;
5794 // Druid Tier 6 Trinket
5795 case 40442:
5797 float chance;
5799 // Starfire
5800 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000004))
5802 triggered_spell_id = 40445;
5803 chance = 25.0f;
5805 // Rejuvenation
5806 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000010))
5808 triggered_spell_id = 40446;
5809 chance = 25.0f;
5811 // Mangle (Bear) and Mangle (Cat)
5812 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000044000000000))
5814 triggered_spell_id = 40452;
5815 chance = 40.0f;
5817 else
5818 return false;
5820 if (!roll_chance_f(chance))
5821 return false;
5823 target = this;
5824 break;
5826 // Maim Interrupt
5827 case 44835:
5829 // Deadly Interrupt Effect
5830 triggered_spell_id = 32747;
5831 break;
5833 // Glyph of Rejuvenation
5834 case 54754:
5836 // less 50% health
5837 if (pVictim->GetMaxHealth() < 2 * pVictim->GetHealth())
5838 return false;
5839 basepoints0 = triggerAmount * damage / 100;
5840 triggered_spell_id = 54755;
5841 break;
5844 // Eclipse
5845 if (dummySpell->SpellIconID == 2856)
5847 if (!procSpell)
5848 return false;
5849 // Only 0 aura can proc
5850 if (effIndex!=0)
5851 return true;
5852 // Wrath crit
5853 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000001))
5855 if (HasAura(48517))
5856 return false;
5857 if (!roll_chance_i(60))
5858 return false;
5859 triggered_spell_id = 48518;
5860 target = this;
5861 break;
5863 // Starfire crit
5864 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000004))
5866 if (HasAura(48518))
5867 return false;
5868 triggered_spell_id = 48517;
5869 target = this;
5870 break;
5872 return false;
5874 // Living Seed
5875 else if (dummySpell->SpellIconID == 2860)
5877 triggered_spell_id = 48504;
5878 basepoints0 = triggerAmount * damage / 100;
5879 break;
5881 break;
5883 case SPELLFAMILY_ROGUE:
5885 switch(dummySpell->Id)
5887 // Deadly Throw Interrupt
5888 case 32748:
5890 // Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw
5891 if (this == pVictim)
5892 return false;
5894 triggered_spell_id = 32747;
5895 break;
5898 // Cut to the Chase
5899 if (dummySpell->SpellIconID == 2909)
5901 // "refresh your Slice and Dice duration to its 5 combo point maximum"
5902 // lookup Slice and Dice
5903 AuraList const& sd = GetAurasByType(SPELL_AURA_MOD_HASTE);
5904 for(AuraList::const_iterator itr = sd.begin(); itr != sd.end(); ++itr)
5906 SpellEntry const *spellProto = (*itr)->GetSpellProto();
5907 if (spellProto->SpellFamilyName == SPELLFAMILY_ROGUE &&
5908 (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000040000)))
5910 (*itr)->SetAuraMaxDuration(GetSpellMaxDuration(spellProto));
5911 (*itr)->RefreshAura();
5912 return true;
5915 return false;
5917 // Deadly Brew
5918 if (dummySpell->SpellIconID == 2963)
5920 triggered_spell_id = 44289;
5921 break;
5923 // Quick Recovery
5924 if (dummySpell->SpellIconID == 2116)
5926 if(!procSpell)
5927 return false;
5929 // energy cost save
5930 basepoints0 = procSpell->manaCost * triggerAmount/100;
5931 if (basepoints0 <= 0)
5932 return false;
5934 target = this;
5935 triggered_spell_id = 31663;
5936 break;
5938 break;
5940 case SPELLFAMILY_HUNTER:
5942 // Aspect of the Viper
5943 if (dummySpell->SpellFamilyFlags & UI64LIT(0x4000000000000))
5945 uint32 maxmana = GetMaxPower(POWER_MANA);
5946 basepoints0 = int32(maxmana* GetAttackTime(RANGED_ATTACK)/1000.0f/100.0f);
5948 target = this;
5949 triggered_spell_id = 34075;
5950 break;
5952 // Thrill of the Hunt
5953 if (dummySpell->SpellIconID == 2236)
5955 if(!procSpell)
5956 return false;
5958 // mana cost save
5959 int32 mana = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
5960 basepoints0 = mana * 40/100;
5961 if(basepoints0 <= 0)
5962 return false;
5964 target = this;
5965 triggered_spell_id = 34720;
5966 break;
5968 // Hunting Party
5969 if ( dummySpell->SpellIconID == 3406 )
5971 triggered_spell_id = 57669;
5972 target = this;
5973 break;
5975 // Lock and Load
5976 if ( dummySpell->SpellIconID == 3579 )
5978 // Proc only from periodic (from trap activation proc another aura of this spell)
5979 if (!(procFlag & PROC_FLAG_ON_DO_PERIODIC) || !roll_chance_i(triggerAmount))
5980 return false;
5981 triggered_spell_id = 56453;
5982 target = this;
5983 break;
5985 // Rapid Recuperation
5986 if ( dummySpell->SpellIconID == 3560 )
5988 // This effect only from Rapid Killing (mana regen)
5989 if (!(procSpell->SpellFamilyFlags & UI64LIT(0x0100000000000000)))
5990 return false;
5992 target = this;
5994 switch(dummySpell->Id)
5996 case 53228: // Rank 1
5997 triggered_spell_id = 56654;
5998 break;
5999 case 53232: // Rank 2
6000 triggered_spell_id = 58882;
6001 break;
6003 break;
6005 break;
6007 case SPELLFAMILY_PALADIN:
6009 // Seal of Righteousness - melee proc dummy (addition ${$MWS*(0.022*$AP+0.044*$SPH)} damage)
6010 if ((dummySpell->SpellFamilyFlags & UI64LIT(0x000000008000000)) && effIndex==0)
6012 triggered_spell_id = 25742;
6013 float ap = GetTotalAttackPowerValue(BASE_ATTACK);
6014 int32 holy = SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
6015 SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, pVictim);
6016 basepoints0 = GetAttackTime(BASE_ATTACK) * int32(ap*0.022f + 0.044f * holy) / 1000;
6017 break;
6019 // Righteous Vengeance
6020 if (dummySpell->SpellIconID == 3025)
6022 // 4 damage tick
6023 basepoints0 = triggerAmount*damage/400;
6024 triggered_spell_id = 61840;
6025 break;
6027 // Sheath of Light
6028 if (dummySpell->SpellIconID == 3030)
6030 // 4 healing tick
6031 basepoints0 = triggerAmount*damage/400;
6032 triggered_spell_id = 54203;
6033 break;
6035 switch(dummySpell->Id)
6037 // Judgement of Light
6038 case 20185:
6040 basepoints0 = int32( pVictim->GetMaxHealth() * triggeredByAura->GetModifier()->m_amount / 100 );
6041 pVictim->CastCustomSpell(pVictim, 20267, &basepoints0, NULL, NULL, true, NULL, triggeredByAura);
6042 return true;
6044 // Judgement of Wisdom
6045 case 20186:
6047 if (pVictim->getPowerType() == POWER_MANA)
6049 // 2% of maximum base mana
6050 basepoints0 = int32(pVictim->GetCreateMana() * 2 / 100);
6051 pVictim->CastCustomSpell(pVictim, 20268, &basepoints0, NULL, NULL, true, NULL, triggeredByAura);
6053 return true;
6055 // Heart of the Crusader (Rank 1)
6056 case 20335:
6057 triggered_spell_id = 21183;
6058 break;
6059 // Heart of the Crusader (Rank 2)
6060 case 20336:
6061 triggered_spell_id = 54498;
6062 break;
6063 // Heart of the Crusader (Rank 3)
6064 case 20337:
6065 triggered_spell_id = 54499;
6066 break;
6067 case 20911: // Blessing of Sanctuary
6068 case 25899: // Greater Blessing of Sanctuary
6070 target = this;
6071 switch (target->getPowerType())
6073 case POWER_MANA:
6074 triggered_spell_id = 57319;
6075 break;
6076 default:
6077 return false;
6079 break;
6081 // Holy Power (Redemption Armor set)
6082 case 28789:
6084 if(!pVictim)
6085 return false;
6087 // Set class defined buff
6088 switch (pVictim->getClass())
6090 case CLASS_PALADIN:
6091 case CLASS_PRIEST:
6092 case CLASS_SHAMAN:
6093 case CLASS_DRUID:
6094 triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
6095 break;
6096 case CLASS_MAGE:
6097 case CLASS_WARLOCK:
6098 triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
6099 break;
6100 case CLASS_HUNTER:
6101 case CLASS_ROGUE:
6102 triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d.
6103 break;
6104 case CLASS_WARRIOR:
6105 triggered_spell_id = 28790; // Increases the friendly target's armor
6106 break;
6107 default:
6108 return false;
6110 break;
6112 // Spiritual Attunement
6113 case 31785:
6114 case 33776:
6116 // if healed by another unit (pVictim)
6117 if(this == pVictim)
6118 return false;
6120 // heal amount
6121 basepoints0 = triggerAmount*damage/100;
6122 target = this;
6123 triggered_spell_id = 31786;
6124 break;
6126 // Seal of Vengeance (damage calc on apply aura)
6127 case 31801:
6129 if(effIndex != 0) // effect 1,2 used by seal unleashing code
6130 return false;
6132 // At melee attack or Hammer of the Righteous spell damage considered as melee attack
6133 if ((procFlag & PROC_FLAG_SUCCESSFUL_MELEE_HIT) || (procSpell && procSpell->Id == 53595) )
6134 triggered_spell_id = 31803; // Holy Vengeance
6136 // Add 5-stack effect from Holy Vengeance
6137 int8 stacks = 0;
6138 AuraList const& auras = target->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
6139 for(AuraList::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr)
6141 if( ((*itr)->GetId() == 31803) && (*itr)->GetCasterGUID()==GetGUID())
6143 stacks = (*itr)->GetStackAmount();
6144 break;
6147 if(stacks >= 5)
6148 CastSpell(target,42463,true,NULL,triggeredByAura);
6149 break;
6151 // Judgements of the Wise
6152 case 31876:
6153 case 31877:
6154 case 31878:
6155 // triggered only at casted Judgement spells, not at additional Judgement effects
6156 if(!procSpell || procSpell->Category != 1210)
6157 return false;
6159 target = this;
6160 triggered_spell_id = 31930;
6162 // Replenishment
6163 CastSpell(this, 57669, true, NULL, triggeredByAura);
6164 break;
6165 // Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal)
6166 case 40470:
6168 if (!procSpell)
6169 return false;
6171 float chance;
6173 // Flash of light/Holy light
6174 if (procSpell->SpellFamilyFlags & UI64LIT(0x00000000C0000000))
6176 triggered_spell_id = 40471;
6177 chance = 15.0f;
6179 // Judgement (any)
6180 else if (GetSpellSpecific(procSpell->Id)==SPELL_JUDGEMENT)
6182 triggered_spell_id = 40472;
6183 chance = 50.0f;
6185 else
6186 return false;
6188 if (!roll_chance_f(chance))
6189 return false;
6191 break;
6193 // Light's Beacon (heal target area aura)
6194 case 53651:
6196 // not do bonus heal for explicit beacon focus healing
6197 if (GetGUID() == triggeredByAura->GetCasterGUID())
6198 return false;
6200 // beacon
6201 Unit* beacon = triggeredByAura->GetCaster();
6202 if (!beacon)
6203 return false;
6205 // find caster main aura at beacon
6206 Aura* dummy = NULL;
6207 Unit::AuraList const& baa = beacon->GetAurasByType(SPELL_AURA_PERIODIC_TRIGGER_SPELL);
6208 for(Unit::AuraList::const_iterator i = baa.begin(); i != baa.end(); ++i)
6210 if ((*i)->GetId() == 53563 && (*i)->GetCasterGUID() == pVictim->GetGUID())
6212 dummy = (*i);
6213 break;
6217 // original heal must be form beacon caster
6218 if (!dummy)
6219 return false;
6221 triggered_spell_id = 53652; // Beacon of Light
6222 basepoints0 = triggeredByAura->GetModifier()->m_amount*damage/100;
6224 // cast with original caster set but beacon to beacon for apply caster mods and avoid LoS check
6225 beacon->CastCustomSpell(beacon,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura,pVictim->GetGUID());
6226 return true;
6228 // Seal of Corruption (damage calc on apply aura)
6229 case 53736:
6231 if(effIndex != 0) // effect 1,2 used by seal unleashing code
6232 return false;
6234 // At melee attack or Hammer of the Righteous spell damage considered as melee attack
6235 if ((procFlag & PROC_FLAG_SUCCESSFUL_MELEE_HIT) || (procSpell && procSpell->Id == 53595))
6236 triggered_spell_id = 53742; // Blood Corruption
6238 // Add 5-stack effect from Blood Corruption
6239 int8 stacks = 0;
6240 AuraList const& auras = target->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
6241 for(AuraList::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr)
6243 if( ((*itr)->GetId() == 53742) && (*itr)->GetCasterGUID()==GetGUID())
6245 stacks = (*itr)->GetStackAmount();
6246 break;
6249 if(stacks >= 5)
6250 CastSpell(target,53739,true,NULL,triggeredByAura);
6251 break;
6253 // Glyph of Flash of Light
6254 case 54936:
6256 triggered_spell_id = 54957;
6257 basepoints0 = triggerAmount*damage/100;
6258 break;
6260 // Glyph of Holy Light
6261 case 54937:
6263 triggered_spell_id = 54968;
6264 basepoints0 = triggerAmount*damage/100;
6265 break;
6267 // Glyph of Divinity
6268 case 54939:
6270 // Lookup base amount mana restore
6271 for (int i=0; i<3;++i)
6272 if (procSpell->Effect[i] == SPELL_EFFECT_ENERGIZE)
6274 int32 mana = procSpell->EffectBasePoints[i];
6275 CastCustomSpell(this, 54986, NULL, &mana, NULL, true, castItem, triggeredByAura);
6276 break;
6278 return true;
6280 // Sacred Shield (buff)
6281 case 58597:
6283 triggered_spell_id = 66922;
6284 SpellEntry const* triggeredEntry = sSpellStore.LookupEntry(triggered_spell_id);
6285 if (!triggeredEntry)
6286 return false;
6288 basepoints0 = int32(damage / (GetSpellDuration(triggeredEntry) / triggeredEntry->EffectAmplitude[0]));
6289 target = this;
6290 break;
6292 // Sacred Shield (talent rank)
6293 case 53601:
6295 triggered_spell_id = 58597;
6296 target = this;
6297 break;
6300 break;
6302 case SPELLFAMILY_SHAMAN:
6304 switch(dummySpell->Id)
6306 // Totemic Power (The Earthshatterer set)
6307 case 28823:
6309 if( !pVictim )
6310 return false;
6312 // Set class defined buff
6313 switch (pVictim->getClass())
6315 case CLASS_PALADIN:
6316 case CLASS_PRIEST:
6317 case CLASS_SHAMAN:
6318 case CLASS_DRUID:
6319 triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
6320 break;
6321 case CLASS_MAGE:
6322 case CLASS_WARLOCK:
6323 triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
6324 break;
6325 case CLASS_HUNTER:
6326 case CLASS_ROGUE:
6327 triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d.
6328 break;
6329 case CLASS_WARRIOR:
6330 triggered_spell_id = 28827; // Increases the friendly target's armor
6331 break;
6332 default:
6333 return false;
6335 break;
6337 // Lesser Healing Wave (Totem of Flowing Water Relic)
6338 case 28849:
6340 target = this;
6341 triggered_spell_id = 28850;
6342 break;
6344 // Windfury Weapon (Passive) 1-5 Ranks
6345 case 33757:
6347 if(GetTypeId()!=TYPEID_PLAYER)
6348 return false;
6350 if(!castItem || !castItem->IsEquipped())
6351 return false;
6353 // custom cooldown processing case
6354 if( cooldown && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
6355 return false;
6357 // Now amount of extra power stored in 1 effect of Enchant spell
6358 // Get it by item enchant id
6359 uint32 spellId;
6360 switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)))
6362 case 283: spellId = 8232; break; // 1 Rank
6363 case 284: spellId = 8235; break; // 2 Rank
6364 case 525: spellId = 10486; break; // 3 Rank
6365 case 1669:spellId = 16362; break; // 4 Rank
6366 case 2636:spellId = 25505; break; // 5 Rank
6367 case 3785:spellId = 58801; break; // 6 Rank
6368 case 3786:spellId = 58803; break; // 7 Rank
6369 case 3787:spellId = 58804; break; // 8 Rank
6370 default:
6372 sLog.outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)",
6373 castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)),dummySpell->Id);
6374 return false;
6378 SpellEntry const* windfurySpellEntry = sSpellStore.LookupEntry(spellId);
6379 if(!windfurySpellEntry)
6381 sLog.outError("Unit::HandleDummyAuraProc: non existed spell id: %u (Windfury)",spellId);
6382 return false;
6385 int32 extra_attack_power = CalculateSpellDamage(windfurySpellEntry, 1, windfurySpellEntry->EffectBasePoints[1], pVictim);
6387 // Off-Hand case
6388 if ( castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
6390 // Value gained from additional AP
6391 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(OFF_ATTACK)/1000/2);
6392 triggered_spell_id = 33750;
6394 // Main-Hand case
6395 else
6397 // Value gained from additional AP
6398 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(BASE_ATTACK)/1000);
6399 triggered_spell_id = 25504;
6402 // apply cooldown before cast to prevent processing itself
6403 if( cooldown )
6404 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
6406 // Attack Twice
6407 for ( uint32 i = 0; i<2; ++i )
6408 CastCustomSpell(pVictim,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
6410 return true;
6412 // Shaman Tier 6 Trinket
6413 case 40463:
6415 if( !procSpell )
6416 return false;
6418 float chance;
6419 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000001))
6421 triggered_spell_id = 40465; // Lightning Bolt
6422 chance = 15.0f;
6424 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080))
6426 triggered_spell_id = 40465; // Lesser Healing Wave
6427 chance = 10.0f;
6429 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000001000000000))
6431 triggered_spell_id = 40466; // Stormstrike
6432 chance = 50.0f;
6434 else
6435 return false;
6437 if (!roll_chance_f(chance))
6438 return false;
6440 target = this;
6441 break;
6443 // Glyph of Healing Wave
6444 case 55440:
6446 // Not proc from self heals
6447 if (this==pVictim)
6448 return false;
6449 basepoints0 = triggerAmount * damage / 100;
6450 target = this;
6451 triggered_spell_id = 55533;
6452 break;
6454 // Spirit Hunt
6455 case 58877:
6457 // Cast on owner
6458 target = GetOwner();
6459 if(!target)
6460 return false;
6461 basepoints0 = triggerAmount * damage / 100;
6462 triggered_spell_id = 58879;
6463 break;
6465 // Shaman T8 Elemental 4P Bonus
6466 case 64928:
6468 basepoints0 = int32( triggerAmount * damage / 100 );
6469 triggered_spell_id = 64930; // Electrified
6470 break;
6473 // Storm, Earth and Fire
6474 if (dummySpell->SpellIconID == 3063)
6476 // Earthbind Totem summon only
6477 if(procSpell->Id != 2484)
6478 return false;
6480 float chance = triggerAmount;
6481 if (!roll_chance_f(chance))
6482 return false;
6484 triggered_spell_id = 64695;
6485 break;
6487 // Ancestral Awakening
6488 if (dummySpell->SpellIconID == 3065)
6490 triggered_spell_id = 52759;
6491 basepoints0 = triggerAmount * damage / 100;
6492 target = this;
6493 break;
6495 // Earth Shield
6496 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000040000000000))
6498 target = this;
6499 basepoints0 = triggerAmount;
6501 // Glyph of Earth Shield
6502 if (Aura* aur = GetDummyAura(63279))
6504 int32 aur_mod = aur->GetModifier()->m_amount;
6505 basepoints0 = int32(basepoints0 * (aur_mod + 100.0f) / 100.0f);
6508 triggered_spell_id = 379;
6509 break;
6511 // Improved Water Shield
6512 if (dummySpell->SpellIconID == 2287)
6514 // Lesser Healing Wave need aditional 60% roll
6515 if ((procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080)) && !roll_chance_i(60))
6516 return false;
6517 // lookup water shield
6518 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
6519 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
6521 if ((*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
6522 ((*itr)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000002000000000)))
6524 uint32 spell = (*itr)->GetSpellProto()->EffectTriggerSpell[(*itr)->GetEffIndex()];
6525 CastSpell(this, spell, true, castItem, triggeredByAura);
6526 if ((*itr)->DropAuraCharge())
6527 RemoveSingleSpellAurasFromStack((*itr)->GetId());
6528 return true;
6531 return false;
6532 break;
6534 // Lightning Overload
6535 if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura
6537 if(!procSpell || GetTypeId() != TYPEID_PLAYER || !pVictim )
6538 return false;
6540 // custom cooldown processing case
6541 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
6542 return false;
6544 uint32 spellId = 0;
6545 // Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost
6546 switch (procSpell->Id)
6548 // Lightning Bolt
6549 case 403: spellId = 45284; break; // Rank 1
6550 case 529: spellId = 45286; break; // Rank 2
6551 case 548: spellId = 45287; break; // Rank 3
6552 case 915: spellId = 45288; break; // Rank 4
6553 case 943: spellId = 45289; break; // Rank 5
6554 case 6041: spellId = 45290; break; // Rank 6
6555 case 10391: spellId = 45291; break; // Rank 7
6556 case 10392: spellId = 45292; break; // Rank 8
6557 case 15207: spellId = 45293; break; // Rank 9
6558 case 15208: spellId = 45294; break; // Rank 10
6559 case 25448: spellId = 45295; break; // Rank 11
6560 case 25449: spellId = 45296; break; // Rank 12
6561 case 49237: spellId = 49239; break; // Rank 13
6562 case 49238: spellId = 49240; break; // Rank 14
6563 // Chain Lightning
6564 case 421: spellId = 45297; break; // Rank 1
6565 case 930: spellId = 45298; break; // Rank 2
6566 case 2860: spellId = 45299; break; // Rank 3
6567 case 10605: spellId = 45300; break; // Rank 4
6568 case 25439: spellId = 45301; break; // Rank 5
6569 case 25442: spellId = 45302; break; // Rank 6
6570 case 49270: spellId = 49268; break; // Rank 7
6571 case 49271: spellId = 49269; break; // Rank 8
6572 default:
6573 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (LO)", procSpell->Id);
6574 return false;
6576 // No thread generated mod
6577 // TODO: exist special flag in spell attributes for this, need found and use!
6578 SpellModifier *mod = new SpellModifier(SPELLMOD_THREAT,SPELLMOD_PCT,-100,triggeredByAura);
6580 ((Player*)this)->AddSpellMod(mod, true);
6582 // Remove cooldown (Chain Lightning - have Category Recovery time)
6583 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000002))
6584 ((Player*)this)->RemoveSpellCooldown(spellId);
6586 CastSpell(pVictim, spellId, true, castItem, triggeredByAura);
6588 ((Player*)this)->AddSpellMod(mod, false);
6590 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6591 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
6593 return true;
6595 // Static Shock
6596 if(dummySpell->SpellIconID == 3059)
6598 // lookup Lightning Shield
6599 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
6600 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
6602 if ((*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
6603 ((*itr)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000000000400)))
6605 uint32 spell = 0;
6606 switch ((*itr)->GetId())
6608 case 324: spell = 26364; break;
6609 case 325: spell = 26365; break;
6610 case 905: spell = 26366; break;
6611 case 945: spell = 26367; break;
6612 case 8134: spell = 26369; break;
6613 case 10431: spell = 26370; break;
6614 case 10432: spell = 26363; break;
6615 case 25469: spell = 26371; break;
6616 case 25472: spell = 26372; break;
6617 case 49280: spell = 49278; break;
6618 case 49281: spell = 49279; break;
6619 default:
6620 return false;
6622 CastSpell(target, spell, true, castItem, triggeredByAura);
6623 if ((*itr)->DropAuraCharge())
6624 RemoveSingleSpellAurasFromStack((*itr)->GetId());
6625 return true;
6628 return false;
6630 // Frozen Power
6631 if (dummySpell->SpellIconID == 3780)
6633 Unit *caster = triggeredByAura->GetCaster();
6635 if (!procSpell || !caster)
6636 return false;
6638 float distance = caster->GetDistance(pVictim);
6639 int32 chance = triggerAmount;
6641 if (distance < 15.0f || !roll_chance_i(chance))
6642 return false;
6644 // make triggered cast apply after current damage spell processing for prevent remove by it
6645 if(Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
6646 spell->AddTriggeredSpell(63685);
6647 return true;
6649 break;
6651 case SPELLFAMILY_DEATHKNIGHT:
6653 // Blood Aura
6654 if (dummySpell->SpellIconID == 2636)
6656 if (GetTypeId() != TYPEID_PLAYER || !((Player*)this)->isHonorOrXPTarget(pVictim))
6657 return false;
6658 basepoints0 = triggerAmount * damage / 100;
6659 triggered_spell_id = 53168;
6660 break;
6662 // Butchery
6663 if (dummySpell->SpellIconID == 2664)
6665 basepoints0 = triggerAmount;
6666 triggered_spell_id = 50163;
6667 target = this;
6668 break;
6670 // Dancing Rune Weapon
6671 if (dummySpell->Id == 49028)
6673 // 1 dummy aura for dismiss rune blade
6674 if (effIndex!=2)
6675 return false;
6676 // TODO: wite script for this "fights on its own, doing the same attacks"
6677 // NOTE: Trigger here on every attack and spell cast
6678 return false;
6680 // Mark of Blood
6681 if (dummySpell->Id == 49005)
6683 // TODO: need more info (cooldowns/PPM)
6684 triggered_spell_id = 61607;
6685 break;
6687 // Vendetta
6688 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000000000010000))
6690 basepoints0 = triggerAmount * GetMaxHealth() / 100;
6691 triggered_spell_id = 50181;
6692 target = this;
6693 break;
6695 // Necrosis
6696 if (dummySpell->SpellIconID == 2709)
6698 basepoints0 = triggerAmount * damage / 100;
6699 triggered_spell_id = 51460;
6700 break;
6702 // Threat of Thassarian
6703 if (dummySpell->SpellIconID == 2023)
6705 // Must Dual Wield
6706 if (!procSpell || !haveOffhandWeapon())
6707 return false;
6708 // Chance as basepoints for dummy aura
6709 if (!roll_chance_i(triggerAmount))
6710 return false;
6712 switch (procSpell->Id)
6714 // Obliterate
6715 case 49020: // Rank 1
6716 triggered_spell_id = 66198; break;
6717 case 51423: // Rank 2
6718 triggered_spell_id = 66972; break;
6719 case 51424: // Rank 3
6720 triggered_spell_id = 66973; break;
6721 case 51425: // Rank 4
6722 triggered_spell_id = 66974; break;
6723 // Frost Strike
6724 case 49143: // Rank 1
6725 triggered_spell_id = 66196; break;
6726 case 51416: // Rank 2
6727 triggered_spell_id = 66958; break;
6728 case 51417: // Rank 3
6729 triggered_spell_id = 66959; break;
6730 case 51418: // Rank 4
6731 triggered_spell_id = 66960; break;
6732 case 51419: // Rank 5
6733 triggered_spell_id = 66961; break;
6734 case 51420: // Rank 6
6735 triggered_spell_id = 66962; break;
6736 // Plague Strike
6737 case 45462: // Rank 1
6738 triggered_spell_id = 66216; break;
6739 case 49917: // Rank 2
6740 triggered_spell_id = 66988; break;
6741 case 49918: // Rank 3
6742 triggered_spell_id = 66989; break;
6743 case 49919: // Rank 4
6744 triggered_spell_id = 66990; break;
6745 case 49920: // Rank 5
6746 triggered_spell_id = 66991; break;
6747 case 49921: // Rank 6
6748 triggered_spell_id = 66992; break;
6749 // Death Strike
6750 case 49998: // Rank 1
6751 triggered_spell_id = 66188; break;
6752 case 49999: // Rank 2
6753 triggered_spell_id = 66950; break;
6754 case 45463: // Rank 3
6755 triggered_spell_id = 66951; break;
6756 case 49923: // Rank 4
6757 triggered_spell_id = 66952; break;
6758 case 49924: // Rank 5
6759 triggered_spell_id = 66953; break;
6760 // Rune Strike
6761 case 56815:
6762 triggered_spell_id = 66217; break;
6763 // Blood Strike
6764 case 45902: // Rank 1
6765 triggered_spell_id = 66215; break;
6766 case 49926: // Rank 2
6767 triggered_spell_id = 66975; break;
6768 case 49927: // Rank 3
6769 triggered_spell_id = 66976; break;
6770 case 49928: // Rank 4
6771 triggered_spell_id = 66977; break;
6772 case 49929: // Rank 5
6773 triggered_spell_id = 66978; break;
6774 case 49930: // Rank 6
6775 triggered_spell_id = 66979; break;
6776 default:
6777 return false;
6779 break;
6781 // Runic Power Back on Snare/Root
6782 if (dummySpell->Id == 61257)
6784 // only for spells and hit/crit (trigger start always) and not start from self casted spells
6785 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
6786 return false;
6787 // Need snare or root mechanic
6788 if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_ROOT_AND_SNARE_MASK))
6789 return false;
6790 triggered_spell_id = 61258;
6791 target = this;
6792 break;
6794 // Wandering Plague
6795 if (dummySpell->SpellIconID == 1614)
6797 if (!roll_chance_f(GetUnitCriticalChance(BASE_ATTACK, pVictim)))
6798 return false;
6799 basepoints0 = triggerAmount * damage / 100;
6800 triggered_spell_id = 50526;
6801 break;
6803 // Blood-Caked Blade
6804 if (dummySpell->SpellIconID == 138)
6806 triggered_spell_id = dummySpell->EffectTriggerSpell[effIndex];
6807 break;
6809 break;
6811 default:
6812 break;
6815 // processed charge only counting case
6816 if(!triggered_spell_id)
6817 return true;
6819 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
6821 if(!triggerEntry)
6823 sLog.outError("Unit::HandleDummyAuraProc: Spell %u have not existed triggered spell %u",dummySpell->Id,triggered_spell_id);
6824 return false;
6827 // default case
6828 if(!target || target!=this && !target->isAlive())
6829 return false;
6831 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
6832 return false;
6834 if(basepoints0)
6835 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
6836 else
6837 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
6839 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6840 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
6842 return true;
6845 bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown)
6847 // Get triggered aura spell info
6848 SpellEntry const* auraSpellInfo = triggeredByAura->GetSpellProto();
6850 // Basepoints of trigger aura
6851 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
6853 // Set trigger spell id, target, custom basepoints
6854 uint32 trigger_spell_id = auraSpellInfo->EffectTriggerSpell[triggeredByAura->GetEffIndex()];
6855 Unit* target = NULL;
6856 int32 basepoints[3] = {0, 0, 0};
6858 if(triggeredByAura->GetModifier()->m_auraname == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE)
6859 basepoints[0] = triggerAmount;
6861 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
6862 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
6864 // Try handle unknown trigger spells
6865 // Custom requirements (not listed in procEx) Warning! damage dealing after this
6866 // Custom triggered spells
6867 switch (auraSpellInfo->SpellFamilyName)
6869 case SPELLFAMILY_GENERIC:
6870 switch(auraSpellInfo->Id)
6872 //case 191: // Elemental Response
6873 // switch (procSpell->School)
6874 // {
6875 // case SPELL_SCHOOL_FIRE: trigger_spell_id = 34192; break;
6876 // case SPELL_SCHOOL_FROST: trigger_spell_id = 34193; break;
6877 // case SPELL_SCHOOL_ARCANE:trigger_spell_id = 34194; break;
6878 // case SPELL_SCHOOL_NATURE:trigger_spell_id = 34195; break;
6879 // case SPELL_SCHOOL_SHADOW:trigger_spell_id = 34196; break;
6880 // case SPELL_SCHOOL_HOLY: trigger_spell_id = 34197; break;
6881 // case SPELL_SCHOOL_NORMAL:trigger_spell_id = 34198; break;
6882 // }
6883 // break;
6884 //case 5301: break; // Defensive State (DND)
6885 //case 7137: break: // Shadow Charge (Rank 1)
6886 //case 7377: break: // Take Immune Periodic Damage <Not Working>
6887 //case 13358: break; // Defensive State (DND)
6888 //case 16092: break; // Defensive State (DND)
6889 //case 18943: break; // Double Attack
6890 //case 19194: break; // Double Attack
6891 //case 19817: break; // Double Attack
6892 //case 19818: break; // Double Attack
6893 //case 22835: break; // Drunken Rage
6894 // trigger_spell_id = 14822; break;
6895 case 23780: // Aegis of Preservation (Aegis of Preservation trinket)
6896 trigger_spell_id = 23781;
6897 break;
6898 //case 24949: break; // Defensive State 2 (DND)
6899 case 27522: // Mana Drain Trigger
6900 case 40336: // Mana Drain Trigger
6901 // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target.
6902 if (isAlive())
6903 CastSpell(this, 29471, true, castItem, triggeredByAura);
6904 if (pVictim && pVictim->isAlive())
6905 CastSpell(pVictim, 27526, true, castItem, triggeredByAura);
6906 return true;
6907 case 31255: // Deadly Swiftness (Rank 1)
6908 // whenever you deal damage to a target who is below 20% health.
6909 if (pVictim->GetHealth() > pVictim->GetMaxHealth() / 5)
6910 return false;
6912 target = this;
6913 trigger_spell_id = 22588;
6914 break;
6915 //case 33207: break; // Gossip NPC Periodic - Fidget
6916 case 33896: // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher)
6917 trigger_spell_id = 33898;
6918 break;
6919 //case 34082: break; // Advantaged State (DND)
6920 //case 34783: break: // Spell Reflection
6921 //case 35205: break: // Vanish
6922 //case 35321: break; // Gushing Wound
6923 //case 36096: break: // Spell Reflection
6924 //case 36207: break: // Steal Weapon
6925 //case 36576: break: // Shaleskin (Shaleskin Flayer, Shaleskin Ripper) 30023 trigger
6926 //case 37030: break; // Chaotic Temperament
6927 //case 38363: break; // Gushing Wound
6928 //case 39215: break; // Gushing Wound
6929 //case 40250: break; // Improved Duration
6930 //case 40329: break; // Demo Shout Sensor
6931 //case 40364: break; // Entangling Roots Sensor
6932 //case 41054: break; // Copy Weapon
6933 // trigger_spell_id = 41055; break;
6934 //case 41248: break; // Consuming Strikes
6935 // trigger_spell_id = 41249; break;
6936 //case 42730: break: // Woe Strike
6937 //case 43453: break: // Rune Ward
6938 //case 43504: break; // Alterac Valley OnKill Proc Aura
6939 //case 44326: break: // Pure Energy Passive
6940 //case 44526: break; // Hate Monster (Spar) (30 sec)
6941 //case 44527: break; // Hate Monster (Spar Buddy) (30 sec)
6942 //case 44819: break; // Hate Monster (Spar Buddy) (>30% Health)
6943 //case 44820: break; // Hate Monster (Spar) (<30%)
6944 case 45057: // Evasive Maneuvers (Commendation of Kael`thas trinket)
6945 // reduce you below $s1% health
6946 if (GetHealth() - damage > GetMaxHealth() * triggerAmount / 100)
6947 return false;
6948 break;
6949 //case 45903: break: // Offensive State
6950 //case 46146: break: // [PH] Ahune Spanky Hands
6951 //case 46939: break; // Black Bow of the Betrayer
6952 // trigger_spell_id = 29471; - gain mana
6953 // 27526; - drain mana if possible
6954 case 43820: // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket)
6955 // Pct value stored in dummy
6956 basepoints[0] = pVictim->GetCreateHealth() * auraSpellInfo->EffectBasePoints[1] / 100;
6957 target = pVictim;
6958 break;
6959 //case 45205: break; // Copy Offhand Weapon
6960 //case 45343: break; // Dark Flame Aura
6961 //case 47300: break; // Dark Flame Aura
6962 //case 48876: break; // Beast's Mark
6963 // trigger_spell_id = 48877; break;
6964 //case 49059: break; // Horde, Hate Monster (Spar Buddy) (>30% Health)
6965 //case 50051: break; // Ethereal Pet Aura
6966 //case 50689: break; // Blood Presence (Rank 1)
6967 //case 50844: break; // Blood Mirror
6968 //case 52856: break; // Charge
6969 //case 54072: break; // Knockback Ball Passive
6970 //case 54476: break; // Blood Presence
6971 //case 54775: break; // Abandon Vehicle on Poly
6972 case 57345: // Darkmoon Card: Greatness
6974 float stat = 0.0f;
6975 // strength
6976 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); }
6977 // agility
6978 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); }
6979 // intellect
6980 if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);}
6981 // spirit
6982 if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235; }
6983 break;
6985 //case 55580: break: // Mana Link
6986 //case 57587: break: // Steal Ranged ()
6987 //case 57594: break; // Copy Ranged Weapon
6988 //case 59237: break; // Beast's Mark
6989 // trigger_spell_id = 59233; break;
6990 //case 59288: break; // Infra-Green Shield
6991 //case 59532: break; // Abandon Passengers on Poly
6992 //case 59735: break: // Woe Strike
6993 case 67702: // Death's Choice, Item - Coliseum 25 Normal Melee Trinket
6995 float stat = 0.0f;
6996 // strength
6997 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67708;stat = GetStat(STAT_STRENGTH); }
6998 // agility
6999 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67703; }
7000 break;
7002 case 67771: // Death's Choice (heroic), Item - Coliseum 25 Heroic Melee Trinket
7004 float stat = 0.0f;
7005 // strength
7006 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67773;stat = GetStat(STAT_STRENGTH); }
7007 // agility
7008 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67772; }
7009 break;
7012 break;
7013 case SPELLFAMILY_MAGE:
7014 if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed
7016 switch (auraSpellInfo->Id)
7018 case 31641: // Rank 1
7019 case 31642: // Rank 2
7020 trigger_spell_id = 31643;
7021 break;
7022 default:
7023 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blazing Speed",auraSpellInfo->Id);
7024 return false;
7027 // Persistent Shield (Scarab Brooch trinket)
7028 else if(auraSpellInfo->Id == 26467)
7030 // This spell originally trigger 13567 - Dummy Trigger (vs dummy efect)
7031 basepoints[0] = damage * 15 / 100;
7032 target = pVictim;
7033 trigger_spell_id = 26470;
7035 break;
7036 case SPELLFAMILY_WARRIOR:
7037 // Deep Wounds (replace triggered spells to directly apply DoT), dot spell have finilyflags
7038 if (auraSpellInfo->SpellFamilyFlags == UI64LIT(0x0) && auraSpellInfo->SpellIconID == 243)
7040 float weaponDamage;
7041 // DW should benefit of attack power, damage percent mods etc.
7042 // TODO: check if using offhand damage is correct and if it should be divided by 2
7043 if (haveOffhandWeapon() && getAttackTimer(BASE_ATTACK) > getAttackTimer(OFF_ATTACK))
7044 weaponDamage = (GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE) + GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE))/2;
7045 else
7046 weaponDamage = (GetFloatValue(UNIT_FIELD_MINDAMAGE) + GetFloatValue(UNIT_FIELD_MAXDAMAGE))/2;
7048 switch (auraSpellInfo->Id)
7050 case 12834: basepoints[0] = int32(weaponDamage * 16 / 100); break;
7051 case 12849: basepoints[0] = int32(weaponDamage * 32 / 100); break;
7052 case 12867: basepoints[0] = int32(weaponDamage * 48 / 100); break;
7053 // Impossible case
7054 default:
7055 sLog.outError("Unit::HandleProcTriggerSpell: DW unknown spell rank %u",auraSpellInfo->Id);
7056 return false;
7059 // 1 tick/sec * 6 sec = 6 ticks
7060 basepoints[0] /= 6;
7062 trigger_spell_id = 12721;
7063 break;
7065 if (auraSpellInfo->Id == 50421) // Scent of Blood
7066 trigger_spell_id = 50422;
7067 break;
7068 case SPELLFAMILY_WARLOCK:
7070 // Pyroclasm
7071 if (auraSpellInfo->SpellIconID == 1137)
7073 if(!pVictim || !pVictim->isAlive() || pVictim == this || procSpell == NULL)
7074 return false;
7075 // Calculate spell tick count for spells
7076 uint32 tick = 1; // Default tick = 1
7078 // Hellfire have 15 tick
7079 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000040))
7080 tick = 15;
7081 // Rain of Fire have 4 tick
7082 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000020))
7083 tick = 4;
7084 else
7085 return false;
7087 // Calculate chance = baseChance / tick
7088 float chance = 0;
7089 switch (auraSpellInfo->Id)
7091 case 18096: chance = 13.0f / tick; break;
7092 case 18073: chance = 26.0f / tick; break;
7094 // Roll chance
7095 if (!roll_chance_f(chance))
7096 return false;
7098 trigger_spell_id = 18093;
7100 // Drain Soul
7101 else if (auraSpellInfo->SpellFamilyFlags & UI64LIT(0x0000000000004000))
7103 Unit::AuraList const& mAddFlatModifier = GetAurasByType(SPELL_AURA_ADD_FLAT_MODIFIER);
7104 for(Unit::AuraList::const_iterator i = mAddFlatModifier.begin(); i != mAddFlatModifier.end(); ++i)
7106 if ((*i)->GetModifier()->m_miscvalue == SPELLMOD_CHANCE_OF_SUCCESS && (*i)->GetSpellProto()->SpellIconID == 113)
7108 // Drain Soul
7109 CastCustomSpell(this, 18371, &basepoints[0], NULL, NULL, true, castItem, triggeredByAura);
7110 break;
7113 // Not remove charge (aura removed on death in any cases)
7114 // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura
7115 return false;
7117 // Nether Protection
7118 else if (auraSpellInfo->SpellIconID == 1985)
7120 if (!procSpell)
7121 return false;
7122 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
7124 case SPELL_SCHOOL_NORMAL:
7125 return false; // ignore
7126 case SPELL_SCHOOL_HOLY: trigger_spell_id = 54370; break;
7127 case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break;
7128 case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break;
7129 case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break;
7130 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break;
7131 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
7132 default:
7133 return false;
7136 // Cheat Death
7137 else if (auraSpellInfo->Id == 28845)
7139 // When your health drops below 20% ....
7140 if (GetHealth() - damage > GetMaxHealth() / 5 || GetHealth() < GetMaxHealth() / 5)
7141 return false;
7143 // Decimation
7144 else if (auraSpellInfo->Id == 63156 || auraSpellInfo->Id == 63158)
7146 // Looking for dummy effect
7147 Aura *aur = GetAura(auraSpellInfo->Id, 1);
7148 if (!aur)
7149 return false;
7151 // If target's health is not below equal certain value (35%) not proc
7152 if ((pVictim->GetHealth() * 100 / pVictim->GetMaxHealth()) > aur->GetModifier()->m_amount)
7153 return false;
7155 break;
7157 case SPELLFAMILY_PRIEST:
7159 // Greater Heal Refund (Avatar Raiment set)
7160 if (auraSpellInfo->Id==37594)
7162 // Not give if target already have full health
7163 if (pVictim->GetHealth() == pVictim->GetMaxHealth())
7164 return false;
7165 // If your Greater Heal brings the target to full health, you gain $37595s1 mana.
7166 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
7167 return false;
7168 trigger_spell_id = 37595;
7170 // Blessed Recovery
7171 else if (auraSpellInfo->SpellIconID == 1875)
7173 switch (auraSpellInfo->Id)
7175 case 27811: trigger_spell_id = 27813; break;
7176 case 27815: trigger_spell_id = 27817; break;
7177 case 27816: trigger_spell_id = 27818; break;
7178 default:
7179 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id);
7180 return false;
7182 basepoints[0] = damage * triggerAmount / 100 / 3;
7183 target = this;
7185 break;
7187 case SPELLFAMILY_DRUID:
7189 // Druid Forms Trinket
7190 if (auraSpellInfo->Id==37336)
7192 switch(m_form)
7194 case FORM_NONE: trigger_spell_id = 37344;break;
7195 case FORM_CAT: trigger_spell_id = 37341;break;
7196 case FORM_BEAR:
7197 case FORM_DIREBEAR: trigger_spell_id = 37340;break;
7198 case FORM_TREE: trigger_spell_id = 37342;break;
7199 case FORM_MOONKIN: trigger_spell_id = 37343;break;
7200 default:
7201 return false;
7204 // Druid T9 Feral Relic (Lacerate, Swipe, Mangle, and Shred)
7205 else if (auraSpellInfo->Id==67353)
7207 switch(m_form)
7209 case FORM_CAT: trigger_spell_id = 67355; break;
7210 case FORM_BEAR:
7211 case FORM_DIREBEAR: trigger_spell_id = 67354; break;
7212 default:
7213 return false;
7216 break;
7218 case SPELLFAMILY_HUNTER:
7219 // Piercing Shots
7220 if (auraSpellInfo->SpellIconID == 3247 && auraSpellInfo->SpellVisual[0] == 0)
7222 basepoints[0] = damage * triggerAmount / 100 / 8;
7223 trigger_spell_id = 63468;
7224 target = pVictim;
7226 // Rapid Recuperation
7227 else if (auraSpellInfo->Id == 53228 || auraSpellInfo->Id == 53232)
7229 // This effect only from Rapid Fire (ability cast)
7230 if (!(procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000020)))
7231 return false;
7233 break;
7234 case SPELLFAMILY_PALADIN:
7237 // Blessed Life
7238 if (auraSpellInfo->SpellIconID == 2137)
7240 switch (auraSpellInfo->Id)
7242 case 31828: // Rank 1
7243 case 31829: // Rank 2
7244 case 31830: // Rank 3
7245 break;
7246 default:
7247 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blessed Life", auraSpellInfo->Id);
7248 return false;
7252 // Healing Discount
7253 if (auraSpellInfo->Id==37705)
7255 trigger_spell_id = 37706;
7256 target = this;
7258 // Soul Preserver
7259 if (auraSpellInfo->Id==60510)
7261 trigger_spell_id = 60515;
7262 target = this;
7264 // Illumination
7265 else if (auraSpellInfo->SpellIconID==241)
7267 if(!procSpell)
7268 return false;
7269 // procspell is triggered spell but we need mana cost of original casted spell
7270 uint32 originalSpellId = procSpell->Id;
7271 // Holy Shock heal
7272 if (procSpell->SpellFamilyFlags & UI64LIT(0x0001000000000000))
7274 switch(procSpell->Id)
7276 case 25914: originalSpellId = 20473; break;
7277 case 25913: originalSpellId = 20929; break;
7278 case 25903: originalSpellId = 20930; break;
7279 case 27175: originalSpellId = 27174; break;
7280 case 33074: originalSpellId = 33072; break;
7281 case 48820: originalSpellId = 48824; break;
7282 case 48821: originalSpellId = 48825; break;
7283 default:
7284 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in HShock",procSpell->Id);
7285 return false;
7288 SpellEntry const *originalSpell = sSpellStore.LookupEntry(originalSpellId);
7289 if(!originalSpell)
7291 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu",originalSpellId);
7292 return false;
7294 // percent stored in effect 1 (class scripts) base points
7295 int32 cost = originalSpell->manaCost + originalSpell->ManaCostPercentage * GetCreateMana() / 100;
7296 basepoints[0] = cost*auraSpellInfo->CalculateSimpleValue(1)/100;
7297 trigger_spell_id = 20272;
7298 target = this;
7300 // Lightning Capacitor
7301 else if (auraSpellInfo->Id==37657)
7303 if(!pVictim || !pVictim->isAlive())
7304 return false;
7305 // stacking
7306 CastSpell(this, 37658, true, NULL, triggeredByAura);
7308 Aura * dummy = GetDummyAura(37658);
7309 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
7310 if(!dummy || dummy->GetStackAmount() < triggerAmount)
7311 return false;
7313 RemoveAurasDueToSpell(37658);
7314 trigger_spell_id = 37661;
7315 target = pVictim;
7317 // Bonus Healing (Crystal Spire of Karabor mace)
7318 else if (auraSpellInfo->Id == 40971)
7320 // If your target is below $s1% health
7321 if (pVictim->GetHealth() > pVictim->GetMaxHealth() * triggerAmount / 100)
7322 return false;
7324 // Thunder Capacitor
7325 else if (auraSpellInfo->Id == 54841)
7327 if(!pVictim || !pVictim->isAlive())
7328 return false;
7329 // stacking
7330 CastSpell(this, 54842, true, NULL, triggeredByAura);
7332 // counting
7333 Aura * dummy = GetDummyAura(54842);
7334 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
7335 if(!dummy || dummy->GetStackAmount() < triggerAmount)
7336 return false;
7338 RemoveAurasDueToSpell(54842);
7339 trigger_spell_id = 54843;
7340 target = pVictim;
7342 break;
7344 case SPELLFAMILY_SHAMAN:
7346 // Lightning Shield (overwrite non existing triggered spell call in spell.dbc
7347 if (auraSpellInfo->SpellFamilyFlags & UI64LIT(0x0000000000000400))
7349 switch(auraSpellInfo->Id)
7351 case 324: // Rank 1
7352 trigger_spell_id = 26364; break;
7353 case 325: // Rank 2
7354 trigger_spell_id = 26365; break;
7355 case 905: // Rank 3
7356 trigger_spell_id = 26366; break;
7357 case 945: // Rank 4
7358 trigger_spell_id = 26367; break;
7359 case 8134: // Rank 5
7360 trigger_spell_id = 26369; break;
7361 case 10431: // Rank 6
7362 trigger_spell_id = 26370; break;
7363 case 10432: // Rank 7
7364 trigger_spell_id = 26363; break;
7365 case 25469: // Rank 8
7366 trigger_spell_id = 26371; break;
7367 case 25472: // Rank 9
7368 trigger_spell_id = 26372; break;
7369 case 49280: // Rank 10
7370 trigger_spell_id = 49278; break;
7371 case 49281: // Rank 11
7372 trigger_spell_id = 49279; break;
7373 default:
7374 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in LShield", auraSpellInfo->Id);
7375 return false;
7378 // Lightning Shield (The Ten Storms set)
7379 else if (auraSpellInfo->Id == 23551)
7381 trigger_spell_id = 23552;
7382 target = pVictim;
7384 // Damage from Lightning Shield (The Ten Storms set)
7385 else if (auraSpellInfo->Id == 23552)
7386 trigger_spell_id = 27635;
7387 // Mana Surge (The Earthfury set)
7388 else if (auraSpellInfo->Id == 23572)
7390 if(!procSpell)
7391 return false;
7392 basepoints[0] = procSpell->manaCost * 35 / 100;
7393 trigger_spell_id = 23571;
7394 target = this;
7396 // Nature's Guardian
7397 else if (auraSpellInfo->SpellIconID == 2013)
7399 // Check health condition - should drop to less 30% (damage deal after this!)
7400 if (!(10*(int32(GetHealth() - damage)) < 3 * GetMaxHealth()))
7401 return false;
7403 if(pVictim && pVictim->isAlive())
7404 pVictim->getThreatManager().modifyThreatPercent(this,-10);
7406 basepoints[0] = triggerAmount * GetMaxHealth() / 100;
7407 trigger_spell_id = 31616;
7408 target = this;
7410 break;
7412 case SPELLFAMILY_DEATHKNIGHT:
7414 // Acclimation
7415 if (auraSpellInfo->SpellIconID == 1930)
7417 if (!procSpell)
7418 return false;
7419 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
7421 case SPELL_SCHOOL_NORMAL:
7422 return false; // ignore
7423 case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break;
7424 case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break;
7425 case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break;
7426 case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break;
7427 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break;
7428 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 50486; break;
7429 default:
7430 return false;
7433 // Blood Presence
7434 else if (auraSpellInfo->Id == 48266)
7436 if (GetTypeId() != TYPEID_PLAYER)
7437 return false;
7438 if (!((Player*)this)->isHonorOrXPTarget(pVictim))
7439 return false;
7440 trigger_spell_id = 50475;
7441 basepoints[0] = damage * triggerAmount / 100;
7443 // Blade Barrier
7444 else if (auraSpellInfo->SpellIconID == 85)
7446 if (GetTypeId() != TYPEID_PLAYER || getClass() != CLASS_DEATH_KNIGHT ||
7447 !((Player*)this)->IsBaseRuneSlotsOnCooldown(RUNE_BLOOD))
7448 return false;
7450 break;
7452 default:
7453 break;
7456 // All ok. Check current trigger spell
7457 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(trigger_spell_id);
7458 if (!triggerEntry)
7460 // Not cast unknown spell
7461 // sLog.outError("Unit::HandleProcTriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?",auraSpellInfo->Id,triggeredByAura->GetEffIndex());
7462 return false;
7465 // not allow proc extra attack spell at extra attack
7466 if (m_extraAttacks && IsSpellHaveEffect(triggerEntry, SPELL_EFFECT_ADD_EXTRA_ATTACKS))
7467 return false;
7469 // Custom basepoints/target for exist spell
7470 // dummy basepoints or other customs
7471 switch(trigger_spell_id)
7473 // Cast positive spell on enemy target
7474 case 7099: // Curse of Mending
7475 case 39647: // Curse of Mending
7476 case 29494: // Temptation
7477 case 20233: // Improved Lay on Hands (cast on target)
7479 target = pVictim;
7480 break;
7482 // Combo points add triggers (need add combopoint only for main target, and after possible combopoints reset)
7483 case 15250: // Rogue Setup
7485 if(!pVictim || pVictim != getVictim()) // applied only for main target
7486 return false;
7487 break; // continue normal case
7489 // Finish movies that add combo
7490 case 14189: // Seal Fate (Netherblade set)
7491 case 14157: // Ruthlessness
7493 // Need add combopoint AFTER finish movie (or they dropped in finish phase)
7494 break;
7496 // Bloodthirst (($m/100)% of max health)
7497 case 23880:
7499 basepoints[0] = int32(GetMaxHealth() * triggerAmount / 100);
7500 break;
7502 // Shamanistic Rage triggered spell
7503 case 30824:
7505 basepoints[0] = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
7506 break;
7508 // Enlightenment (trigger only from mana cost spells)
7509 case 35095:
7511 if(!procSpell || procSpell->powerType!=POWER_MANA || procSpell->manaCost==0 && procSpell->ManaCostPercentage==0 && procSpell->manaCostPerlevel==0)
7512 return false;
7513 break;
7515 // Demonic Pact
7516 case 48090:
7518 // As the spell is proced from pet's attack - find owner
7519 Unit* owner = GetOwner();
7520 if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
7521 return false;
7523 // This spell doesn't stack, but refreshes duration. So we receive current bonuses to minus them later.
7524 int32 curBonus = 0;
7525 if (Aura* aur = owner->GetAura(48090,0))
7526 curBonus = aur->GetModifier()->m_amount;
7527 int32 spellDamage = owner->SpellBaseDamageBonus(SPELL_SCHOOL_MASK_MAGIC) - curBonus;
7528 if(spellDamage <= 0)
7529 return false;
7531 // percent stored in owner talent dummy
7532 AuraList const& dummyAuras = owner->GetAurasByType(SPELL_AURA_DUMMY);
7533 for (AuraList::const_iterator i = dummyAuras.begin(); i != dummyAuras.end(); ++i)
7535 if ((*i)->GetSpellProto()->SpellIconID == 3220)
7537 basepoints[0] = basepoints[1] = int32(spellDamage * (*i)->GetModifier()->m_amount / 100);
7538 break;
7541 break;
7543 // Sword and Board
7544 case 50227:
7546 // Remove cooldown on Shield Slam
7547 if (GetTypeId() == TYPEID_PLAYER)
7548 ((Player*)this)->RemoveSpellCategoryCooldown(1209, true);
7549 break;
7551 // Maelstrom Weapon
7552 case 53817:
7554 // have rank dependent proc chance, ignore too often cases
7555 // PPM = 2.5 * (rank of talent),
7556 uint32 rank = sSpellMgr.GetSpellRank(auraSpellInfo->Id);
7557 // 5 rank -> 100% 4 rank -> 80% and etc from full rate
7558 if(!roll_chance_i(20*rank))
7559 return false;
7560 break;
7562 // Brain Freeze
7563 case 57761:
7565 if(!procSpell)
7566 return false;
7567 // For trigger from Blizzard need exist Improved Blizzard
7568 if (procSpell->SpellFamilyName==SPELLFAMILY_MAGE && (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080)))
7570 bool found = false;
7571 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7572 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7574 int32 script = (*i)->GetModifier()->m_miscvalue;
7575 if(script==836 || script==988 || script==989)
7577 found=true;
7578 break;
7581 if(!found)
7582 return false;
7584 break;
7586 // Astral Shift
7587 case 52179:
7589 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
7590 return false;
7592 // Need stun, fear or silence mechanic
7593 if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_SILENCE_AND_STUN_AND_FEAR_MASK))
7594 return false;
7595 break;
7597 // Burning Determination
7598 case 54748:
7600 if(!procSpell)
7601 return false;
7602 // Need Interrupt or Silenced mechanic
7603 if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_INTERRUPT_AND_SILENCE_MASK))
7604 return false;
7605 break;
7607 // Lock and Load
7608 case 56453:
7610 // Proc only from trap activation (from periodic proc another aura of this spell)
7611 if (!(procFlags & PROC_FLAG_ON_TRAP_ACTIVATION) || !roll_chance_i(triggerAmount))
7612 return false;
7613 break;
7615 // Druid - Savage Defense
7616 case 62606:
7618 basepoints[0] = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
7619 break;
7623 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(trigger_spell_id))
7624 return false;
7626 // try detect target manually if not set
7627 if ( target == NULL )
7628 target = !(procFlags & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) && IsPositiveSpell(trigger_spell_id) ? this : pVictim;
7630 // default case
7631 if(!target || target!=this && !target->isAlive())
7632 return false;
7634 if(basepoints[0] || basepoints[1] || basepoints[2])
7635 CastCustomSpell(target,trigger_spell_id,
7636 basepoints[0] ? &basepoints[0] : NULL,
7637 basepoints[1] ? &basepoints[1] : NULL,
7638 basepoints[2] ? &basepoints[2] : NULL,
7639 true,castItem,triggeredByAura);
7640 else
7641 CastSpell(target,trigger_spell_id,true,castItem,triggeredByAura);
7643 if( cooldown && GetTypeId()==TYPEID_PLAYER )
7644 ((Player*)this)->AddSpellCooldown(trigger_spell_id,0,time(NULL) + cooldown);
7646 return true;
7649 bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, uint32 damage, Aura *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown)
7651 int32 scriptId = triggeredByAura->GetModifier()->m_miscvalue;
7653 if(!pVictim || !pVictim->isAlive())
7654 return false;
7656 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
7657 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
7659 // Basepoints of trigger aura
7660 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
7662 uint32 triggered_spell_id = 0;
7664 switch(scriptId)
7666 case 836: // Improved Blizzard (Rank 1)
7668 if (!procSpell || procSpell->SpellVisual[0]!=9487)
7669 return false;
7670 triggered_spell_id = 12484;
7671 break;
7673 case 988: // Improved Blizzard (Rank 2)
7675 if (!procSpell || procSpell->SpellVisual[0]!=9487)
7676 return false;
7677 triggered_spell_id = 12485;
7678 break;
7680 case 989: // Improved Blizzard (Rank 3)
7682 if (!procSpell || procSpell->SpellVisual[0]!=9487)
7683 return false;
7684 triggered_spell_id = 12486;
7685 break;
7687 case 4086: // Improved Mend Pet (Rank 1)
7688 case 4087: // Improved Mend Pet (Rank 2)
7690 if(!roll_chance_i(triggerAmount))
7691 return false;
7693 triggered_spell_id = 24406;
7694 break;
7696 case 4533: // Dreamwalker Raiment 2 pieces bonus
7698 // Chance 50%
7699 if (!roll_chance_i(50))
7700 return false;
7702 switch (pVictim->getPowerType())
7704 case POWER_MANA: triggered_spell_id = 28722; break;
7705 case POWER_RAGE: triggered_spell_id = 28723; break;
7706 case POWER_ENERGY: triggered_spell_id = 28724; break;
7707 default:
7708 return false;
7710 break;
7712 case 4537: // Dreamwalker Raiment 6 pieces bonus
7713 triggered_spell_id = 28750; // Blessing of the Claw
7714 break;
7715 case 5497: // Improved Mana Gems (Serpent-Coil Braid)
7716 triggered_spell_id = 37445; // Mana Surge
7717 break;
7718 case 6953: // Warbringer
7719 RemoveAurasAtMechanicImmunity(IMMUNE_TO_ROOT_AND_SNARE_MASK,0,true);
7720 return true;
7721 case 7010: // Revitalize (rank 1)
7722 case 7011: // Revitalize (rank 2)
7723 case 7012: // Revitalize (rank 3)
7725 if(!roll_chance_i(triggerAmount))
7726 return false;
7728 switch( pVictim->getPowerType() )
7730 case POWER_MANA: triggered_spell_id = 48542; break;
7731 case POWER_RAGE: triggered_spell_id = 48541; break;
7732 case POWER_ENERGY: triggered_spell_id = 48540; break;
7733 case POWER_RUNIC_POWER: triggered_spell_id = 48543; break;
7734 default: return false;
7736 break;
7740 // not processed
7741 if(!triggered_spell_id)
7742 return false;
7744 // standard non-dummy case
7745 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
7747 if(!triggerEntry)
7749 sLog.outError("Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u",triggered_spell_id,scriptId);
7750 return false;
7753 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
7754 return false;
7756 CastSpell(pVictim, triggered_spell_id, true, castItem, triggeredByAura);
7758 if( cooldown && GetTypeId()==TYPEID_PLAYER )
7759 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
7761 return true;
7764 void Unit::setPowerType(Powers new_powertype)
7766 SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype);
7768 if(GetTypeId() == TYPEID_PLAYER)
7770 if(((Player*)this)->GetGroup())
7771 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE);
7773 else if(((Creature*)this)->isPet())
7775 Pet *pet = ((Pet*)this);
7776 if(pet->isControlled())
7778 Unit *owner = GetOwner();
7779 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
7780 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE);
7784 switch(new_powertype)
7786 default:
7787 case POWER_MANA:
7788 break;
7789 case POWER_RAGE:
7790 SetMaxPower(POWER_RAGE,GetCreatePowers(POWER_RAGE));
7791 SetPower( POWER_RAGE,0);
7792 break;
7793 case POWER_FOCUS:
7794 SetMaxPower(POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
7795 SetPower( POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
7796 break;
7797 case POWER_ENERGY:
7798 SetMaxPower(POWER_ENERGY,GetCreatePowers(POWER_ENERGY));
7799 break;
7800 case POWER_HAPPINESS:
7801 SetMaxPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
7802 SetPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
7803 break;
7807 FactionTemplateEntry const* Unit::getFactionTemplateEntry() const
7809 FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry(getFaction());
7810 if(!entry)
7812 static uint64 guid = 0; // prevent repeating spam same faction problem
7814 if(GetGUID() != guid)
7816 if(GetTypeId() == TYPEID_PLAYER)
7817 sLog.outError("Player %s have invalid faction (faction template id) #%u", ((Player*)this)->GetName(), getFaction());
7818 else
7819 sLog.outError("Creature (template id: %u) have invalid faction (faction template id) #%u", ((Creature*)this)->GetCreatureInfo()->Entry, getFaction());
7820 guid = GetGUID();
7823 return entry;
7826 bool Unit::IsHostileTo(Unit const* unit) const
7828 // always non-hostile to self
7829 if(unit==this)
7830 return false;
7832 // always non-hostile to GM in GM mode
7833 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
7834 return false;
7836 // always hostile to enemy
7837 if(getVictim()==unit || unit->getVictim()==this)
7838 return true;
7840 // test pet/charm masters instead pers/charmeds
7841 Unit const* testerOwner = GetCharmerOrOwner();
7842 Unit const* targetOwner = unit->GetCharmerOrOwner();
7844 // always hostile to owner's enemy
7845 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
7846 return true;
7848 // always hostile to enemy owner
7849 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
7850 return true;
7852 // always hostile to owner of owner's enemy
7853 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
7854 return true;
7856 Unit const* tester = testerOwner ? testerOwner : this;
7857 Unit const* target = targetOwner ? targetOwner : unit;
7859 // always non-hostile to target with common owner, or to owner/pet
7860 if(tester==target)
7861 return false;
7863 // special cases (Duel, etc)
7864 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
7866 Player const* pTester = (Player const*)tester;
7867 Player const* pTarget = (Player const*)target;
7869 // Duel
7870 if(pTester->duel && pTester->duel->opponent == pTarget && pTester->duel->startTime != 0)
7871 return true;
7873 // Group
7874 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
7875 return false;
7877 // Sanctuary
7878 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
7879 return false;
7881 // PvP FFA state
7882 if(pTester->IsFFAPvP() && pTarget->IsFFAPvP())
7883 return true;
7885 //= PvP states
7886 // Green/Blue (can't attack)
7887 if(pTester->GetTeam()==pTarget->GetTeam())
7888 return false;
7890 // Red (can attack) if true, Blue/Yellow (can't attack) in another case
7891 return pTester->IsPvP() && pTarget->IsPvP();
7894 // faction base cases
7895 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
7896 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
7897 if(!tester_faction || !target_faction)
7898 return false;
7900 if(target->isAttackingPlayer() && tester->IsContestedGuard())
7901 return true;
7903 // PvC forced reaction and reputation case
7904 if(tester->GetTypeId()==TYPEID_PLAYER)
7906 // forced reaction
7907 if(target_faction->faction)
7909 if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
7910 return *force <= REP_HOSTILE;
7912 // if faction have reputation then hostile state for tester at 100% dependent from at_war state
7913 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
7914 if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
7915 return (factionState->Flags & FACTION_FLAG_AT_WAR);
7918 // CvP forced reaction and reputation case
7919 else if(target->GetTypeId()==TYPEID_PLAYER)
7921 // forced reaction
7922 if(tester_faction->faction)
7924 if(ReputationRank const* force = ((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
7925 return *force <= REP_HOSTILE;
7927 // apply reputation state
7928 FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction);
7929 if(raw_tester_faction && raw_tester_faction->reputationListID >=0 )
7930 return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) <= REP_HOSTILE;
7934 // common faction based case (CvC,PvC,CvP)
7935 return tester_faction->IsHostileTo(*target_faction);
7938 bool Unit::IsFriendlyTo(Unit const* unit) const
7940 // always friendly to self
7941 if(unit==this)
7942 return true;
7944 // always friendly to GM in GM mode
7945 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
7946 return true;
7948 // always non-friendly to enemy
7949 if(getVictim()==unit || unit->getVictim()==this)
7950 return false;
7952 // test pet/charm masters instead pers/charmeds
7953 Unit const* testerOwner = GetCharmerOrOwner();
7954 Unit const* targetOwner = unit->GetCharmerOrOwner();
7956 // always non-friendly to owner's enemy
7957 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
7958 return false;
7960 // always non-friendly to enemy owner
7961 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
7962 return false;
7964 // always non-friendly to owner of owner's enemy
7965 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
7966 return false;
7968 Unit const* tester = testerOwner ? testerOwner : this;
7969 Unit const* target = targetOwner ? targetOwner : unit;
7971 // always friendly to target with common owner, or to owner/pet
7972 if(tester==target)
7973 return true;
7975 // special cases (Duel)
7976 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
7978 Player const* pTester = (Player const*)tester;
7979 Player const* pTarget = (Player const*)target;
7981 // Duel
7982 if(pTester->duel && pTester->duel->opponent == target && pTester->duel->startTime != 0)
7983 return false;
7985 // Group
7986 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
7987 return true;
7989 // Sanctuary
7990 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
7991 return true;
7993 // PvP FFA state
7994 if(pTester->IsFFAPvP() && pTarget->IsFFAPvP())
7995 return false;
7997 //= PvP states
7998 // Green/Blue (non-attackable)
7999 if(pTester->GetTeam()==pTarget->GetTeam())
8000 return true;
8002 // Blue (friendly/non-attackable) if not PVP, or Yellow/Red in another case (attackable)
8003 return !pTarget->IsPvP();
8006 // faction base cases
8007 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
8008 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
8009 if(!tester_faction || !target_faction)
8010 return false;
8012 if(target->isAttackingPlayer() && tester->IsContestedGuard())
8013 return false;
8015 // PvC forced reaction and reputation case
8016 if(tester->GetTypeId()==TYPEID_PLAYER)
8018 // forced reaction
8019 if(target_faction->faction)
8021 if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
8022 return *force >= REP_FRIENDLY;
8024 // if faction have reputation then friendly state for tester at 100% dependent from at_war state
8025 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
8026 if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
8027 return !(factionState->Flags & FACTION_FLAG_AT_WAR);
8030 // CvP forced reaction and reputation case
8031 else if(target->GetTypeId()==TYPEID_PLAYER)
8033 // forced reaction
8034 if(tester_faction->faction)
8036 if(ReputationRank const* force =((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
8037 return *force >= REP_FRIENDLY;
8039 // apply reputation state
8040 if(FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction))
8041 if(raw_tester_faction->reputationListID >=0 )
8042 return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) >= REP_FRIENDLY;
8046 // common faction based case (CvC,PvC,CvP)
8047 return tester_faction->IsFriendlyTo(*target_faction);
8050 bool Unit::IsHostileToPlayers() const
8052 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
8053 if(!my_faction || !my_faction->faction)
8054 return false;
8056 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
8057 if(raw_faction && raw_faction->reputationListID >=0 )
8058 return false;
8060 return my_faction->IsHostileToPlayers();
8063 bool Unit::IsNeutralToAll() const
8065 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
8066 if(!my_faction || !my_faction->faction)
8067 return true;
8069 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
8070 if(raw_faction && raw_faction->reputationListID >=0 )
8071 return false;
8073 return my_faction->IsNeutralToAll();
8076 bool Unit::Attack(Unit *victim, bool meleeAttack)
8078 if(!victim || victim == this)
8079 return false;
8081 // dead units can neither attack nor be attacked
8082 if(!isAlive() || !victim->IsInWorld() || !victim->isAlive())
8083 return false;
8085 // player cannot attack in mount state
8086 if(GetTypeId()==TYPEID_PLAYER && IsMounted())
8087 return false;
8089 // nobody can attack GM in GM-mode
8090 if(victim->GetTypeId()==TYPEID_PLAYER)
8092 if(((Player*)victim)->isGameMaster())
8093 return false;
8095 else
8097 if(((Creature*)victim)->IsInEvadeMode())
8098 return false;
8101 // remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack)
8102 if(HasAuraType(SPELL_AURA_MOD_UNATTACKABLE))
8103 RemoveSpellsCausingAura(SPELL_AURA_MOD_UNATTACKABLE);
8105 // in fighting already
8106 if (m_attacking)
8108 if (m_attacking == victim)
8110 // switch to melee attack from ranged/magic
8111 if( meleeAttack && !hasUnitState(UNIT_STAT_MELEE_ATTACKING) )
8113 addUnitState(UNIT_STAT_MELEE_ATTACKING);
8114 SendMeleeAttackStart(victim);
8115 return true;
8117 return false;
8120 // remove old target data
8121 AttackStop(true);
8123 // new battle
8124 else
8126 // set position before any AI calls/assistance
8127 if(GetTypeId()==TYPEID_UNIT)
8128 ((Creature*)this)->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ());
8131 // Set our target
8132 SetTargetGUID(victim->GetGUID());
8134 if(meleeAttack)
8135 addUnitState(UNIT_STAT_MELEE_ATTACKING);
8137 m_attacking = victim;
8138 m_attacking->_addAttacker(this);
8140 if (GetTypeId() == TYPEID_UNIT)
8142 ((Creature*)this)->SendAIReaction(AI_REACTION_AGGRO);
8143 ((Creature*)this)->CallAssistance();
8146 // delay offhand weapon attack to next attack time
8147 if(haveOffhandWeapon())
8148 resetAttackTimer(OFF_ATTACK);
8150 if(meleeAttack)
8151 SendMeleeAttackStart(victim);
8153 return true;
8156 bool Unit::AttackStop(bool targetSwitch /*=false*/)
8158 if (!m_attacking)
8159 return false;
8161 Unit* victim = m_attacking;
8163 m_attacking->_removeAttacker(this);
8164 m_attacking = NULL;
8166 // Clear our target
8167 SetTargetGUID(0);
8169 clearUnitState(UNIT_STAT_MELEE_ATTACKING);
8171 InterruptSpell(CURRENT_MELEE_SPELL);
8173 // reset only at real combat stop
8174 if(!targetSwitch && GetTypeId()==TYPEID_UNIT )
8176 ((Creature*)this)->SetNoCallAssistance(false);
8178 if (((Creature*)this)->HasSearchedAssistance())
8180 ((Creature*)this)->SetNoSearchAssistance(false);
8181 UpdateSpeed(MOVE_RUN, false);
8185 SendMeleeAttackStop(victim);
8187 return true;
8190 void Unit::CombatStop(bool includingCast)
8192 if (includingCast && IsNonMeleeSpellCasted(false))
8193 InterruptNonMeleeSpells(false);
8195 AttackStop();
8196 RemoveAllAttackers();
8197 if( GetTypeId()==TYPEID_PLAYER )
8198 ((Player*)this)->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel
8199 ClearInCombat();
8202 struct CombatStopWithPetsHelper
8204 explicit CombatStopWithPetsHelper(bool _includingCast) : includingCast(_includingCast) {}
8205 void operator()(Unit* unit) const { unit->CombatStop(includingCast); }
8206 bool includingCast;
8209 void Unit::CombatStopWithPets(bool includingCast)
8211 CombatStop(includingCast);
8212 CallForAllControlledUnits(CombatStopWithPetsHelper(includingCast),false,true,true);
8215 struct IsAttackingPlayerHelper
8217 explicit IsAttackingPlayerHelper() {}
8218 bool operator()(Unit* unit) const { return unit->isAttackingPlayer(); }
8221 bool Unit::isAttackingPlayer() const
8223 if(hasUnitState(UNIT_STAT_ATTACK_PLAYER))
8224 return true;
8226 return CheckAllControlledUnits(IsAttackingPlayerHelper(),true,true,true);
8229 void Unit::RemoveAllAttackers()
8231 while (!m_attackers.empty())
8233 AttackerSet::iterator iter = m_attackers.begin();
8234 if(!(*iter)->AttackStop())
8236 sLog.outError("WORLD: Unit has an attacker that isn't attacking it!");
8237 m_attackers.erase(iter);
8242 bool Unit::HasAuraStateForCaster(AuraState flag, uint64 caster) const
8244 if(!HasAuraState(flag))
8245 return false;
8247 // single per-caster aura state
8248 if(flag == AURA_STATE_CONFLAGRATE)
8250 Unit::AuraList const& dotList = GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
8251 for(Unit::AuraList::const_iterator i = dotList.begin(); i != dotList.end(); ++i)
8253 if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK &&
8254 (*i)->GetCasterGUID() == caster &&
8255 // Immolate
8256 (((*i)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000000000004)) ||
8257 // Shadowflame
8258 ((*i)->GetSpellProto()->SpellFamilyFlags2 & 0x00000002)))
8260 return true;
8264 return false;
8267 return true;
8270 void Unit::ModifyAuraState(AuraState flag, bool apply)
8272 if (apply)
8274 if (!HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)))
8276 SetFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
8277 if(GetTypeId() == TYPEID_PLAYER)
8279 const PlayerSpellMap& sp_list = ((Player*)this)->GetSpellMap();
8280 for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
8282 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
8283 SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first);
8284 if (!spellInfo || !IsPassiveSpell(itr->first)) continue;
8285 if (spellInfo->CasterAuraState == flag)
8286 CastSpell(this, itr->first, true, NULL);
8291 else
8293 if (HasFlag(UNIT_FIELD_AURASTATE,1<<(flag-1)))
8295 RemoveFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
8297 if (flag != AURA_STATE_ENRAGE) // enrage aura state triggering continues auras
8299 Unit::AuraMap& tAuras = GetAuras();
8300 for (Unit::AuraMap::iterator itr = tAuras.begin(); itr != tAuras.end();)
8302 SpellEntry const* spellProto = (*itr).second->GetSpellProto();
8303 if (spellProto->CasterAuraState == flag)
8305 // exceptions (applied at state but not removed at state change)
8306 // Rampage
8307 if(spellProto->SpellIconID==2006 && spellProto->SpellFamilyName==SPELLFAMILY_WARRIOR && spellProto->SpellFamilyFlags==0x100000)
8309 ++itr;
8310 continue;
8313 RemoveAura(itr);
8315 else
8316 ++itr;
8323 Unit *Unit::GetOwner() const
8325 if(uint64 ownerid = GetOwnerGUID())
8326 return ObjectAccessor::GetUnit(*this, ownerid);
8327 return NULL;
8330 Unit *Unit::GetCharmer() const
8332 if(uint64 charmerid = GetCharmerGUID())
8333 return ObjectAccessor::GetUnit(*this, charmerid);
8334 return NULL;
8337 Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself()
8339 uint64 guid = GetCharmerOrOwnerGUID();
8340 if(IS_PLAYER_GUID(guid))
8341 return ObjectAccessor::FindPlayer(guid);
8343 return GetTypeId()==TYPEID_PLAYER ? (Player*)this : NULL;
8346 Pet* Unit::GetPet() const
8348 if(uint64 pet_guid = GetPetGUID())
8350 if(Pet* pet = GetMap()->GetPet(pet_guid))
8351 return pet;
8353 sLog.outError("Unit::GetPet: Pet %u not exist.",GUID_LOPART(pet_guid));
8354 const_cast<Unit*>(this)->SetPet(0);
8357 return NULL;
8360 Unit* Unit::GetCharm() const
8362 if (uint64 charm_guid = GetCharmGUID())
8364 if(Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid))
8365 return pet;
8367 sLog.outError("Unit::GetCharm: Charmed creature %u not exist.",GUID_LOPART(charm_guid));
8368 const_cast<Unit*>(this)->SetCharm(NULL);
8371 return NULL;
8374 void Unit::Uncharm()
8376 if (Unit* charm = GetCharm())
8378 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
8379 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
8383 float Unit::GetCombatDistance( const Unit* target ) const
8385 float radius = target->GetFloatValue(UNIT_FIELD_COMBATREACH) + GetFloatValue(UNIT_FIELD_COMBATREACH);
8386 float dx = GetPositionX() - target->GetPositionX();
8387 float dy = GetPositionY() - target->GetPositionY();
8388 float dz = GetPositionZ() - target->GetPositionZ();
8389 float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - radius;
8390 return ( dist > 0 ? dist : 0);
8393 void Unit::SetPet(Pet* pet)
8395 SetPetGUID(pet ? pet->GetGUID() : 0);
8397 if(pet && GetTypeId() == TYPEID_PLAYER)
8398 ((Player*)this)->SendPetGUIDs();
8400 // FIXME: hack, speed must be set only at follow
8401 if(pet && GetTypeId()==TYPEID_PLAYER)
8402 for(int i = 0; i < MAX_MOVE_TYPE; ++i)
8403 pet->SetSpeed(UnitMoveType(i), m_speed_rate[i], true);
8406 void Unit::SetCharm(Unit* pet)
8408 SetCharmGUID(pet ? pet->GetGUID() : 0);
8411 void Unit::AddGuardian( Pet* pet )
8413 m_guardianPets.insert(pet->GetGUID());
8416 void Unit::RemoveGuardian( Pet* pet )
8418 m_guardianPets.erase(pet->GetGUID());
8421 void Unit::RemoveGuardians()
8423 while(!m_guardianPets.empty())
8425 uint64 guid = *m_guardianPets.begin();
8426 if(Pet* pet = GetMap()->GetPet(guid))
8427 pet->Remove(PET_SAVE_AS_DELETED);
8429 m_guardianPets.erase(guid);
8433 Pet* Unit::FindGuardianWithEntry(uint32 entry)
8435 // pet guid middle part is entry (and creature also)
8436 // and in guardian list must be guardians with same entry _always_
8437 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
8438 if(Pet* pet = GetMap()->GetPet(*itr))
8439 if (pet->GetEntry() == entry)
8440 return pet;
8442 return NULL;
8445 void Unit::UnsummonAllTotems()
8447 for (int8 i = 0; i < MAX_TOTEM; ++i)
8449 if(!m_TotemSlot[i])
8450 continue;
8452 Creature *OldTotem = GetMap()->GetCreature(m_TotemSlot[i]);
8453 if (OldTotem && OldTotem->isTotem())
8454 ((Totem*)OldTotem)->UnSummon();
8458 int32 Unit::DealHeal(Unit *pVictim, uint32 addhealth, SpellEntry const *spellProto, bool critical)
8460 int32 gain = pVictim->ModifyHealth(int32(addhealth));
8462 Unit* unit = this;
8464 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
8465 unit = GetOwner();
8467 if (unit->GetTypeId()==TYPEID_PLAYER)
8469 // overheal = addhealth - gain
8470 unit->SendHealSpellLog(pVictim, spellProto->Id, addhealth, addhealth - gain, critical);
8472 if (BattleGround *bg = ((Player*)unit)->GetBattleGround())
8473 bg->UpdatePlayerScore((Player*)unit, SCORE_HEALING_DONE, gain);
8475 // use the actual gain, as the overheal shall not be counted, skip gain 0 (it ignored anyway in to criteria)
8476 if (gain)
8477 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE, gain, 0, pVictim);
8479 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED, addhealth);
8482 if (pVictim->GetTypeId()==TYPEID_PLAYER)
8484 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED, gain);
8485 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED, addhealth);
8488 return gain;
8491 Unit* Unit::SelectMagnetTarget(Unit *victim, SpellEntry const *spellInfo)
8493 if(!victim)
8494 return NULL;
8496 // Magic case
8497 if(spellInfo && (spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC))
8499 Unit::AuraList const& magnetAuras = victim->GetAurasByType(SPELL_AURA_SPELL_MAGNET);
8500 for(Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
8501 if(Unit* magnet = (*itr)->GetCaster())
8502 if(magnet->IsWithinLOSInMap(this) && magnet->isAlive())
8503 return magnet;
8505 // Melee && ranged case
8506 else
8508 AuraList const& hitTriggerAuras = victim->GetAurasByType(SPELL_AURA_ADD_CASTER_HIT_TRIGGER);
8509 for(AuraList::const_iterator i = hitTriggerAuras.begin(); i != hitTriggerAuras.end(); ++i)
8510 if(Unit* magnet = (*i)->GetCaster())
8511 if(magnet->isAlive() && magnet->IsWithinLOSInMap(this))
8512 if(roll_chance_i((*i)->GetModifier()->m_amount))
8513 return magnet;
8516 return victim;
8519 void Unit::SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, uint32 OverHeal, bool critical)
8521 // we guess size
8522 WorldPacket data(SMSG_SPELLHEALLOG, (8+8+4+4+1));
8523 data.append(pVictim->GetPackGUID());
8524 data.append(GetPackGUID());
8525 data << uint32(SpellID);
8526 data << uint32(Damage);
8527 data << uint32(OverHeal);
8528 data << uint8(critical ? 1 : 0);
8529 data << uint8(0); // unused in client?
8530 SendMessageToSet(&data, true);
8533 void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
8535 WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1));
8536 data.append(pVictim->GetPackGUID());
8537 data.append(GetPackGUID());
8538 data << uint32(SpellID);
8539 data << uint32(powertype);
8540 data << uint32(Damage);
8541 SendMessageToSet(&data, true);
8544 void Unit::EnergizeBySpell(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
8546 SendEnergizeSpellLog(pVictim, SpellID, Damage, powertype);
8547 // needs to be called after sending spell log
8548 pVictim->ModifyPower(powertype, Damage);
8551 uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack)
8553 if(!spellProto || !pVictim || damagetype==DIRECT_DAMAGE )
8554 return pdamage;
8556 // For totems get damage bonus from owner (statue isn't totem in fact)
8557 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
8559 if(Unit* owner = GetOwner())
8560 return owner->SpellDamageBonus(pVictim, spellProto, pdamage, damagetype);
8563 // Taken/Done total percent damage auras
8564 float DoneTotalMod = 1.0f;
8565 float TakenTotalMod = 1.0f;
8566 int32 DoneTotal = 0;
8567 int32 TakenTotal = 0;
8569 // ..done
8570 // Creature damage
8571 if( GetTypeId() == TYPEID_UNIT && !((Creature*)this)->isPet() )
8572 DoneTotalMod *= ((Creature*)this)->GetSpellDamageMod(((Creature*)this)->GetCreatureInfo()->rank);
8574 if (!(spellProto->AttributesEx6 & SPELL_ATTR_EX6_NO_DMG_PERCENT_MODS))
8576 AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
8577 for(AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
8579 if( ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto)) &&
8580 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
8581 // -1 == any item class (not wand then)
8582 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
8583 // 0 == any inventory type (not wand then)
8585 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8590 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8591 // Add flat bonus from spell damage versus
8592 DoneTotal += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask);
8593 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
8594 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
8595 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8596 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8598 // done scripted mod (take it from owner)
8599 Unit *owner = GetOwner();
8600 if (!owner) owner = this;
8601 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8602 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
8604 if (!(*i)->isAffectedOnSpell(spellProto))
8605 continue;
8606 switch((*i)->GetModifier()->m_miscvalue)
8608 case 4920: // Molten Fury
8609 case 4919:
8610 case 6917: // Death's Embrace
8611 case 6926:
8612 case 6928:
8614 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
8615 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
8616 break;
8618 // Soul Siphon
8619 case 4992:
8620 case 4993:
8622 // effect 1 m_amount
8623 int32 maxPercent = (*i)->GetModifier()->m_amount;
8624 // effect 0 m_amount
8625 int32 stepPercent = CalculateSpellDamage((*i)->GetSpellProto(), 0, (*i)->GetSpellProto()->EffectBasePoints[0], this);
8626 // count affliction effects and calc additional damage in percentage
8627 int32 modPercent = 0;
8628 AuraMap const& victimAuras = pVictim->GetAuras();
8629 for (AuraMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
8631 SpellEntry const* m_spell = itr->second->GetSpellProto();
8632 if (m_spell->SpellFamilyName != SPELLFAMILY_WARLOCK || !(m_spell->SpellFamilyFlags & UI64LIT(0x0004071B8044C402)))
8633 continue;
8634 modPercent += stepPercent * itr->second->GetStackAmount();
8635 if (modPercent >= maxPercent)
8637 modPercent = maxPercent;
8638 break;
8641 DoneTotalMod *= (modPercent+100.0f)/100.0f;
8642 break;
8644 case 6916: // Death's Embrace
8645 case 6925:
8646 case 6927:
8647 if (HasAuraState(AURA_STATE_HEALTHLESS_20_PERCENT))
8648 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
8649 break;
8650 case 5481: // Starfire Bonus
8652 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, UI64LIT(0x0000000000200002)))
8653 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8654 break;
8656 case 4418: // Increased Shock Damage
8657 case 4554: // Increased Lightning Damage
8658 case 4555: // Improved Moonfire
8659 case 5142: // Increased Lightning Damage
8660 case 5147: // Improved Consecration / Libram of Resurgence
8661 case 5148: // Idol of the Shooting Star
8662 case 6008: // Increased Lightning Damage / Totem of Hex
8664 DoneTotal+=(*i)->GetModifier()->m_amount;
8665 break;
8667 // Tundra Stalker
8668 // Merciless Combat
8669 case 7277:
8671 // Merciless Combat
8672 if ((*i)->GetSpellProto()->SpellIconID == 2656)
8674 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
8675 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
8677 else // Tundra Stalker
8679 // Frost Fever (target debuff)
8680 if (pVictim->GetAura(SPELL_AURA_MOD_HASTE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0000000000000000), 0x00000002))
8681 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8682 break;
8684 break;
8686 case 7293: // Rage of Rivendare
8688 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0200000000000000)))
8689 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8690 break;
8692 // Twisted Faith
8693 case 7377:
8695 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, UI64LIT(0x0000000000008000), 0, GetGUID()))
8696 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8697 break;
8699 // Marked for Death
8700 case 7598:
8701 case 7599:
8702 case 7600:
8703 case 7601:
8704 case 7602:
8706 if (pVictim->GetAura(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, UI64LIT(0x0000000000000400)))
8707 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8708 break;
8713 // Custom scripted damage
8714 switch(spellProto->SpellFamilyName)
8716 case SPELLFAMILY_MAGE:
8718 // Ice Lance
8719 if (spellProto->SpellIconID == 186)
8721 if (pVictim->isFrozen())
8723 float multiplier = 3.0f;
8725 // if target have higher level
8726 if (pVictim->getLevel() > getLevel())
8727 // Glyph of Ice Lance
8728 if (Aura* glyph = GetDummyAura(56377))
8729 multiplier = glyph->GetModifier()->m_amount;
8731 DoneTotalMod *= multiplier;
8734 // Torment the weak affected (Arcane Barrage, Arcane Blast, Frostfire Bolt, Arcane Missiles, Fireball)
8735 if ((spellProto->SpellFamilyFlags & UI64LIT(0x0000900020200021)) &&
8736 (pVictim->HasAuraType(SPELL_AURA_MOD_DECREASE_SPEED) || pVictim->HasAuraType(SPELL_AURA_MELEE_SLOW)))
8738 //Search for Torment the weak dummy aura
8739 Unit::AuraList const& ttw = GetAurasByType(SPELL_AURA_DUMMY);
8740 for(Unit::AuraList::const_iterator i = ttw.begin(); i != ttw.end(); ++i)
8742 if ((*i)->GetSpellProto()->SpellIconID == 3263)
8744 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f) / 100.0f;
8745 break;
8749 break;
8751 case SPELLFAMILY_WARLOCK:
8753 // Drain Soul
8754 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000004000))
8756 if (pVictim->GetHealth() * 100 / pVictim->GetMaxHealth() <= 25)
8757 DoneTotalMod *= 4;
8759 break;
8761 case SPELLFAMILY_DEATHKNIGHT:
8763 // Icy Touch, Howling Blast and Frost Strike
8764 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000600000002))
8766 // search disease
8767 bool found = false;
8768 Unit::AuraMap const& auras = pVictim->GetAuras();
8769 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr)
8771 if(itr->second->GetSpellProto()->Dispel == DISPEL_DISEASE)
8773 found = true;
8774 break;
8777 if(!found)
8778 break;
8780 // search for Glacier Rot dummy aura
8781 Unit::AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
8782 for(Unit::AuraList::const_iterator i = dummyAuras.begin(); i != dummyAuras.end(); ++i)
8784 if ((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()] == 7244)
8786 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f) / 100.0f;
8787 break;
8791 break;
8793 default:
8794 break;
8798 // ..taken
8799 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
8800 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
8802 if ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto))
8803 TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
8806 // .. taken pct: dummy auras
8807 if (pVictim->GetTypeId() == TYPEID_PLAYER)
8809 //Cheat Death
8810 if (Aura *dummy = pVictim->GetDummyAura(45182))
8812 float mod = -((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2*4;
8813 if (mod < dummy->GetModifier()->m_amount)
8814 mod = dummy->GetModifier()->m_amount;
8815 TakenTotalMod *= (mod+100.0f)/100.0f;
8819 // From caster spells
8820 AuraList const& mOwnerTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_FROM_CASTER);
8821 for(AuraList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i)
8823 if ((*i)->GetCasterGUID() == GetGUID() && (*i)->isAffectedOnSpell(spellProto))
8824 TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
8827 // Mod damage from spell mechanic
8828 TakenTotalMod *= pVictim->GetTotalAuraMultiplierByMiscValueForMask(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT,GetAllSpellMechanicMask(spellProto));
8830 // Mod damage taken from AoE spells
8831 if(IsAreaOfEffectSpell(spellProto))
8833 AuraList const& avoidAuras = pVictim->GetAurasByType(SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE);
8834 for(AuraList::const_iterator itr = avoidAuras.begin(); itr != avoidAuras.end(); ++itr)
8835 TakenTotalMod *= ((*itr)->GetModifier()->m_amount + 100.0f) / 100.0f;
8838 // Taken/Done fixed damage bonus auras
8839 int32 DoneAdvertisedBenefit = SpellBaseDamageBonus(GetSpellSchoolMask(spellProto));
8840 int32 TakenAdvertisedBenefit = SpellBaseDamageBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
8842 // Pets just add their bonus damage to their spell damage
8843 // note that their spell damage is just gain of their own auras
8844 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
8845 DoneAdvertisedBenefit += ((Pet*)this)->GetBonusDamage();
8847 float LvlPenalty = CalculateLevelPenalty(spellProto);
8848 // Spellmod SpellDamage
8849 float SpellModSpellDamage = 100.0f;
8850 if(Player* modOwner = GetSpellModOwner())
8851 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_SPELL_BONUS_DAMAGE,SpellModSpellDamage);
8852 SpellModSpellDamage /= 100.0f;
8854 // Check for table values
8855 if (SpellBonusEntry const* bonus = sSpellMgr.GetSpellBonusData(spellProto->Id))
8857 float coeff;
8858 if (damagetype == DOT)
8859 coeff = bonus->dot_damage * LvlPenalty * stack;
8860 else
8861 coeff = bonus->direct_damage * LvlPenalty * stack;
8863 if (bonus->ap_bonus)
8864 DoneTotal += int32(bonus->ap_bonus * GetTotalAttackPowerValue(BASE_ATTACK) * stack);
8866 DoneTotal += int32(DoneAdvertisedBenefit * coeff * SpellModSpellDamage);
8867 TakenTotal += int32(TakenAdvertisedBenefit * coeff);
8869 // Default calculation
8870 else if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
8872 // Damage over Time spells bonus calculation
8873 float DotFactor = 1.0f;
8874 if (damagetype == DOT)
8876 if (!IsChanneledSpell(spellProto))
8877 DotFactor = GetSpellDuration(spellProto) / 15000.0f;
8879 if (uint16 DotTicks = GetSpellAuraMaxTicks(spellProto))
8881 DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
8882 TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
8885 // Distribute Damage over multiple effects, reduce by AoE
8886 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
8887 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
8888 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
8889 for(int j = 0; j < 3; ++j)
8891 if (spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
8892 (spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA &&
8893 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH))
8895 CastingTime /= 2;
8896 break;
8899 DoneTotal += int32(DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * SpellModSpellDamage);
8900 TakenTotal+= int32(TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty);
8903 float tmpDamage = (pdamage + DoneTotal) * DoneTotalMod;
8904 // apply spellmod to Done damage (flat and pct)
8905 if(Player* modOwner = GetSpellModOwner())
8906 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
8908 tmpDamage = (tmpDamage + TakenTotal) * TakenTotalMod;
8910 return tmpDamage > 0 ? uint32(tmpDamage) : 0;
8913 int32 Unit::SpellBaseDamageBonus(SpellSchoolMask schoolMask)
8915 int32 DoneAdvertisedBenefit = 0;
8917 // ..done
8918 AuraList const& mDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
8919 for(AuraList::const_iterator i = mDamageDone.begin();i != mDamageDone.end(); ++i)
8921 if (((*i)->GetModifier()->m_miscvalue & schoolMask) != 0 &&
8922 (*i)->GetSpellProto()->EquippedItemClass == -1 && // -1 == any item class (not wand then)
8923 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0) // 0 == any inventory type (not wand then)
8924 DoneAdvertisedBenefit += (*i)->GetModifier()->m_amount;
8927 if (GetTypeId() == TYPEID_PLAYER)
8929 // Base value
8930 DoneAdvertisedBenefit +=((Player*)this)->GetBaseSpellPowerBonus();
8932 // Damage bonus from stats
8933 AuraList const& mDamageDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT);
8934 for(AuraList::const_iterator i = mDamageDoneOfStatPercent.begin();i != mDamageDoneOfStatPercent.end(); ++i)
8936 if((*i)->GetModifier()->m_miscvalue & schoolMask)
8938 // stat used stored in miscValueB for this aura
8939 Stats usedStat = Stats((*i)->GetMiscBValue());
8940 DoneAdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
8943 // ... and attack power
8944 AuraList const& mDamageDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER);
8945 for(AuraList::const_iterator i =mDamageDonebyAP.begin();i != mDamageDonebyAP.end(); ++i)
8947 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
8948 DoneAdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
8952 return DoneAdvertisedBenefit;
8955 int32 Unit::SpellBaseDamageBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
8957 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8959 int32 TakenAdvertisedBenefit = 0;
8960 // ..done (for creature type by mask) in taken
8961 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
8962 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
8964 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8965 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
8968 // ..taken
8969 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
8970 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
8972 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
8973 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
8976 return TakenAdvertisedBenefit;
8979 bool Unit::isSpellCrit(Unit *pVictim, SpellEntry const *spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType)
8981 // not critting spell
8982 if((spellProto->AttributesEx2 & SPELL_ATTR_EX2_CANT_CRIT))
8983 return false;
8985 float crit_chance = 0.0f;
8986 switch(spellProto->DmgClass)
8988 case SPELL_DAMAGE_CLASS_NONE:
8989 return false;
8990 case SPELL_DAMAGE_CLASS_MAGIC:
8992 if (schoolMask & SPELL_SCHOOL_MASK_NORMAL)
8993 crit_chance = 0.0f;
8994 // For other schools
8995 else if (GetTypeId() == TYPEID_PLAYER)
8996 crit_chance = GetFloatValue( PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask));
8997 else
8999 crit_chance = m_baseSpellCritChance;
9000 crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
9002 // taken
9003 if (pVictim)
9005 if (!IsPositiveSpell(spellProto->Id))
9007 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE
9008 crit_chance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask);
9009 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE
9010 crit_chance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
9011 // Modify by player victim resilience
9012 crit_chance -= pVictim->GetSpellCritChanceReduction();
9015 // scripted (increase crit chance ... against ... target by x%)
9016 // scripted (Increases the critical effect chance of your .... by x% on targets ...)
9017 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
9018 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
9020 if (!((*i)->isAffectedOnSpell(spellProto)))
9021 continue;
9022 switch((*i)->GetModifier()->m_miscvalue)
9024 case 849: if (pVictim->isFrozen()) crit_chance+= 17.0f; break; //Shatter Rank 1
9025 case 910: if (pVictim->isFrozen()) crit_chance+= 34.0f; break; //Shatter Rank 2
9026 case 911: if (pVictim->isFrozen()) crit_chance+= 50.0f; break; //Shatter Rank 3
9027 case 7917: // Glyph of Shadowburn
9028 if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
9029 crit_chance+=(*i)->GetModifier()->m_amount;
9030 break;
9031 case 7997: // Renewed Hope
9032 case 7998:
9033 if (pVictim->HasAura(6788))
9034 crit_chance+=(*i)->GetModifier()->m_amount;
9035 break;
9036 default:
9037 break;
9040 // Custom crit by class
9041 switch(spellProto->SpellFamilyName)
9043 case SPELLFAMILY_PRIEST:
9044 // Flash Heal
9045 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000800))
9047 if (pVictim->GetHealth() > pVictim->GetMaxHealth()/2)
9048 break;
9049 AuraList const& mDummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
9050 for(AuraList::const_iterator i = mDummyAuras.begin(); i!= mDummyAuras.end(); ++i)
9052 // Improved Flash Heal
9053 if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_PRIEST &&
9054 (*i)->GetSpellProto()->SpellIconID == 2542)
9056 crit_chance+=(*i)->GetModifier()->m_amount;
9057 break;
9061 break;
9062 case SPELLFAMILY_PALADIN:
9063 // Sacred Shield
9064 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000040000000))
9066 Aura *aura = pVictim->GetDummyAura(58597);
9067 if (aura && aura->GetCasterGUID() == GetGUID())
9068 crit_chance+=aura->GetModifier()->m_amount;
9070 // Exorcism
9071 else if (spellProto->Category == 19)
9073 if (pVictim->GetCreatureTypeMask() & CREATURE_TYPEMASK_DEMON_OR_UNDEAD)
9074 return true;
9076 break;
9077 case SPELLFAMILY_SHAMAN:
9078 // Lava Burst
9079 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000100000000000))
9081 // Flame Shock
9082 if (Aura *flameShock = pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, UI64LIT(0x0000000010000000), 0, GetGUID()))
9083 return true;
9085 break;
9088 break;
9090 case SPELL_DAMAGE_CLASS_MELEE:
9091 case SPELL_DAMAGE_CLASS_RANGED:
9093 if (pVictim)
9094 crit_chance = GetUnitCriticalChance(attackType, pVictim);
9096 crit_chance+= GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
9097 break;
9099 default:
9100 return false;
9102 // percent done
9103 // only players use intelligence for critical chance computations
9104 if(Player* modOwner = GetSpellModOwner())
9105 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance);
9107 crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f;
9108 if (roll_chance_f(crit_chance))
9109 return true;
9110 return false;
9113 uint32 Unit::SpellCriticalDamageBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
9115 // Calculate critical bonus
9116 int32 crit_bonus;
9117 switch(spellProto->DmgClass)
9119 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
9120 case SPELL_DAMAGE_CLASS_RANGED:
9121 crit_bonus = damage;
9122 break;
9123 default:
9124 crit_bonus = damage / 2; // for spells is 50%
9125 break;
9128 // adds additional damage to crit_bonus (from talents)
9129 if(Player* modOwner = GetSpellModOwner())
9130 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
9132 if(!pVictim)
9133 return damage += crit_bonus;
9135 int32 critPctDamageMod = 0;
9136 if(spellProto->DmgClass >= SPELL_DAMAGE_CLASS_MELEE)
9138 if(GetWeaponAttackType(spellProto) == RANGED_ATTACK)
9139 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
9140 else
9141 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
9143 else
9144 critPctDamageMod += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_DAMAGE,GetSpellSchoolMask(spellProto));
9146 critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS, GetSpellSchoolMask(spellProto));
9148 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
9149 critPctDamageMod += GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask);
9151 if(critPctDamageMod!=0)
9152 crit_bonus = int32(crit_bonus * float((100.0f + critPctDamageMod)/100.0f));
9154 if(crit_bonus > 0)
9155 damage += crit_bonus;
9157 return damage;
9160 uint32 Unit::SpellCriticalHealingBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
9162 // Calculate critical bonus
9163 int32 crit_bonus;
9164 switch(spellProto->DmgClass)
9166 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
9167 case SPELL_DAMAGE_CLASS_RANGED:
9168 // TODO: write here full calculation for melee/ranged spells
9169 crit_bonus = damage;
9170 break;
9171 default:
9172 crit_bonus = damage / 2; // for spells is 50%
9173 break;
9176 if(pVictim)
9178 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
9179 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
9182 if(crit_bonus > 0)
9183 damage += crit_bonus;
9185 damage = int32(damage * GetTotalAuraMultiplier(SPELL_AURA_MOD_CRITICAL_HEALING_AMOUNT));
9187 return damage;
9190 uint32 Unit::SpellHealingBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 healamount, DamageEffectType damagetype, uint32 stack)
9192 // No heal amount for this class spells
9193 if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE)
9194 return healamount;
9196 // For totems get healing bonus from owner (statue isn't totem in fact)
9197 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
9198 if(Unit* owner = GetOwner())
9199 return owner->SpellHealingBonus(pVictim, spellProto, healamount, damagetype, stack);
9201 // Healing Done
9202 // Taken/Done total percent damage auras
9203 float DoneTotalMod = 1.0f;
9204 float TakenTotalMod = 1.0f;
9205 int32 DoneTotal = 0;
9206 int32 TakenTotal = 0;
9208 // Healing done percent
9209 AuraList const& mHealingDonePct = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT);
9210 for(AuraList::const_iterator i = mHealingDonePct.begin();i != mHealingDonePct.end(); ++i)
9211 DoneTotalMod *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
9213 // done scripted mod (take it from owner)
9214 Unit *owner = GetOwner();
9215 if (!owner) owner = this;
9216 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
9217 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
9219 if (!(*i)->isAffectedOnSpell(spellProto))
9220 continue;
9221 switch((*i)->GetModifier()->m_miscvalue)
9223 case 4415: // Increased Rejuvenation Healing
9224 case 4953:
9225 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
9226 DoneTotal+=(*i)->GetModifier()->m_amount;
9227 break;
9228 case 7997: // Renewed Hope
9229 case 7998:
9230 if (pVictim->HasAura(6788))
9231 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
9232 break;
9233 case 21: // Test of Faith
9234 case 6935:
9235 case 6918:
9236 if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
9237 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
9238 break;
9239 case 7798: // Glyph of Regrowth
9241 if (pVictim->GetAura(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, UI64LIT(0x0000000000000040)))
9242 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9243 break;
9245 case 8477: // Nourish Heal Boost
9247 int32 stepPercent = (*i)->GetModifier()->m_amount;
9248 int32 modPercent = 0;
9249 AuraMap const& victimAuras = pVictim->GetAuras();
9250 for (AuraMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
9252 if (itr->second->GetCasterGUID()!=GetGUID())
9253 continue;
9254 SpellEntry const* m_spell = itr->second->GetSpellProto();
9255 if (m_spell->SpellFamilyName != SPELLFAMILY_DRUID ||
9256 !(m_spell->SpellFamilyFlags & UI64LIT(0x0000001000000050)))
9257 continue;
9258 modPercent += stepPercent * itr->second->GetStackAmount();
9260 DoneTotalMod *= (modPercent+100.0f)/100.0f;
9261 break;
9263 case 7871: // Glyph of Lesser Healing Wave
9265 if (pVictim->GetAura(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, UI64LIT(0x0000040000000000), 0, GetGUID()))
9266 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9267 break;
9269 default:
9270 break;
9274 // Taken/Done fixed damage bonus auras
9275 int32 DoneAdvertisedBenefit = SpellBaseHealingBonus(GetSpellSchoolMask(spellProto));
9276 int32 TakenAdvertisedBenefit = SpellBaseHealingBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
9278 float LvlPenalty = CalculateLevelPenalty(spellProto);
9279 // Spellmod SpellDamage
9280 float SpellModSpellDamage = 100.0f;
9281 if(Player* modOwner = GetSpellModOwner())
9282 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_SPELL_BONUS_DAMAGE, SpellModSpellDamage);
9283 SpellModSpellDamage /= 100.0f;
9285 // Check for table values
9286 SpellBonusEntry const* bonus = sSpellMgr.GetSpellBonusData(spellProto->Id);
9287 if (bonus)
9289 float coeff;
9290 if (damagetype == DOT)
9291 coeff = bonus->dot_damage * LvlPenalty * stack;
9292 else
9293 coeff = bonus->direct_damage * LvlPenalty * stack;
9295 if (bonus->ap_bonus)
9296 DoneTotal += int32(bonus->ap_bonus * GetTotalAttackPowerValue(BASE_ATTACK) * stack);
9298 DoneTotal += int32(DoneAdvertisedBenefit * coeff * SpellModSpellDamage);
9299 TakenTotal += int32(TakenAdvertisedBenefit * coeff);
9301 // Default calculation
9302 else if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
9304 // Damage over Time spells bonus calculation
9305 float DotFactor = 1.0f;
9306 if(damagetype == DOT)
9308 if(!IsChanneledSpell(spellProto))
9309 DotFactor = GetSpellDuration(spellProto) / 15000.0f;
9310 uint16 DotTicks = GetSpellAuraMaxTicks(spellProto);
9311 if(DotTicks)
9313 DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
9314 TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
9317 // Distribute Damage over multiple effects, reduce by AoE
9318 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
9319 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
9320 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
9321 for(int j = 0; j < 3; ++j)
9323 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
9324 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
9326 CastingTime /= 2;
9327 break;
9330 DoneTotal += int32(DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * SpellModSpellDamage * 1.88f);
9331 TakenTotal += int32(TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * 1.88f);
9334 // use float as more appropriate for negative values and percent applying
9335 float heal = (healamount + DoneTotal)*DoneTotalMod;
9336 // apply spellmod to Done amount
9337 if(Player* modOwner = GetSpellModOwner())
9338 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal);
9340 // Taken mods
9341 // Healing Wave cast
9342 if (spellProto->SpellFamilyName == SPELLFAMILY_SHAMAN && (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000040)))
9344 // Search for Healing Way on Victim
9345 Unit::AuraList const& auraDummy = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
9346 for(Unit::AuraList::const_iterator itr = auraDummy.begin(); itr!=auraDummy.end(); ++itr)
9347 if((*itr)->GetId() == 29203)
9348 TakenTotalMod *= ((*itr)->GetModifier()->m_amount+100.0f) / 100.0f;
9351 // Healing taken percent
9352 float minval = pVictim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
9353 if(minval)
9354 TakenTotalMod *= (100.0f + minval) / 100.0f;
9356 float maxval = pVictim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
9357 if(maxval)
9358 TakenTotalMod *= (100.0f + maxval) / 100.0f;
9360 AuraList const& mHealingGet= pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING_RECEIVED);
9361 for(AuraList::const_iterator i = mHealingGet.begin(); i != mHealingGet.end(); ++i)
9362 if ((*i)->isAffectedOnSpell(spellProto))
9363 TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
9365 heal = (heal + TakenTotal) * TakenTotalMod;
9367 return heal < 0 ? 0 : uint32(heal);
9370 int32 Unit::SpellBaseHealingBonus(SpellSchoolMask schoolMask)
9372 int32 AdvertisedBenefit = 0;
9374 AuraList const& mHealingDone = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE);
9375 for(AuraList::const_iterator i = mHealingDone.begin();i != mHealingDone.end(); ++i)
9376 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
9377 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
9379 // Healing bonus of spirit, intellect and strength
9380 if (GetTypeId() == TYPEID_PLAYER)
9382 // Base value
9383 AdvertisedBenefit +=((Player*)this)->GetBaseSpellPowerBonus();
9385 // Healing bonus from stats
9386 AuraList const& mHealingDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT);
9387 for(AuraList::const_iterator i = mHealingDoneOfStatPercent.begin();i != mHealingDoneOfStatPercent.end(); ++i)
9389 // stat used dependent from misc value (stat index)
9390 Stats usedStat = Stats((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()]);
9391 AdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
9394 // ... and attack power
9395 AuraList const& mHealingDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER);
9396 for(AuraList::const_iterator i = mHealingDonebyAP.begin();i != mHealingDonebyAP.end(); ++i)
9397 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
9398 AdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
9400 return AdvertisedBenefit;
9403 int32 Unit::SpellBaseHealingBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
9405 int32 AdvertisedBenefit = 0;
9406 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING);
9407 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
9408 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
9409 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
9411 return AdvertisedBenefit;
9414 bool Unit::IsImmunedToDamage(SpellSchoolMask shoolMask)
9416 //If m_immuneToSchool type contain this school type, IMMUNE damage.
9417 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
9418 for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
9419 if (itr->type & shoolMask)
9420 return true;
9422 //If m_immuneToDamage type contain magic, IMMUNE damage.
9423 SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
9424 for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
9425 if (itr->type & shoolMask)
9426 return true;
9428 return false;
9431 bool Unit::IsImmunedToSpell(SpellEntry const* spellInfo)
9433 if (!spellInfo)
9434 return false;
9436 //TODO add spellEffect immunity checks!, player with flag in bg is imune to imunity buffs from other friendly players!
9437 //SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_EFFECT];
9439 SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_DISPEL];
9440 for(SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr)
9441 if (itr->type == spellInfo->Dispel)
9442 return true;
9444 if (!(spellInfo->AttributesEx & SPELL_ATTR_EX_UNAFFECTED_BY_SCHOOL_IMMUNE) && // unaffected by school immunity
9445 !(spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)) // can remove immune (by dispell or immune it)
9447 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
9448 for(SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
9449 if (!(IsPositiveSpell(itr->spellId) && IsPositiveSpell(spellInfo->Id)) &&
9450 (itr->type & GetSpellSchoolMask(spellInfo)))
9451 return true;
9454 if(uint32 mechanic = spellInfo->Mechanic)
9456 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
9457 for(SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
9458 if (itr->type == mechanic)
9459 return true;
9461 AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MECHANIC_IMMUNITY_MASK);
9462 for(AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
9463 if ((*iter)->GetModifier()->m_miscvalue & (1 << (mechanic-1)))
9464 return true;
9467 return false;
9470 bool Unit::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
9472 //If m_immuneToEffect type contain this effect type, IMMUNE effect.
9473 uint32 effect = spellInfo->Effect[index];
9474 SpellImmuneList const& effectList = m_spellImmune[IMMUNITY_EFFECT];
9475 for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr)
9476 if (itr->type == effect)
9477 return true;
9479 if(uint32 mechanic = spellInfo->EffectMechanic[index])
9481 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
9482 for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
9483 if (itr->type == mechanic)
9484 return true;
9486 AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MECHANIC_IMMUNITY_MASK);
9487 for(AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
9488 if ((*iter)->GetModifier()->m_miscvalue & (1 << (mechanic-1)))
9489 return true;
9492 if(uint32 aura = spellInfo->EffectApplyAuraName[index])
9494 SpellImmuneList const& list = m_spellImmune[IMMUNITY_STATE];
9495 for(SpellImmuneList::const_iterator itr = list.begin(); itr != list.end(); ++itr)
9496 if (itr->type == aura)
9497 return true;
9499 // Check for immune to application of harmful magical effects
9500 AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MOD_IMMUNE_AURA_APPLY_SCHOOL);
9501 for(AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
9502 if (spellInfo->Dispel == DISPEL_MAGIC && // Magic debuff
9503 ((*iter)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellInfo)) && // Check school
9504 !IsPositiveEffect(spellInfo->Id, index)) // Harmful
9505 return true;
9508 return false;
9511 bool Unit::IsDamageToThreatSpell(SpellEntry const * spellInfo) const
9513 if (!spellInfo)
9514 return false;
9516 uint32 family = spellInfo->SpellFamilyName;
9517 uint64 flags = spellInfo->SpellFamilyFlags;
9519 if ((family == 5 && flags == 256) || //Searing Pain
9520 (family == 6 && flags == 8192) || //Mind Blast
9521 (family == 11 && flags == 1048576)) //Earth Shock
9522 return true;
9524 return false;
9527 uint32 Unit::MeleeDamageBonus(Unit *pVictim, uint32 pdamage,WeaponAttackType attType, SpellEntry const *spellProto, DamageEffectType damagetype, uint32 stack)
9529 if (!pVictim)
9530 return pdamage;
9532 if (pdamage == 0)
9533 return pdamage;
9535 // differentiate for weapon damage based spells
9536 bool isWeaponDamageBasedSpell = !(spellProto && (damagetype == DOT || IsSpellHaveEffect(spellProto, SPELL_EFFECT_SCHOOL_DAMAGE)));
9537 Item* pWeapon = GetTypeId() == TYPEID_PLAYER ? ((Player*)this)->GetWeaponForAttack(attType,true,false) : NULL;
9538 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
9539 uint32 schoolMask = spellProto ? spellProto->SchoolMask : GetMeleeDamageSchoolMask();
9540 uint32 mechanicMask = spellProto ? GetAllSpellMechanicMask(spellProto) : 0;
9542 // Shred also have bonus as MECHANIC_BLEED damages
9543 if (spellProto && spellProto->SpellFamilyName==SPELLFAMILY_DRUID && spellProto->SpellFamilyFlags & UI64LIT(0x00008000))
9544 mechanicMask |= (1 << (MECHANIC_BLEED-1));
9547 // FLAT damage bonus auras
9548 // =======================
9549 int32 DoneFlat = 0;
9550 int32 TakenFlat = 0;
9551 int32 APbonus = 0;
9553 // ..done flat, already included in wepon damage based spells
9554 if (!isWeaponDamageBasedSpell)
9556 AuraList const& mModDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
9557 for(AuraList::const_iterator i = mModDamageDone.begin(); i != mModDamageDone.end(); ++i)
9559 if ((*i)->GetModifier()->m_miscvalue & schoolMask && // schoolmask has to fit with the intrinsic spell school
9560 (*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask() && // AND schoolmask has to fit with weapon damage school (essential for non-physical spells)
9561 ((*i)->GetSpellProto()->EquippedItemClass == -1 || // general, weapon independent
9562 pWeapon && pWeapon->IsFitToSpellRequirements((*i)->GetSpellProto()))) // OR used weapon fits aura requirements
9564 DoneFlat += (*i)->GetModifier()->m_amount;
9568 // Pets just add their bonus damage to their melee damage
9569 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
9570 DoneFlat += ((Pet*)this)->GetBonusDamage();
9573 // ..done flat (by creature type mask)
9574 DoneFlat += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE, creatureTypeMask);
9576 // ..done flat (base at attack power for marked target and base at attack power for creature type)
9577 if (attType == RANGED_ATTACK)
9579 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS);
9580 APbonus += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS, creatureTypeMask);
9581 TakenFlat += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN);
9583 else
9585 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS);
9586 APbonus += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS, creatureTypeMask);
9587 TakenFlat += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN);
9590 // ..taken flat (by school mask)
9591 TakenFlat += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_DAMAGE_TAKEN, schoolMask);
9593 // PERCENT damage auras
9594 // ====================
9595 float DonePercent = 1.0f;
9596 float TakenPercent = 1.0f;
9598 // ..done pct, already included in weapon damage based spells
9599 if(!isWeaponDamageBasedSpell)
9601 AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
9602 for(AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
9604 if ((*i)->GetModifier()->m_miscvalue & schoolMask && // schoolmask has to fit with the intrinsic spell school
9605 (*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask() && // AND schoolmask has to fit with weapon damage school (essential for non-physical spells)
9606 ((*i)->GetSpellProto()->EquippedItemClass == -1 || // general, weapon independent
9607 pWeapon && pWeapon->IsFitToSpellRequirements((*i)->GetSpellProto()))) // OR used weapon fits aura requirements
9609 DonePercent *= ((*i)->GetModifier()->m_amount+100.0f) / 100.0f;
9613 if (attType == OFF_ATTACK)
9614 DonePercent *= GetModifierValue(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_PCT); // no school check required
9617 // ..done pct (by creature type mask)
9618 DonePercent *= GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS, creatureTypeMask);
9620 // ..taken pct (by school mask)
9621 TakenPercent *= pVictim->GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN, schoolMask);
9623 // ..taken pct (by mechanic mask)
9624 TakenPercent *= pVictim->GetTotalAuraMultiplierByMiscValueForMask(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT,mechanicMask);
9626 // ..taken pct (melee/ranged)
9627 if(attType == RANGED_ATTACK)
9628 TakenPercent *= pVictim->GetTotalAuraMultiplier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT);
9629 else
9630 TakenPercent *= pVictim->GetTotalAuraMultiplier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT);
9632 // ..taken pct (aoe avoidance)
9633 if(spellProto && IsAreaOfEffectSpell(spellProto))
9634 TakenPercent *= pVictim->GetTotalAuraMultiplier(SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE);
9637 // special dummys/class sripts and other effects
9638 // =============================================
9639 Unit *owner = GetOwner();
9640 if (!owner)
9641 owner = this;
9643 // ..done (class scripts)
9644 if(spellProto)
9646 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
9647 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
9649 if (!(*i)->isAffectedOnSpell(spellProto))
9650 continue;
9652 switch((*i)->GetModifier()->m_miscvalue)
9654 // Tundra Stalker
9655 // Merciless Combat
9656 case 7277:
9658 // Merciless Combat
9659 if ((*i)->GetSpellProto()->SpellIconID == 2656)
9661 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
9662 DonePercent *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
9664 else // Tundra Stalker
9666 // Frost Fever (target debuff)
9667 if (pVictim->GetAura(SPELL_AURA_MOD_HASTE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0000000000000000), 0x00000002))
9668 DonePercent *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9669 break;
9671 break;
9673 case 7293: // Rage of Rivendare
9675 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0200000000000000)))
9676 DonePercent *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9677 break;
9679 // Marked for Death
9680 case 7598:
9681 case 7599:
9682 case 7600:
9683 case 7601:
9684 case 7602:
9686 if (pVictim->GetAura(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, UI64LIT(0x0000000000000400)))
9687 DonePercent *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9688 break;
9694 // .. taken (dummy auras)
9695 AuraList const& mDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
9696 for(AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
9698 switch((*i)->GetSpellProto()->SpellIconID)
9700 //Cheat Death
9701 case 2109:
9702 if((*i)->GetModifier()->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)
9704 if(pVictim->GetTypeId() != TYPEID_PLAYER)
9705 continue;
9707 float mod = ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f);
9708 if (mod < (*i)->GetModifier()->m_amount)
9709 mod = (*i)->GetModifier()->m_amount;
9711 TakenPercent *= (mod + 100.0f) / 100.0f;
9713 break;
9717 // .. taken (class scripts)
9718 AuraList const& mclassScritAuras = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
9719 for(AuraList::const_iterator i = mclassScritAuras.begin(); i != mclassScritAuras.end(); ++i)
9721 switch((*i)->GetMiscValue())
9723 // Dirty Deeds
9724 case 6427:
9725 case 6428:
9726 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
9728 Aura* eff0 = GetAura((*i)->GetId(), 0);
9729 if (!eff0 || (*i)->GetEffIndex() != 1)
9731 sLog.outError("Spell structure of DD (%u) changed.",(*i)->GetId());
9732 continue;
9735 // effect 0 have expected value but in negative state
9736 TakenPercent *= (-eff0->GetModifier()->m_amount + 100.0f) / 100.0f;
9738 break;
9743 // final calculation
9744 // =================
9746 // scaling of non weapon based spells
9747 if (!isWeaponDamageBasedSpell)
9749 float LvlPenalty = CalculateLevelPenalty(spellProto);
9751 // Check for table values
9752 if (SpellBonusEntry const* bonus = sSpellMgr.GetSpellBonusData(spellProto->Id))
9754 float coeff;
9755 if (damagetype == DOT)
9756 coeff = bonus->dot_damage * LvlPenalty * stack;
9757 else
9758 coeff = bonus->direct_damage * LvlPenalty * stack;
9760 if (bonus->ap_bonus)
9761 DoneFlat += bonus->ap_bonus * (GetTotalAttackPowerValue(BASE_ATTACK) + APbonus) * stack;
9763 DoneFlat *= coeff;
9764 TakenFlat *= coeff;
9766 // Default calculation
9767 else if (DoneFlat || TakenFlat)
9769 // Damage over Time spells bonus calculation
9770 float DotFactor = 1.0f;
9771 if(damagetype == DOT)
9773 if(!IsChanneledSpell(spellProto))
9774 DotFactor = GetSpellDuration(spellProto) / 15000.0f;
9775 uint16 DotTicks = GetSpellAuraMaxTicks(spellProto);
9776 if(DotTicks)
9778 DoneFlat = DoneFlat * int32(stack) / DotTicks;
9779 TakenFlat = TakenFlat * int32(stack) / DotTicks;
9782 // Distribute Damage over multiple effects, reduce by AoE
9783 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
9784 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
9785 DoneFlat *= (CastingTime / 3500.0f) * DotFactor * LvlPenalty;
9786 TakenFlat*= (CastingTime / 3500.0f) * DotFactor * LvlPenalty;
9789 // weapon damage based spells
9790 else if( APbonus || DoneFlat )
9792 bool normalized = spellProto ? IsSpellHaveEffect(spellProto, SPELL_EFFECT_NORMALIZED_WEAPON_DMG) : false;
9793 DoneFlat += int32(APbonus / 14.0f * GetAPMultiplier(attType,normalized));
9795 // for weapon damage based spells we still have to apply damage done percent mods
9796 // (that are already included into pdamage) to not-yet included DoneFlat
9797 // e.g. from doneVersusCreature, apBonusVs...
9798 UnitMods unitMod;
9799 switch(attType)
9801 default:
9802 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
9803 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
9804 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
9807 DoneFlat *= GetModifierValue(unitMod, TOTAL_PCT);
9810 float tmpDamage = float(int32(pdamage) + DoneFlat) * DonePercent;
9812 // apply spellmod to Done damage
9813 if(spellProto)
9815 if(Player* modOwner = GetSpellModOwner())
9816 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
9819 tmpDamage = (tmpDamage + TakenFlat) * TakenPercent;
9821 // bonus result can be negative
9822 return tmpDamage > 0 ? uint32(tmpDamage) : 0;
9825 void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply)
9827 if (apply)
9829 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(), next; itr != m_spellImmune[op].end(); itr = next)
9831 next = itr; ++next;
9832 if(itr->type == type)
9834 m_spellImmune[op].erase(itr);
9835 next = m_spellImmune[op].begin();
9838 SpellImmune Immune;
9839 Immune.spellId = spellId;
9840 Immune.type = type;
9841 m_spellImmune[op].push_back(Immune);
9843 else
9845 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(); itr != m_spellImmune[op].end(); ++itr)
9847 if(itr->spellId == spellId)
9849 m_spellImmune[op].erase(itr);
9850 break;
9857 void Unit::ApplySpellDispelImmunity(const SpellEntry * spellProto, DispelType type, bool apply)
9859 ApplySpellImmune(spellProto->Id,IMMUNITY_DISPEL, type, apply);
9861 if (apply && spellProto->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)
9862 RemoveAurasWithDispelType(type);
9865 float Unit::GetWeaponProcChance() const
9867 // normalized proc chance for weapon attack speed
9868 // (odd formula...)
9869 if (isAttackReady(BASE_ATTACK))
9870 return (GetAttackTime(BASE_ATTACK) * 1.8f / 1000.0f);
9871 else if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
9872 return (GetAttackTime(OFF_ATTACK) * 1.6f / 1000.0f);
9874 return 0.0f;
9877 float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM) const
9879 // proc per minute chance calculation
9880 if (PPM <= 0.0f) return 0.0f;
9881 return WeaponSpeed * PPM / 600.0f; // result is chance in percents (probability = Speed_in_sec * (PPM / 60))
9884 void Unit::Mount(uint32 mount, uint32 spellId)
9886 if (!mount)
9887 return;
9889 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNTING);
9891 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount);
9893 SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
9895 if (GetTypeId() == TYPEID_PLAYER)
9897 // Called by Taxi system / GM command
9898 if (!spellId)
9899 ((Player*)this)->UnsummonPetTemporaryIfAny();
9900 // Called by mount aura
9901 else if (SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellId))
9903 // Flying case (Unsummon any pet)
9904 if (IsSpellHaveAura(spellInfo, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED))
9905 ((Player*)this)->UnsummonPetTemporaryIfAny();
9906 // Normal case (Unsummon only permanent pet)
9907 else if (Pet* pet = GetPet())
9909 if (pet->IsPermanentPetFor((Player*)this) && !((Player*)this)->InArena())
9910 ((Player*)this)->UnsummonPetTemporaryIfAny();
9911 else
9912 pet->ApplyModeFlags(PET_MODE_DISABLE_ACTIONS,true);
9918 void Unit::Unmount()
9920 if (!IsMounted())
9921 return;
9923 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED);
9925 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
9926 RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
9928 // only resummon old pet if the player is already added to a map
9929 // this prevents adding a pet to a not created map which would otherwise cause a crash
9930 // (it could probably happen when logging in after a previous crash)
9931 if(GetTypeId() == TYPEID_PLAYER)
9933 if(Pet* pet = GetPet())
9934 pet->ApplyModeFlags(PET_MODE_DISABLE_ACTIONS,false);
9935 else
9936 ((Player*)this)->ResummonPetTemporaryUnSummonedIfAny();
9940 void Unit::SetInCombatWith(Unit* enemy)
9942 Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf();
9943 if (eOwner->IsPvP())
9945 SetInCombatState(true,enemy);
9946 return;
9949 //check for duel
9950 if (eOwner->GetTypeId() == TYPEID_PLAYER && ((Player*)eOwner)->duel)
9952 Unit const* myOwner = GetCharmerOrOwnerOrSelf();
9953 if(((Player const*)eOwner)->duel->opponent == myOwner)
9955 SetInCombatState(true,enemy);
9956 return;
9960 SetInCombatState(false,enemy);
9963 void Unit::SetInCombatState(bool PvP, Unit* enemy)
9965 // only alive units can be in combat
9966 if (!isAlive())
9967 return;
9969 if (PvP)
9970 m_CombatTimer = 5000;
9972 bool creatureNotInCombat = GetTypeId()==TYPEID_UNIT && !HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
9974 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
9976 if (isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
9977 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
9979 if (creatureNotInCombat)
9981 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
9983 if (((Creature*)this)->AI())
9984 ((Creature*)this)->AI()->EnterCombat(enemy);
9988 void Unit::ClearInCombat()
9990 m_CombatTimer = 0;
9991 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
9993 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
9994 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
9996 // Player's state will be cleared in Player::UpdateContestedPvP
9997 if (GetTypeId() != TYPEID_PLAYER)
9999 Creature* creature = (Creature*)this;
10000 if (creature->GetCreatureInfo() && creature->GetCreatureInfo()->unit_flags & UNIT_FLAG_OOC_NOT_ATTACKABLE)
10001 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
10003 clearUnitState(UNIT_STAT_ATTACK_PLAYER);
10005 else
10006 ((Player*)this)->UpdatePotionCooldown();
10009 bool Unit::isTargetableForAttack(bool inverseAlive /*=false*/) const
10011 if (GetTypeId()==TYPEID_PLAYER && ((Player *)this)->isGameMaster())
10012 return false;
10014 if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE))
10015 return false;
10017 // to be removed if unit by any reason enter combat
10018 if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE))
10019 return false;
10021 // inversealive is needed for some spells which need to be casted at dead targets (aoe)
10022 if (isAlive() == inverseAlive)
10023 return false;
10025 return IsInWorld() && !hasUnitState(UNIT_STAT_DIED) && !isInFlight();
10028 int32 Unit::ModifyHealth(int32 dVal)
10030 int32 gain = 0;
10032 if(dVal==0)
10033 return 0;
10035 int32 curHealth = (int32)GetHealth();
10037 int32 val = dVal + curHealth;
10038 if(val <= 0)
10040 SetHealth(0);
10041 return -curHealth;
10044 int32 maxHealth = (int32)GetMaxHealth();
10046 if(val < maxHealth)
10048 SetHealth(val);
10049 gain = val - curHealth;
10051 else if(curHealth != maxHealth)
10053 SetHealth(maxHealth);
10054 gain = maxHealth - curHealth;
10057 return gain;
10060 int32 Unit::ModifyPower(Powers power, int32 dVal)
10062 int32 gain = 0;
10064 if(dVal==0)
10065 return 0;
10067 int32 curPower = (int32)GetPower(power);
10069 int32 val = dVal + curPower;
10070 if(val <= 0)
10072 SetPower(power,0);
10073 return -curPower;
10076 int32 maxPower = (int32)GetMaxPower(power);
10078 if(val < maxPower)
10080 SetPower(power,val);
10081 gain = val - curPower;
10083 else if(curPower != maxPower)
10085 SetPower(power,maxPower);
10086 gain = maxPower - curPower;
10089 return gain;
10092 bool Unit::isVisibleForOrDetect(Unit const* u, WorldObject const* viewPoint, bool detect, bool inVisibleList, bool is3dDistance) const
10094 if(!u || !IsInMap(u))
10095 return false;
10097 // Always can see self
10098 if (u==this)
10099 return true;
10101 // player visible for other player if not logout and at same transport
10102 // including case when player is out of world
10103 bool at_same_transport =
10104 GetTypeId() == TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER &&
10105 !((Player*)this)->GetSession()->PlayerLogout() && !((Player*)u)->GetSession()->PlayerLogout() &&
10106 !((Player*)this)->GetSession()->PlayerLoading() && !((Player*)u)->GetSession()->PlayerLoading() &&
10107 ((Player*)this)->GetTransport() && ((Player*)this)->GetTransport() == ((Player*)u)->GetTransport();
10109 // not in world
10110 if(!at_same_transport && (!IsInWorld() || !u->IsInWorld()))
10111 return false;
10113 // forbidden to seen (at GM respawn command)
10114 if(m_Visibility==VISIBILITY_RESPAWN)
10115 return false;
10117 Map& _map = *u->GetMap();
10118 // Grid dead/alive checks
10119 if (u->GetTypeId()==TYPEID_PLAYER)
10121 // non visible at grid for any stealth state
10122 if(!IsVisibleInGridForPlayer((Player *)u))
10123 return false;
10125 // if player is dead then he can't detect anyone in any cases
10126 if(!u->isAlive())
10127 detect = false;
10129 else
10131 // all dead creatures/players not visible for any creatures
10132 if(!u->isAlive() || !isAlive())
10133 return false;
10136 // always seen by far sight caster
10137 if (u->GetTypeId()==TYPEID_PLAYER && ((Player*)u)->GetFarSight()==GetGUID())
10138 return true;
10140 // different visible distance checks
10141 if (u->isInFlight()) // what see player in flight
10143 // use object grey distance for all (only see objects any way)
10144 if (!IsWithinDistInMap(viewPoint,World::GetMaxVisibleDistanceInFlight()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
10145 return false;
10147 else if(!isAlive()) // distance for show body
10149 if (!IsWithinDistInMap(viewPoint,World::GetMaxVisibleDistanceForObject()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
10150 return false;
10152 else if(GetTypeId()==TYPEID_PLAYER) // distance for show player
10154 if(u->GetTypeId()==TYPEID_PLAYER)
10156 // Players far than max visible distance for player or not in our map are not visible too
10157 if (!at_same_transport && !IsWithinDistInMap(viewPoint, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
10158 return false;
10160 else
10162 // Units far than max visible distance for creature or not in our map are not visible too
10163 if (!IsWithinDistInMap(viewPoint, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
10164 return false;
10167 else if(GetCharmerOrOwnerGUID()) // distance for show pet/charmed
10169 // Pet/charmed far than max visible distance for player or not in our map are not visible too
10170 if (!IsWithinDistInMap(viewPoint, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
10171 return false;
10173 else // distance for show creature
10175 // Units far than max visible distance for creature or not in our map are not visible too
10176 if (!IsWithinDistInMap(viewPoint, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
10177 return false;
10180 // always seen by owner
10181 if (GetCharmerOrOwnerGUID()==u->GetGUID())
10182 return true;
10184 // isInvisibleForAlive() those units can only be seen by dead or if other
10185 // unit is also invisible for alive.. if an isinvisibleforalive unit dies we
10186 // should be able to see it too
10187 if (u->isAlive() && isAlive() && isInvisibleForAlive() != u->isInvisibleForAlive())
10188 if (u->GetTypeId() != TYPEID_PLAYER || !((Player *)u)->isGameMaster())
10189 return false;
10191 // Visible units, always are visible for all units, except for units under invisibility and phases
10192 if (m_Visibility == VISIBILITY_ON && u->m_invisibilityMask==0 && InSamePhase(u))
10193 return true;
10195 // GMs see any players, not higher GMs and all units in any phase
10196 if (u->GetTypeId() == TYPEID_PLAYER && ((Player *)u)->isGameMaster())
10198 if(GetTypeId() == TYPEID_PLAYER)
10199 return ((Player *)this)->GetSession()->GetSecurity() <= ((Player *)u)->GetSession()->GetSecurity();
10200 else
10201 return true;
10204 // non faction visibility non-breakable for non-GMs
10205 if (m_Visibility == VISIBILITY_OFF)
10206 return false;
10208 // phased visibility (both must phased in same way)
10209 if(!InSamePhase(u))
10210 return false;
10212 // raw invisibility
10213 bool invisible = (m_invisibilityMask != 0 || u->m_invisibilityMask !=0);
10215 // detectable invisibility case
10216 if( invisible && (
10217 // Invisible units, always are visible for units under same invisibility type
10218 (m_invisibilityMask & u->m_invisibilityMask)!=0 ||
10219 // Invisible units, always are visible for unit that can detect this invisibility (have appropriate level for detect)
10220 u->canDetectInvisibilityOf(this) ||
10221 // Units that can detect invisibility always are visible for units that can be detected
10222 canDetectInvisibilityOf(u) ))
10224 invisible = false;
10227 // special cases for always overwrite invisibility/stealth
10228 if(invisible || m_Visibility == VISIBILITY_GROUP_STEALTH)
10230 // non-hostile case
10231 if (!u->IsHostileTo(this))
10233 // 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)
10234 if(GetTypeId()==TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER)
10236 if(((Player*)this)->IsGroupVisibleFor(((Player*)u)))
10237 return true;
10239 // else apply same rules as for hostile case (detecting check for stealth)
10242 // hostile case
10243 else
10245 // Hunter mark functionality
10246 AuraList const& auras = GetAurasByType(SPELL_AURA_MOD_STALKED);
10247 for(AuraList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
10248 if((*iter)->GetCasterGUID()==u->GetGUID())
10249 return true;
10251 // else apply detecting check for stealth
10254 // none other cases for detect invisibility, so invisible
10255 if(invisible)
10256 return false;
10258 // else apply stealth detecting check
10261 // unit got in stealth in this moment and must ignore old detected state
10262 if (m_Visibility == VISIBILITY_GROUP_NO_DETECT)
10263 return false;
10265 // GM invisibility checks early, invisibility if any detectable, so if not stealth then visible
10266 if (m_Visibility != VISIBILITY_GROUP_STEALTH)
10267 return true;
10269 // NOW ONLY STEALTH CASE
10271 //if in non-detect mode then invisible for unit
10272 //mobs always detect players (detect == true)... return 'false' for those mobs which have (detect == false)
10273 //players detect players only in Player::HandleStealthedUnitsDetection()
10274 if (!detect)
10275 return (u->GetTypeId() == TYPEID_PLAYER) ? ((Player*)u)->HaveAtClient(this) : false;
10277 // Special cases
10279 // If is attacked then stealth is lost, some creature can use stealth too
10280 if( !getAttackers().empty() )
10281 return true;
10283 // If there is collision rogue is seen regardless of level difference
10284 if (IsWithinDist(u,0.24f))
10285 return true;
10287 //If a mob or player is stunned he will not be able to detect stealth
10288 if (u->hasUnitState(UNIT_STAT_STUNNED) && (u != this))
10289 return false;
10291 // set max ditance
10292 float visibleDistance = (u->GetTypeId() == TYPEID_PLAYER) ? MAX_PLAYER_STEALTH_DETECT_RANGE : ((Creature const*)u)->GetAttackDistance(this);
10294 //Always invisible from back (when stealth detection is on), also filter max distance cases
10295 bool isInFront = viewPoint->isInFrontInMap(this, visibleDistance);
10296 if(!isInFront)
10297 return false;
10299 // if doesn't have stealth detection (Shadow Sight), then check how stealthy the unit is, otherwise just check los
10300 if(!u->HasAuraType(SPELL_AURA_DETECT_STEALTH))
10302 //Calculation if target is in front
10304 //Visible distance based on stealth value (stealth rank 4 300MOD, 10.5 - 3 = 7.5)
10305 visibleDistance = 10.5f - (GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH)/100.0f);
10307 //Visible distance is modified by
10308 //-Level Diff (every level diff = 1.0f in visible distance)
10309 visibleDistance += int32(u->getLevelForTarget(this)) - int32(getLevelForTarget(u));
10311 //This allows to check talent tree and will add addition stealth dependent on used points)
10312 int32 stealthMod = GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_LEVEL);
10313 if(stealthMod < 0)
10314 stealthMod = 0;
10316 //-Stealth Mod(positive like Master of Deception) and Stealth Detection(negative like paranoia)
10317 //based on wowwiki every 5 mod we have 1 more level diff in calculation
10318 visibleDistance += (int32(u->GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_DETECT)) - stealthMod)/5.0f;
10319 visibleDistance = visibleDistance > MAX_PLAYER_STEALTH_DETECT_RANGE ? MAX_PLAYER_STEALTH_DETECT_RANGE : visibleDistance;
10321 // recheck new distance
10322 if(visibleDistance <= 0 || !IsWithinDist(viewPoint,visibleDistance))
10323 return false;
10326 // Now check is target visible with LoS
10327 float ox,oy,oz;
10328 viewPoint->GetPosition(ox,oy,oz);
10329 return IsWithinLOS(ox,oy,oz);
10332 void Unit::SetVisibility(UnitVisibility x)
10334 m_Visibility = x;
10336 if(IsInWorld())
10338 Map *m = GetMap();
10340 if(GetTypeId()==TYPEID_PLAYER)
10341 m->PlayerRelocation((Player*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
10342 else
10343 m->CreatureRelocation((Creature*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
10347 bool Unit::canDetectInvisibilityOf(Unit const* u) const
10349 if(uint32 mask = (m_detectInvisibilityMask & u->m_invisibilityMask))
10351 for(uint32 i = 0; i < 10; ++i)
10353 if(((1 << i) & mask)==0)
10354 continue;
10356 // find invisibility level
10357 uint32 invLevel = 0;
10358 Unit::AuraList const& iAuras = u->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY);
10359 for(Unit::AuraList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr)
10360 if(((*itr)->GetModifier()->m_miscvalue)==i && invLevel < (*itr)->GetModifier()->m_amount)
10361 invLevel = (*itr)->GetModifier()->m_amount;
10363 // find invisibility detect level
10364 uint32 detectLevel = 0;
10365 Unit::AuraList const& dAuras = GetAurasByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION);
10366 for(Unit::AuraList::const_iterator itr = dAuras.begin(); itr != dAuras.end(); ++itr)
10367 if(((*itr)->GetModifier()->m_miscvalue)==i && detectLevel < (*itr)->GetModifier()->m_amount)
10368 detectLevel = (*itr)->GetModifier()->m_amount;
10370 if(i==6 && GetTypeId()==TYPEID_PLAYER) // special drunk detection case
10372 detectLevel = ((Player*)this)->GetDrunkValue();
10375 if(invLevel <= detectLevel)
10376 return true;
10380 return false;
10383 void Unit::UpdateSpeed(UnitMoveType mtype, bool forced)
10385 int32 main_speed_mod = 0;
10386 float stack_bonus = 1.0f;
10387 float non_stack_bonus = 1.0f;
10389 switch(mtype)
10391 case MOVE_WALK:
10392 return;
10393 case MOVE_RUN:
10395 if (IsMounted()) // Use on mount auras
10397 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED);
10398 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS);
10399 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK))/100.0f;
10401 else
10403 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED);
10404 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS);
10405 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK))/100.0f;
10407 break;
10409 case MOVE_RUN_BACK:
10410 return;
10411 case MOVE_SWIM:
10413 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SWIM_SPEED);
10414 break;
10416 case MOVE_SWIM_BACK:
10417 return;
10418 case MOVE_FLIGHT:
10420 if (IsMounted()) // Use on mount auras
10421 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
10422 else // Use not mount (shapeshift for example) auras (should stack)
10423 main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_SPEED_FLIGHT);
10424 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_FLIGHT_SPEED_ALWAYS);
10425 non_stack_bonus = (100.0 + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK))/100.0f;
10426 break;
10428 case MOVE_FLIGHT_BACK:
10429 return;
10430 default:
10431 sLog.outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype);
10432 return;
10435 float bonus = non_stack_bonus > stack_bonus ? non_stack_bonus : stack_bonus;
10436 // now we ready for speed calculation
10437 float speed = main_speed_mod ? bonus*(100.0f + main_speed_mod)/100.0f : bonus;
10439 switch(mtype)
10441 case MOVE_RUN:
10442 case MOVE_SWIM:
10443 case MOVE_FLIGHT:
10445 // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need
10446 // TODO: possible affect only on MOVE_RUN
10447 if(int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED))
10449 // Use speed from aura
10450 float max_speed = normalization / baseMoveSpeed[mtype];
10451 if (speed > max_speed)
10452 speed = max_speed;
10454 break;
10456 default:
10457 break;
10460 // for creature case, we check explicit if mob searched for assistance
10461 if (GetTypeId() == TYPEID_UNIT)
10463 if (((Creature*)this)->HasSearchedAssistance())
10464 speed *= 0.66f; // best guessed value, so this will be 33% reduction. Based off initial speed, mob can then "run", "walk fast" or "walk".
10467 // Apply strongest slow aura mod to speed
10468 int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED);
10469 if (slow)
10471 speed *=(100.0f + slow)/100.0f;
10472 float min_speed = (float)GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MINIMUM_SPEED) / 100.0f;
10473 if (speed < min_speed)
10474 speed = min_speed;
10476 SetSpeed(mtype, speed, forced);
10479 float Unit::GetSpeed( UnitMoveType mtype ) const
10481 return m_speed_rate[mtype]*baseMoveSpeed[mtype];
10484 void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced)
10486 if (rate < 0)
10487 rate = 0.0f;
10489 // Update speed only on change
10490 if (m_speed_rate[mtype] == rate)
10491 return;
10493 m_speed_rate[mtype] = rate;
10495 propagateSpeedChange();
10497 WorldPacket data;
10498 if(!forced)
10500 switch(mtype)
10502 case MOVE_WALK:
10503 data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8+4+2+4+4+4+4+4+4+4);
10504 break;
10505 case MOVE_RUN:
10506 data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8+4+2+4+4+4+4+4+4+4);
10507 break;
10508 case MOVE_RUN_BACK:
10509 data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
10510 break;
10511 case MOVE_SWIM:
10512 data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8+4+2+4+4+4+4+4+4+4);
10513 break;
10514 case MOVE_SWIM_BACK:
10515 data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
10516 break;
10517 case MOVE_TURN_RATE:
10518 data.Initialize(MSG_MOVE_SET_TURN_RATE, 8+4+2+4+4+4+4+4+4+4);
10519 break;
10520 case MOVE_FLIGHT:
10521 data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8+4+2+4+4+4+4+4+4+4);
10522 break;
10523 case MOVE_FLIGHT_BACK:
10524 data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
10525 break;
10526 case MOVE_PITCH_RATE:
10527 data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8+4+2+4+4+4+4+4+4+4);
10528 break;
10529 default:
10530 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
10531 return;
10534 data.append(GetPackGUID());
10535 data << uint32(0); // movement flags
10536 data << uint16(0); // unk flags
10537 data << uint32(getMSTime());
10538 data << float(GetPositionX());
10539 data << float(GetPositionY());
10540 data << float(GetPositionZ());
10541 data << float(GetOrientation());
10542 data << uint32(0); // fall time
10543 data << float(GetSpeed(mtype));
10544 SendMessageToSet( &data, true );
10546 else
10548 if(GetTypeId() == TYPEID_PLAYER)
10550 // register forced speed changes for WorldSession::HandleForceSpeedChangeAck
10551 // and do it only for real sent packets and use run for run/mounted as client expected
10552 ++((Player*)this)->m_forced_speed_changes[mtype];
10555 switch(mtype)
10557 case MOVE_WALK:
10558 data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE, 16);
10559 break;
10560 case MOVE_RUN:
10561 data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE, 17);
10562 break;
10563 case MOVE_RUN_BACK:
10564 data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE, 16);
10565 break;
10566 case MOVE_SWIM:
10567 data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE, 16);
10568 break;
10569 case MOVE_SWIM_BACK:
10570 data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, 16);
10571 break;
10572 case MOVE_TURN_RATE:
10573 data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE, 16);
10574 break;
10575 case MOVE_FLIGHT:
10576 data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE, 16);
10577 break;
10578 case MOVE_FLIGHT_BACK:
10579 data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, 16);
10580 break;
10581 case MOVE_PITCH_RATE:
10582 data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE, 16);
10583 break;
10584 default:
10585 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
10586 return;
10588 data.append(GetPackGUID());
10589 data << (uint32)0; // moveEvent, NUM_PMOVE_EVTS = 0x39
10590 if (mtype == MOVE_RUN)
10591 data << uint8(0); // new 2.1.0
10592 data << float(GetSpeed(mtype));
10593 SendMessageToSet( &data, true );
10595 if(Pet* pet = GetPet())
10596 pet->SetSpeed(MOVE_RUN, m_speed_rate[mtype],forced);
10599 void Unit::SetHover(bool on)
10601 if(on)
10602 CastSpell(this, 11010, true);
10603 else
10604 RemoveAurasDueToSpell(11010);
10607 void Unit::setDeathState(DeathState s)
10609 if (s != ALIVE && s!= JUST_ALIVED)
10611 CombatStop();
10612 DeleteThreatList();
10613 ClearComboPointHolders(); // any combo points pointed to unit lost at it death
10615 if(IsNonMeleeSpellCasted(false))
10616 InterruptNonMeleeSpells(false);
10619 if (s == JUST_DIED)
10621 RemoveAllAurasOnDeath();
10622 RemoveGuardians();
10623 UnsummonAllTotems();
10625 // after removing a Fearaura (in RemoveAllAurasOnDeath)
10626 // Unit::SetFeared is called and makes that creatures attack player again
10627 StopMoving();
10629 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false);
10630 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, false);
10631 // remove aurastates allowing special moves
10632 ClearAllReactives();
10633 ClearDiminishings();
10635 else if(s == JUST_ALIVED)
10637 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground)
10640 if (m_deathState != ALIVE && s == ALIVE)
10642 //_ApplyAllAuraMods();
10644 m_deathState = s;
10647 /*########################################
10648 ######## ########
10649 ######## AGGRO SYSTEM ########
10650 ######## ########
10651 ########################################*/
10652 bool Unit::CanHaveThreatList() const
10654 // only creatures can have threat list
10655 if( GetTypeId() != TYPEID_UNIT )
10656 return false;
10658 // only alive units can have threat list
10659 if( !isAlive() )
10660 return false;
10662 // totems can not have threat list
10663 if( ((Creature*)this)->isTotem() )
10664 return false;
10666 // vehicles can not have threat list
10667 if( ((Creature*)this)->isVehicle() )
10668 return false;
10670 // pets can not have a threat list, unless they are controlled by a creature
10671 if( ((Creature*)this)->isPet() && IS_PLAYER_GUID(((Pet*)this)->GetOwnerGUID()) )
10672 return false;
10674 return true;
10677 //======================================================================
10679 float Unit::ApplyTotalThreatModifier(float threat, SpellSchoolMask schoolMask)
10681 if (!HasAuraType(SPELL_AURA_MOD_THREAT))
10682 return threat;
10684 if (schoolMask == SPELL_SCHOOL_MASK_NONE)
10685 return threat;
10687 SpellSchools school = GetFirstSchoolInMask(schoolMask);
10689 return threat * m_threatModifier[school];
10692 //======================================================================
10694 void Unit::AddThreat(Unit* pVictim, float threat /*= 0.0f*/, bool crit /*= false*/, SpellSchoolMask schoolMask /*= SPELL_SCHOOL_MASK_NONE*/, SpellEntry const *threatSpell /*= NULL*/)
10696 // Only mobs can manage threat lists
10697 if(CanHaveThreatList())
10698 m_ThreatManager.addThreat(pVictim, threat, crit, schoolMask, threatSpell);
10701 //======================================================================
10703 void Unit::DeleteThreatList()
10705 if(CanHaveThreatList() && !m_ThreatManager.isThreatListEmpty())
10706 SendThreatClear();
10707 m_ThreatManager.clearReferences();
10710 //======================================================================
10712 void Unit::TauntApply(Unit* taunter)
10714 assert(GetTypeId()== TYPEID_UNIT);
10716 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
10717 return;
10719 if(!CanHaveThreatList())
10720 return;
10722 Unit *target = getVictim();
10723 if(target && target == taunter)
10724 return;
10726 SetInFront(taunter);
10727 if (((Creature*)this)->AI())
10728 ((Creature*)this)->AI()->AttackStart(taunter);
10730 m_ThreatManager.tauntApply(taunter);
10733 //======================================================================
10735 void Unit::TauntFadeOut(Unit *taunter)
10737 assert(GetTypeId()== TYPEID_UNIT);
10739 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
10740 return;
10742 if(!CanHaveThreatList())
10743 return;
10745 Unit *target = getVictim();
10746 if(!target || target != taunter)
10747 return;
10749 if(m_ThreatManager.isThreatListEmpty())
10751 if(((Creature*)this)->AI())
10752 ((Creature*)this)->AI()->EnterEvadeMode();
10753 return;
10756 m_ThreatManager.tauntFadeOut(taunter);
10757 target = m_ThreatManager.getHostileTarget();
10759 if (target && target != taunter)
10761 SetInFront(target);
10762 if (((Creature*)this)->AI())
10763 ((Creature*)this)->AI()->AttackStart(target);
10767 //======================================================================
10769 bool Unit::SelectHostileTarget()
10771 //function provides main threat functionality
10772 //next-victim-selection algorithm and evade mode are called
10773 //threat list sorting etc.
10775 assert(GetTypeId()== TYPEID_UNIT);
10777 if (!this->isAlive())
10778 return false;
10779 //This function only useful once AI has been initialized
10780 if (!((Creature*)this)->AI())
10781 return false;
10783 Unit* target = NULL;
10785 // First checking if we have some taunt on us
10786 const AuraList& tauntAuras = GetAurasByType(SPELL_AURA_MOD_TAUNT);
10787 if ( !tauntAuras.empty() )
10789 Unit* caster;
10791 // The last taunt aura caster is alive an we are happy to attack him
10792 if ( (caster = tauntAuras.back()->GetCaster()) && caster->isAlive() )
10793 return true;
10794 else if (tauntAuras.size() > 1)
10796 // We do not have last taunt aura caster but we have more taunt auras,
10797 // so find first available target
10799 // Auras are pushed_back, last caster will be on the end
10800 AuraList::const_iterator aura = --tauntAuras.end();
10803 --aura;
10804 if ( (caster = (*aura)->GetCaster()) &&
10805 caster->IsInMap(this) && caster->isTargetableForAttack() && caster->isInAccessablePlaceFor((Creature*)this) )
10807 target = caster;
10808 break;
10810 }while (aura != tauntAuras.begin());
10814 if ( !target && !m_ThreatManager.isThreatListEmpty() )
10815 // No taunt aura or taunt aura caster is dead standart target selection
10816 target = m_ThreatManager.getHostileTarget();
10818 if(target)
10820 if(!hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_DIED))
10821 SetInFront(target);
10822 ((Creature*)this)->AI()->AttackStart(target);
10823 return true;
10826 // no target but something prevent go to evade mode
10827 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_TAUNT) )
10828 return false;
10830 // last case when creature don't must go to evade mode:
10831 // it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list
10832 // for example at owner command to pet attack some far away creature
10833 // Note: creature not have targeted movement generator but have attacker in this case
10834 if (GetMotionMaster()->GetCurrentMovementGeneratorType() != TARGETED_MOTION_TYPE || hasUnitState(UNIT_STAT_FOLLOW))
10836 for(AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr)
10838 if ((*itr)->IsInMap(this) && (*itr)->isTargetableForAttack() && (*itr)->isInAccessablePlaceFor((Creature*)this))
10839 return false;
10843 // enter in evade mode in other case
10844 ((Creature*)this)->AI()->EnterEvadeMode();
10846 return false;
10849 //======================================================================
10850 //======================================================================
10851 //======================================================================
10853 int32 Unit::CalculateSpellDamage(SpellEntry const* spellProto, uint8 effect_index, int32 effBasePoints, Unit const* target)
10855 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
10857 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
10859 int32 level = int32(getLevel());
10860 if (level > (int32)spellProto->maxLevel && spellProto->maxLevel > 0)
10861 level = (int32)spellProto->maxLevel;
10862 else if (level < (int32)spellProto->baseLevel)
10863 level = (int32)spellProto->baseLevel;
10864 level-= (int32)spellProto->spellLevel;
10866 float basePointsPerLevel = spellProto->EffectRealPointsPerLevel[effect_index];
10867 float randomPointsPerLevel = spellProto->EffectDicePerLevel[effect_index];
10868 int32 basePoints = int32(effBasePoints + level * basePointsPerLevel);
10869 int32 randomPoints = int32(spellProto->EffectDieSides[effect_index] + level * randomPointsPerLevel);
10870 float comboDamage = spellProto->EffectPointsPerComboPoint[effect_index];
10872 // range can have possitive and negative values, so order its for irand
10873 int32 randvalue = int32(spellProto->EffectBaseDice[effect_index]) >= randomPoints
10874 ? irand(randomPoints, int32(spellProto->EffectBaseDice[effect_index]))
10875 : irand(int32(spellProto->EffectBaseDice[effect_index]), randomPoints);
10877 int32 value = basePoints + randvalue;
10878 //random damage
10879 if(comboDamage != 0 && unitPlayer && target && (target->GetGUID() == unitPlayer->GetComboTarget()))
10880 value += (int32)(comboDamage * comboPoints);
10882 if(Player* modOwner = GetSpellModOwner())
10884 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_ALL_EFFECTS, value);
10885 switch(effect_index)
10887 case 0:
10888 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT1, value);
10889 break;
10890 case 1:
10891 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT2, value);
10892 break;
10893 case 2:
10894 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT3, value);
10895 break;
10899 if(spellProto->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION && spellProto->spellLevel &&
10900 spellProto->Effect[effect_index] != SPELL_EFFECT_WEAPON_PERCENT_DAMAGE &&
10901 spellProto->Effect[effect_index] != SPELL_EFFECT_KNOCK_BACK &&
10902 (spellProto->Effect[effect_index] != SPELL_EFFECT_APPLY_AURA || spellProto->EffectApplyAuraName[effect_index] != SPELL_AURA_MOD_DECREASE_SPEED))
10903 value = int32(value*0.25f*exp(getLevel()*(70-spellProto->spellLevel)/1000.0f));
10905 return value;
10908 int32 Unit::CalculateSpellDuration(SpellEntry const* spellProto, uint8 effect_index, Unit const* target)
10910 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
10912 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
10914 int32 minduration = GetSpellDuration(spellProto);
10915 int32 maxduration = GetSpellMaxDuration(spellProto);
10917 int32 duration;
10919 if( minduration != -1 && minduration != maxduration )
10920 duration = minduration + int32((maxduration - minduration) * comboPoints / 5);
10921 else
10922 duration = minduration;
10924 if (duration > 0)
10926 int32 mechanic = GetEffectMechanic(spellProto, effect_index);
10927 // Find total mod value (negative bonus)
10928 int32 durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD, mechanic);
10929 // Modify from SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL aura (stack always ?)
10930 durationMod_always+=target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL, spellProto->Dispel);
10931 // Find max mod (negative bonus)
10932 int32 durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK, mechanic);
10934 if (!IsPositiveSpell(spellProto->Id))
10935 durationMod_always += target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DURATION_OF_MAGIC_EFFECTS, spellProto->DmgClass);
10937 int32 durationMod = 0;
10938 // Select strongest negative mod
10939 if (durationMod_always > durationMod_not_stack)
10940 durationMod = durationMod_not_stack;
10941 else
10942 durationMod = durationMod_always;
10944 if (durationMod != 0)
10945 duration = int32(int64(duration) * (100+durationMod) /100);
10947 if (duration < 0) duration = 0;
10950 return duration;
10953 DiminishingLevels Unit::GetDiminishing(DiminishingGroup group)
10955 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
10957 if(i->DRGroup != group)
10958 continue;
10960 if(!i->hitCount)
10961 return DIMINISHING_LEVEL_1;
10963 if(!i->hitTime)
10964 return DIMINISHING_LEVEL_1;
10966 // If last spell was casted more than 15 seconds ago - reset the count.
10967 if(i->stack==0 && getMSTimeDiff(i->hitTime,getMSTime()) > 15000)
10969 i->hitCount = DIMINISHING_LEVEL_1;
10970 return DIMINISHING_LEVEL_1;
10972 // or else increase the count.
10973 else
10975 return DiminishingLevels(i->hitCount);
10978 return DIMINISHING_LEVEL_1;
10981 void Unit::IncrDiminishing(DiminishingGroup group)
10983 // Checking for existing in the table
10984 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
10986 if(i->DRGroup != group)
10987 continue;
10988 if(i->hitCount < DIMINISHING_LEVEL_IMMUNE)
10989 i->hitCount += 1;
10990 return;
10992 m_Diminishing.push_back(DiminishingReturn(group,getMSTime(),DIMINISHING_LEVEL_2));
10995 void Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration,Unit* caster,DiminishingLevels Level, int32 limitduration)
10997 if(duration == -1 || group == DIMINISHING_NONE || caster->IsFriendlyTo(this) )
10998 return;
11000 // Duration of crowd control abilities on pvp target is limited by 10 sec. (2.2.0)
11001 if(limitduration > 0 && duration > limitduration)
11003 // test pet/charm masters instead pets/charmeds
11004 Unit const* targetOwner = GetCharmerOrOwner();
11005 Unit const* casterOwner = caster->GetCharmerOrOwner();
11007 Unit const* target = targetOwner ? targetOwner : this;
11008 Unit const* source = casterOwner ? casterOwner : caster;
11010 if(target->GetTypeId() == TYPEID_PLAYER && source->GetTypeId() == TYPEID_PLAYER)
11011 duration = limitduration;
11014 float mod = 1.0f;
11016 // Some diminishings applies to mobs too (for example, Stun)
11017 if((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER && GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL)
11019 DiminishingLevels diminish = Level;
11020 switch(diminish)
11022 case DIMINISHING_LEVEL_1: break;
11023 case DIMINISHING_LEVEL_2: mod = 0.5f; break;
11024 case DIMINISHING_LEVEL_3: mod = 0.25f; break;
11025 case DIMINISHING_LEVEL_IMMUNE: mod = 0.0f;break;
11026 default: break;
11030 duration = int32(duration * mod);
11033 void Unit::ApplyDiminishingAura( DiminishingGroup group, bool apply )
11035 // Checking for existing in the table
11036 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
11038 if(i->DRGroup != group)
11039 continue;
11041 if(apply)
11042 i->stack += 1;
11043 else if(i->stack)
11045 i->stack -= 1;
11046 // Remember time after last aura from group removed
11047 if (i->stack == 0)
11048 i->hitTime = getMSTime();
11050 break;
11054 Unit* Unit::GetUnit(WorldObject const& object, uint64 guid)
11056 return ObjectAccessor::GetUnit(object,guid);
11059 bool Unit::isVisibleForInState( Player const* u, WorldObject const* viewPoint, bool inVisibleList ) const
11061 return isVisibleForOrDetect(u, viewPoint, false, inVisibleList, false);
11064 /// returns true if creature can't be seen by alive units
11065 bool Unit::isInvisibleForAlive() const
11067 if (m_AuraFlags & UNIT_AURAFLAG_ALIVE_INVISIBLE)
11068 return true;
11069 // TODO: maybe spiritservices also have just an aura
11070 return isSpiritService();
11073 uint32 Unit::GetCreatureType() const
11075 if(GetTypeId() == TYPEID_PLAYER)
11077 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
11078 if(ssEntry && ssEntry->creatureType > 0)
11079 return ssEntry->creatureType;
11080 else
11081 return CREATURE_TYPE_HUMANOID;
11083 else
11084 return ((Creature*)this)->GetCreatureInfo()->type;
11087 /*#######################################
11088 ######## ########
11089 ######## STAT SYSTEM ########
11090 ######## ########
11091 #######################################*/
11093 bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply)
11095 if(unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
11097 sLog.outError("ERROR in HandleStatModifier(): non existed UnitMods or wrong UnitModifierType!");
11098 return false;
11101 float val = 1.0f;
11103 switch(modifierType)
11105 case BASE_VALUE:
11106 case TOTAL_VALUE:
11107 m_auraModifiersGroup[unitMod][modifierType] += apply ? amount : -amount;
11108 break;
11109 case BASE_PCT:
11110 case TOTAL_PCT:
11111 if(amount <= -100.0f) //small hack-fix for -100% modifiers
11112 amount = -200.0f;
11114 val = (100.0f + amount) / 100.0f;
11115 m_auraModifiersGroup[unitMod][modifierType] *= apply ? val : (1.0f/val);
11116 break;
11118 default:
11119 break;
11122 if(!CanModifyStats())
11123 return false;
11125 switch(unitMod)
11127 case UNIT_MOD_STAT_STRENGTH:
11128 case UNIT_MOD_STAT_AGILITY:
11129 case UNIT_MOD_STAT_STAMINA:
11130 case UNIT_MOD_STAT_INTELLECT:
11131 case UNIT_MOD_STAT_SPIRIT: UpdateStats(GetStatByAuraGroup(unitMod)); break;
11133 case UNIT_MOD_ARMOR: UpdateArmor(); break;
11134 case UNIT_MOD_HEALTH: UpdateMaxHealth(); break;
11136 case UNIT_MOD_MANA:
11137 case UNIT_MOD_RAGE:
11138 case UNIT_MOD_FOCUS:
11139 case UNIT_MOD_ENERGY:
11140 case UNIT_MOD_HAPPINESS:
11141 case UNIT_MOD_RUNE:
11142 case UNIT_MOD_RUNIC_POWER: UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); break;
11144 case UNIT_MOD_RESISTANCE_HOLY:
11145 case UNIT_MOD_RESISTANCE_FIRE:
11146 case UNIT_MOD_RESISTANCE_NATURE:
11147 case UNIT_MOD_RESISTANCE_FROST:
11148 case UNIT_MOD_RESISTANCE_SHADOW:
11149 case UNIT_MOD_RESISTANCE_ARCANE: UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); break;
11151 case UNIT_MOD_ATTACK_POWER: UpdateAttackPowerAndDamage(); break;
11152 case UNIT_MOD_ATTACK_POWER_RANGED: UpdateAttackPowerAndDamage(true); break;
11154 case UNIT_MOD_DAMAGE_MAINHAND: UpdateDamagePhysical(BASE_ATTACK); break;
11155 case UNIT_MOD_DAMAGE_OFFHAND: UpdateDamagePhysical(OFF_ATTACK); break;
11156 case UNIT_MOD_DAMAGE_RANGED: UpdateDamagePhysical(RANGED_ATTACK); break;
11158 default:
11159 break;
11162 return true;
11165 float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const
11167 if( unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
11169 sLog.outError("trial to access non existed modifier value from UnitMods!");
11170 return 0.0f;
11173 if(modifierType == TOTAL_PCT && m_auraModifiersGroup[unitMod][modifierType] <= 0.0f)
11174 return 0.0f;
11176 return m_auraModifiersGroup[unitMod][modifierType];
11179 float Unit::GetTotalStatValue(Stats stat) const
11181 UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat);
11183 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
11184 return 0.0f;
11186 // value = ((base_value * base_pct) + total_value) * total_pct
11187 float value = m_auraModifiersGroup[unitMod][BASE_VALUE] + GetCreateStat(stat);
11188 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
11189 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
11190 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
11192 return value;
11195 float Unit::GetTotalAuraModValue(UnitMods unitMod) const
11197 if(unitMod >= UNIT_MOD_END)
11199 sLog.outError("trial to access non existed UnitMods in GetTotalAuraModValue()!");
11200 return 0.0f;
11203 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
11204 return 0.0f;
11206 float value = m_auraModifiersGroup[unitMod][BASE_VALUE];
11207 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
11208 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
11209 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
11211 return value;
11214 SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const
11216 SpellSchools school = SPELL_SCHOOL_NORMAL;
11218 switch(unitMod)
11220 case UNIT_MOD_RESISTANCE_HOLY: school = SPELL_SCHOOL_HOLY; break;
11221 case UNIT_MOD_RESISTANCE_FIRE: school = SPELL_SCHOOL_FIRE; break;
11222 case UNIT_MOD_RESISTANCE_NATURE: school = SPELL_SCHOOL_NATURE; break;
11223 case UNIT_MOD_RESISTANCE_FROST: school = SPELL_SCHOOL_FROST; break;
11224 case UNIT_MOD_RESISTANCE_SHADOW: school = SPELL_SCHOOL_SHADOW; break;
11225 case UNIT_MOD_RESISTANCE_ARCANE: school = SPELL_SCHOOL_ARCANE; break;
11227 default:
11228 break;
11231 return school;
11234 Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const
11236 Stats stat = STAT_STRENGTH;
11238 switch(unitMod)
11240 case UNIT_MOD_STAT_STRENGTH: stat = STAT_STRENGTH; break;
11241 case UNIT_MOD_STAT_AGILITY: stat = STAT_AGILITY; break;
11242 case UNIT_MOD_STAT_STAMINA: stat = STAT_STAMINA; break;
11243 case UNIT_MOD_STAT_INTELLECT: stat = STAT_INTELLECT; break;
11244 case UNIT_MOD_STAT_SPIRIT: stat = STAT_SPIRIT; break;
11246 default:
11247 break;
11250 return stat;
11253 Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const
11255 switch(unitMod)
11257 case UNIT_MOD_MANA: return POWER_MANA;
11258 case UNIT_MOD_RAGE: return POWER_RAGE;
11259 case UNIT_MOD_FOCUS: return POWER_FOCUS;
11260 case UNIT_MOD_ENERGY: return POWER_ENERGY;
11261 case UNIT_MOD_HAPPINESS: return POWER_HAPPINESS;
11262 case UNIT_MOD_RUNE: return POWER_RUNE;
11263 case UNIT_MOD_RUNIC_POWER:return POWER_RUNIC_POWER;
11264 default: return POWER_MANA;
11267 return POWER_MANA;
11270 float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const
11272 if (attType == RANGED_ATTACK)
11274 int32 ap = GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS);
11275 if (ap < 0)
11276 return 0.0f;
11277 return ap * (1.0f + GetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER));
11279 else
11281 int32 ap = GetInt32Value(UNIT_FIELD_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS);
11282 if (ap < 0)
11283 return 0.0f;
11284 return ap * (1.0f + GetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER));
11288 float Unit::GetWeaponDamageRange(WeaponAttackType attType ,WeaponDamageRange type) const
11290 if (attType == OFF_ATTACK && !haveOffhandWeapon())
11291 return 0.0f;
11293 return m_weaponDamage[attType][type];
11296 void Unit::SetLevel(uint32 lvl)
11298 SetUInt32Value(UNIT_FIELD_LEVEL, lvl);
11300 // group update
11301 if ((GetTypeId() == TYPEID_PLAYER) && ((Player*)this)->GetGroup())
11302 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL);
11305 void Unit::SetHealth(uint32 val)
11307 uint32 maxHealth = GetMaxHealth();
11308 if(maxHealth < val)
11309 val = maxHealth;
11311 SetUInt32Value(UNIT_FIELD_HEALTH, val);
11313 // group update
11314 if(GetTypeId() == TYPEID_PLAYER)
11316 if(((Player*)this)->GetGroup())
11317 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP);
11319 else if(((Creature*)this)->isPet())
11321 Pet *pet = ((Pet*)this);
11322 if(pet->isControlled())
11324 Unit *owner = GetOwner();
11325 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11326 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP);
11331 void Unit::SetMaxHealth(uint32 val)
11333 uint32 health = GetHealth();
11334 SetUInt32Value(UNIT_FIELD_MAXHEALTH, val);
11336 // group update
11337 if(GetTypeId() == TYPEID_PLAYER)
11339 if(((Player*)this)->GetGroup())
11340 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP);
11342 else if(((Creature*)this)->isPet())
11344 Pet *pet = ((Pet*)this);
11345 if(pet->isControlled())
11347 Unit *owner = GetOwner();
11348 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11349 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP);
11353 if(val < health)
11354 SetHealth(val);
11357 void Unit::SetPower(Powers power, uint32 val)
11359 if(GetPower(power) == val)
11360 return;
11362 uint32 maxPower = GetMaxPower(power);
11363 if(maxPower < val)
11364 val = maxPower;
11366 SetStatInt32Value(UNIT_FIELD_POWER1 + power, val);
11368 WorldPacket data(SMSG_POWER_UPDATE);
11369 data.append(GetPackGUID());
11370 data << uint8(power);
11371 data << uint32(val);
11372 SendMessageToSet(&data, GetTypeId() == TYPEID_PLAYER ? true : false);
11374 // group update
11375 if(GetTypeId() == TYPEID_PLAYER)
11377 if(((Player*)this)->GetGroup())
11378 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
11380 else if(((Creature*)this)->isPet())
11382 Pet *pet = ((Pet*)this);
11383 if(pet->isControlled())
11385 Unit *owner = GetOwner();
11386 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11387 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
11390 // Update the pet's character sheet with happiness damage bonus
11391 if(pet->getPetType() == HUNTER_PET && power == POWER_HAPPINESS)
11393 pet->UpdateDamagePhysical(BASE_ATTACK);
11398 void Unit::SetMaxPower(Powers power, uint32 val)
11400 uint32 cur_power = GetPower(power);
11401 SetStatInt32Value(UNIT_FIELD_MAXPOWER1 + power, val);
11403 // group update
11404 if(GetTypeId() == TYPEID_PLAYER)
11406 if(((Player*)this)->GetGroup())
11407 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
11409 else if(((Creature*)this)->isPet())
11411 Pet *pet = ((Pet*)this);
11412 if(pet->isControlled())
11414 Unit *owner = GetOwner();
11415 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11416 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
11420 if(val < cur_power)
11421 SetPower(power, val);
11424 void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply)
11426 ApplyModUInt32Value(UNIT_FIELD_POWER1+power, val, apply);
11428 // group update
11429 if(GetTypeId() == TYPEID_PLAYER)
11431 if(((Player*)this)->GetGroup())
11432 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
11434 else if(((Creature*)this)->isPet())
11436 Pet *pet = ((Pet*)this);
11437 if(pet->isControlled())
11439 Unit *owner = GetOwner();
11440 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11441 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
11446 void Unit::ApplyMaxPowerMod(Powers power, uint32 val, bool apply)
11448 ApplyModUInt32Value(UNIT_FIELD_MAXPOWER1+power, val, apply);
11450 // group update
11451 if(GetTypeId() == TYPEID_PLAYER)
11453 if(((Player*)this)->GetGroup())
11454 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
11456 else if(((Creature*)this)->isPet())
11458 Pet *pet = ((Pet*)this);
11459 if(pet->isControlled())
11461 Unit *owner = GetOwner();
11462 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11463 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
11468 void Unit::ApplyAuraProcTriggerDamage( Aura* aura, bool apply )
11470 AuraList& tAuraProcTriggerDamage = m_modAuras[SPELL_AURA_PROC_TRIGGER_DAMAGE];
11471 if(apply)
11472 tAuraProcTriggerDamage.push_back(aura);
11473 else
11474 tAuraProcTriggerDamage.remove(aura);
11477 uint32 Unit::GetCreatePowers( Powers power ) const
11479 // POWER_FOCUS and POWER_HAPPINESS only have hunter pet
11480 switch(power)
11482 case POWER_MANA: return GetCreateMana();
11483 case POWER_RAGE: return 1000;
11484 case POWER_FOCUS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 100);
11485 case POWER_ENERGY: return 100;
11486 case POWER_HAPPINESS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 1050000);
11487 case POWER_RUNIC_POWER: return 1000;
11488 case POWER_RUNE: return 0;
11489 case POWER_HEALTH: return 0;
11492 return 0;
11495 void Unit::AddToWorld()
11497 Object::AddToWorld();
11500 void Unit::RemoveFromWorld()
11502 // cleanup
11503 if (IsInWorld())
11505 Uncharm();
11506 RemoveNotOwnSingleTargetAuras();
11507 RemoveGuardians();
11508 RemoveAllGameObjects();
11509 RemoveAllDynObjects();
11510 CleanupDeletedAuras();
11513 Object::RemoveFromWorld();
11516 void Unit::CleanupsBeforeDelete()
11518 if(m_uint32Values) // only for fully created object
11520 InterruptNonMeleeSpells(true);
11521 m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList
11522 CombatStop();
11523 ClearComboPointHolders();
11524 DeleteThreatList();
11525 getHostileRefManager().setOnlineOfflineState(false);
11526 RemoveAllAuras(AURA_REMOVE_BY_DELETE);
11527 GetMotionMaster()->Clear(false); // remove different non-standard movement generators.
11529 WorldObject::CleanupsBeforeDelete();
11532 CharmInfo* Unit::InitCharmInfo(Unit *charm)
11534 if(!m_charmInfo)
11535 m_charmInfo = new CharmInfo(charm);
11536 return m_charmInfo;
11539 CharmInfo::CharmInfo(Unit* unit)
11540 : m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_reactState(REACT_PASSIVE), m_petnumber(0)
11542 for(int i = 0; i < CREATURE_MAX_SPELLS; ++i)
11543 m_charmspells[i].SetActionAndType(0,ACT_DISABLED);
11546 void CharmInfo::InitPetActionBar()
11548 // the first 3 SpellOrActions are attack, follow and stay
11549 for(uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_START - ACTION_BAR_INDEX_START; ++i)
11550 SetActionBar(ACTION_BAR_INDEX_START + i,COMMAND_ATTACK - i,ACT_COMMAND);
11552 // middle 4 SpellOrActions are spells/special attacks/abilities
11553 for(uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_END-ACTION_BAR_INDEX_PET_SPELL_START; ++i)
11554 SetActionBar(ACTION_BAR_INDEX_PET_SPELL_START + i,0,ACT_DISABLED);
11556 // last 3 SpellOrActions are reactions
11557 for(uint32 i = 0; i < ACTION_BAR_INDEX_END - ACTION_BAR_INDEX_PET_SPELL_END; ++i)
11558 SetActionBar(ACTION_BAR_INDEX_PET_SPELL_END + i,COMMAND_ATTACK - i,ACT_REACTION);
11561 void CharmInfo::InitEmptyActionBar()
11563 SetActionBar(ACTION_BAR_INDEX_START,COMMAND_ATTACK,ACT_COMMAND);
11564 for(uint32 x = ACTION_BAR_INDEX_START+1; x < ACTION_BAR_INDEX_END; ++x)
11565 SetActionBar(x,0,ACT_PASSIVE);
11568 void CharmInfo::InitPossessCreateSpells()
11570 InitEmptyActionBar(); //charm action bar
11572 if(m_unit->GetTypeId() == TYPEID_PLAYER) //possessed players don't have spells, keep the action bar empty
11573 return;
11575 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
11577 if (IsPassiveSpell(((Creature*)m_unit)->m_spells[x]))
11578 m_unit->CastSpell(m_unit, ((Creature*)m_unit)->m_spells[x], true);
11579 else
11580 AddSpellToActionBar(((Creature*)m_unit)->m_spells[x], ACT_PASSIVE);
11584 void CharmInfo::InitCharmCreateSpells()
11586 if(m_unit->GetTypeId() == TYPEID_PLAYER) //charmed players don't have spells
11588 InitEmptyActionBar();
11589 return;
11592 InitPetActionBar();
11594 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
11596 uint32 spellId = ((Creature*)m_unit)->m_spells[x];
11598 if(!spellId)
11600 m_charmspells[x].SetActionAndType(spellId,ACT_DISABLED);
11601 continue;
11604 if (IsPassiveSpell(spellId))
11606 m_unit->CastSpell(m_unit, spellId, true);
11607 m_charmspells[x].SetActionAndType(spellId,ACT_PASSIVE);
11609 else
11611 m_charmspells[x].SetActionAndType(spellId,ACT_DISABLED);
11613 ActiveStates newstate;
11614 bool onlyselfcast = true;
11615 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
11617 if(!spellInfo) onlyselfcast = false;
11618 for(uint32 i = 0;i<3 && onlyselfcast;++i) //non existent spell will not make any problems as onlyselfcast would be false -> break right away
11620 if(spellInfo->EffectImplicitTargetA[i] != TARGET_SELF && spellInfo->EffectImplicitTargetA[i] != 0)
11621 onlyselfcast = false;
11624 if(onlyselfcast || !IsPositiveSpell(spellId)) //only self cast and spells versus enemies are autocastable
11625 newstate = ACT_DISABLED;
11626 else
11627 newstate = ACT_PASSIVE;
11629 AddSpellToActionBar(spellId, newstate);
11634 bool CharmInfo::AddSpellToActionBar(uint32 spell_id, ActiveStates newstate)
11636 uint32 first_id = sSpellMgr.GetFirstSpellInChain(spell_id);
11638 // new spell rank can be already listed
11639 for(uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
11641 if (uint32 action = PetActionBar[i].GetAction())
11643 if (PetActionBar[i].IsActionBarForSpell() && sSpellMgr.GetFirstSpellInChain(action) == first_id)
11645 PetActionBar[i].SetAction(spell_id);
11646 return true;
11651 // or use empty slot in other case
11652 for(uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
11654 if (!PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell())
11656 SetActionBar(i,spell_id,newstate == ACT_DECIDE ? ACT_DISABLED : newstate);
11657 return true;
11660 return false;
11663 bool CharmInfo::RemoveSpellFromActionBar(uint32 spell_id)
11665 uint32 first_id = sSpellMgr.GetFirstSpellInChain(spell_id);
11667 for(uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
11669 if (uint32 action = PetActionBar[i].GetAction())
11671 if (PetActionBar[i].IsActionBarForSpell() && sSpellMgr.GetFirstSpellInChain(action) == first_id)
11673 SetActionBar(i,0,ACT_DISABLED);
11674 return true;
11679 return false;
11682 void CharmInfo::ToggleCreatureAutocast(uint32 spellid, bool apply)
11684 if(IsPassiveSpell(spellid))
11685 return;
11687 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
11688 if(spellid == m_charmspells[x].GetAction())
11689 m_charmspells[x].SetType(apply ? ACT_ENABLED : ACT_DISABLED);
11692 void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow)
11694 m_petnumber = petnumber;
11695 if(statwindow)
11696 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber);
11697 else
11698 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0);
11701 void CharmInfo::LoadPetActionBar(const std::string& data )
11703 InitPetActionBar();
11705 Tokens tokens = StrSplit(data, " ");
11707 if (tokens.size() != (ACTION_BAR_INDEX_END-ACTION_BAR_INDEX_START)*2)
11708 return; // non critical, will reset to default
11710 int index;
11711 Tokens::iterator iter;
11712 for(iter = tokens.begin(), index = ACTION_BAR_INDEX_START; index < ACTION_BAR_INDEX_END; ++iter, ++index )
11714 // use unsigned cast to avoid sign negative format use at long-> ActiveStates (int) conversion
11715 uint8 type = atol((*iter).c_str());
11716 ++iter;
11717 uint32 action = atol((*iter).c_str());
11719 PetActionBar[index].SetActionAndType(action,ActiveStates(type));
11721 // check correctness
11722 if(PetActionBar[index].IsActionBarForSpell() && !sSpellStore.LookupEntry(PetActionBar[index].GetAction()))
11723 SetActionBar(index,0,ACT_DISABLED);
11727 void CharmInfo::BuildActionBar( WorldPacket* data )
11729 for(uint32 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
11730 *data << uint32(PetActionBar[i].packedData);
11733 void CharmInfo::SetSpellAutocast( uint32 spell_id, bool state )
11735 for(int i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
11737 if(spell_id == PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell())
11739 PetActionBar[i].SetType(state ? ACT_ENABLED : ACT_DISABLED);
11740 break;
11745 bool Unit::isFrozen() const
11747 return HasAuraState(AURA_STATE_FROZEN);
11750 struct ProcTriggeredData
11752 ProcTriggeredData(SpellProcEventEntry const * _spellProcEvent, Aura* _triggeredByAura)
11753 : spellProcEvent(_spellProcEvent), triggeredByAura(_triggeredByAura),
11754 triggeredByAura_SpellPair(Unit::spellEffectPair(triggeredByAura->GetId(),triggeredByAura->GetEffIndex()))
11756 SpellProcEventEntry const *spellProcEvent;
11757 Aura* triggeredByAura;
11758 Unit::spellEffectPair triggeredByAura_SpellPair;
11761 typedef std::list< ProcTriggeredData > ProcTriggeredList;
11762 typedef std::list< uint32> RemoveSpellList;
11764 // List of auras that CAN be trigger but may not exist in spell_proc_event
11765 // in most case need for drop charges
11766 // in some types of aura need do additional check
11767 // for example SPELL_AURA_MECHANIC_IMMUNITY - need check for mechanic
11768 bool InitTriggerAuraData()
11770 for (int i=0;i<TOTAL_AURAS;++i)
11772 isTriggerAura[i]=false;
11773 isNonTriggerAura[i] = false;
11775 isTriggerAura[SPELL_AURA_DUMMY] = true;
11776 isTriggerAura[SPELL_AURA_MOD_CONFUSE] = true;
11777 isTriggerAura[SPELL_AURA_MOD_THREAT] = true;
11778 isTriggerAura[SPELL_AURA_MOD_STUN] = true; // Aura not have charges but need remove him on trigger
11779 isTriggerAura[SPELL_AURA_MOD_DAMAGE_DONE] = true;
11780 isTriggerAura[SPELL_AURA_MOD_DAMAGE_TAKEN] = true;
11781 isTriggerAura[SPELL_AURA_MOD_RESISTANCE] = true;
11782 isTriggerAura[SPELL_AURA_MOD_ROOT] = true;
11783 isTriggerAura[SPELL_AURA_REFLECT_SPELLS] = true;
11784 isTriggerAura[SPELL_AURA_DAMAGE_IMMUNITY] = true;
11785 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL] = true;
11786 isTriggerAura[SPELL_AURA_PROC_TRIGGER_DAMAGE] = true;
11787 isTriggerAura[SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK] = true;
11788 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT] = true;
11789 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL] = true;
11790 isTriggerAura[SPELL_AURA_REFLECT_SPELLS_SCHOOL] = true;
11791 isTriggerAura[SPELL_AURA_MECHANIC_IMMUNITY] = true;
11792 isTriggerAura[SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN] = true;
11793 isTriggerAura[SPELL_AURA_SPELL_MAGNET] = true;
11794 isTriggerAura[SPELL_AURA_MOD_ATTACK_POWER] = true;
11795 isTriggerAura[SPELL_AURA_ADD_CASTER_HIT_TRIGGER] = true;
11796 isTriggerAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true;
11797 isTriggerAura[SPELL_AURA_MOD_MECHANIC_RESISTANCE] = true;
11798 isTriggerAura[SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS] = true;
11799 isTriggerAura[SPELL_AURA_MOD_HASTE] = true;
11800 isTriggerAura[SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE]=true;
11801 isTriggerAura[SPELL_AURA_PRAYER_OF_MENDING] = true;
11802 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE] = true;
11803 isTriggerAura[SPELL_AURA_MOD_DAMAGE_FROM_CASTER] = true;
11804 isTriggerAura[SPELL_AURA_MOD_SPELL_CRIT_CHANCE] = true;
11805 isTriggerAura[SPELL_AURA_MAELSTROM_WEAPON] = true;
11807 isNonTriggerAura[SPELL_AURA_MOD_POWER_REGEN]=true;
11808 isNonTriggerAura[SPELL_AURA_REDUCE_PUSHBACK]=true;
11810 return true;
11813 uint32 createProcExtendMask(SpellNonMeleeDamage *damageInfo, SpellMissInfo missCondition)
11815 uint32 procEx = PROC_EX_NONE;
11816 // Check victim state
11817 if (missCondition!=SPELL_MISS_NONE)
11818 switch (missCondition)
11820 case SPELL_MISS_MISS: procEx|=PROC_EX_MISS; break;
11821 case SPELL_MISS_RESIST: procEx|=PROC_EX_RESIST; break;
11822 case SPELL_MISS_DODGE: procEx|=PROC_EX_DODGE; break;
11823 case SPELL_MISS_PARRY: procEx|=PROC_EX_PARRY; break;
11824 case SPELL_MISS_BLOCK: procEx|=PROC_EX_BLOCK; break;
11825 case SPELL_MISS_EVADE: procEx|=PROC_EX_EVADE; break;
11826 case SPELL_MISS_IMMUNE: procEx|=PROC_EX_IMMUNE; break;
11827 case SPELL_MISS_IMMUNE2: procEx|=PROC_EX_IMMUNE; break;
11828 case SPELL_MISS_DEFLECT: procEx|=PROC_EX_DEFLECT;break;
11829 case SPELL_MISS_ABSORB: procEx|=PROC_EX_ABSORB; break;
11830 case SPELL_MISS_REFLECT: procEx|=PROC_EX_REFLECT;break;
11831 default:
11832 break;
11834 else
11836 // On block
11837 if (damageInfo->blocked)
11838 procEx|=PROC_EX_BLOCK;
11839 // On absorb
11840 if (damageInfo->absorb)
11841 procEx|=PROC_EX_ABSORB;
11842 // On crit
11843 if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT)
11844 procEx|=PROC_EX_CRITICAL_HIT;
11845 else
11846 procEx|=PROC_EX_NORMAL_HIT;
11848 return procEx;
11851 void Unit::ProcDamageAndSpellFor( bool isVictim, Unit * pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const * procSpell, uint32 damage )
11853 // For melee/ranged based attack need update skills and set some Aura states
11854 if (procFlag & MELEE_BASED_TRIGGER_MASK)
11856 // Update skills here for players
11857 if (GetTypeId() == TYPEID_PLAYER)
11859 // On melee based hit/miss/resist need update skill (for victim and attacker)
11860 if (procExtra&(PROC_EX_NORMAL_HIT|PROC_EX_MISS|PROC_EX_RESIST))
11862 if (pTarget->GetTypeId() != TYPEID_PLAYER && pTarget->GetCreatureType() != CREATURE_TYPE_CRITTER)
11863 ((Player*)this)->UpdateCombatSkills(pTarget, attType, isVictim);
11865 // Update defence if player is victim and parry/dodge/block
11866 if (isVictim && procExtra&(PROC_EX_DODGE|PROC_EX_PARRY|PROC_EX_BLOCK))
11867 ((Player*)this)->UpdateDefense();
11869 // If exist crit/parry/dodge/block need update aura state (for victim and attacker)
11870 if (procExtra & (PROC_EX_CRITICAL_HIT|PROC_EX_PARRY|PROC_EX_DODGE|PROC_EX_BLOCK))
11872 // for victim
11873 if (isVictim)
11875 // if victim and dodge attack
11876 if (procExtra&PROC_EX_DODGE)
11878 //Update AURA_STATE on dodge
11879 if (getClass() != CLASS_ROGUE) // skip Rogue Riposte
11881 ModifyAuraState(AURA_STATE_DEFENSE, true);
11882 StartReactiveTimer( REACTIVE_DEFENSE );
11885 // if victim and parry attack
11886 if (procExtra & PROC_EX_PARRY)
11888 // For Hunters only Counterattack (skip Mongoose bite)
11889 if (getClass() == CLASS_HUNTER)
11891 ModifyAuraState(AURA_STATE_HUNTER_PARRY, true);
11892 StartReactiveTimer( REACTIVE_HUNTER_PARRY );
11894 else
11896 ModifyAuraState(AURA_STATE_DEFENSE, true);
11897 StartReactiveTimer( REACTIVE_DEFENSE );
11900 // if and victim block attack
11901 if (procExtra & PROC_EX_BLOCK)
11903 ModifyAuraState(AURA_STATE_DEFENSE,true);
11904 StartReactiveTimer( REACTIVE_DEFENSE );
11907 else //For attacker
11909 // Overpower on victim dodge
11910 if (procExtra&PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR)
11912 ((Player*)this)->AddComboPoints(pTarget, 1);
11913 StartReactiveTimer( REACTIVE_OVERPOWER );
11919 RemoveSpellList removedSpells;
11920 ProcTriggeredList procTriggered;
11921 // Fill procTriggered list
11922 for(AuraMap::const_iterator itr = GetAuras().begin(); itr!= GetAuras().end(); ++itr)
11924 // skip deleted auras (possible at recursive triggered call
11925 if(itr->second->IsDeleted())
11926 continue;
11928 SpellProcEventEntry const* spellProcEvent = NULL;
11929 if(!IsTriggeredAtSpellProcEvent(pTarget, itr->second, procSpell, procFlag, procExtra, attType, isVictim, (damage > 0), spellProcEvent))
11930 continue;
11932 itr->second->SetInUse(true); // prevent aura deletion
11933 procTriggered.push_back( ProcTriggeredData(spellProcEvent, itr->second) );
11936 // Nothing found
11937 if (procTriggered.empty())
11938 return;
11940 // Handle effects proceed this time
11941 for(ProcTriggeredList::const_iterator i = procTriggered.begin(); i != procTriggered.end(); ++i)
11943 // Some auras can be deleted in function called in this loop (except first, ofc)
11944 Aura *triggeredByAura = i->triggeredByAura;
11945 if(triggeredByAura->IsDeleted())
11946 continue;
11948 SpellProcEventEntry const *spellProcEvent = i->spellProcEvent;
11949 Modifier *auraModifier = triggeredByAura->GetModifier();
11950 SpellEntry const *spellInfo = triggeredByAura->GetSpellProto();
11951 bool useCharges = triggeredByAura->GetAuraCharges() > 0;
11952 // For players set spell cooldown if need
11953 uint32 cooldown = 0;
11954 if (GetTypeId() == TYPEID_PLAYER && spellProcEvent && spellProcEvent->cooldown)
11955 cooldown = spellProcEvent->cooldown;
11957 switch(auraModifier->m_auraname)
11959 case SPELL_AURA_PROC_TRIGGER_SPELL:
11961 sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
11962 // Don`t drop charge or add cooldown for not started trigger
11963 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
11965 triggeredByAura->SetInUse(false);
11966 continue;
11968 break;
11970 case SPELL_AURA_PROC_TRIGGER_DAMAGE:
11972 sLog.outDebug("ProcDamageAndSpell: doing %u damage from spell id %u (triggered by %s aura of spell %u)", auraModifier->m_amount, spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
11973 SpellNonMeleeDamage damageInfo(this, pTarget, spellInfo->Id, spellInfo->SchoolMask);
11974 CalculateSpellDamage(&damageInfo, auraModifier->m_amount, spellInfo);
11975 DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb);
11976 SendSpellNonMeleeDamageLog(&damageInfo);
11977 DealSpellDamage(&damageInfo, true);
11978 break;
11980 case SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN:
11981 case SPELL_AURA_MANA_SHIELD:
11982 case SPELL_AURA_OBS_MOD_MANA:
11983 case SPELL_AURA_ADD_PCT_MODIFIER:
11984 case SPELL_AURA_DUMMY:
11986 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());
11987 if (!HandleDummyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
11989 triggeredByAura->SetInUse(false);
11990 continue;
11992 break;
11994 case SPELL_AURA_MOD_HASTE:
11996 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());
11997 if (!HandleHasteAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
11999 triggeredByAura->SetInUse(false);
12000 continue;
12002 break;
12004 case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
12006 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());
12007 if (!HandleOverrideClassScriptAuraProc(pTarget, damage, triggeredByAura, procSpell, cooldown))
12009 triggeredByAura->SetInUse(false);
12010 continue;
12012 break;
12014 case SPELL_AURA_PRAYER_OF_MENDING:
12016 sLog.outDebug("ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
12017 (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
12019 HandleMendingAuraProc(triggeredByAura);
12020 break;
12022 case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE:
12024 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());
12026 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
12028 triggeredByAura->SetInUse(false);
12029 continue;
12031 break;
12033 case SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK:
12034 // Skip melee hits or instant cast spells
12035 if (procSpell == NULL || GetSpellCastTime(procSpell) == 0)
12037 triggeredByAura->SetInUse(false);
12038 continue;
12040 break;
12041 case SPELL_AURA_REFLECT_SPELLS_SCHOOL:
12042 // Skip Melee hits and spells ws wrong school
12043 if (procSpell == NULL || (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0)
12045 triggeredByAura->SetInUse(false);
12046 continue;
12048 break;
12049 case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT:
12050 case SPELL_AURA_MOD_POWER_COST_SCHOOL:
12051 // Skip melee hits and spells ws wrong school or zero cost
12052 if (procSpell == NULL ||
12053 (procSpell->manaCost == 0 && procSpell->ManaCostPercentage == 0) || // Cost check
12054 (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0) // School check
12056 triggeredByAura->SetInUse(false);
12057 continue;
12059 break;
12060 case SPELL_AURA_MECHANIC_IMMUNITY:
12061 // Compare mechanic
12062 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
12064 triggeredByAura->SetInUse(false);
12065 continue;
12067 break;
12068 case SPELL_AURA_MOD_MECHANIC_RESISTANCE:
12069 // Compare mechanic
12070 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
12072 triggeredByAura->SetInUse(false);
12073 continue;
12075 break;
12076 case SPELL_AURA_MOD_DAMAGE_FROM_CASTER:
12077 // Compare casters
12078 if (triggeredByAura->GetCasterGUID() != pTarget->GetGUID())
12080 triggeredByAura->SetInUse(false);
12081 continue;
12083 break;
12084 case SPELL_AURA_MOD_SPELL_CRIT_CHANCE:
12085 if (!procSpell)
12087 triggeredByAura->SetInUse(false);
12088 continue;
12090 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());
12091 if (!HandleSpellCritChanceAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
12093 triggeredByAura->SetInUse(false);
12094 continue;
12096 break;
12097 case SPELL_AURA_MAELSTROM_WEAPON:
12098 sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s maelstrom aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
12100 // remove all stack;
12101 RemoveSpellsCausingAura(SPELL_AURA_MAELSTROM_WEAPON);
12102 triggeredByAura->SetInUse(false); // this safe, aura locked
12103 continue; // avoid re-remove attempts
12104 default:
12105 // nothing do, just charges counter
12106 break;
12109 // Remove charge (aura can be removed by triggers)
12110 if(useCharges && !triggeredByAura->IsDeleted())
12112 // If last charge dropped add spell to remove list
12113 if(triggeredByAura->DropAuraCharge())
12114 removedSpells.push_back(triggeredByAura->GetId());
12117 triggeredByAura->SetInUse(false);
12119 if (!removedSpells.empty())
12121 // Sort spells and remove dublicates
12122 removedSpells.sort();
12123 removedSpells.unique();
12124 // Remove auras from removedAuras
12125 for(RemoveSpellList::const_iterator i = removedSpells.begin(); i != removedSpells.end();++i)
12126 RemoveSingleSpellAurasFromStack(*i);
12130 SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const
12132 return SPELL_SCHOOL_MASK_NORMAL;
12135 Player* Unit::GetSpellModOwner()
12137 if(GetTypeId()==TYPEID_PLAYER)
12138 return (Player*)this;
12139 if(((Creature*)this)->isPet() || ((Creature*)this)->isTotem())
12141 Unit* owner = GetOwner();
12142 if(owner && owner->GetTypeId()==TYPEID_PLAYER)
12143 return (Player*)owner;
12145 return NULL;
12148 ///----------Pet responses methods-----------------
12149 void Unit::SendPetCastFail(uint32 spellid, SpellCastResult msg)
12151 if(msg == SPELL_CAST_OK)
12152 return;
12154 Unit *owner = GetCharmerOrOwner();
12155 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
12156 return;
12158 WorldPacket data(SMSG_PET_CAST_FAILED, 1 + 4 + 1);
12159 data << uint8(0); // cast count?
12160 data << uint32(spellid);
12161 data << uint8(msg);
12162 // uint32 for some reason
12163 // uint32 for some reason
12164 ((Player*)owner)->GetSession()->SendPacket(&data);
12167 void Unit::SendPetActionFeedback (uint8 msg)
12169 Unit* owner = GetOwner();
12170 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
12171 return;
12173 WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1);
12174 data << uint8(msg);
12175 ((Player*)owner)->GetSession()->SendPacket(&data);
12178 void Unit::SendPetTalk (uint32 pettalk)
12180 Unit* owner = GetOwner();
12181 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
12182 return;
12184 WorldPacket data(SMSG_PET_ACTION_SOUND, 8 + 4);
12185 data << uint64(GetGUID());
12186 data << uint32(pettalk);
12187 ((Player*)owner)->GetSession()->SendPacket(&data);
12190 void Unit::SendPetAIReaction(uint64 guid)
12192 Unit* owner = GetOwner();
12193 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
12194 return;
12196 WorldPacket data(SMSG_AI_REACTION, 8 + 4);
12197 data << uint64(guid);
12198 data << uint32(AI_REACTION_AGGRO);
12199 ((Player*)owner)->GetSession()->SendPacket(&data);
12202 ///----------End of Pet responses methods----------
12204 void Unit::StopMoving()
12206 clearUnitState(UNIT_STAT_MOVING);
12208 // send explicit stop packet
12209 // player expected for correct work MONSTER_MOVE_WALK
12210 SendMonsterMove(GetPositionX(), GetPositionY(), GetPositionZ(), 0, GetTypeId()==TYPEID_PLAYER ? MONSTER_MOVE_WALK : MONSTER_MOVE_NONE, 0);
12212 // update position and orientation for near players
12213 WorldPacket data;
12214 BuildHeartBeatMsg(&data);
12215 SendMessageToSet(&data,false);
12218 void Unit::SetFeared(bool apply, uint64 const& casterGUID, uint32 spellID, uint32 time)
12220 if( apply )
12222 if(HasAuraType(SPELL_AURA_PREVENTS_FLEEING))
12223 return;
12225 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
12227 GetMotionMaster()->MovementExpired(false);
12228 CastStop(GetGUID()==casterGUID ? spellID : 0);
12230 Unit* caster = ObjectAccessor::GetUnit(*this,casterGUID);
12232 GetMotionMaster()->MoveFleeing(caster, time); // caster==NULL processed in MoveFleeing
12234 else
12236 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
12238 GetMotionMaster()->MovementExpired(false);
12240 if( GetTypeId() != TYPEID_PLAYER && isAlive() )
12242 // restore appropriate movement generator
12243 if(getVictim())
12244 GetMotionMaster()->MoveChase(getVictim());
12245 else
12246 GetMotionMaster()->Initialize();
12248 // attack caster if can
12249 Unit* caster = Unit::GetUnit(*this, casterGUID);
12250 if(caster && ((Creature*)this)->AI())
12251 ((Creature*)this)->AI()->AttackedBy(caster);
12255 if (GetTypeId() == TYPEID_PLAYER)
12256 ((Player*)this)->SetClientControl(this, !apply);
12259 void Unit::SetConfused(bool apply, uint64 const& casterGUID, uint32 spellID)
12261 if( apply )
12263 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
12265 CastStop(GetGUID()==casterGUID ? spellID : 0);
12267 GetMotionMaster()->MoveConfused();
12269 else
12271 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
12273 GetMotionMaster()->MovementExpired(false);
12275 if (GetTypeId() != TYPEID_PLAYER && isAlive())
12277 // restore appropriate movement generator
12278 if(getVictim())
12279 GetMotionMaster()->MoveChase(getVictim());
12280 else
12281 GetMotionMaster()->Initialize();
12285 if(GetTypeId() == TYPEID_PLAYER)
12286 ((Player*)this)->SetClientControl(this, !apply);
12289 void Unit::SetFeignDeath(bool apply, uint64 const& casterGUID, uint32 spellID)
12291 if( apply )
12294 WorldPacket data(SMSG_FEIGN_DEATH_RESISTED, 9);
12295 data<<GetGUID();
12296 data<<uint8(0);
12297 SendMessageToSet(&data,true);
12300 if(GetTypeId() != TYPEID_PLAYER)
12301 StopMoving();
12302 else
12303 ((Player*)this)->m_movementInfo.SetMovementFlags(MOVEMENTFLAG_NONE);
12305 // blizz like 2.0.x
12306 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29);
12307 // blizz like 2.0.x
12308 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH);
12309 // blizz like 2.0.x
12310 SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_DEAD);
12312 addUnitState(UNIT_STAT_DIED);
12313 CombatStop();
12314 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION);
12316 // prevent interrupt message
12317 if (casterGUID == GetGUID())
12318 FinishSpell(CURRENT_GENERIC_SPELL,false);
12319 InterruptNonMeleeSpells(true);
12320 getHostileRefManager().deleteReferences();
12322 else
12325 WorldPacket data(SMSG_FEIGN_DEATH_RESISTED, 9);
12326 data<<GetGUID();
12327 data<<uint8(1);
12328 SendMessageToSet(&data,true);
12330 // blizz like 2.0.x
12331 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29);
12332 // blizz like 2.0.x
12333 RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH);
12334 // blizz like 2.0.x
12335 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_DEAD);
12337 clearUnitState(UNIT_STAT_DIED);
12339 if (GetTypeId() != TYPEID_PLAYER && isAlive())
12341 // restore appropriate movement generator
12342 if(getVictim())
12343 GetMotionMaster()->MoveChase(getVictim());
12344 else
12345 GetMotionMaster()->Initialize();
12351 bool Unit::IsSitState() const
12353 uint8 s = getStandState();
12354 return
12355 s == UNIT_STAND_STATE_SIT_CHAIR || s == UNIT_STAND_STATE_SIT_LOW_CHAIR ||
12356 s == UNIT_STAND_STATE_SIT_MEDIUM_CHAIR || s == UNIT_STAND_STATE_SIT_HIGH_CHAIR ||
12357 s == UNIT_STAND_STATE_SIT;
12360 bool Unit::IsStandState() const
12362 uint8 s = getStandState();
12363 return !IsSitState() && s != UNIT_STAND_STATE_SLEEP && s != UNIT_STAND_STATE_KNEEL;
12366 void Unit::SetStandState(uint8 state)
12368 SetByteValue(UNIT_FIELD_BYTES_1, 0, state);
12370 if (IsStandState())
12371 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED);
12373 if(GetTypeId()==TYPEID_PLAYER)
12375 WorldPacket data(SMSG_STANDSTATE_UPDATE, 1);
12376 data << (uint8)state;
12377 ((Player*)this)->GetSession()->SendPacket(&data);
12381 bool Unit::IsPolymorphed() const
12383 return GetSpellSpecific(getTransForm())==SPELL_MAGE_POLYMORPH;
12386 void Unit::SetDisplayId(uint32 modelId)
12388 SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId);
12390 if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
12392 Pet *pet = ((Pet*)this);
12393 if(!pet->isControlled())
12394 return;
12395 Unit *owner = GetOwner();
12396 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
12397 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID);
12401 void Unit::ClearComboPointHolders()
12403 while(!m_ComboPointHolders.empty())
12405 uint32 lowguid = *m_ComboPointHolders.begin();
12407 Player* plr = sObjectMgr.GetPlayer(MAKE_NEW_GUID(lowguid, 0, HIGHGUID_PLAYER));
12408 if(plr && plr->GetComboTarget()==GetGUID()) // recheck for safe
12409 plr->ClearComboPoints(); // remove also guid from m_ComboPointHolders;
12410 else
12411 m_ComboPointHolders.erase(lowguid); // or remove manually
12415 void Unit::ClearAllReactives()
12417 for(int i=0; i < MAX_REACTIVE; ++i)
12418 m_reactiveTimer[i] = 0;
12420 if (HasAuraState( AURA_STATE_DEFENSE))
12421 ModifyAuraState(AURA_STATE_DEFENSE, false);
12422 if (getClass() == CLASS_HUNTER && HasAuraState( AURA_STATE_HUNTER_PARRY))
12423 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
12424 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
12425 ((Player*)this)->ClearComboPoints();
12428 void Unit::UpdateReactives( uint32 p_time )
12430 for(int i = 0; i < MAX_REACTIVE; ++i)
12432 ReactiveType reactive = ReactiveType(i);
12434 if(!m_reactiveTimer[reactive])
12435 continue;
12437 if ( m_reactiveTimer[reactive] <= p_time)
12439 m_reactiveTimer[reactive] = 0;
12441 switch ( reactive )
12443 case REACTIVE_DEFENSE:
12444 if (HasAuraState(AURA_STATE_DEFENSE))
12445 ModifyAuraState(AURA_STATE_DEFENSE, false);
12446 break;
12447 case REACTIVE_HUNTER_PARRY:
12448 if ( getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
12449 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
12450 break;
12451 case REACTIVE_OVERPOWER:
12452 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
12453 ((Player*)this)->ClearComboPoints();
12454 break;
12455 default:
12456 break;
12459 else
12461 m_reactiveTimer[reactive] -= p_time;
12466 Unit* Unit::SelectNearbyTarget(Unit* except /*= NULL*/) const
12468 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
12469 Cell cell(p);
12470 cell.data.Part.reserved = ALL_DISTRICT;
12471 cell.SetNoCreate();
12473 std::list<Unit *> targets;
12476 MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, ATTACK_DISTANCE);
12477 MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> searcher(this, targets, u_check);
12479 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
12480 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
12482 CellLock<GridReadGuard> cell_lock(cell, p);
12483 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap(), *this, ATTACK_DISTANCE);
12484 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap(), *this, ATTACK_DISTANCE);
12487 // remove current target
12488 if(except)
12489 targets.remove(except);
12491 // remove not LoS targets
12492 for(std::list<Unit *>::iterator tIter = targets.begin(); tIter != targets.end();)
12494 if(!IsWithinLOSInMap(*tIter))
12496 std::list<Unit *>::iterator tIter2 = tIter;
12497 ++tIter;
12498 targets.erase(tIter2);
12500 else
12501 ++tIter;
12504 // no appropriate targets
12505 if(targets.empty())
12506 return NULL;
12508 // select random
12509 uint32 rIdx = urand(0,targets.size()-1);
12510 std::list<Unit *>::const_iterator tcIter = targets.begin();
12511 for(uint32 i = 0; i < rIdx; ++i)
12512 ++tcIter;
12514 return *tcIter;
12517 bool Unit::hasNegativeAuraWithInterruptFlag(uint32 flag)
12519 for (AuraMap::const_iterator iter = m_Auras.begin(); iter != m_Auras.end(); ++iter)
12521 if (!iter->second->IsPositive() && iter->second->GetSpellProto()->AuraInterruptFlags & flag)
12522 return true;
12524 return false;
12527 void Unit::ApplyAttackTimePercentMod( WeaponAttackType att,float val, bool apply )
12529 if(val > 0)
12531 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply);
12532 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,val,!apply);
12534 else
12536 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply);
12537 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,-val,apply);
12541 void Unit::ApplyCastTimePercentMod(float val, bool apply )
12543 if(val > 0)
12544 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,val,!apply);
12545 else
12546 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,-val,apply);
12549 uint32 Unit::GetCastingTimeForBonus( SpellEntry const *spellProto, DamageEffectType damagetype, uint32 CastingTime )
12551 // Not apply this to creature casted spells with casttime==0
12552 if(CastingTime==0 && GetTypeId()==TYPEID_UNIT && !((Creature*)this)->isPet())
12553 return 3500;
12555 if (CastingTime > 7000) CastingTime = 7000;
12556 if (CastingTime < 1500) CastingTime = 1500;
12558 if(damagetype == DOT && !IsChanneledSpell(spellProto))
12559 CastingTime = 3500;
12561 int32 overTime = 0;
12562 uint8 effects = 0;
12563 bool DirectDamage = false;
12564 bool AreaEffect = false;
12566 for ( uint32 i=0; i<3;++i)
12568 switch ( spellProto->Effect[i] )
12570 case SPELL_EFFECT_SCHOOL_DAMAGE:
12571 case SPELL_EFFECT_POWER_DRAIN:
12572 case SPELL_EFFECT_HEALTH_LEECH:
12573 case SPELL_EFFECT_ENVIRONMENTAL_DAMAGE:
12574 case SPELL_EFFECT_POWER_BURN:
12575 case SPELL_EFFECT_HEAL:
12576 DirectDamage = true;
12577 break;
12578 case SPELL_EFFECT_APPLY_AURA:
12579 switch ( spellProto->EffectApplyAuraName[i] )
12581 case SPELL_AURA_PERIODIC_DAMAGE:
12582 case SPELL_AURA_PERIODIC_HEAL:
12583 case SPELL_AURA_PERIODIC_LEECH:
12584 if ( GetSpellDuration(spellProto) )
12585 overTime = GetSpellDuration(spellProto);
12586 break;
12587 default:
12588 // -5% per additional effect
12589 ++effects;
12590 break;
12592 default:
12593 break;
12596 if(IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetA[i])) || IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetB[i])))
12597 AreaEffect = true;
12600 // Combined Spells with Both Over Time and Direct Damage
12601 if ( overTime > 0 && CastingTime > 0 && DirectDamage )
12603 // mainly for DoTs which are 3500 here otherwise
12604 uint32 OriginalCastTime = GetSpellCastTime(spellProto);
12605 if (OriginalCastTime > 7000) OriginalCastTime = 7000;
12606 if (OriginalCastTime < 1500) OriginalCastTime = 1500;
12607 // Portion to Over Time
12608 float PtOT = (overTime / 15000.0f) / ((overTime / 15000.0f) + (OriginalCastTime / 3500.0f));
12610 if ( damagetype == DOT )
12611 CastingTime = uint32(CastingTime * PtOT);
12612 else if ( PtOT < 1.0f )
12613 CastingTime = uint32(CastingTime * (1 - PtOT));
12614 else
12615 CastingTime = 0;
12618 // Area Effect Spells receive only half of bonus
12619 if ( AreaEffect )
12620 CastingTime /= 2;
12622 // -5% of total per any additional effect
12623 for ( uint8 i=0; i<effects; ++i)
12625 if ( CastingTime > 175 )
12627 CastingTime -= 175;
12629 else
12631 CastingTime = 0;
12632 break;
12636 return CastingTime;
12639 void Unit::UpdateAuraForGroup(uint8 slot)
12641 if(GetTypeId() == TYPEID_PLAYER)
12643 Player* player = (Player*)this;
12644 if(player->GetGroup())
12646 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_AURAS);
12647 player->SetAuraUpdateMask(slot);
12650 else if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
12652 Pet *pet = ((Pet*)this);
12653 if(pet->isControlled())
12655 Unit *owner = GetOwner();
12656 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
12658 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_AURAS);
12659 pet->SetAuraUpdateMask(slot);
12665 float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized)
12667 if (!normalized || GetTypeId() != TYPEID_PLAYER)
12668 return float(GetAttackTime(attType))/1000.0f;
12670 Item *Weapon = ((Player*)this)->GetWeaponForAttack(attType, true, false);
12671 if (!Weapon)
12672 return 2.4; // fist attack
12674 switch (Weapon->GetProto()->InventoryType)
12676 case INVTYPE_2HWEAPON:
12677 return 3.3;
12678 case INVTYPE_RANGED:
12679 case INVTYPE_RANGEDRIGHT:
12680 case INVTYPE_THROWN:
12681 return 2.8;
12682 case INVTYPE_WEAPON:
12683 case INVTYPE_WEAPONMAINHAND:
12684 case INVTYPE_WEAPONOFFHAND:
12685 default:
12686 return Weapon->GetProto()->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7 : 2.4;
12690 Aura* Unit::GetDummyAura( uint32 spell_id ) const
12692 Unit::AuraList const& mDummy = GetAurasByType(SPELL_AURA_DUMMY);
12693 for(Unit::AuraList::const_iterator itr = mDummy.begin(); itr != mDummy.end(); ++itr)
12694 if ((*itr)->GetId() == spell_id)
12695 return *itr;
12697 return NULL;
12700 void Unit::SetContestedPvP(Player *attackedPlayer)
12702 Player* player = GetCharmerOrOwnerPlayerOrPlayerItself();
12704 if(!player || attackedPlayer && (attackedPlayer == player || player->duel && player->duel->opponent == attackedPlayer))
12705 return;
12707 player->SetContestedPvPTimer(30000);
12708 if(!player->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
12710 player->addUnitState(UNIT_STAT_ATTACK_PLAYER);
12711 player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
12712 // call MoveInLineOfSight for nearby contested guards
12713 SetVisibility(GetVisibility());
12715 if(!hasUnitState(UNIT_STAT_ATTACK_PLAYER))
12717 addUnitState(UNIT_STAT_ATTACK_PLAYER);
12718 // call MoveInLineOfSight for nearby contested guards
12719 SetVisibility(GetVisibility());
12723 void Unit::AddPetAura(PetAura const* petSpell)
12725 m_petAuras.insert(petSpell);
12726 if(Pet* pet = GetPet())
12727 pet->CastPetAura(petSpell);
12730 void Unit::RemovePetAura(PetAura const* petSpell)
12732 m_petAuras.erase(petSpell);
12733 if(Pet* pet = GetPet())
12734 pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry()));
12737 Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget,uint32 spell_id)
12739 Pet* pet = new Pet(HUNTER_PET);
12741 if(!pet->CreateBaseAtCreature(creatureTarget))
12743 delete pet;
12744 return NULL;
12747 pet->SetOwnerGUID(GetGUID());
12748 pet->SetCreatorGUID(GetGUID());
12749 pet->setFaction(getFaction());
12750 pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id);
12752 if(GetTypeId()==TYPEID_PLAYER)
12753 pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
12755 if(IsPvP())
12756 pet->SetPvP(true);
12758 if(IsFFAPvP())
12759 pet->SetFFAPvP(true);
12761 uint32 level = (creatureTarget->getLevel() < (getLevel() - 5)) ? (getLevel() - 5) : creatureTarget->getLevel();
12763 if(!pet->InitStatsForLevel(level))
12765 sLog.outError("Pet::InitStatsForLevel() failed for creature (Entry: %u)!",creatureTarget->GetEntry());
12766 delete pet;
12767 return NULL;
12770 pet->GetCharmInfo()->SetPetNumber(sObjectMgr.GeneratePetNumber(), true);
12771 // this enables pet details window (Shift+P)
12772 pet->AIM_Initialize();
12773 pet->InitPetCreateSpells();
12774 pet->InitLevelupSpellsForLevel();
12775 pet->InitTalentForLevel();
12776 pet->SetHealth(pet->GetMaxHealth());
12778 return pet;
12781 bool Unit::IsTriggeredAtSpellProcEvent(Unit *pVictim, Aura* aura, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const*& spellProcEvent )
12783 SpellEntry const* spellProto = aura->GetSpellProto ();
12785 // Get proc Event Entry
12786 spellProcEvent = sSpellMgr.GetSpellProcEvent(spellProto->Id);
12788 // Aura info stored here
12789 Modifier *mod = aura->GetModifier();
12790 // Skip this auras
12791 if (isNonTriggerAura[mod->m_auraname])
12792 return false;
12793 // If not trigger by default and spellProcEvent==NULL - skip
12794 if (!isTriggerAura[mod->m_auraname] && spellProcEvent==NULL)
12795 return false;
12797 // Get EventProcFlag
12798 uint32 EventProcFlag;
12799 if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags
12800 EventProcFlag = spellProcEvent->procFlags;
12801 else
12802 EventProcFlag = spellProto->procFlags; // else get from spell proto
12803 // Continue if no trigger exist
12804 if (!EventProcFlag)
12805 return false;
12807 // Check spellProcEvent data requirements
12808 if(!SpellMgr::IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active))
12809 return false;
12811 // In most cases req get honor or XP from kill
12812 if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER)
12814 bool allow = ((Player*)this)->isHonorOrXPTarget(pVictim);
12815 // Shadow Word: Death - can trigger from every kill
12816 if (aura->GetId() == 32409)
12817 allow = true;
12818 if (!allow)
12819 return false;
12821 // Aura added by spell can`t trogger from self (prevent drop charges/do triggers)
12822 // But except periodic triggers (can triggered from self)
12823 if(procSpell && procSpell->Id == spellProto->Id && !(spellProto->procFlags & PROC_FLAG_ON_TAKE_PERIODIC))
12824 return false;
12826 // Check if current equipment allows aura to proc
12827 if(!isVictim && GetTypeId() == TYPEID_PLAYER)
12829 if(spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
12831 Item *item = NULL;
12832 if(attType == BASE_ATTACK)
12833 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
12834 else if (attType == OFF_ATTACK)
12835 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
12836 else
12837 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
12839 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
12840 return false;
12842 else if(spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
12844 // Check if player is wearing shield
12845 Item *item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
12846 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
12847 return false;
12850 // Get chance from spell
12851 float chance = (float)spellProto->procChance;
12852 // If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance;
12853 if(spellProcEvent && spellProcEvent->customChance)
12854 chance = spellProcEvent->customChance;
12855 // If PPM exist calculate chance from PPM
12856 if(!isVictim && spellProcEvent && spellProcEvent->ppmRate != 0)
12858 uint32 WeaponSpeed = GetAttackTime(attType);
12859 chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate);
12861 // Apply chance modifer aura
12862 if(Player* modOwner = GetSpellModOwner())
12864 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
12865 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_FREQUENCY_OF_SUCCESS,chance);
12868 return roll_chance_f(chance);
12871 bool Unit::HandleMendingAuraProc( Aura* triggeredByAura )
12873 // aura can be deleted at casts
12874 SpellEntry const* spellProto = triggeredByAura->GetSpellProto();
12875 uint32 effIdx = triggeredByAura->GetEffIndex();
12876 int32 heal = triggeredByAura->GetModifier()->m_amount;
12877 uint64 caster_guid = triggeredByAura->GetCasterGUID();
12879 // jumps
12880 int32 jumps = triggeredByAura->GetAuraCharges()-1;
12882 // current aura expire
12883 triggeredByAura->SetAuraCharges(1); // will removed at next charges decrease
12885 // next target selection
12886 if(jumps > 0 && GetTypeId()==TYPEID_PLAYER && IS_PLAYER_GUID(caster_guid))
12888 float radius;
12889 if (spellProto->EffectRadiusIndex[effIdx])
12890 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
12891 else
12892 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
12894 if(Player* caster = ((Player*)triggeredByAura->GetCaster()))
12896 caster->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius,NULL);
12898 if(Player* target = ((Player*)this)->GetNextRandomRaidMember(radius))
12900 // aura will applied from caster, but spell casted from current aura holder
12901 SpellModifier *mod = new SpellModifier(SPELLMOD_CHARGES,SPELLMOD_FLAT,jumps-5,spellProto->Id,spellProto->SpellFamilyFlags,spellProto->SpellFamilyFlags2);
12903 // remove before apply next (locked against deleted)
12904 triggeredByAura->SetInUse(true);
12905 RemoveAurasByCasterSpell(spellProto->Id,caster->GetGUID());
12907 caster->AddSpellMod(mod, true);
12908 CastCustomSpell(target,spellProto->Id,&heal,NULL,NULL,true,NULL,triggeredByAura,caster->GetGUID());
12909 caster->AddSpellMod(mod, false);
12910 triggeredByAura->SetInUse(false);
12915 // heal
12916 CastCustomSpell(this,33110,&heal,NULL,NULL,true,NULL,NULL,caster_guid);
12917 return true;
12920 void Unit::RemoveAurasAtMechanicImmunity(uint32 mechMask, uint32 exceptSpellId, bool non_positive /*= false*/)
12922 Unit::AuraMap& auras = GetAuras();
12923 for(Unit::AuraMap::iterator iter = auras.begin(); iter != auras.end();)
12925 SpellEntry const *spell = iter->second->GetSpellProto();
12926 if (spell->Id == exceptSpellId)
12927 ++iter;
12928 else if (non_positive && iter->second->IsPositive())
12929 ++iter;
12930 else if (spell->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY)
12931 ++iter;
12932 else if (GetSpellMechanicMask(spell, iter->second->GetEffIndex()) & mechMask)
12934 RemoveAurasDueToSpell(spell->Id);
12935 if(auras.empty())
12936 break;
12937 else
12938 iter = auras.begin();
12940 else
12941 ++iter;
12945 void Unit::SetPhaseMask(uint32 newPhaseMask, bool update)
12947 if(newPhaseMask==GetPhaseMask())
12948 return;
12950 if(IsInWorld())
12951 RemoveNotOwnSingleTargetAuras(newPhaseMask); // we can lost access to caster or target
12953 WorldObject::SetPhaseMask(newPhaseMask,update);
12955 if(IsInWorld())
12956 if(Pet* pet = GetPet())
12957 pet->SetPhaseMask(newPhaseMask,true);
12960 void Unit::NearTeleportTo( float x, float y, float z, float orientation, bool casting /*= false*/ )
12962 if(GetTypeId() == TYPEID_PLAYER)
12963 ((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));
12964 else
12966 GetMap()->CreatureRelocation((Creature*)this, x, y, z, orientation);
12968 WorldPacket data;
12969 BuildHeartBeatMsg(&data);
12970 SendMessageToSet(&data, false);
12974 struct SetPvPHelper
12976 explicit SetPvPHelper(bool _state) : state(_state) {}
12977 void operator()(Unit* unit) const { unit->SetPvP(state); }
12978 bool state;
12981 void Unit::SetPvP( bool state )
12983 if(state)
12984 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP);
12985 else
12986 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP);
12988 CallForAllControlledUnits(SetPvPHelper(state),true,true,true);
12991 struct SetFFAPvPHelper
12993 explicit SetFFAPvPHelper(bool _state) : state(_state) {}
12994 void operator()(Unit* unit) const { unit->SetFFAPvP(state); }
12995 bool state;
12998 void Unit::SetFFAPvP( bool state )
13000 if(state)
13001 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
13002 else
13003 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
13005 CallForAllControlledUnits(SetFFAPvPHelper(state),true,true,true);
13008 void Unit::KnockBackFrom(Unit* target, float horizintalSpeed, float verticalSpeed)
13010 float angle = this == target ? GetOrientation() + M_PI : target->GetAngle(this);
13011 float vsin = sin(angle);
13012 float vcos = cos(angle);
13014 // Effect propertly implemented only for players
13015 if(GetTypeId()==TYPEID_PLAYER)
13017 WorldPacket data(SMSG_MOVE_KNOCK_BACK, 8+4+4+4+4+4);
13018 data.append(GetPackGUID());
13019 data << uint32(0); // Sequence
13020 data << float(vcos); // x direction
13021 data << float(vsin); // y direction
13022 data << float(horizintalSpeed); // Horizontal speed
13023 data << float(-verticalSpeed); // Z Movement speed (vertical)
13024 ((Player*)this)->GetSession()->SendPacket(&data);
13026 else
13028 float dis = horizintalSpeed;
13030 float ox, oy, oz;
13031 GetPosition(ox, oy, oz);
13033 float fx = ox + dis * vcos;
13034 float fy = oy + dis * vsin;
13035 float fz = oz;
13037 float fx2, fy2, fz2; // getObjectHitPos overwrite last args in any result case
13038 if(VMAP::VMapFactory::createOrGetVMapManager()->getObjectHitPos(GetMapId(), ox,oy,oz+0.5, fx,fy,oz+0.5,fx2,fy2,fz2, -0.5))
13040 fx = fx2;
13041 fy = fy2;
13042 fz = fz2;
13043 UpdateGroundPositionZ(fx, fy, fz);
13046 //FIXME: this mostly hack, must exist some packet for proper creature move at client side
13047 // with CreatureRelocation at server side
13048 NearTeleportTo(fx, fy, fz, GetOrientation(), this == target);
13052 float Unit::GetCombatRatingReduction(CombatRating cr) const
13054 if (GetTypeId() == TYPEID_PLAYER)
13055 return ((Player const*)this)->GetRatingBonusValue(cr);
13056 else if (((Creature const*)this)->isPet())
13058 // Player's pet have 0.4 resilience from owner
13059 if (Unit* owner = GetOwner())
13060 if(owner->GetTypeId() == TYPEID_PLAYER)
13061 return ((Player*)owner)->GetRatingBonusValue(cr) * 0.4f;
13064 return 0.0f;
13067 uint32 Unit::GetCombatRatingDamageReduction(CombatRating cr, float rate, float cap, uint32 damage) const
13069 float percent = GetCombatRatingReduction(cr) * rate;
13070 if (percent > cap)
13071 percent = cap;
13072 return uint32 (percent * damage / 100.0f);
13075 void Unit::SendThreatUpdate()
13077 ThreatList const& tlist = getThreatManager().getThreatList();
13078 if (uint32 count = tlist.size())
13080 sLog.outDebug( "WORLD: Send SMSG_THREAT_UPDATE Message" );
13081 WorldPacket data(SMSG_THREAT_UPDATE, 8 + count * 8);
13082 data.append(GetPackGUID());
13083 data << uint32(count);
13084 for (ThreatList::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr)
13086 data.appendPackGUID((*itr)->getUnitGuid());
13087 data << uint32((*itr)->getThreat());
13089 SendMessageToSet(&data, false);
13093 void Unit::SendHighestThreatUpdate(HostileReference* pHostilReference)
13095 ThreatList const& tlist = getThreatManager().getThreatList();
13096 if (uint32 count = tlist.size())
13098 sLog.outDebug( "WORLD: Send SMSG_HIGHEST_THREAT_UPDATE Message" );
13099 WorldPacket data(SMSG_HIGHEST_THREAT_UPDATE, 8 + 8 + count * 8);
13100 data.append(GetPackGUID());
13101 data.appendPackGUID(pHostilReference->getUnitGuid());
13102 data << uint32(count);
13103 for (ThreatList::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr)
13105 data.appendPackGUID((*itr)->getUnitGuid());
13106 data << uint32((*itr)->getThreat());
13108 SendMessageToSet(&data, false);
13112 void Unit::SendThreatClear()
13114 sLog.outDebug( "WORLD: Send SMSG_THREAT_CLEAR Message" );
13115 WorldPacket data(SMSG_THREAT_CLEAR, 8);
13116 data.append(GetPackGUID());
13117 SendMessageToSet(&data, false);
13120 void Unit::SendThreatRemove(HostileReference* pHostileReference)
13122 sLog.outDebug( "WORLD: Send SMSG_THREAT_REMOVE Message" );
13123 WorldPacket data(SMSG_THREAT_REMOVE, 8 + 8);
13124 data.append(GetPackGUID());
13125 data.appendPackGUID(pHostileReference->getUnitGuid());
13126 SendMessageToSet(&data, false);
13129 struct StopAttackFactionHelper
13131 explicit StopAttackFactionHelper(uint32 _faction_id) : faction_id(_faction_id) {}
13132 void operator()(Unit* unit) const { unit->StopAttackFaction(faction_id); }
13133 uint32 faction_id;
13136 void Unit::StopAttackFaction(uint32 faction_id)
13138 if (Unit* victim = getVictim())
13140 if (victim->getFactionTemplateEntry()->faction==faction_id)
13142 AttackStop();
13143 if (IsNonMeleeSpellCasted(false))
13144 InterruptNonMeleeSpells(false);
13146 // melee and ranged forced attack cancel
13147 if (GetTypeId() == TYPEID_PLAYER)
13148 ((Player*)this)->SendAttackSwingCancelAttack();
13152 AttackerSet const& attackers = getAttackers();
13153 for(AttackerSet::const_iterator itr = attackers.begin(); itr != attackers.end();)
13155 if ((*itr)->getFactionTemplateEntry()->faction==faction_id)
13157 (*itr)->AttackStop();
13158 itr = attackers.begin();
13160 else
13161 ++itr;
13164 getHostileRefManager().deleteReferencesForFaction(faction_id);
13166 CallForAllControlledUnits(StopAttackFactionHelper(faction_id),false,true,true);
13169 void Unit::CleanupDeletedAuras()
13171 // really delete auras "deleted" while processing its ApplyModify code
13172 for(AuraList::const_iterator itr = m_deletedAuras.begin(); itr != m_deletedAuras.end(); ++itr)
13173 delete *itr;
13174 m_deletedAuras.clear();