[9581] Fixed apply damage reduction to melee/ranged damage.
[getmangos.git] / src / game / Unit.cpp
blobfbcf302a78e225beb41b0ccd6eee009032b1ce62
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 "ObjectGuid.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 "TemporarySummon.h"
39 #include "Formulas.h"
40 #include "Pet.h"
41 #include "Util.h"
42 #include "Totem.h"
43 #include "BattleGround.h"
44 #include "InstanceSaveMgr.h"
45 #include "GridNotifiersImpl.h"
46 #include "CellImpl.h"
47 #include "Path.h"
48 #include "Traveller.h"
49 #include "VMapFactory.h"
50 #include "MovementGenerator.h"
52 #include <math.h>
54 float baseMoveSpeed[MAX_MOVE_TYPE] =
56 2.5f, // MOVE_WALK
57 7.0f, // MOVE_RUN
58 1.25f, // MOVE_RUN_BACK
59 4.722222f, // MOVE_SWIM
60 4.5f, // MOVE_SWIM_BACK
61 3.141594f, // MOVE_TURN_RATE
62 7.0f, // MOVE_FLIGHT
63 4.5f, // MOVE_FLIGHT_BACK
64 3.14f // MOVE_PITCH_RATE
67 // Used for prepare can/can`t trigger aura
68 static bool InitTriggerAuraData();
69 // Define can trigger auras
70 static bool isTriggerAura[TOTAL_AURAS];
71 // Define can`t trigger auras (need for disable second trigger)
72 static bool isNonTriggerAura[TOTAL_AURAS];
73 // Prepare lists
74 static bool procPrepared = InitTriggerAuraData();
76 void MovementInfo::Read(ByteBuffer &data)
78 data >> moveFlags;
79 data >> moveFlags2;
80 data >> time;
81 data >> pos.x;
82 data >> pos.y;
83 data >> pos.z;
84 data >> pos.o;
86 if(HasMovementFlag(MOVEFLAG_ONTRANSPORT))
88 data >> t_guid.ReadAsPacked();
89 data >> t_pos.x;
90 data >> t_pos.y;
91 data >> t_pos.z;
92 data >> t_pos.o;
93 data >> t_time;
94 data >> t_seat;
96 if(moveFlags2 & MOVEFLAG2_UNK1)
97 data >> t_time2;
100 if((HasMovementFlag(MovementFlags(MOVEFLAG_SWIMMING | MOVEFLAG_FLYING))) || (moveFlags2 & MOVEFLAG2_ALLOW_PITCHING))
102 data >> s_pitch;
105 data >> fallTime;
107 if(HasMovementFlag(MOVEFLAG_FALLING))
109 data >> j_velocity;
110 data >> j_sinAngle;
111 data >> j_cosAngle;
112 data >> j_xyspeed;
115 if(HasMovementFlag(MOVEFLAG_SPLINE_ELEVATION))
117 data >> u_unk1;
121 void MovementInfo::Write(ByteBuffer &data) const
123 data << moveFlags;
124 data << moveFlags2;
125 data << time;
126 data << pos.x;
127 data << pos.y;
128 data << pos.z;
129 data << pos.o;
131 if(HasMovementFlag(MOVEFLAG_ONTRANSPORT))
133 data << t_guid.WriteAsPacked();
134 data << t_pos.x;
135 data << t_pos.y;
136 data << t_pos.z;
137 data << t_pos.o;
138 data << t_time;
139 data << t_seat;
141 if(moveFlags2 & MOVEFLAG2_UNK1)
142 data << t_time2;
145 if((HasMovementFlag(MovementFlags(MOVEFLAG_SWIMMING | MOVEFLAG_FLYING))) || (moveFlags2 & MOVEFLAG2_ALLOW_PITCHING))
147 data << s_pitch;
150 data << fallTime;
152 if(HasMovementFlag(MOVEFLAG_FALLING))
154 data << j_velocity;
155 data << j_sinAngle;
156 data << j_cosAngle;
157 data << j_xyspeed;
160 if(HasMovementFlag(MOVEFLAG_SPLINE_ELEVATION))
162 data << u_unk1;
166 Unit::Unit()
167 : WorldObject(), i_motionMaster(this), m_ThreatManager(this), m_HostileRefManager(this)
169 m_objectType |= TYPEMASK_UNIT;
170 m_objectTypeId = TYPEID_UNIT;
172 m_updateFlag = (UPDATEFLAG_HIGHGUID | UPDATEFLAG_LIVING | UPDATEFLAG_HAS_POSITION);
174 m_attackTimer[BASE_ATTACK] = 0;
175 m_attackTimer[OFF_ATTACK] = 0;
176 m_attackTimer[RANGED_ATTACK] = 0;
177 m_modAttackSpeedPct[BASE_ATTACK] = 1.0f;
178 m_modAttackSpeedPct[OFF_ATTACK] = 1.0f;
179 m_modAttackSpeedPct[RANGED_ATTACK] = 1.0f;
181 m_extraAttacks = 0;
183 m_state = 0;
184 m_form = FORM_NONE;
185 m_deathState = ALIVE;
187 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
188 m_currentSpells[i] = NULL;
190 m_castCounter = 0;
192 m_addDmgOnce = 0;
194 for(int i = 0; i < MAX_TOTEM_SLOT; ++i)
195 m_TotemSlot[i] = 0;
197 m_ObjectSlot[0] = m_ObjectSlot[1] = m_ObjectSlot[2] = m_ObjectSlot[3] = 0;
198 //m_Aura = NULL;
199 //m_AurasCheck = 2000;
200 //m_removeAuraTimer = 4;
201 m_AurasUpdateIterator = m_Auras.end();
202 m_AuraFlags = 0;
204 m_Visibility = VISIBILITY_ON;
206 m_detectInvisibilityMask = 0;
207 m_invisibilityMask = 0;
208 m_transform = 0;
209 m_ShapeShiftFormSpellId = 0;
210 m_canModifyStats = false;
212 for (int i = 0; i < MAX_SPELL_IMMUNITY; ++i)
213 m_spellImmune[i].clear();
214 for (int i = 0; i < UNIT_MOD_END; ++i)
216 m_auraModifiersGroup[i][BASE_VALUE] = 0.0f;
217 m_auraModifiersGroup[i][BASE_PCT] = 1.0f;
218 m_auraModifiersGroup[i][TOTAL_VALUE] = 0.0f;
219 m_auraModifiersGroup[i][TOTAL_PCT] = 1.0f;
221 // implement 50% base damage from offhand
222 m_auraModifiersGroup[UNIT_MOD_DAMAGE_OFFHAND][TOTAL_PCT] = 0.5f;
224 for (int i = 0; i < MAX_ATTACK; ++i)
226 m_weaponDamage[i][MINDAMAGE] = BASE_MINDAMAGE;
227 m_weaponDamage[i][MAXDAMAGE] = BASE_MAXDAMAGE;
229 for (int i = 0; i < MAX_STATS; ++i)
230 m_createStats[i] = 0.0f;
232 m_attacking = NULL;
233 m_modMeleeHitChance = 0.0f;
234 m_modRangedHitChance = 0.0f;
235 m_modSpellHitChance = 0.0f;
236 m_baseSpellCritChance = 5;
238 m_CombatTimer = 0;
239 m_lastManaUseTimer = 0;
241 //m_victimThreat = 0.0f;
242 for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
243 m_threatModifier[i] = 1.0f;
244 m_isSorted = true;
245 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
246 m_speed_rate[i] = 1.0f;
248 m_charmInfo = NULL;
250 // remove aurastates allowing special moves
251 for(int i=0; i < MAX_REACTIVE; ++i)
252 m_reactiveTimer[i] = 0;
255 Unit::~Unit()
257 // set current spells as deletable
258 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
260 if (m_currentSpells[i])
262 m_currentSpells[i]->SetReferencedFromCurrent(false);
263 m_currentSpells[i] = NULL;
267 if (m_charmInfo)
268 delete m_charmInfo;
270 // those should be already removed at "RemoveFromWorld()" call
271 assert(m_gameObj.size() == 0);
272 assert(m_dynObjGUIDs.size() == 0);
273 assert(m_deletedAuras.size() == 0);
276 void Unit::Update( uint32 p_time )
278 if(!IsInWorld())
279 return;
281 /*if(p_time > m_AurasCheck)
283 m_AurasCheck = 2000;
284 _UpdateAura();
285 }else
286 m_AurasCheck -= p_time;*/
288 // WARNING! Order of execution here is important, do not change.
289 // Spells must be processed with event system BEFORE they go to _UpdateSpells.
290 // Or else we may have some SPELL_STATE_FINISHED spells stalled in pointers, that is bad.
291 m_Events.Update( p_time );
292 _UpdateSpells( p_time );
294 CleanupDeletedAuras();
296 if (m_lastManaUseTimer)
298 if (p_time >= m_lastManaUseTimer)
299 m_lastManaUseTimer = 0;
300 else
301 m_lastManaUseTimer -= p_time;
304 if (CanHaveThreatList())
305 getThreatManager().UpdateForClient(p_time);
307 // update combat timer only for players and pets
308 if (isInCombat() && (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet() || ((Creature*)this)->isCharmed()))
310 // Check UNIT_STAT_MELEE_ATTACKING or UNIT_STAT_CHASE (without UNIT_STAT_FOLLOW in this case) so pets can reach far away
311 // targets without stopping half way there and running off.
312 // These flags are reset after target dies or another command is given.
313 if (m_HostileRefManager.isEmpty())
315 // m_CombatTimer set at aura start and it will be freeze until aura removing
316 if (m_CombatTimer <= p_time)
317 CombatStop();
318 else
319 m_CombatTimer -= p_time;
323 if (uint32 base_att = getAttackTimer(BASE_ATTACK))
325 setAttackTimer(BASE_ATTACK, (p_time >= base_att ? 0 : base_att - p_time) );
328 // update abilities available only for fraction of time
329 UpdateReactives( p_time );
331 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, GetHealth() < GetMaxHealth()*0.20f);
332 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, GetHealth() < GetMaxHealth()*0.35f);
333 ModifyAuraState(AURA_STATE_HEALTH_ABOVE_75_PERCENT, GetHealth() > GetMaxHealth()*0.75f);
335 i_motionMaster.UpdateMotion(p_time);
338 bool Unit::haveOffhandWeapon() const
340 if(GetTypeId() == TYPEID_PLAYER)
341 return ((Player*)this)->GetWeaponForAttack(OFF_ATTACK,true,true);
342 else
343 return false;
346 void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, SplineType type, SplineFlags flags, uint32 Time, Player* player)
348 float moveTime = (float)Time;
350 WorldPacket data( SMSG_MONSTER_MOVE, (41 + GetPackGUID().size()) );
351 data << GetPackGUID();
352 data << uint8(0); // new in 3.1
353 data << GetPositionX() << GetPositionY() << GetPositionZ();
354 data << uint32(getMSTime());
356 data << uint8(type); // unknown
357 switch(type)
359 case SPLINETYPE_NORMAL: // normal packet
360 break;
361 case SPLINETYPE_STOP: // stop packet (raw pos?)
362 SendMessageToSet( &data, true );
363 return;
364 case SPLINETYPE_FACINGSPOT: // facing spot, not used currently
365 data << float(0);
366 data << float(0);
367 data << float(0);
368 break;
369 case SPLINETYPE_FACINGTARGET:
370 data << uint64(m_InteractionObject); // set in SetFacingToObject()
371 break;
372 case SPLINETYPE_FACINGANGLE: // not used currently
373 data << float(0); // facing angle
374 break;
377 data << uint32(flags);
379 if(flags & SPLINEFLAG_WALKMODE)
380 moveTime *= 1.05f;
382 data << uint32(moveTime); // Time in between points
383 data << uint32(1); // 1 single waypoint
384 data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B
386 if(player)
387 player->GetSession()->SendPacket(&data);
388 else
389 SendMessageToSet( &data, true );
392 void Unit::SendMonsterMoveByPath(Path const& path, uint32 start, uint32 end, SplineFlags flags)
394 uint32 traveltime = uint32(path.GetTotalLength(start, end) * 32);
396 uint32 pathSize = end - start;
398 WorldPacket data( SMSG_MONSTER_MOVE, (GetPackGUID().size()+1+4+4+4+4+1+4+4+4+pathSize*4*3) );
399 data << GetPackGUID();
400 data << uint8(0);
401 data << GetPositionX();
402 data << GetPositionY();
403 data << GetPositionZ();
404 data << uint32(getMSTime());
405 data << uint8(SPLINETYPE_NORMAL);
406 data << uint32(flags);
407 data << uint32(traveltime);
408 data << uint32(pathSize);
409 data.append((char*)path.GetNodes(start), pathSize * 4 * 3);
410 SendMessageToSet(&data, true);
413 void Unit::SendMonsterMoveWithSpeed(float x, float y, float z, uint32 transitTime, Player* player)
415 if (!transitTime)
417 if(GetTypeId()==TYPEID_PLAYER)
419 Traveller<Player> traveller(*(Player*)this);
420 transitTime = traveller.GetTotalTrevelTimeTo(x, y, z);
422 else
424 Traveller<Creature> traveller(*(Creature*)this);
425 transitTime = traveller.GetTotalTrevelTimeTo(x, y, z);
428 //float orientation = (float)atan2((double)dy, (double)dx);
429 SplineFlags flags = GetTypeId() == TYPEID_PLAYER ? SPLINEFLAG_WALKMODE : ((Creature*)this)->GetSplineFlags();
430 SendMonsterMove(x, y, z, SPLINETYPE_NORMAL, flags, transitTime, player);
433 void Unit::BuildHeartBeatMsg(WorldPacket *data) const
435 MovementFlags move_flags = GetTypeId()==TYPEID_PLAYER
436 ? ((Player const*)this)->m_movementInfo.GetMovementFlags()
437 : MOVEFLAG_NONE;
439 data->Initialize(MSG_MOVE_HEARTBEAT, 32);
440 *data << GetPackGUID();
441 *data << uint32(move_flags); // movement flags
442 *data << uint16(0); // 2.3.0
443 *data << uint32(getMSTime()); // time
444 *data << float(GetPositionX());
445 *data << float(GetPositionY());
446 *data << float(GetPositionZ());
447 *data << float(GetOrientation());
448 *data << uint32(0);
451 void Unit::resetAttackTimer(WeaponAttackType type)
453 m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]);
456 bool Unit::canReachWithAttack(Unit *pVictim) const
458 assert(pVictim);
459 float reach = GetFloatValue(UNIT_FIELD_COMBATREACH);
460 if( reach <= 0.0f )
461 reach = 1.0f;
462 return IsWithinDistInMap(pVictim, reach);
465 void Unit::RemoveSpellsCausingAura(AuraType auraType)
467 if (auraType >= TOTAL_AURAS) return;
468 AuraList::const_iterator iter, next;
469 for (iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end(); iter = next)
471 next = iter;
472 ++next;
474 if (*iter)
476 RemoveAurasDueToSpell((*iter)->GetId());
477 if (!m_modAuras[auraType].empty())
478 next = m_modAuras[auraType].begin();
479 else
480 return;
485 bool Unit::HasAuraType(AuraType auraType) const
487 return (!m_modAuras[auraType].empty());
490 /* Called by DealDamage for auras that have a chance to be dispelled on damage taken. */
491 void Unit::RemoveSpellbyDamageTaken(AuraType auraType, uint32 damage)
493 if(!HasAuraType(auraType))
494 return;
496 // The chance to dispel an aura depends on the damage taken with respect to the casters level.
497 uint32 max_dmg = getLevel() > 8 ? 25 * getLevel() - 150 : 50;
498 float chance = float(damage) / max_dmg * 100.0f;
499 if (roll_chance_f(chance))
500 RemoveSpellsCausingAura(auraType);
503 void Unit::DealDamageMods(Unit *pVictim, uint32 &damage, uint32* absorb)
505 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
507 if(absorb)
508 absorb += damage;
509 damage = 0;
510 return;
513 //You don't lose health from damage taken from another player while in a sanctuary
514 //You still see it in the combat log though
515 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
517 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
518 if(area && area->flags & AREA_FLAG_SANCTUARY) //sanctuary
520 if(absorb)
521 absorb += damage;
522 damage = 0;
526 uint32 originalDamage = damage;
528 //Script Event damage Deal
529 if( GetTypeId()== TYPEID_UNIT && ((Creature *)this)->AI())
530 ((Creature *)this)->AI()->DamageDeal(pVictim, damage);
531 //Script Event damage taken
532 if( pVictim->GetTypeId()== TYPEID_UNIT && ((Creature *)pVictim)->AI() )
533 ((Creature *)pVictim)->AI()->DamageTaken(this, damage);
535 if(absorb && originalDamage > damage)
536 absorb += (originalDamage - damage);
539 uint32 Unit::DealDamage(Unit *pVictim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellEntry const *spellProto, bool durabilityLoss)
541 // remove affects from victim (including from 0 damage and DoTs)
542 if(pVictim != this)
543 pVictim->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
545 // remove affects from attacker at any non-DoT damage (including 0 damage)
546 if( damagetype != DOT)
548 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
549 RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
551 if(pVictim != this)
552 RemoveSpellsCausingAura(SPELL_AURA_MOD_INVISIBILITY);
554 if(pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->IsStandState() && !pVictim->hasUnitState(UNIT_STAT_STUNNED))
555 pVictim->SetStandState(UNIT_STAND_STATE_STAND);
558 if(!damage)
560 // Rage from physical damage received .
561 if(cleanDamage && cleanDamage->damage && (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL) && pVictim->GetTypeId() == TYPEID_PLAYER && (pVictim->getPowerType() == POWER_RAGE))
562 ((Player*)pVictim)->RewardRage(cleanDamage->damage, 0, false);
564 return 0;
566 if (!spellProto || !IsSpellHaveAura(spellProto,SPELL_AURA_MOD_FEAR))
567 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_FEAR, damage);
568 // root type spells do not dispel the root effect
569 if (!spellProto || !(spellProto->Mechanic == MECHANIC_ROOT || IsSpellHaveAura(spellProto,SPELL_AURA_MOD_ROOT)))
570 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_ROOT, damage);
572 // no xp,health if type 8 /critters/
573 if(pVictim->GetTypeId() != TYPEID_PLAYER && pVictim->GetCreatureType() == CREATURE_TYPE_CRITTER)
575 pVictim->setDeathState(JUST_DIED);
576 pVictim->SetHealth(0);
578 // allow loot only if has loot_id in creature_template
579 CreatureInfo const* cInfo = ((Creature*)pVictim)->GetCreatureInfo();
580 if(cInfo && cInfo->lootid)
581 pVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
583 // some critters required for quests (need normal entry instead possible heroic in any cases)
584 if(GetTypeId() == TYPEID_PLAYER)
585 if(CreatureInfo const* normalInfo = ObjectMgr::GetCreatureTemplate(pVictim->GetEntry()))
586 ((Player*)this)->KilledMonster(normalInfo,pVictim->GetGUID());
588 return damage;
591 DEBUG_LOG("DealDamageStart");
593 uint32 health = pVictim->GetHealth();
594 sLog.outDetail("deal dmg:%d to health:%d ",damage,health);
596 // duel ends when player has 1 or less hp
597 bool duel_hasEnded = false;
598 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->duel && damage >= (health-1))
600 // prevent kill only if killed in duel and killed by opponent or opponent controlled creature
601 if(((Player*)pVictim)->duel->opponent==this || ((Player*)pVictim)->duel->opponent->GetGUID() == GetOwnerGUID())
602 damage = health-1;
604 duel_hasEnded = true;
606 //Get in CombatState
607 if(pVictim != this && damagetype != DOT)
609 SetInCombatWith(pVictim);
610 pVictim->SetInCombatWith(this);
612 if(Player* attackedPlayer = pVictim->GetCharmerOrOwnerPlayerOrPlayerItself())
613 SetContestedPvP(attackedPlayer);
616 // Rage from Damage made (only from direct weapon damage)
617 if( cleanDamage && damagetype==DIRECT_DAMAGE && this != pVictim && GetTypeId() == TYPEID_PLAYER && (getPowerType() == POWER_RAGE))
619 uint32 weaponSpeedHitFactor;
621 switch(cleanDamage->attackType)
623 case BASE_ATTACK:
625 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
626 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 7);
627 else
628 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
630 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
632 break;
634 case OFF_ATTACK:
636 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
637 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
638 else
639 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 1.75f);
641 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
643 break;
645 case RANGED_ATTACK:
646 break;
650 if (GetTypeId() == TYPEID_PLAYER && this != pVictim)
652 Player *killer = ((Player*)this);
654 // in bg, count dmg if victim is also a player
655 if (pVictim->GetTypeId()==TYPEID_PLAYER)
657 if (BattleGround *bg = killer->GetBattleGround())
659 // FIXME: kept by compatibility. don't know in BG if the restriction apply.
660 bg->UpdatePlayerScore(killer, SCORE_DAMAGE_DONE, damage);
664 killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE, damage, 0, pVictim);
665 killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT, damage);
668 if (pVictim->GetTypeId() == TYPEID_PLAYER)
669 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED, damage);
671 if (pVictim->GetTypeId() == TYPEID_UNIT && !((Creature*)pVictim)->isPet() && !((Creature*)pVictim)->hasLootRecipient())
672 ((Creature*)pVictim)->SetLootRecipient(this);
674 if (health <= damage)
676 DEBUG_LOG("DealDamage: victim just died");
678 // find player: owner of controlled `this` or `this` itself maybe
679 Player *player = GetCharmerOrOwnerPlayerOrPlayerItself();
681 // find owner of pVictim, used for creature cases, AI calls
682 Unit* pOwner = pVictim->GetCharmerOrOwner();
684 if(pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->GetLootRecipient())
685 player = ((Creature*)pVictim)->GetLootRecipient();
687 if (pVictim->GetTypeId() == TYPEID_PLAYER)
689 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, health);
690 if (player)
691 player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL,1,0,pVictim);
694 // Reward player, his pets, and group/raid members
695 // call kill spell proc event (before real die and combat stop to triggering auras removed at death/combat stop)
696 if(player && player!=pVictim)
698 player->RewardPlayerAndGroupAtKill(pVictim);
699 player->ProcDamageAndSpell(pVictim, PROC_FLAG_KILL, PROC_FLAG_KILLED, PROC_EX_NONE, 0);
701 WorldPacket data(SMSG_PARTYKILLLOG, (8+8)); //send event PARTY_KILL
702 data << uint64(player->GetGUID()); //player with killing blow
703 data << uint64(pVictim->GetGUID()); //victim
704 if (Group *group = player->GetGroup())
705 group->BroadcastPacket(&data, group->GetMemberGroup(player->GetGUID()));
706 else
707 player->SendDirectMessage(&data);
710 DEBUG_LOG("DealDamageAttackStop");
712 // stop combat
713 pVictim->CombatStop();
714 pVictim->getHostileRefManager().deleteReferences();
716 bool damageFromSpiritOfRedemtionTalent = spellProto && spellProto->Id == 27795;
718 // if talent known but not triggered (check priest class for speedup check)
719 Aura* spiritOfRedemtionTalentReady = NULL;
720 if( !damageFromSpiritOfRedemtionTalent && // not called from SPELL_AURA_SPIRIT_OF_REDEMPTION
721 pVictim->GetTypeId()==TYPEID_PLAYER && pVictim->getClass()==CLASS_PRIEST )
723 AuraList const& vDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
724 for(AuraList::const_iterator itr = vDummyAuras.begin(); itr != vDummyAuras.end(); ++itr)
726 if((*itr)->GetSpellProto()->SpellIconID==1654)
728 spiritOfRedemtionTalentReady = *itr;
729 break;
734 DEBUG_LOG("SET JUST_DIED");
735 if(!spiritOfRedemtionTalentReady)
736 pVictim->setDeathState(JUST_DIED);
738 DEBUG_LOG("DealDamageHealth1");
740 if(spiritOfRedemtionTalentReady)
742 // save value before aura remove
743 uint32 ressSpellId = pVictim->GetUInt32Value(PLAYER_SELF_RES_SPELL);
744 if(!ressSpellId)
745 ressSpellId = ((Player*)pVictim)->GetResurrectionSpellId();
747 //Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers)
748 pVictim->RemoveAllAurasOnDeath();
750 // restore for use at real death
751 pVictim->SetUInt32Value(PLAYER_SELF_RES_SPELL,ressSpellId);
753 // FORM_SPIRITOFREDEMPTION and related auras
754 pVictim->CastSpell(pVictim,27827,true,NULL,spiritOfRedemtionTalentReady);
756 else
757 pVictim->SetHealth(0);
759 // remember victim PvP death for corpse type and corpse reclaim delay
760 // at original death (not at SpiritOfRedemtionTalent timeout)
761 if( pVictim->GetTypeId()==TYPEID_PLAYER && !damageFromSpiritOfRedemtionTalent )
762 ((Player*)pVictim)->SetPvPDeath(player!=NULL);
764 // Call KilledUnit for creatures
765 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->AI())
766 ((Creature*)this)->AI()->KilledUnit(pVictim);
768 // achievement stuff
769 if (pVictim->GetTypeId() == TYPEID_PLAYER)
771 if (GetTypeId() == TYPEID_UNIT)
772 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE, GetEntry());
773 else if(GetTypeId() == TYPEID_PLAYER && pVictim != this)
774 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER, 1, ((Player*)this)->GetTeam());
777 // 10% durability loss on death
778 // clean InHateListOf
779 if (pVictim->GetTypeId() == TYPEID_PLAYER)
781 // only if not player and not controlled by player pet. And not at BG
782 if (durabilityLoss && !player && !((Player*)pVictim)->InBattleGround())
784 DEBUG_LOG("We are dead, loosing 10 percents durability");
785 ((Player*)pVictim)->DurabilityLossAll(0.10f,false);
786 // durability lost message
787 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
788 ((Player*)pVictim)->GetSession()->SendPacket(&data);
791 else // creature died
793 DEBUG_LOG("DealDamageNotPlayer");
794 Creature *cVictim = (Creature*)pVictim;
796 if(!cVictim->isPet())
798 cVictim->DeleteThreatList();
799 // only lootable if it has loot or can drop gold
800 if(cVictim->GetCreatureInfo()->lootid || cVictim->GetCreatureInfo()->maxgold > 0)
801 cVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
802 else
803 cVictim->lootForBody = true; // needed for skinning
805 // Call creature just died function
806 if (cVictim->AI())
807 cVictim->AI()->JustDied(this);
809 if (cVictim->isTemporarySummon())
811 TemporarySummon* pSummon = (TemporarySummon*)cVictim;
812 if (IS_CREATURE_GUID(pSummon->GetSummonerGUID()))
813 if(Creature* pSummoner = cVictim->GetMap()->GetCreature(pSummon->GetSummonerGUID()))
814 if (pSummoner->AI())
815 pSummoner->AI()->SummonedCreatureJustDied(cVictim);
817 else if (pOwner && pOwner->GetTypeId() == TYPEID_UNIT)
819 if (((Creature*)pOwner)->AI())
820 ((Creature*)pOwner)->AI()->SummonedCreatureJustDied(cVictim);
823 // Dungeon specific stuff, only applies to players killing creatures
824 if(cVictim->GetInstanceId())
826 Map *m = cVictim->GetMap();
827 Player *creditedPlayer = GetCharmerOrOwnerPlayerOrPlayerItself();
828 // TODO: do instance binding anyway if the charmer/owner is offline
830 if(m->IsDungeon() && creditedPlayer)
832 if (m->IsRaidOrHeroicDungeon())
834 if(cVictim->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
835 ((InstanceMap *)m)->PermBindAllPlayers(creditedPlayer);
837 else
839 // the reset time is set but not added to the scheduler
840 // until the players leave the instance
841 time_t resettime = cVictim->GetRespawnTimeEx() + 2 * HOUR;
842 if(InstanceSave *save = sInstanceSaveMgr.GetInstanceSave(cVictim->GetInstanceId()))
843 if(save->GetResetTime() < resettime) save->SetResetTime(resettime);
849 // last damage from non duel opponent or opponent controlled creature
850 if(duel_hasEnded)
852 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
853 Player *he = (Player*)pVictim;
855 assert(he->duel);
857 he->duel->opponent->CombatStopWithPets(true);
858 he->CombatStopWithPets(true);
860 he->DuelComplete(DUEL_INTERUPTED);
863 // battleground things (do this at the end, so the death state flag will be properly set to handle in the bg->handlekill)
864 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->InBattleGround())
866 Player *killed = ((Player*)pVictim);
867 if(BattleGround *bg = killed->GetBattleGround())
868 if(player)
869 bg->HandleKillPlayer(killed, player);
871 else if(pVictim->GetTypeId() == TYPEID_UNIT)
873 if (player)
874 if (BattleGround *bg = player->GetBattleGround())
875 bg->HandleKillUnit((Creature*)pVictim, player);
878 else // if (health <= damage)
880 DEBUG_LOG("DealDamageAlive");
882 if (pVictim->GetTypeId() == TYPEID_PLAYER)
883 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, damage);
885 pVictim->ModifyHealth(- (int32)damage);
887 if(damagetype != DOT)
889 if(!getVictim())
891 // if not have main target then attack state with target (including AI call)
892 //start melee attacks only after melee hit
893 Attack(pVictim,(damagetype == DIRECT_DAMAGE));
896 // if damage pVictim call AI reaction
897 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
898 ((Creature*)pVictim)->AI()->AttackedBy(this);
901 // polymorphed, hex and other negative transformed cases
902 uint32 morphSpell = pVictim->getTransForm();
903 if (morphSpell && !IsPositiveSpell(morphSpell))
905 if (SpellEntry const* morphEntry = sSpellStore.LookupEntry(morphSpell))
907 if (IsSpellHaveAura(morphEntry, SPELL_AURA_MOD_CONFUSE))
908 pVictim->RemoveAurasDueToSpell(morphSpell);
909 else if (IsSpellHaveAura(morphEntry, SPELL_AURA_MOD_PACIFY_SILENCE))
910 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_PACIFY_SILENCE, damage);
914 if(damagetype == DIRECT_DAMAGE || damagetype == SPELL_DIRECT_DAMAGE)
916 if (!spellProto || !(spellProto->AuraInterruptFlags&AURA_INTERRUPT_FLAG_DIRECT_DAMAGE))
917 pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DIRECT_DAMAGE);
919 if (pVictim->GetTypeId() != TYPEID_PLAYER)
921 if(spellProto && IsDamageToThreatSpell(spellProto))
922 pVictim->AddThreat(this, float(damage*2), (cleanDamage && cleanDamage->hitOutCome == MELEE_HIT_CRIT), damageSchoolMask, spellProto);
923 else
924 pVictim->AddThreat(this, float(damage), (cleanDamage && cleanDamage->hitOutCome == MELEE_HIT_CRIT), damageSchoolMask, spellProto);
926 else // victim is a player
928 // Rage from damage received
929 if(this != pVictim && pVictim->getPowerType() == POWER_RAGE)
931 uint32 rage_damage = damage + (cleanDamage ? cleanDamage->damage : 0);
932 ((Player*)pVictim)->RewardRage(rage_damage, 0, false);
935 // random durability for items (HIT TAKEN)
936 if (roll_chance_f(sWorld.getConfig(CONFIG_FLOAT_RATE_DURABILITY_LOSS_DAMAGE)))
938 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
939 ((Player*)pVictim)->DurabilityPointLossForEquipSlot(slot);
943 if(GetTypeId()==TYPEID_PLAYER)
945 // random durability for items (HIT DONE)
946 if (roll_chance_f(sWorld.getConfig(CONFIG_FLOAT_RATE_DURABILITY_LOSS_DAMAGE)))
948 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
949 ((Player*)this)->DurabilityPointLossForEquipSlot(slot);
953 // TODO: Store auras by interrupt flag to speed this up.
954 AuraMap& vAuras = pVictim->GetAuras();
955 for (AuraMap::const_iterator i = vAuras.begin(), next; i != vAuras.end(); i = next)
957 const SpellEntry *se = i->second->GetSpellProto();
958 next = i; ++next;
959 if (spellProto && spellProto->Id == se->Id) // Not drop auras added by self
960 continue;
961 if( se->AuraInterruptFlags & AURA_INTERRUPT_FLAG_DAMAGE )
963 bool remove = true;
964 if (se->procFlags & (1<<3))
966 if (!roll_chance_i(se->procChance))
967 remove = false;
969 if (remove)
971 pVictim->RemoveAurasDueToSpell(i->second->GetId());
972 // FIXME: this may cause the auras with proc chance to be rerolled several times
973 next = vAuras.begin();
978 if (damagetype != NODAMAGE && damage && pVictim->GetTypeId() == TYPEID_PLAYER)
980 if( damagetype != DOT )
982 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
984 // skip channeled spell (processed differently below)
985 if (i == CURRENT_CHANNELED_SPELL)
986 continue;
988 if(Spell* spell = pVictim->GetCurrentSpell(CurrentSpellTypes(i)))
990 if(spell->getState() == SPELL_STATE_PREPARING)
992 if(spell->m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_ABORT_ON_DMG)
993 pVictim->InterruptSpell(CurrentSpellTypes(i));
994 else
995 spell->Delayed();
1001 if(Spell* spell = pVictim->m_currentSpells[CURRENT_CHANNELED_SPELL])
1003 if (spell->getState() == SPELL_STATE_CASTING)
1005 uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags;
1006 if( channelInterruptFlags & CHANNEL_FLAG_DELAY )
1008 if(pVictim!=this) //don't shorten the duration of channeling if you damage yourself
1009 spell->DelayedChannel();
1011 else if( (channelInterruptFlags & (CHANNEL_FLAG_DAMAGE | CHANNEL_FLAG_DAMAGE2)) )
1013 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
1014 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
1017 else if (spell->getState() == SPELL_STATE_DELAYED)
1018 // break channeled spell in delayed state on damage
1020 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
1021 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
1026 // last damage from duel opponent
1027 if(duel_hasEnded)
1029 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
1030 Player *he = (Player*)pVictim;
1032 assert(he->duel);
1034 he->SetHealth(1);
1036 he->duel->opponent->CombatStopWithPets(true);
1037 he->CombatStopWithPets(true);
1039 he->CastSpell(he, 7267, true); // beg
1040 he->DuelComplete(DUEL_WON);
1044 DEBUG_LOG("DealDamageEnd returned %d damage", damage);
1046 return damage;
1049 void Unit::CastStop(uint32 except_spellid)
1051 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
1052 if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id!=except_spellid)
1053 InterruptSpell(CurrentSpellTypes(i),false);
1056 void Unit::CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
1058 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
1060 if(!spellInfo)
1062 sLog.outError("CastSpell: unknown spell id %i by caster: %s %u)", spellId,(GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
1063 return;
1066 CastSpell(Victim,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
1069 void Unit::CastSpell(Unit* Victim,SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
1071 if(!spellInfo)
1073 sLog.outError("CastSpell: unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
1074 return;
1077 if (castItem)
1078 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
1080 if(!originalCaster && triggeredByAura)
1081 originalCaster = triggeredByAura->GetCasterGUID();
1083 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
1085 SpellCastTargets targets;
1086 targets.setUnitTarget( Victim );
1087 spell->m_CastItem = castItem;
1088 spell->prepare(&targets, triggeredByAura);
1091 void Unit::CastCustomSpell(Unit* Victim,uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
1093 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
1095 if(!spellInfo)
1097 sLog.outError("CastCustomSpell: unknown spell id %i", spellId);
1098 return;
1101 CastCustomSpell(Victim,spellInfo,bp0,bp1,bp2,triggered,castItem,triggeredByAura, originalCaster);
1104 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)
1106 if(!spellInfo)
1108 sLog.outError("CastCustomSpell: unknown spell");
1109 return;
1112 if (castItem)
1113 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
1115 if(!originalCaster && triggeredByAura)
1116 originalCaster = triggeredByAura->GetCasterGUID();
1118 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster);
1120 if(bp0)
1121 spell->m_currentBasePoints[EFFECT_INDEX_0] = *bp0-int32(spellInfo->EffectBaseDice[EFFECT_INDEX_0]);
1123 if(bp1)
1124 spell->m_currentBasePoints[EFFECT_INDEX_1] = *bp1-int32(spellInfo->EffectBaseDice[EFFECT_INDEX_1]);
1126 if(bp2)
1127 spell->m_currentBasePoints[EFFECT_INDEX_2] = *bp2-int32(spellInfo->EffectBaseDice[EFFECT_INDEX_2]);
1129 SpellCastTargets targets;
1130 targets.setUnitTarget( Victim );
1131 spell->m_CastItem = castItem;
1132 spell->prepare(&targets, triggeredByAura);
1135 // used for scripting
1136 void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
1138 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
1140 if(!spellInfo)
1142 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()));
1143 return;
1146 CastSpell(x, y, z,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
1149 // used for scripting
1150 void Unit::CastSpell(float x, float y, float z, SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
1152 if(!spellInfo)
1154 sLog.outError("CastSpell(x,y,z): unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
1155 return;
1158 if (castItem)
1159 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
1161 if(!originalCaster && triggeredByAura)
1162 originalCaster = triggeredByAura->GetCasterGUID();
1164 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
1166 SpellCastTargets targets;
1167 targets.setDestination(x, y, z);
1168 spell->m_CastItem = castItem;
1169 spell->prepare(&targets, triggeredByAura);
1172 // Obsolete func need remove, here only for comotability vs another patches
1173 uint32 Unit::SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage)
1175 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellID);
1176 SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, spellInfo->SchoolMask);
1177 CalculateSpellDamage(&damageInfo, damage, spellInfo);
1178 DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb);
1179 SendSpellNonMeleeDamageLog(&damageInfo);
1180 DealSpellDamage(&damageInfo, true);
1181 return damageInfo.damage;
1184 void Unit::CalculateSpellDamage(SpellNonMeleeDamage *damageInfo, int32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType)
1186 SpellSchoolMask damageSchoolMask = SpellSchoolMask(damageInfo->schoolMask);
1187 Unit *pVictim = damageInfo->target;
1189 if (damage < 0)
1190 return;
1192 if(!this || !pVictim)
1193 return;
1194 if(!this->isAlive() || !pVictim->isAlive())
1195 return;
1197 // Check spell crit chance
1198 bool crit = isSpellCrit(pVictim, spellInfo, damageSchoolMask, attackType);
1199 bool blocked = false;
1201 // damage bonus (per damage class)
1202 switch (spellInfo->DmgClass)
1204 // Melee and Ranged Spells
1205 case SPELL_DAMAGE_CLASS_RANGED:
1206 case SPELL_DAMAGE_CLASS_MELEE:
1208 //Calculate damage bonus
1209 damage = MeleeDamageBonus(pVictim, damage, attackType, spellInfo, SPELL_DIRECT_DAMAGE);
1210 // Get blocked status
1211 blocked = isSpellBlocked(pVictim, spellInfo, attackType);
1213 // if crit add critical bonus
1214 if (crit)
1216 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1217 damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim);
1218 // Resilience - reduce crit damage
1219 uint32 redunction_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageSchoolMask);
1220 if (attackType != RANGED_ATTACK)
1221 damage -= pVictim->GetMeleeCritDamageReduction(redunction_affected_damage);
1222 else
1223 damage -= pVictim->GetRangedCritDamageReduction(redunction_affected_damage);
1226 break;
1227 // Magical Attacks
1228 case SPELL_DAMAGE_CLASS_NONE:
1229 case SPELL_DAMAGE_CLASS_MAGIC:
1231 // Calculate damage bonus
1232 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1233 // If crit add critical bonus
1234 if (crit)
1236 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1237 damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim);
1238 // Resilience - reduce crit damage
1239 uint32 redunction_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageSchoolMask);
1240 damage -= pVictim->GetSpellCritDamageReduction(redunction_affected_damage);
1243 break;
1246 // only from players
1247 if (GetTypeId() == TYPEID_PLAYER)
1249 uint32 redunction_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageSchoolMask);
1250 damage -= pVictim->GetSpellDamageReduction(redunction_affected_damage);
1253 // damage mitigation
1254 if (damage > 0)
1256 // physical damage => armor
1257 if (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL)
1259 uint32 armor_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageSchoolMask);
1260 damage = damage - armor_affected_damage + CalcArmorReducedDamage(pVictim, armor_affected_damage);
1263 // block (only for damage class ranged and -melee, also non-physical damage possible)
1264 if (blocked)
1266 damageInfo->blocked = pVictim->GetShieldBlockValue();
1267 if (damage < (int32)damageInfo->blocked)
1268 damageInfo->blocked = damage;
1269 damage-=damageInfo->blocked;
1272 uint32 absorb_affected_damage = CalcNotIgnoreAbsorbDamage(damage,damageSchoolMask,spellInfo);
1273 CalcAbsorbResist(pVictim, damageSchoolMask, SPELL_DIRECT_DAMAGE, absorb_affected_damage, &damageInfo->absorb, &damageInfo->resist, !(spellInfo->AttributesEx2 & SPELL_ATTR_EX2_CANT_REFLECTED));
1274 damage-= damageInfo->absorb + damageInfo->resist;
1276 else
1277 damage = 0;
1278 damageInfo->damage = damage;
1281 void Unit::DealSpellDamage(SpellNonMeleeDamage *damageInfo, bool durabilityLoss)
1283 if (!damageInfo)
1284 return;
1286 Unit *pVictim = damageInfo->target;
1288 if(!this || !pVictim)
1289 return;
1291 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1292 return;
1294 SpellEntry const *spellProto = sSpellStore.LookupEntry(damageInfo->SpellID);
1295 if (spellProto == NULL)
1297 sLog.outDebug("Unit::DealSpellDamage have wrong damageInfo->SpellID: %u", damageInfo->SpellID);
1298 return;
1301 //You don't lose health from damage taken from another player while in a sanctuary
1302 //You still see it in the combat log though
1303 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1305 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1306 if(area && area->flags & AREA_FLAG_SANCTUARY) // sanctuary
1307 return;
1310 // Call default DealDamage (send critical in hit info for threat calculation)
1311 CleanDamage cleanDamage(damageInfo->cleanDamage, BASE_ATTACK, damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT ? MELEE_HIT_CRIT : MELEE_HIT_NORMAL);
1312 DealDamage(pVictim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, SpellSchoolMask(damageInfo->schoolMask), spellProto, durabilityLoss);
1315 //TODO for melee need create structure as in
1316 void Unit::CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType)
1318 damageInfo->attacker = this;
1319 damageInfo->target = pVictim;
1320 damageInfo->damageSchoolMask = GetMeleeDamageSchoolMask();
1321 damageInfo->attackType = attackType;
1322 damageInfo->damage = 0;
1323 damageInfo->cleanDamage = 0;
1324 damageInfo->absorb = 0;
1325 damageInfo->resist = 0;
1326 damageInfo->blocked_amount = 0;
1328 damageInfo->TargetState = 0;
1329 damageInfo->HitInfo = 0;
1330 damageInfo->procAttacker = PROC_FLAG_NONE;
1331 damageInfo->procVictim = PROC_FLAG_NONE;
1332 damageInfo->procEx = PROC_EX_NONE;
1333 damageInfo->hitOutCome = MELEE_HIT_EVADE;
1335 if(!this || !pVictim)
1336 return;
1337 if(!this->isAlive() || !pVictim->isAlive())
1338 return;
1340 // Select HitInfo/procAttacker/procVictim flag based on attack type
1341 switch (attackType)
1343 case BASE_ATTACK:
1344 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_HIT;
1345 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;
1346 damageInfo->HitInfo = HITINFO_NORMALSWING2;
1347 break;
1348 case OFF_ATTACK:
1349 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_HIT | PROC_FLAG_SUCCESSFUL_OFFHAND_HIT;
1350 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;//|PROC_FLAG_TAKEN_OFFHAND_HIT // not used
1351 damageInfo->HitInfo = HITINFO_LEFTSWING;
1352 break;
1353 case RANGED_ATTACK:
1354 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
1355 damageInfo->procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
1356 damageInfo->HitInfo = 0x08;// test
1357 break;
1358 default:
1359 break;
1362 // Physical Immune check
1363 if (damageInfo->target->IsImmunedToDamage(damageInfo->damageSchoolMask))
1365 damageInfo->HitInfo |= HITINFO_NORMALSWING;
1366 damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE;
1368 damageInfo->procEx |=PROC_EX_IMMUNE;
1369 damageInfo->damage = 0;
1370 damageInfo->cleanDamage = 0;
1371 return;
1373 damage += CalculateDamage (damageInfo->attackType, false);
1374 // Add melee damage bonus
1375 damage = MeleeDamageBonus(damageInfo->target, damage, damageInfo->attackType);
1376 // Calculate armor reduction
1378 uint32 armor_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageInfo->damageSchoolMask);
1379 damageInfo->damage = damage - armor_affected_damage + CalcArmorReducedDamage(damageInfo->target, armor_affected_damage);
1380 damageInfo->cleanDamage += damage - damageInfo->damage;
1382 damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType);
1384 // Disable parry or dodge for ranged attack
1385 if (damageInfo->attackType == RANGED_ATTACK)
1387 if (damageInfo->hitOutCome == MELEE_HIT_PARRY) damageInfo->hitOutCome = MELEE_HIT_NORMAL;
1388 if (damageInfo->hitOutCome == MELEE_HIT_DODGE) damageInfo->hitOutCome = MELEE_HIT_MISS;
1391 switch(damageInfo->hitOutCome)
1393 case MELEE_HIT_EVADE:
1395 damageInfo->HitInfo |= HITINFO_MISS|HITINFO_SWINGNOHITSOUND;
1396 damageInfo->TargetState = VICTIMSTATE_EVADES;
1398 damageInfo->procEx|=PROC_EX_EVADE;
1399 damageInfo->damage = 0;
1400 damageInfo->cleanDamage = 0;
1401 return;
1403 case MELEE_HIT_MISS:
1405 damageInfo->HitInfo |= HITINFO_MISS;
1406 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1408 damageInfo->procEx|=PROC_EX_MISS;
1409 damageInfo->damage = 0;
1410 damageInfo->cleanDamage = 0;
1411 break;
1413 case MELEE_HIT_NORMAL:
1414 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1415 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1416 break;
1417 case MELEE_HIT_CRIT:
1419 damageInfo->HitInfo |= HITINFO_CRITICALHIT;
1420 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1422 damageInfo->procEx|=PROC_EX_CRITICAL_HIT;
1423 // Crit bonus calc
1424 damageInfo->damage += damageInfo->damage;
1425 int32 mod=0;
1426 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1427 if(damageInfo->attackType == RANGED_ATTACK)
1428 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1429 else
1430 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1432 mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS, SPELL_SCHOOL_MASK_NORMAL);
1434 uint32 crTypeMask = damageInfo->target->GetCreatureTypeMask();
1436 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1437 mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1438 if (mod!=0)
1439 damageInfo->damage = int32((damageInfo->damage) * float((100.0f + mod)/100.0f));
1441 // Resilience - reduce crit damage
1442 uint32 redunction_affected_damage = CalcNotIgnoreDamageRedunction(damageInfo->damage,damageInfo->damageSchoolMask);
1443 uint32 resilienceReduction;
1444 if (attackType != RANGED_ATTACK)
1445 resilienceReduction = pVictim->GetMeleeCritDamageReduction(redunction_affected_damage);
1446 else
1447 resilienceReduction = pVictim->GetRangedCritDamageReduction(redunction_affected_damage);
1449 damageInfo->damage -= resilienceReduction;
1450 damageInfo->cleanDamage += resilienceReduction;
1451 break;
1453 case MELEE_HIT_PARRY:
1454 damageInfo->TargetState = VICTIMSTATE_PARRY;
1455 damageInfo->procEx |= PROC_EX_PARRY;
1456 damageInfo->cleanDamage += damageInfo->damage;
1457 damageInfo->damage = 0;
1458 break;
1460 case MELEE_HIT_DODGE:
1461 damageInfo->TargetState = VICTIMSTATE_DODGE;
1462 damageInfo->procEx|=PROC_EX_DODGE;
1463 damageInfo->cleanDamage += damageInfo->damage;
1464 damageInfo->damage = 0;
1465 break;
1466 case MELEE_HIT_BLOCK:
1468 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1469 damageInfo->HitInfo |= HITINFO_BLOCK;
1470 damageInfo->procEx |= PROC_EX_BLOCK;
1471 damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue();
1473 // Target has a chance to double the blocked amount if it has SPELL_AURA_MOD_BLOCK_CRIT_CHANCE
1474 if (roll_chance_i(pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_CRIT_CHANCE)))
1475 damageInfo->blocked_amount *= 2;
1477 if (damageInfo->blocked_amount >= damageInfo->damage)
1479 damageInfo->TargetState = VICTIMSTATE_BLOCKS;
1480 damageInfo->blocked_amount = damageInfo->damage;
1481 damageInfo->procEx |= PROC_EX_FULL_BLOCK;
1483 else
1484 damageInfo->procEx |= PROC_EX_NORMAL_HIT; // Partial blocks can still cause attacker procs
1486 damageInfo->damage -= damageInfo->blocked_amount;
1487 damageInfo->cleanDamage += damageInfo->blocked_amount;
1488 break;
1490 case MELEE_HIT_GLANCING:
1492 damageInfo->HitInfo |= HITINFO_GLANCING;
1493 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1494 damageInfo->procEx |= PROC_EX_NORMAL_HIT;
1495 float reducePercent = 1.0f; //damage factor
1496 // calculate base values and mods
1497 float baseLowEnd = 1.3f;
1498 float baseHighEnd = 1.2f;
1499 switch(getClass()) // lowering base values for casters
1501 case CLASS_SHAMAN:
1502 case CLASS_PRIEST:
1503 case CLASS_MAGE:
1504 case CLASS_WARLOCK:
1505 case CLASS_DRUID:
1506 baseLowEnd -= 0.7f;
1507 baseHighEnd -= 0.3f;
1508 break;
1511 float maxLowEnd = 0.6f;
1512 switch(getClass()) // upper for melee classes
1514 case CLASS_WARRIOR:
1515 case CLASS_ROGUE:
1516 maxLowEnd = 0.91f; //If the attacker is a melee class then instead the lower value of 0.91
1519 // calculate values
1520 int32 diff = damageInfo->target->GetDefenseSkillValue() - GetWeaponSkillValue(damageInfo->attackType);
1521 float lowEnd = baseLowEnd - ( 0.05f * diff );
1522 float highEnd = baseHighEnd - ( 0.03f * diff );
1524 // apply max/min bounds
1525 if ( lowEnd < 0.01f ) //the low end must not go bellow 0.01f
1526 lowEnd = 0.01f;
1527 else if ( lowEnd > maxLowEnd ) //the smaller value of this and 0.6 is kept as the low end
1528 lowEnd = maxLowEnd;
1530 if ( highEnd < 0.2f ) //high end limits
1531 highEnd = 0.2f;
1532 if ( highEnd > 0.99f )
1533 highEnd = 0.99f;
1535 if(lowEnd > highEnd) // prevent negative range size
1536 lowEnd = highEnd;
1538 reducePercent = lowEnd + rand_norm_f() * ( highEnd - lowEnd );
1540 damageInfo->cleanDamage += damageInfo->damage-uint32(reducePercent * damageInfo->damage);
1541 damageInfo->damage = uint32(reducePercent * damageInfo->damage);
1542 break;
1544 case MELEE_HIT_CRUSHING:
1546 damageInfo->HitInfo |= HITINFO_CRUSHING;
1547 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1548 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1549 // 150% normal damage
1550 damageInfo->damage += (damageInfo->damage / 2);
1551 break;
1553 default:
1555 break;
1558 // only from players
1559 if (GetTypeId() == TYPEID_PLAYER)
1561 uint32 redunction_affected_damage = CalcNotIgnoreDamageRedunction(damageInfo->damage,damageInfo->damageSchoolMask);
1562 uint32 resilienceReduction;
1563 if (attackType != RANGED_ATTACK)
1564 resilienceReduction = pVictim->GetMeleeDamageReduction(redunction_affected_damage);
1565 else
1566 resilienceReduction = pVictim->GetRangedDamageReduction(redunction_affected_damage);
1567 damageInfo->damage -= resilienceReduction;
1568 damageInfo->cleanDamage += resilienceReduction;
1571 // Calculate absorb resist
1572 if(int32(damageInfo->damage) > 0)
1574 damageInfo->procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1576 // Calculate absorb & resists
1577 uint32 absorb_affected_damage = CalcNotIgnoreAbsorbDamage(damageInfo->damage,damageInfo->damageSchoolMask);
1578 CalcAbsorbResist(damageInfo->target, damageInfo->damageSchoolMask, DIRECT_DAMAGE, absorb_affected_damage, &damageInfo->absorb, &damageInfo->resist, true);
1579 damageInfo->damage-=damageInfo->absorb + damageInfo->resist;
1580 if (damageInfo->absorb)
1582 damageInfo->HitInfo|=HITINFO_ABSORB;
1583 damageInfo->procEx|=PROC_EX_ABSORB;
1585 if (damageInfo->resist)
1586 damageInfo->HitInfo|=HITINFO_RESIST;
1589 else // Umpossible get negative result but....
1590 damageInfo->damage = 0;
1593 void Unit::DealMeleeDamage(CalcDamageInfo *damageInfo, bool durabilityLoss)
1595 if (damageInfo==0) return;
1596 Unit *pVictim = damageInfo->target;
1598 if(!this || !pVictim)
1599 return;
1601 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1602 return;
1604 //You don't lose health from damage taken from another player while in a sanctuary
1605 //You still see it in the combat log though
1606 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1608 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1609 if(area && area->flags & AREA_FLAG_SANCTUARY) // sanctuary
1610 return;
1613 // Hmmmm dont like this emotes client must by self do all animations
1614 if (damageInfo->HitInfo&HITINFO_CRITICALHIT)
1615 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_WOUNDCRITICAL);
1616 if(damageInfo->blocked_amount && damageInfo->TargetState!=VICTIMSTATE_BLOCKS)
1617 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_PARRYSHIELD);
1619 if(damageInfo->TargetState == VICTIMSTATE_PARRY)
1621 // Get attack timers
1622 float offtime = float(pVictim->getAttackTimer(OFF_ATTACK));
1623 float basetime = float(pVictim->getAttackTimer(BASE_ATTACK));
1624 // Reduce attack time
1625 if (pVictim->haveOffhandWeapon() && offtime < basetime)
1627 float percent20 = pVictim->GetAttackTime(OFF_ATTACK) * 0.20f;
1628 float percent60 = 3.0f * percent20;
1629 if(offtime > percent20 && offtime <= percent60)
1631 pVictim->setAttackTimer(OFF_ATTACK, uint32(percent20));
1633 else if(offtime > percent60)
1635 offtime -= 2.0f * percent20;
1636 pVictim->setAttackTimer(OFF_ATTACK, uint32(offtime));
1639 else
1641 float percent20 = pVictim->GetAttackTime(BASE_ATTACK) * 0.20f;
1642 float percent60 = 3.0f * percent20;
1643 if(basetime > percent20 && basetime <= percent60)
1645 pVictim->setAttackTimer(BASE_ATTACK, uint32(percent20));
1647 else if(basetime > percent60)
1649 basetime -= 2.0f * percent20;
1650 pVictim->setAttackTimer(BASE_ATTACK, uint32(basetime));
1655 // Call default DealDamage
1656 CleanDamage cleanDamage(damageInfo->cleanDamage,damageInfo->attackType,damageInfo->hitOutCome);
1657 DealDamage(pVictim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, damageInfo->damageSchoolMask, NULL, durabilityLoss);
1659 // If this is a creature and it attacks from behind it has a probability to daze it's victim
1660 if( (damageInfo->hitOutCome==MELEE_HIT_CRIT || damageInfo->hitOutCome==MELEE_HIT_CRUSHING || damageInfo->hitOutCome==MELEE_HIT_NORMAL || damageInfo->hitOutCome==MELEE_HIT_GLANCING) &&
1661 GetTypeId() != TYPEID_PLAYER && !((Creature*)this)->GetCharmerOrOwnerGUID() && !pVictim->HasInArc(M_PI_F, this) )
1663 // -probability is between 0% and 40%
1664 // 20% base chance
1665 float Probability = 20.0f;
1667 //there is a newbie protection, at level 10 just 7% base chance; assuming linear function
1668 if( pVictim->getLevel() < 30 )
1669 Probability = 0.65f*pVictim->getLevel()+0.5f;
1671 uint32 VictimDefense=pVictim->GetDefenseSkillValue();
1672 uint32 AttackerMeleeSkill=GetUnitMeleeSkill();
1674 Probability *= AttackerMeleeSkill/(float)VictimDefense;
1676 if(Probability > 40.0f)
1677 Probability = 40.0f;
1679 if(roll_chance_f(Probability))
1680 CastSpell(pVictim, 1604, true);
1683 // If not miss
1684 if (!(damageInfo->HitInfo & HITINFO_MISS))
1686 // on weapon hit casts
1687 if(GetTypeId() == TYPEID_PLAYER && pVictim->isAlive())
1688 ((Player*)this)->CastItemCombatSpell(pVictim, damageInfo->attackType);
1690 // victim's damage shield
1691 std::set<Aura*> alreadyDone;
1692 AuraList const& vDamageShields = pVictim->GetAurasByType(SPELL_AURA_DAMAGE_SHIELD);
1693 for(AuraList::const_iterator i = vDamageShields.begin(); i != vDamageShields.end();)
1695 if (alreadyDone.find(*i) == alreadyDone.end())
1697 alreadyDone.insert(*i);
1698 uint32 damage=(*i)->GetModifier()->m_amount;
1699 SpellEntry const *i_spellProto = (*i)->GetSpellProto();
1700 //Calculate absorb resist ??? no data in opcode for this possibly unable to absorb or resist?
1701 //uint32 absorb;
1702 //uint32 resist;
1703 //CalcAbsorbResist(pVictim, SpellSchools(spellProto->School), SPELL_DIRECT_DAMAGE, damage, &absorb, &resist);
1704 //damage-=absorb + resist;
1706 pVictim->DealDamageMods(this,damage,NULL);
1708 WorldPacket data(SMSG_SPELLDAMAGESHIELD,(8+8+4+4+4+4));
1709 data << uint64(pVictim->GetGUID());
1710 data << uint64(GetGUID());
1711 data << uint32(i_spellProto->Id);
1712 data << uint32(damage); // Damage
1713 data << uint32(0); // Overkill
1714 data << uint32(i_spellProto->SchoolMask);
1715 pVictim->SendMessageToSet(&data, true );
1717 pVictim->DealDamage(this, damage, 0, SPELL_DIRECT_DAMAGE, GetSpellSchoolMask(i_spellProto), i_spellProto, true);
1719 i = vDamageShields.begin();
1721 else
1722 ++i;
1728 void Unit::HandleEmoteCommand(uint32 anim_id)
1730 WorldPacket data( SMSG_EMOTE, 4 + 8 );
1731 data << uint32(anim_id);
1732 data << uint64(GetGUID());
1733 SendMessageToSet(&data, true);
1736 uint32 Unit::CalcNotIgnoreAbsorbDamage( uint32 damage, SpellSchoolMask damageSchoolMask, SpellEntry const* spellInfo /*= NULL*/)
1738 float absorb_affected_rate = 1.0f;
1739 Unit::AuraList const& ignoreAbsorbSchool = GetAurasByType(SPELL_AURA_MOD_IGNORE_ABSORB_SCHOOL);
1740 for(Unit::AuraList::const_iterator i = ignoreAbsorbSchool.begin(); i != ignoreAbsorbSchool.end(); ++i)
1741 if ((*i)->GetMiscValue() & damageSchoolMask)
1742 absorb_affected_rate *= (100.0f - (*i)->GetModifier()->m_amount)/100.0f;
1744 if(spellInfo)
1746 Unit::AuraList const& ignoreAbsorbForSpell = GetAurasByType(SPELL_AURA_MOD_IGNORE_ABSORB_FOR_SPELL);
1747 for(Unit::AuraList::const_iterator citr = ignoreAbsorbForSpell.begin(); citr != ignoreAbsorbForSpell.end(); ++citr)
1748 if ((*citr)->isAffectedOnSpell(spellInfo))
1749 absorb_affected_rate *= (100.0f - (*citr)->GetModifier()->m_amount)/100.0f;
1752 return absorb_affected_rate <= 0.0f ? 0 : (absorb_affected_rate < 1.0f ? uint32(damage * absorb_affected_rate) : damage);
1755 uint32 Unit::CalcNotIgnoreDamageRedunction( uint32 damage, SpellSchoolMask damageSchoolMask)
1757 float absorb_affected_rate = 1.0f;
1758 Unit::AuraList const& ignoreAbsorb = GetAurasByType(SPELL_AURA_MOD_IGNORE_DAMAGE_REDUCTION_SCHOOL);
1759 for(Unit::AuraList::const_iterator i = ignoreAbsorb.begin(); i != ignoreAbsorb.end(); ++i)
1760 if ((*i)->GetMiscValue() & damageSchoolMask)
1761 absorb_affected_rate *= (100.0f - (*i)->GetModifier()->m_amount)/100.0f;
1763 return absorb_affected_rate <= 0.0f ? 0 : (absorb_affected_rate < 1.0f ? uint32(damage * absorb_affected_rate) : damage);
1766 uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage)
1768 uint32 newdamage = 0;
1769 float armor = (float)pVictim->GetArmor();
1771 // Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura
1772 armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL);
1774 // Apply Player CR_ARMOR_PENETRATION rating and percent talents
1775 if (GetTypeId()==TYPEID_PLAYER)
1776 armor *= 1.0f - ((Player*)this)->GetArmorPenetrationPct() / 100.0f;
1778 if (armor < 0.0f)
1779 armor = 0.0f;
1781 float levelModifier = (float)getLevel();
1782 if (levelModifier > 59)
1783 levelModifier = levelModifier + (4.5f * (levelModifier-59));
1785 float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40);
1786 tmpvalue = tmpvalue/(1.0f + tmpvalue);
1788 if (tmpvalue < 0.0f)
1789 tmpvalue = 0.0f;
1790 if (tmpvalue > 0.75f)
1791 tmpvalue = 0.75f;
1793 newdamage = uint32(damage - (damage * tmpvalue));
1795 return (newdamage > 1) ? newdamage : 1;
1798 void Unit::CalcAbsorbResist(Unit *pVictim,SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist, bool canReflect)
1800 if(!pVictim || !pVictim->isAlive() || !damage)
1801 return;
1803 // Magic damage, check for resists
1804 if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL)==0)
1806 // Get base victim resistance for school
1807 float tmpvalue2 = (float)pVictim->GetResistance(GetFirstSchoolInMask(schoolMask));
1808 // Ignore resistance by self SPELL_AURA_MOD_TARGET_RESISTANCE aura
1809 tmpvalue2 += (float)GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask);
1811 tmpvalue2 *= (float)(0.15f / getLevel());
1812 if (tmpvalue2 < 0.0f)
1813 tmpvalue2 = 0.0f;
1814 if (tmpvalue2 > 0.75f)
1815 tmpvalue2 = 0.75f;
1816 uint32 ran = urand(0, 100);
1817 float faq[4] = {24.0f,6.0f,4.0f,6.0f};
1818 uint8 m = 0;
1819 float Binom = 0.0f;
1820 for (uint8 i = 0; i < 4; ++i)
1822 Binom += 2400 *( powf(tmpvalue2, float(i)) * powf( (1-tmpvalue2), float(4-i)))/faq[i];
1823 if (ran > Binom )
1824 ++m;
1825 else
1826 break;
1828 if (damagetype == DOT && m == 4)
1829 *resist += uint32(damage - 1);
1830 else
1831 *resist += uint32(damage * m / 4);
1832 if(*resist > damage)
1833 *resist = damage;
1835 else
1836 *resist = 0;
1838 int32 RemainingDamage = damage - *resist;
1840 // Get unit state (need for some absorb check)
1841 uint32 unitflag = pVictim->GetUInt32Value(UNIT_FIELD_FLAGS);
1842 // Reflect damage spells (not cast any damage spell in aura lookup)
1843 uint32 reflectSpell = 0;
1844 int32 reflectDamage = 0;
1845 Aura* reflectTriggeredBy = NULL; // expected as not expired at reflect as in current cases
1846 // Death Prevention Aura
1847 SpellEntry const* preventDeathSpell = NULL;
1848 int32 preventDeathAmount = 0;
1850 // full absorb cases (by chance)
1851 AuraList const& vAbsorb = pVictim->GetAurasByType(SPELL_AURA_SCHOOL_ABSORB);
1852 for(AuraList::const_iterator i = vAbsorb.begin(); i != vAbsorb.end() && RemainingDamage > 0; ++i)
1854 // only work with proper school mask damage
1855 Modifier* i_mod = (*i)->GetModifier();
1856 if (!(i_mod->m_miscvalue & schoolMask))
1857 continue;
1859 SpellEntry const* i_spellProto = (*i)->GetSpellProto();
1860 // Fire Ward or Frost Ward
1861 if(i_spellProto->SpellFamilyName == SPELLFAMILY_MAGE && i_spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000108))
1863 int chance = 0;
1864 Unit::AuraList const& auras = pVictim->GetAurasByType(SPELL_AURA_ADD_PCT_MODIFIER);
1865 for (Unit::AuraList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
1867 SpellEntry const* itr_spellProto = (*itr)->GetSpellProto();
1868 // Frost Warding (chance full absorb)
1869 if (itr_spellProto->SpellFamilyName == SPELLFAMILY_MAGE && itr_spellProto->SpellIconID == 501)
1871 // chance stored in next dummy effect
1872 chance = itr_spellProto->CalculateSimpleValue(EFFECT_INDEX_1);
1873 break;
1876 if(roll_chance_i(chance))
1878 int32 amount = RemainingDamage;
1879 RemainingDamage = 0;
1880 // Frost Warding (mana regen)
1881 pVictim->CastCustomSpell(pVictim, 57776, &amount, NULL, NULL, true, NULL, *i);
1882 break;
1887 // Need remove expired auras after
1888 bool existExpired = false;
1890 // absorb without mana cost
1891 AuraList const& vSchoolAbsorb = pVictim->GetAurasByType(SPELL_AURA_SCHOOL_ABSORB);
1892 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end() && RemainingDamage > 0; ++i)
1894 Modifier* mod = (*i)->GetModifier();
1895 if (!(mod->m_miscvalue & schoolMask))
1896 continue;
1898 SpellEntry const* spellProto = (*i)->GetSpellProto();
1900 // Max Amount can be absorbed by this aura
1901 int32 currentAbsorb = mod->m_amount;
1903 // Found empty aura (impossible but..)
1904 if (currentAbsorb <=0)
1906 existExpired = true;
1907 continue;
1909 // Handle custom absorb auras
1910 // TODO: try find better way
1911 switch(spellProto->SpellFamilyName)
1913 case SPELLFAMILY_GENERIC:
1915 // Astral Shift
1916 if (spellProto->SpellIconID == 3066)
1918 //reduces all damage taken while stun, fear or silence
1919 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1920 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1921 continue;
1923 // Nerves of Steel
1924 if (spellProto->SpellIconID == 2115)
1926 // while affected by Stun and Fear
1927 if (unitflag&(UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING))
1928 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1929 continue;
1931 // Spell Deflection
1932 if (spellProto->SpellIconID == 3006)
1934 // You have a chance equal to your Parry chance
1935 if (damagetype == DIRECT_DAMAGE && // Only for direct damage
1936 roll_chance_f(pVictim->GetUnitParryChance())) // Roll chance
1937 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1938 continue;
1940 // Reflective Shield (Lady Malande boss)
1941 if (spellProto->Id == 41475 && canReflect)
1943 if(RemainingDamage < currentAbsorb)
1944 reflectDamage = RemainingDamage / 2;
1945 else
1946 reflectDamage = currentAbsorb / 2;
1947 reflectSpell = 33619;
1948 reflectTriggeredBy = *i;
1949 break;
1951 if (spellProto->Id == 39228 || // Argussian Compass
1952 spellProto->Id == 60218) // Essence of Gossamer
1954 // Max absorb stored in 1 dummy effect
1955 if (spellProto->EffectBasePoints[EFFECT_INDEX_1] < currentAbsorb)
1956 currentAbsorb = spellProto->EffectBasePoints[EFFECT_INDEX_1];
1957 break;
1959 break;
1961 case SPELLFAMILY_DRUID:
1963 // Primal Tenacity
1964 if (spellProto->SpellIconID == 2253)
1966 //reduces all damage taken while Stunned
1967 if (unitflag & UNIT_FLAG_STUNNED)
1968 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1969 continue;
1971 break;
1973 case SPELLFAMILY_ROGUE:
1975 // Cheat Death (make less prio with Guardian Spirit case)
1976 if (!preventDeathSpell && spellProto->SpellIconID == 2109 &&
1977 pVictim->GetTypeId()==TYPEID_PLAYER && // Only players
1978 !((Player*)pVictim)->HasSpellCooldown(31231) &&
1979 // Only if no cooldown
1980 roll_chance_i((*i)->GetModifier()->m_amount))
1981 // Only if roll
1983 preventDeathSpell = (*i)->GetSpellProto();
1984 continue;
1986 break;
1988 case SPELLFAMILY_PRIEST:
1990 // Guardian Spirit
1991 if (spellProto->SpellIconID == 2873)
1993 preventDeathSpell = (*i)->GetSpellProto();
1994 preventDeathAmount = (*i)->GetModifier()->m_amount;
1995 continue;
1997 // Reflective Shield
1998 if (spellProto->SpellFamilyFlags == 0x1 && canReflect)
2000 if (pVictim == this)
2001 break;
2002 Unit* caster = (*i)->GetCaster();
2003 if (!caster)
2004 break;
2005 AuraList const& vOverRideCS = caster->GetAurasByType(SPELL_AURA_DUMMY);
2006 for(AuraList::const_iterator k = vOverRideCS.begin(); k != vOverRideCS.end(); ++k)
2008 switch((*k)->GetModifier()->m_miscvalue)
2010 case 5065: // Rank 1
2011 case 5064: // Rank 2
2013 if(RemainingDamage >= currentAbsorb)
2014 reflectDamage = (*k)->GetModifier()->m_amount * currentAbsorb/100;
2015 else
2016 reflectDamage = (*k)->GetModifier()->m_amount * RemainingDamage/100;
2017 reflectSpell = 33619;
2018 reflectTriggeredBy = *i;
2019 } break;
2020 default: break;
2023 break;
2025 break;
2027 case SPELLFAMILY_SHAMAN:
2029 // Astral Shift
2030 if (spellProto->SpellIconID == 3066)
2032 //reduces all damage taken while stun, fear or silence
2033 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
2034 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
2035 continue;
2037 break;
2039 case SPELLFAMILY_DEATHKNIGHT:
2041 // Shadow of Death
2042 if (spellProto->SpellIconID == 1958)
2044 // TODO: absorb only while transform
2045 continue;
2047 // Anti-Magic Shell (on self)
2048 if (spellProto->Id == 48707)
2050 // damage absorbed by Anti-Magic Shell energizes the DK with additional runic power.
2051 // This, if I'm not mistaken, shows that we get back ~2% of the absorbed damage as runic power.
2052 int32 absorbed = RemainingDamage * currentAbsorb / 100;
2053 int32 regen = absorbed * 2 / 10;
2054 pVictim->CastCustomSpell(pVictim, 49088, &regen, NULL, NULL, true, NULL, *i);
2055 RemainingDamage -= absorbed;
2056 continue;
2058 // Anti-Magic Shell (on single party/raid member)
2059 if (spellProto->Id == 50462)
2061 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
2062 continue;
2064 // Anti-Magic Zone
2065 if (spellProto->Id == 50461)
2067 Unit* caster = (*i)->GetCaster();
2068 if (!caster)
2069 continue;
2070 int32 absorbed = RemainingDamage * currentAbsorb / 100;
2071 int32 canabsorb = caster->GetHealth();
2072 if (canabsorb < absorbed)
2073 absorbed = canabsorb;
2075 RemainingDamage -= absorbed;
2077 uint32 ab_damage = absorbed;
2078 DealDamageMods(caster,ab_damage,NULL);
2079 DealDamage(caster, ab_damage, NULL, damagetype, schoolMask, 0, false);
2080 continue;
2082 break;
2084 default:
2085 break;
2088 // currentAbsorb - damage can be absorbed by shield
2089 // If need absorb less damage
2090 if (RemainingDamage < currentAbsorb)
2091 currentAbsorb = RemainingDamage;
2093 RemainingDamage -= currentAbsorb;
2095 // Reduce shield amount
2096 mod->m_amount-=currentAbsorb;
2097 if((*i)->DropAuraCharge())
2098 mod->m_amount = 0;
2099 // Need remove it later
2100 if (mod->m_amount<=0)
2101 existExpired = true;
2104 // Remove all expired absorb auras
2105 if (existExpired)
2107 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end();)
2109 if ((*i)->GetModifier()->m_amount<=0)
2111 pVictim->RemoveAurasDueToSpell((*i)->GetId());
2112 i = vSchoolAbsorb.begin();
2114 else
2115 ++i;
2119 // Cast back reflect damage spell
2120 if (canReflect && reflectSpell)
2121 pVictim->CastCustomSpell(this, reflectSpell, &reflectDamage, NULL, NULL, true, NULL, reflectTriggeredBy);
2123 // absorb by mana cost
2124 AuraList const& vManaShield = pVictim->GetAurasByType(SPELL_AURA_MANA_SHIELD);
2125 for(AuraList::const_iterator i = vManaShield.begin(), next; i != vManaShield.end() && RemainingDamage > 0; i = next)
2127 next = i; ++next;
2129 // check damage school mask
2130 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
2131 continue;
2133 int32 currentAbsorb;
2134 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
2135 currentAbsorb = (*i)->GetModifier()->m_amount;
2136 else
2137 currentAbsorb = RemainingDamage;
2139 if (float manaMultiplier = (*i)->GetSpellProto()->EffectMultipleValue[(*i)->GetEffIndex()])
2141 if(Player *modOwner = pVictim->GetSpellModOwner())
2142 modOwner->ApplySpellMod((*i)->GetId(), SPELLMOD_MULTIPLE_VALUE, manaMultiplier);
2144 int32 maxAbsorb = int32(pVictim->GetPower(POWER_MANA) / manaMultiplier);
2145 if (currentAbsorb > maxAbsorb)
2146 currentAbsorb = maxAbsorb;
2148 int32 manaReduction = int32(currentAbsorb * manaMultiplier);
2149 pVictim->ApplyPowerMod(POWER_MANA, manaReduction, false);
2152 (*i)->GetModifier()->m_amount -= currentAbsorb;
2153 if((*i)->GetModifier()->m_amount <= 0)
2155 pVictim->RemoveAurasDueToSpell((*i)->GetId());
2156 next = vManaShield.begin();
2159 RemainingDamage -= currentAbsorb;
2162 // effects dependent from full absorb amount
2163 if (int32 full_absorb = damage - RemainingDamage - *resist)
2165 Unit::AuraList const& auras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
2166 for (Unit::AuraList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
2168 SpellEntry const* itr_spellProto = (*itr)->GetSpellProto();
2170 // Incanter's Absorption
2171 if (itr_spellProto->SpellFamilyName == SPELLFAMILY_GENERIC &&
2172 itr_spellProto->SpellIconID == 2941)
2175 int32 amount = int32(full_absorb * (*itr)->GetModifier()->m_amount / 100);
2177 // apply normalized part of already accumulated amount in aura
2178 if (Aura* spdAura = pVictim->GetAura(44413, EFFECT_INDEX_0))
2179 amount += spdAura->GetModifier()->m_amount * spdAura->GetAuraDuration() / spdAura->GetAuraMaxDuration();
2181 // limit 5 health percents
2182 int32 health_5percent = pVictim->GetMaxHealth()*5/100;
2183 if(amount > health_5percent)
2184 amount = health_5percent;
2186 // Incanter's Absorption (triggered absorb based spell power, will replace existed if any)
2187 pVictim->CastCustomSpell(pVictim, 44413, &amount, NULL, NULL, true);
2188 break;
2193 // only split damage if not damaging yourself
2194 if(pVictim != this)
2196 AuraList const& vSplitDamageFlat = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_FLAT);
2197 for(AuraList::const_iterator i = vSplitDamageFlat.begin(), next; i != vSplitDamageFlat.end() && RemainingDamage >= 0; i = next)
2199 next = i; ++next;
2201 // check damage school mask
2202 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
2203 continue;
2205 // Damage can be splitted only if aura has an alive caster
2206 Unit *caster = (*i)->GetCaster();
2207 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
2208 continue;
2210 int32 currentAbsorb;
2211 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
2212 currentAbsorb = (*i)->GetModifier()->m_amount;
2213 else
2214 currentAbsorb = RemainingDamage;
2216 RemainingDamage -= currentAbsorb;
2219 uint32 splitted = currentAbsorb;
2220 uint32 splitted_absorb = 0;
2221 DealDamageMods(caster,splitted,&splitted_absorb);
2223 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, splitted_absorb, 0, false, 0, false);
2225 CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL);
2226 DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
2229 AuraList const& vSplitDamagePct = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_PCT);
2230 for(AuraList::const_iterator i = vSplitDamagePct.begin(), next; i != vSplitDamagePct.end() && RemainingDamage >= 0; i = next)
2232 next = i; ++next;
2234 // check damage school mask
2235 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
2236 continue;
2238 // Damage can be splitted only if aura has an alive caster
2239 Unit *caster = (*i)->GetCaster();
2240 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
2241 continue;
2243 uint32 splitted = uint32(RemainingDamage * (*i)->GetModifier()->m_amount / 100.0f);
2245 RemainingDamage -= int32(splitted);
2247 uint32 split_absorb = 0;
2248 DealDamageMods(caster,splitted,&split_absorb);
2250 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, split_absorb, 0, false, 0, false);
2252 CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL);
2253 DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
2257 // Apply death prevention spells effects
2258 if (preventDeathSpell && RemainingDamage >= (int32)pVictim->GetHealth())
2260 switch(preventDeathSpell->SpellFamilyName)
2262 // Cheat Death
2263 case SPELLFAMILY_ROGUE:
2265 // Cheat Death
2266 if (preventDeathSpell->SpellIconID == 2109)
2268 pVictim->CastSpell(pVictim,31231,true);
2269 ((Player*)pVictim)->AddSpellCooldown(31231,0,time(NULL)+60);
2270 // with health > 10% lost health until health==10%, in other case no losses
2271 uint32 health10 = pVictim->GetMaxHealth()/10;
2272 RemainingDamage = pVictim->GetHealth() > health10 ? pVictim->GetHealth() - health10 : 0;
2274 break;
2276 // Guardian Spirit
2277 case SPELLFAMILY_PRIEST:
2279 // Guardian Spirit
2280 if (preventDeathSpell->SpellIconID == 2873)
2282 int32 healAmount = pVictim->GetMaxHealth() * preventDeathAmount / 100;
2283 pVictim->CastCustomSpell(pVictim, 48153, &healAmount, NULL, NULL, true);
2284 pVictim->RemoveAurasDueToSpell(preventDeathSpell->Id);
2285 RemainingDamage = 0;
2287 break;
2292 *absorb = damage - RemainingDamage - *resist;
2295 void Unit::AttackerStateUpdate (Unit *pVictim, WeaponAttackType attType, bool extra )
2297 if(hasUnitState(UNIT_STAT_CAN_NOT_REACT) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) )
2298 return;
2300 if (!pVictim->isAlive())
2301 return;
2303 if(IsNonMeleeSpellCasted(false))
2304 return;
2306 uint32 hitInfo;
2307 if (attType == BASE_ATTACK)
2308 hitInfo = HITINFO_NORMALSWING2;
2309 else if (attType == OFF_ATTACK)
2310 hitInfo = HITINFO_LEFTSWING;
2311 else
2312 return; // ignore ranged case
2314 uint32 extraAttacks = m_extraAttacks;
2316 // melee attack spell casted at main hand attack only
2317 if (attType == BASE_ATTACK && m_currentSpells[CURRENT_MELEE_SPELL])
2319 m_currentSpells[CURRENT_MELEE_SPELL]->cast();
2321 // not recent extra attack only at any non extra attack (melee spell case)
2322 if(!extra && extraAttacks)
2324 while(m_extraAttacks)
2326 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
2327 if(m_extraAttacks > 0)
2328 --m_extraAttacks;
2331 return;
2334 // attack can be redirected to another target
2335 pVictim = SelectMagnetTarget(pVictim);
2337 CalcDamageInfo damageInfo;
2338 CalculateMeleeDamage(pVictim, 0, &damageInfo, attType);
2339 // Send log damage message to client
2340 DealDamageMods(pVictim,damageInfo.damage,&damageInfo.absorb);
2341 SendAttackStateUpdate(&damageInfo);
2342 ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.damage, damageInfo.attackType);
2343 DealMeleeDamage(&damageInfo,true);
2345 if (GetTypeId() == TYPEID_PLAYER)
2346 DEBUG_LOG("AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
2347 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
2348 else
2349 DEBUG_LOG("AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
2350 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
2352 // if damage pVictim call AI reaction
2353 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
2354 ((Creature*)pVictim)->AI()->AttackedBy(this);
2356 // extra attack only at any non extra attack (normal case)
2357 if(!extra && extraAttacks)
2359 while(m_extraAttacks)
2361 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
2362 if(m_extraAttacks > 0)
2363 --m_extraAttacks;
2368 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType) const
2370 // This is only wrapper
2372 // Miss chance based on melee
2373 float miss_chance = MeleeMissChanceCalc(pVictim, attType);
2375 // Critical hit chance
2376 float crit_chance = GetUnitCriticalChance(attType, pVictim);
2378 // stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case)
2379 float dodge_chance = pVictim->GetUnitDodgeChance();
2380 float block_chance = pVictim->GetUnitBlockChance();
2381 float parry_chance = pVictim->GetUnitParryChance();
2383 // Useful if want to specify crit & miss chances for melee, else it could be removed
2384 DEBUG_LOG("MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance,crit_chance,dodge_chance,parry_chance,block_chance);
2386 return RollMeleeOutcomeAgainst(pVictim, attType, int32(crit_chance*100), int32(miss_chance*100), int32(dodge_chance*100),int32(parry_chance*100),int32(block_chance*100));
2389 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst (const Unit *pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const
2391 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2392 return MELEE_HIT_EVADE;
2394 int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(pVictim);
2395 int32 victimMaxSkillValueForLevel = pVictim->GetMaxSkillValueForLevel(this);
2397 int32 attackerWeaponSkill = GetWeaponSkillValue(attType,pVictim);
2398 int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this);
2400 // bonus from skills is 0.04%
2401 int32 skillBonus = 4 * ( attackerWeaponSkill - victimMaxSkillValueForLevel );
2402 int32 sum = 0, tmp = 0;
2403 int32 roll = urand (0, 10000);
2405 DEBUG_LOG ("RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus);
2406 DEBUG_LOG ("RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d",
2407 roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance);
2409 tmp = miss_chance;
2411 if (tmp > 0 && roll < (sum += tmp ))
2413 DEBUG_LOG ("RollMeleeOutcomeAgainst: MISS");
2414 return MELEE_HIT_MISS;
2417 // always crit against a sitting target (except 0 crit chance)
2418 if( pVictim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !pVictim->IsStandState() )
2420 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT (sitting victim)");
2421 return MELEE_HIT_CRIT;
2424 // Dodge chance
2426 // only players can't dodge if attacker is behind
2427 if (pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->HasInArc(M_PI_F,this))
2429 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind and victim was a player.");
2431 else
2433 // Reduce dodge chance by attacker expertise rating
2434 if (GetTypeId() == TYPEID_PLAYER)
2435 dodge_chance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2436 else
2437 dodge_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
2439 // Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2440 dodge_chance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE);
2442 tmp = dodge_chance;
2443 if ( (tmp > 0) // check if unit _can_ dodge
2444 && ((tmp -= skillBonus) > 0)
2445 && roll < (sum += tmp))
2447 DEBUG_LOG ("RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum-tmp, sum);
2448 return MELEE_HIT_DODGE;
2452 // parry & block chances
2454 // check if attack comes from behind, nobody can parry or block if attacker is behind
2455 if (!pVictim->HasInArc(M_PI_F,this))
2457 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind.");
2459 else
2461 // Reduce parry chance by attacker expertise rating
2462 if (GetTypeId() == TYPEID_PLAYER)
2463 parry_chance-= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2464 else
2465 parry_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
2467 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY) )
2469 int32 tmp2 = int32(parry_chance);
2470 if ( (tmp2 > 0) // check if unit _can_ parry
2471 && ((tmp2 -= skillBonus) > 0)
2472 && (roll < (sum += tmp2)))
2474 DEBUG_LOG ("RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum-tmp2, sum);
2475 return MELEE_HIT_PARRY;
2479 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) )
2481 tmp = block_chance;
2482 if ( (tmp > 0) // check if unit _can_ block
2483 && ((tmp -= skillBonus) > 0)
2484 && (roll < (sum += tmp)))
2486 DEBUG_LOG ("RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum-tmp, sum);
2487 return MELEE_HIT_BLOCK;
2492 // Critical chance
2493 tmp = crit_chance;
2495 if (tmp > 0 && roll < (sum += tmp))
2497 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum-tmp, sum);
2498 return MELEE_HIT_CRIT;
2501 // 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)
2502 if( attType != RANGED_ATTACK &&
2503 (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet()) &&
2504 pVictim->GetTypeId() != TYPEID_PLAYER && !((Creature*)pVictim)->isPet() &&
2505 getLevel() < pVictim->getLevelForTarget(this) )
2507 // cap possible value (with bonuses > max skill)
2508 int32 skill = attackerWeaponSkill;
2509 int32 maxskill = attackerMaxSkillValueForLevel;
2510 skill = (skill > maxskill) ? maxskill : skill;
2512 tmp = (10 + (victimDefenseSkill - skill)) * 100;
2513 tmp = tmp > 4000 ? 4000 : tmp;
2514 if (roll < (sum += tmp))
2516 DEBUG_LOG ("RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum-4000, sum);
2517 return MELEE_HIT_GLANCING;
2521 // mobs can score crushing blows if they're 4 or more levels above victim
2522 if (getLevelForTarget(pVictim) >= pVictim->getLevelForTarget(this) + 4 &&
2523 // can be from by creature (if can) or from controlled player that considered as creature
2524 (GetTypeId()!=TYPEID_PLAYER && !((Creature*)this)->isPet() &&
2525 !(((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH) ||
2526 GetTypeId()==TYPEID_PLAYER && GetCharmerOrOwnerGUID()))
2528 // when their weapon skill is 15 or more above victim's defense skill
2529 tmp = victimDefenseSkill;
2530 int32 tmpmax = victimMaxSkillValueForLevel;
2531 // having defense above your maximum (from items, talents etc.) has no effect
2532 tmp = tmp > tmpmax ? tmpmax : tmp;
2533 // tmp = mob's level * 5 - player's current defense skill
2534 tmp = attackerMaxSkillValueForLevel - tmp;
2535 if(tmp >= 15)
2537 // add 2% chance per lacking skill point, min. is 15%
2538 tmp = tmp * 200 - 1500;
2539 if (roll < (sum += tmp))
2541 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum-tmp, sum);
2542 return MELEE_HIT_CRUSHING;
2547 DEBUG_LOG ("RollMeleeOutcomeAgainst: NORMAL");
2548 return MELEE_HIT_NORMAL;
2551 uint32 Unit::CalculateDamage (WeaponAttackType attType, bool normalized)
2553 float min_damage, max_damage;
2555 if (normalized && GetTypeId()==TYPEID_PLAYER)
2556 ((Player*)this)->CalculateMinMaxDamage(attType,normalized,min_damage, max_damage);
2557 else
2559 switch (attType)
2561 case RANGED_ATTACK:
2562 min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE);
2563 max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE);
2564 break;
2565 case BASE_ATTACK:
2566 min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE);
2567 max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE);
2568 break;
2569 case OFF_ATTACK:
2570 min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE);
2571 max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE);
2572 break;
2573 // Just for good manner
2574 default:
2575 min_damage = 0.0f;
2576 max_damage = 0.0f;
2577 break;
2581 if (min_damage > max_damage)
2583 std::swap(min_damage,max_damage);
2586 if(max_damage == 0.0f)
2587 max_damage = 5.0f;
2589 return urand((uint32)min_damage, (uint32)max_damage);
2592 float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const
2594 if(spellProto->spellLevel <= 0)
2595 return 1.0f;
2597 float LvlPenalty = 0.0f;
2599 if(spellProto->spellLevel < 20)
2600 LvlPenalty = 20.0f - spellProto->spellLevel * 3.75f;
2601 float LvlFactor = (float(spellProto->spellLevel) + 6.0f) / float(getLevel());
2602 if(LvlFactor > 1.0f)
2603 LvlFactor = 1.0f;
2605 return (100.0f - LvlPenalty) * LvlFactor / 100.0f;
2608 void Unit::SendMeleeAttackStart(Unit* pVictim)
2610 WorldPacket data( SMSG_ATTACKSTART, 8 + 8 );
2611 data << uint64(GetGUID());
2612 data << uint64(pVictim->GetGUID());
2614 SendMessageToSet(&data, true);
2615 DEBUG_LOG( "WORLD: Sent SMSG_ATTACKSTART" );
2618 void Unit::SendMeleeAttackStop(Unit* victim)
2620 if(!victim)
2621 return;
2623 WorldPacket data( SMSG_ATTACKSTOP, (4+16) ); // we guess size
2624 data << GetPackGUID();
2625 data << victim->GetPackGUID(); // can be 0x00...
2626 data << uint32(0); // can be 0x1
2627 SendMessageToSet(&data, true);
2628 sLog.outDetail("%s %u stopped attacking %s %u", (GetTypeId()==TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), (victim->GetTypeId()==TYPEID_PLAYER ? "player" : "creature"),victim->GetGUIDLow());
2630 /*if(victim->GetTypeId() == TYPEID_UNIT)
2631 ((Creature*)victim)->AI().EnterEvadeMode(this);*/
2634 bool Unit::isSpellBlocked(Unit *pVictim, SpellEntry const * /*spellProto*/, WeaponAttackType attackType)
2636 if (pVictim->HasInArc(M_PI_F,this))
2638 /* Currently not exist spells with ignore block
2639 // Ignore combat result aura (parry/dodge check on prepare)
2640 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2641 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2643 if (!(*i)->isAffectedOnSpell(spellProto))
2644 continue;
2645 if ((*i)->GetModifier()->m_miscvalue == )
2646 return false;
2650 // Check creatures flags_extra for disable block
2651 if(pVictim->GetTypeId()==TYPEID_UNIT &&
2652 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK )
2653 return false;
2655 float blockChance = pVictim->GetUnitBlockChance();
2656 blockChance += (int32(GetWeaponSkillValue(attackType)) - int32(pVictim->GetMaxSkillValueForLevel()))*0.04f;
2657 if (roll_chance_f(blockChance))
2658 return true;
2660 return false;
2663 // Melee based spells can be miss, parry or dodge on this step
2664 // Crit or block - determined on damage calculation phase! (and can be both in some time)
2665 float Unit::MeleeSpellMissChance(Unit *pVictim, WeaponAttackType attType, int32 skillDiff, SpellEntry const *spell)
2667 // Calculate hit chance (more correct for chance mod)
2668 int32 HitChance;
2670 // PvP - PvE melee chances
2671 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2672 int32 leveldif = pVictim->getLevelForTarget(this) - getLevelForTarget(pVictim);
2673 if(leveldif < 3)
2674 HitChance = 95 - leveldif;
2675 else
2676 HitChance = 93 - (leveldif - 2) * lchance;
2678 // Hit chance depends from victim auras
2679 if(attType == RANGED_ATTACK)
2680 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2681 else
2682 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2684 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2685 if(Player *modOwner = GetSpellModOwner())
2686 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, HitChance);
2688 // Miss = 100 - hit
2689 float miss_chance= 100.0f - HitChance;
2691 // Bonuses from attacker aura and ratings
2692 if (attType == RANGED_ATTACK)
2693 miss_chance -= m_modRangedHitChance;
2694 else
2695 miss_chance -= m_modMeleeHitChance;
2697 // bonus from skills is 0.04%
2698 miss_chance -= skillDiff * 0.04f;
2700 // Limit miss chance from 0 to 60%
2701 if (miss_chance < 0.0f)
2702 return 0.0f;
2703 if (miss_chance > 60.0f)
2704 return 60.0f;
2705 return miss_chance;
2708 // Melee based spells hit result calculations
2709 SpellMissInfo Unit::MeleeSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2711 WeaponAttackType attType = BASE_ATTACK;
2713 if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED)
2714 attType = RANGED_ATTACK;
2716 // bonus from skills is 0.04% per skill Diff
2717 int32 attackerWeaponSkill = int32(GetWeaponSkillValue(attType,pVictim));
2718 int32 skillDiff = attackerWeaponSkill - int32(pVictim->GetMaxSkillValueForLevel(this));
2719 int32 fullSkillDiff = attackerWeaponSkill - int32(pVictim->GetDefenseSkillValue(this));
2721 uint32 roll = urand (0, 10000);
2723 uint32 missChance = uint32(MeleeSpellMissChance(pVictim, attType, fullSkillDiff, spell)*100.0f);
2724 // Roll miss
2725 uint32 tmp = missChance;
2726 if (roll < tmp)
2727 return SPELL_MISS_MISS;
2729 // Chance resist mechanic (select max value from every mechanic spell effect)
2730 int32 resist_mech = 0;
2731 // Get effects mechanic and chance
2732 for(int eff = 0; eff < MAX_EFFECT_INDEX; ++eff)
2734 int32 effect_mech = GetEffectMechanic(spell, SpellEffectIndex(eff));
2735 if (effect_mech)
2737 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2738 if (resist_mech < temp*100)
2739 resist_mech = temp*100;
2742 // Roll chance
2743 tmp += resist_mech;
2744 if (roll < tmp)
2745 return SPELL_MISS_RESIST;
2747 bool canDodge = true;
2748 bool canParry = true;
2750 // Same spells cannot be parry/dodge
2751 if (spell->Attributes & SPELL_ATTR_IMPOSSIBLE_DODGE_PARRY_BLOCK)
2752 return SPELL_MISS_NONE;
2754 // Ranged attack cannot be parry/dodge only deflect
2755 if (attType == RANGED_ATTACK)
2757 // only if in front
2758 if (pVictim->HasInArc(M_PI_F,this))
2760 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2761 tmp+=deflect_chance;
2762 if (roll < tmp)
2763 return SPELL_MISS_DEFLECT;
2765 return SPELL_MISS_NONE;
2768 // Check for attack from behind
2769 if (!pVictim->HasInArc(M_PI_F,this))
2771 // Can`t dodge from behind in PvP (but its possible in PvE)
2772 if (GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
2773 canDodge = false;
2774 // Can`t parry
2775 canParry = false;
2777 // Check creatures flags_extra for disable parry
2778 if(pVictim->GetTypeId()==TYPEID_UNIT)
2780 uint32 flagEx = ((Creature*)pVictim)->GetCreatureInfo()->flags_extra;
2781 if( flagEx & CREATURE_FLAG_EXTRA_NO_PARRY )
2782 canParry = false;
2784 // Ignore combat result aura
2785 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2786 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2788 if (!(*i)->isAffectedOnSpell(spell))
2789 continue;
2790 switch((*i)->GetModifier()->m_miscvalue)
2792 case MELEE_HIT_DODGE: canDodge = false; break;
2793 case MELEE_HIT_BLOCK: break; // Block check in hit step
2794 case MELEE_HIT_PARRY: canParry = false; break;
2795 default:
2796 DEBUG_LOG("Spell %u SPELL_AURA_IGNORE_COMBAT_RESULT have unhandled state %d", (*i)->GetId(), (*i)->GetModifier()->m_miscvalue);
2797 break;
2801 if (canDodge)
2803 // Roll dodge
2804 int32 dodgeChance = int32(pVictim->GetUnitDodgeChance()*100.0f) - skillDiff * 4;
2805 // Reduce enemy dodge chance by SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2806 dodgeChance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE)*100;
2807 // Reduce dodge chance by attacker expertise rating
2808 if (GetTypeId() == TYPEID_PLAYER)
2809 dodgeChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2810 else
2811 dodgeChance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
2812 if (dodgeChance < 0)
2813 dodgeChance = 0;
2815 tmp += dodgeChance;
2816 if (roll < tmp)
2817 return SPELL_MISS_DODGE;
2820 if (canParry)
2822 // Roll parry
2823 int32 parryChance = int32(pVictim->GetUnitParryChance()*100.0f) - skillDiff * 4;
2824 // Reduce parry chance by attacker expertise rating
2825 if (GetTypeId() == TYPEID_PLAYER)
2826 parryChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2827 else
2828 parryChance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
2829 if (parryChance < 0)
2830 parryChance = 0;
2832 tmp += parryChance;
2833 if (roll < tmp)
2834 return SPELL_MISS_PARRY;
2837 return SPELL_MISS_NONE;
2840 // TODO need use unit spell resistances in calculations
2841 SpellMissInfo Unit::MagicSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2843 // Can`t miss on dead target (on skinning for example)
2844 if (!pVictim->isAlive())
2845 return SPELL_MISS_NONE;
2847 SpellSchoolMask schoolMask = GetSpellSchoolMask(spell);
2848 // PvP - PvE spell misschances per leveldif > 2
2849 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 7 : 11;
2850 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2852 // Base hit chance from attacker and victim levels
2853 int32 modHitChance;
2854 if(leveldif < 3)
2855 modHitChance = 96 - leveldif;
2856 else
2857 modHitChance = 94 - (leveldif - 2) * lchance;
2859 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2860 if(Player *modOwner = GetSpellModOwner())
2861 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance);
2862 // Increase from attacker SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT auras
2863 modHitChance+=GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT, schoolMask);
2864 // Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras
2865 modHitChance+= pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask);
2866 // Reduce spell hit chance for Area of effect spells from victim SPELL_AURA_MOD_AOE_AVOIDANCE aura
2867 if (IsAreaOfEffectSpell(spell))
2868 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE);
2869 // Reduce spell hit chance for dispel mechanic spells from victim SPELL_AURA_MOD_DISPEL_RESIST
2870 if (IsDispelSpell(spell))
2871 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_DISPEL_RESIST);
2872 // Chance resist mechanic (select max value from every mechanic spell effect)
2873 int32 resist_mech = 0;
2874 // Get effects mechanic and chance
2875 for(int eff = 0; eff < MAX_EFFECT_INDEX; ++eff)
2877 int32 effect_mech = GetEffectMechanic(spell, SpellEffectIndex(eff));
2878 if (effect_mech)
2880 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2881 if (resist_mech < temp)
2882 resist_mech = temp;
2885 // Apply mod
2886 modHitChance-=resist_mech;
2888 // Chance resist debuff
2889 modHitChance-=pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel));
2891 int32 HitChance = modHitChance * 100;
2892 // Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings
2893 HitChance += int32(m_modSpellHitChance*100.0f);
2895 // Decrease hit chance from victim rating bonus
2896 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2897 HitChance -= int32(((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_SPELL)*100.0f);
2899 if (HitChance < 100) HitChance = 100;
2900 if (HitChance > 10000) HitChance = 10000;
2902 int32 tmp = 10000 - HitChance;
2904 int32 rand = irand(0,10000);
2906 if (rand < tmp)
2907 return SPELL_MISS_MISS;
2909 // cast by caster in front of victim
2910 if (pVictim->HasInArc(M_PI_F,this))
2912 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2913 tmp+=deflect_chance;
2914 if (rand < tmp)
2915 return SPELL_MISS_DEFLECT;
2918 return SPELL_MISS_NONE;
2921 // Calculate spell hit result can be:
2922 // Every spell can: Evade/Immune/Reflect/Sucesful hit
2923 // For melee based spells:
2924 // Miss
2925 // Dodge
2926 // Parry
2927 // For spells
2928 // Resist
2929 SpellMissInfo Unit::SpellHitResult(Unit *pVictim, SpellEntry const *spell, bool CanReflect)
2931 // Return evade for units in evade mode
2932 if (pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2933 return SPELL_MISS_EVADE;
2935 // Check for immune
2936 if (pVictim->IsImmunedToSpell(spell))
2937 return SPELL_MISS_IMMUNE;
2939 // All positive spells can`t miss
2940 // TODO: client not show miss log for this spells - so need find info for this in dbc and use it!
2941 if (IsPositiveSpell(spell->Id))
2942 return SPELL_MISS_NONE;
2944 // Check for immune
2945 if (pVictim->IsImmunedToDamage(GetSpellSchoolMask(spell)))
2946 return SPELL_MISS_IMMUNE;
2948 // Try victim reflect spell
2949 if (CanReflect)
2951 int32 reflectchance = pVictim->GetTotalAuraModifier(SPELL_AURA_REFLECT_SPELLS);
2952 Unit::AuraList const& mReflectSpellsSchool = pVictim->GetAurasByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL);
2953 for(Unit::AuraList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i)
2954 if((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spell))
2955 reflectchance += (*i)->GetModifier()->m_amount;
2956 if (reflectchance > 0 && roll_chance_i(reflectchance))
2958 // Start triggers for remove charges if need (trigger only for victim, and mark as active spell)
2959 ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT, PROC_EX_REFLECT, 1, BASE_ATTACK, spell);
2960 return SPELL_MISS_REFLECT;
2964 switch (spell->DmgClass)
2966 case SPELL_DAMAGE_CLASS_RANGED:
2967 case SPELL_DAMAGE_CLASS_MELEE:
2968 return MeleeSpellHitResult(pVictim, spell);
2969 case SPELL_DAMAGE_CLASS_NONE:
2970 case SPELL_DAMAGE_CLASS_MAGIC:
2971 return MagicSpellHitResult(pVictim, spell);
2973 return SPELL_MISS_NONE;
2976 float Unit::MeleeMissChanceCalc(const Unit *pVictim, WeaponAttackType attType) const
2978 if(!pVictim)
2979 return 0.0f;
2981 // Base misschance 5%
2982 float misschance = 5.0f;
2984 // DualWield - Melee spells and physical dmg spells - 5% , white damage 24%
2985 if (haveOffhandWeapon() && attType != RANGED_ATTACK)
2987 bool isNormal = false;
2988 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
2990 if( m_currentSpells[i] && (GetSpellSchoolMask(m_currentSpells[i]->m_spellInfo) & SPELL_SCHOOL_MASK_NORMAL) )
2992 isNormal = true;
2993 break;
2996 if (isNormal || m_currentSpells[CURRENT_MELEE_SPELL])
2997 misschance = 5.0f;
2998 else
2999 misschance = 24.0f;
3002 // PvP : PvE melee misschances per leveldif > 2
3003 int32 chance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
3005 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
3006 if(leveldif < 0)
3007 leveldif = 0;
3009 // Hit chance from attacker based on ratings and auras
3010 float m_modHitChance;
3011 if (attType == RANGED_ATTACK)
3012 m_modHitChance = m_modRangedHitChance;
3013 else
3014 m_modHitChance = m_modMeleeHitChance;
3016 if(leveldif < 3)
3017 misschance += (leveldif - m_modHitChance);
3018 else
3019 misschance += ((leveldif - 2) * chance - m_modHitChance);
3021 // Hit chance for victim based on ratings
3022 if (pVictim->GetTypeId()==TYPEID_PLAYER)
3024 if (attType == RANGED_ATTACK)
3025 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_RANGED);
3026 else
3027 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_MELEE);
3030 // Modify miss chance by victim auras
3031 if(attType == RANGED_ATTACK)
3032 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
3033 else
3034 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
3036 // Modify miss chance from skill difference ( bonus from skills is 0.04% )
3037 int32 skillBonus = int32(GetWeaponSkillValue(attType,pVictim)) - int32(pVictim->GetDefenseSkillValue(this));
3038 misschance -= skillBonus * 0.04f;
3040 // Limit miss chance from 0 to 60%
3041 if ( misschance < 0.0f)
3042 return 0.0f;
3043 if ( misschance > 60.0f)
3044 return 60.0f;
3046 return misschance;
3049 uint32 Unit::GetDefenseSkillValue(Unit const* target) const
3051 if(GetTypeId() == TYPEID_PLAYER)
3053 // in PvP use full skill instead current skill value
3054 uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER)
3055 ? ((Player*)this)->GetMaxSkillValue(SKILL_DEFENSE)
3056 : ((Player*)this)->GetSkillValue(SKILL_DEFENSE);
3057 value += uint32(((Player*)this)->GetRatingBonusValue(CR_DEFENSE_SKILL));
3058 return value;
3060 else
3061 return GetUnitMeleeSkill(target);
3064 float Unit::GetUnitDodgeChance() const
3066 if(hasUnitState(UNIT_STAT_STUNNED))
3067 return 0.0f;
3068 if( GetTypeId() == TYPEID_PLAYER )
3069 return GetFloatValue(PLAYER_DODGE_PERCENTAGE);
3070 else
3072 if(((Creature const*)this)->isTotem())
3073 return 0.0f;
3074 else
3076 float dodge = 5.0f;
3077 dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT);
3078 return dodge > 0.0f ? dodge : 0.0f;
3083 float Unit::GetUnitParryChance() const
3085 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
3086 return 0.0f;
3088 float chance = 0.0f;
3090 if(GetTypeId() == TYPEID_PLAYER)
3092 Player const* player = (Player const*)this;
3093 if(player->CanParry() )
3095 Item *tmpitem = player->GetWeaponForAttack(BASE_ATTACK,true,true);
3096 if(!tmpitem)
3097 tmpitem = player->GetWeaponForAttack(OFF_ATTACK,true,true);
3099 if(tmpitem)
3100 chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE);
3103 else if(GetTypeId() == TYPEID_UNIT)
3105 if(GetCreatureType() == CREATURE_TYPE_HUMANOID)
3107 chance = 5.0f;
3108 chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT);
3112 return chance > 0.0f ? chance : 0.0f;
3115 float Unit::GetUnitBlockChance() const
3117 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
3118 return 0.0f;
3120 if(GetTypeId() == TYPEID_PLAYER)
3122 Player const* player = (Player const*)this;
3123 if(player->CanBlock() )
3125 Item *tmpitem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
3126 if(tmpitem && !tmpitem->IsBroken() && tmpitem->GetProto()->Block)
3127 return GetFloatValue(PLAYER_BLOCK_PERCENTAGE);
3129 // is player but has no block ability or no not broken shield equipped
3130 return 0.0f;
3132 else
3134 if(((Creature const*)this)->isTotem())
3135 return 0.0f;
3136 else
3138 float block = 5.0f;
3139 block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT);
3140 return block > 0.0f ? block : 0.0f;
3145 float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit *pVictim) const
3147 float crit;
3149 if(GetTypeId() == TYPEID_PLAYER)
3151 switch(attackType)
3153 case BASE_ATTACK:
3154 crit = GetFloatValue( PLAYER_CRIT_PERCENTAGE );
3155 break;
3156 case OFF_ATTACK:
3157 crit = GetFloatValue( PLAYER_OFFHAND_CRIT_PERCENTAGE );
3158 break;
3159 case RANGED_ATTACK:
3160 crit = GetFloatValue( PLAYER_RANGED_CRIT_PERCENTAGE );
3161 break;
3162 // Just for good manner
3163 default:
3164 crit = 0.0f;
3165 break;
3168 else
3170 crit = 5.0f;
3171 crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PERCENT);
3174 // flat aura mods
3175 if(attackType == RANGED_ATTACK)
3176 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE);
3177 else
3178 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE);
3180 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
3182 // reduce crit chance from Rating for players
3183 if (attackType != RANGED_ATTACK)
3184 crit -= pVictim->GetMeleeCritChanceReduction();
3185 else
3186 crit -= pVictim->GetRangedCritChanceReduction();
3188 // Apply crit chance from defence skill
3189 crit += (int32(GetMaxSkillValueForLevel(pVictim)) - int32(pVictim->GetDefenseSkillValue(this))) * 0.04f;
3191 if (crit < 0.0f)
3192 crit = 0.0f;
3193 return crit;
3196 uint32 Unit::GetWeaponSkillValue (WeaponAttackType attType, Unit const* target) const
3198 uint32 value = 0;
3199 if(GetTypeId() == TYPEID_PLAYER)
3201 Item* item = ((Player*)this)->GetWeaponForAttack(attType,true,true);
3203 // feral or unarmed skill only for base attack
3204 if(attType != BASE_ATTACK && !item )
3205 return 0;
3207 if(IsInFeralForm())
3208 return GetMaxSkillValueForLevel(); // always maximized SKILL_FERAL_COMBAT in fact
3210 // weapon skill or (unarmed for base attack)
3211 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
3213 // in PvP use full skill instead current skill value
3214 value = (target && target->GetTypeId() == TYPEID_PLAYER)
3215 ? ((Player*)this)->GetMaxSkillValue(skill)
3216 : ((Player*)this)->GetSkillValue(skill);
3217 // Modify value from ratings
3218 value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL));
3219 switch (attType)
3221 case BASE_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_MAINHAND));break;
3222 case OFF_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_OFFHAND));break;
3223 case RANGED_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_RANGED));break;
3226 else
3227 value = GetUnitMeleeSkill(target);
3228 return value;
3231 void Unit::_UpdateSpells( uint32 time )
3233 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
3234 _UpdateAutoRepeatSpell();
3236 // remove finished spells from current pointers
3237 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
3239 if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED)
3241 m_currentSpells[i]->SetReferencedFromCurrent(false);
3242 m_currentSpells[i] = NULL; // remove pointer
3246 // update auras
3247 // m_AurasUpdateIterator can be updated in inderect called code at aura remove to skip next planned to update but removed auras
3248 for (m_AurasUpdateIterator = m_Auras.begin(); m_AurasUpdateIterator != m_Auras.end();)
3250 Aura* i_aura = m_AurasUpdateIterator->second;
3251 ++m_AurasUpdateIterator; // need shift to next for allow update if need into aura update
3252 i_aura->UpdateAura(time);
3255 // remove expired auras
3256 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end();)
3258 if ((*i).second)
3260 if ( !(*i).second->GetAuraDuration() && !((*i).second->IsPermanent() || ((*i).second->IsPassive())) )
3261 RemoveAura(i);
3262 else
3263 ++i;
3265 else
3266 ++i;
3269 if(!m_gameObj.empty())
3271 GameObjectList::iterator ite1, dnext1;
3272 for (ite1 = m_gameObj.begin(); ite1 != m_gameObj.end(); ite1 = dnext1)
3274 dnext1 = ite1;
3275 //(*i)->Update( difftime );
3276 if( !(*ite1)->isSpawned() )
3278 (*ite1)->SetOwnerGUID(0);
3279 (*ite1)->SetRespawnTime(0);
3280 (*ite1)->Delete();
3281 dnext1 = m_gameObj.erase(ite1);
3283 else
3284 ++dnext1;
3289 void Unit::_UpdateAutoRepeatSpell()
3291 bool isAutoShot = m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id == SPELL_ID_AUTOSHOT;
3293 //check movement
3294 if (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->isMoving())
3296 // cancel wand shoot
3297 if(!isAutoShot)
3298 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3299 // auto shot just waits
3300 return;
3303 // check spell casts
3304 if (IsNonMeleeSpellCasted(false, false, true))
3306 // cancel wand shoot
3307 if(!isAutoShot)
3309 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3310 return;
3312 // auto shot is delayed by everythihng, except ranged(!) CURRENT_GENERIC_SPELL's -> recheck that
3313 else if (!(m_currentSpells[CURRENT_GENERIC_SPELL] && m_currentSpells[CURRENT_GENERIC_SPELL]->IsRangedSpell()))
3314 return;
3317 //castroutine
3318 if (isAttackReady(RANGED_ATTACK))
3320 // Check if able to cast
3321 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->CheckCast(true) != SPELL_CAST_OK)
3323 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3324 return;
3327 // we want to shoot
3328 Spell* spell = new Spell(this, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, true, 0);
3329 spell->prepare(&(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_targets));
3331 // all went good, reset attack
3332 resetAttackTimer(RANGED_ATTACK);
3336 void Unit::SetCurrentCastedSpell( Spell * pSpell )
3338 assert(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells
3340 CurrentSpellTypes CSpellType = pSpell->GetCurrentContainer();
3342 if (pSpell == m_currentSpells[CSpellType]) return; // avoid breaking self
3344 // break same type spell if it is not delayed
3345 InterruptSpell(CSpellType,false);
3347 // special breakage effects:
3348 switch (CSpellType)
3350 case CURRENT_GENERIC_SPELL:
3352 // generic spells always break channeled not delayed spells
3353 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3355 // autorepeat breaking
3356 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3358 // break autorepeat if not Auto Shot
3359 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3360 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3362 } break;
3364 case CURRENT_CHANNELED_SPELL:
3366 // channel spells always break generic non-delayed and any channeled spells
3367 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3368 InterruptSpell(CURRENT_CHANNELED_SPELL);
3370 // it also does break autorepeat if not Auto Shot
3371 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] &&
3372 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT )
3373 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3374 } break;
3376 case CURRENT_AUTOREPEAT_SPELL:
3378 // only Auto Shoot does not break anything
3379 if (pSpell->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3381 // generic autorepeats break generic non-delayed and channeled non-delayed spells
3382 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3383 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3384 // special action: first cast delay
3385 if ( getAttackTimer(RANGED_ATTACK) < 500 )
3386 setAttackTimer(RANGED_ATTACK,500);
3388 } break;
3390 default:
3392 // other spell types don't break anything now
3393 } break;
3396 // current spell (if it is still here) may be safely deleted now
3397 if (m_currentSpells[CSpellType])
3398 m_currentSpells[CSpellType]->SetReferencedFromCurrent(false);
3400 // set new current spell
3401 m_currentSpells[CSpellType] = pSpell;
3402 pSpell->SetReferencedFromCurrent(true);
3404 pSpell->m_selfContainer = &(m_currentSpells[pSpell->GetCurrentContainer()]);
3407 void Unit::InterruptSpell(CurrentSpellTypes spellType, bool withDelayed, bool sendAutoRepeatCancelToClient)
3409 assert(spellType < CURRENT_MAX_SPELL);
3411 if (m_currentSpells[spellType] && (withDelayed || m_currentSpells[spellType]->getState() != SPELL_STATE_DELAYED) )
3413 // send autorepeat cancel message for autorepeat spells
3414 if (spellType == CURRENT_AUTOREPEAT_SPELL && sendAutoRepeatCancelToClient)
3416 if(GetTypeId() == TYPEID_PLAYER)
3417 ((Player*)this)->SendAutoRepeatCancel(this);
3420 if (m_currentSpells[spellType]->getState() != SPELL_STATE_FINISHED)
3421 m_currentSpells[spellType]->cancel();
3423 // cancel can interrupt spell already (caster cancel ->target aura remove -> caster iterrupt)
3424 if (m_currentSpells[spellType])
3426 m_currentSpells[spellType]->SetReferencedFromCurrent(false);
3427 m_currentSpells[spellType] = NULL;
3432 void Unit::FinishSpell(CurrentSpellTypes spellType, bool ok /*= true*/)
3434 Spell* spell = m_currentSpells[spellType];
3435 if (!spell)
3436 return;
3438 if (spellType == CURRENT_CHANNELED_SPELL)
3439 spell->SendChannelUpdate(0);
3441 spell->finish(ok);
3445 bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat) const
3447 // We don't do loop here to explicitly show that melee spell is excluded.
3448 // Maybe later some special spells will be excluded too.
3450 // generic spells are casted when they are not finished and not delayed
3451 if ( m_currentSpells[CURRENT_GENERIC_SPELL] &&
3452 (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
3453 (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
3454 return(true);
3456 // channeled spells may be delayed, but they are still considered casted
3457 else if ( !skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] &&
3458 (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED) )
3459 return(true);
3461 // autorepeat spells may be finished or delayed, but they are still considered casted
3462 else if ( !skipAutorepeat && m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3463 return(true);
3465 return(false);
3468 void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id)
3470 // generic spells are interrupted if they are not finished or delayed
3471 if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id==spell_id))
3472 InterruptSpell(CURRENT_GENERIC_SPELL,withDelayed);
3474 // autorepeat spells are interrupted if they are not finished or delayed
3475 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id==spell_id))
3476 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,withDelayed);
3478 // channeled spells are interrupted if they are not finished, even if they are delayed
3479 if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id==spell_id))
3480 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
3483 Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const
3485 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
3486 if(m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id==spell_id)
3487 return m_currentSpells[i];
3488 return NULL;
3491 void Unit::SetInFront(Unit const* target)
3493 SetOrientation(GetAngle(target));
3496 void Unit::SetFacingTo(float ori)
3498 // update orientation at server
3499 SetOrientation(ori);
3501 // and client
3502 WorldPacket data;
3503 BuildHeartBeatMsg(&data);
3504 SendMessageToSet(&data, false);
3507 // Consider move this to Creature:: since only creature appear to be able to use this
3508 void Unit::SetFacingToObject(WorldObject* pObject)
3510 if (GetTypeId() != TYPEID_UNIT)
3511 return;
3513 // never face when already moving
3514 if (!IsStopped())
3515 return;
3517 m_InteractionObject = pObject->GetGUID();
3519 // TODO: figure out under what conditions creature will move towards object instead of facing it where it currently is.
3521 SetOrientation(GetAngle(pObject));
3522 SendMonsterMove(GetPositionX(), GetPositionY(), GetPositionZ(), SPLINETYPE_FACINGTARGET, ((Creature*)this)->GetSplineFlags(), 0);
3525 bool Unit::isInAccessablePlaceFor(Creature const* c) const
3527 if(IsInWater())
3528 return c->canSwim();
3529 else
3530 return c->canWalk() || c->canFly();
3533 bool Unit::IsInWater() const
3535 return GetBaseMap()->IsInWater(GetPositionX(),GetPositionY(), GetPositionZ());
3538 bool Unit::IsUnderWater() const
3540 return GetBaseMap()->IsUnderWater(GetPositionX(),GetPositionY(),GetPositionZ());
3543 void Unit::DeMorph()
3545 SetDisplayId(GetNativeDisplayId());
3548 int32 Unit::GetTotalAuraModifier(AuraType auratype) const
3550 int32 modifier = 0;
3552 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3553 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3554 modifier += (*i)->GetModifier()->m_amount;
3556 return modifier;
3559 float Unit::GetTotalAuraMultiplier(AuraType auratype) const
3561 float multiplier = 1.0f;
3563 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3564 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3565 multiplier *= (100.0f + (*i)->GetModifier()->m_amount)/100.0f;
3567 return multiplier;
3570 int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype) const
3572 int32 modifier = 0;
3574 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3575 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3576 if ((*i)->GetModifier()->m_amount > modifier)
3577 modifier = (*i)->GetModifier()->m_amount;
3579 return modifier;
3582 int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const
3584 int32 modifier = 0;
3586 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3587 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3588 if ((*i)->GetModifier()->m_amount < modifier)
3589 modifier = (*i)->GetModifier()->m_amount;
3591 return modifier;
3594 int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3596 if(!misc_mask)
3597 return 0;
3599 int32 modifier = 0;
3601 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3602 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3604 Modifier* mod = (*i)->GetModifier();
3605 if (mod->m_miscvalue & misc_mask)
3606 modifier += mod->m_amount;
3608 return modifier;
3611 float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const
3613 if(!misc_mask)
3614 return 1.0f;
3616 float multiplier = 1.0f;
3618 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3619 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3621 Modifier* mod = (*i)->GetModifier();
3622 if (mod->m_miscvalue & misc_mask)
3623 multiplier *= (100.0f + mod->m_amount)/100.0f;
3625 return multiplier;
3628 int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3630 if(!misc_mask)
3631 return 0;
3633 int32 modifier = 0;
3635 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3636 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3638 Modifier* mod = (*i)->GetModifier();
3639 if (mod->m_miscvalue & misc_mask && mod->m_amount > modifier)
3640 modifier = mod->m_amount;
3643 return modifier;
3646 int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3648 if(!misc_mask)
3649 return 0;
3651 int32 modifier = 0;
3653 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3654 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3656 Modifier* mod = (*i)->GetModifier();
3657 if (mod->m_miscvalue & misc_mask && mod->m_amount < modifier)
3658 modifier = mod->m_amount;
3661 return modifier;
3664 int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3666 int32 modifier = 0;
3668 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3669 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3671 Modifier* mod = (*i)->GetModifier();
3672 if (mod->m_miscvalue == misc_value)
3673 modifier += mod->m_amount;
3675 return modifier;
3678 float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const
3680 float multiplier = 1.0f;
3682 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3683 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3685 Modifier* mod = (*i)->GetModifier();
3686 if (mod->m_miscvalue == misc_value)
3687 multiplier *= (100.0f + mod->m_amount)/100.0f;
3689 return multiplier;
3692 int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3694 int32 modifier = 0;
3696 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3697 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3699 Modifier* mod = (*i)->GetModifier();
3700 if (mod->m_miscvalue == misc_value && mod->m_amount > modifier)
3701 modifier = mod->m_amount;
3704 return modifier;
3707 int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3709 int32 modifier = 0;
3711 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3712 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3714 Modifier* mod = (*i)->GetModifier();
3715 if (mod->m_miscvalue == misc_value && mod->m_amount < modifier)
3716 modifier = mod->m_amount;
3719 return modifier;
3722 float Unit::GetTotalAuraMultiplierByMiscValueForMask(AuraType auratype, uint32 mask) const
3724 if(!mask)
3725 return 1.0f;
3727 float multiplier = 1.0f;
3729 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3730 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3732 Modifier* mod = (*i)->GetModifier();
3733 if (mask & (1 << (mod->m_miscvalue -1)))
3734 multiplier *= (100.0f + mod->m_amount)/100.0f;
3736 return multiplier;
3739 bool Unit::AddAura(Aura *Aur)
3741 SpellEntry const* aurSpellInfo = Aur->GetSpellProto();
3743 // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load)
3744 if( !isAlive() && !IsDeathPersistentSpell(aurSpellInfo) &&
3745 !IsDeathOnlySpell(aurSpellInfo) &&
3746 (GetTypeId()!=TYPEID_PLAYER || !((Player*)this)->GetSession()->PlayerLoading()) )
3748 delete Aur;
3749 return false;
3752 if(Aur->GetTarget() != this)
3754 sLog.outError("Aura (spell %u eff %u) add to aura list of %s (lowguid: %u) but Aura target is %s (lowguid: %u)",
3755 Aur->GetId(),Aur->GetEffIndex(),(GetTypeId()==TYPEID_PLAYER?"player":"creature"),GetGUIDLow(),
3756 (Aur->GetTarget()->GetTypeId()==TYPEID_PLAYER?"player":"creature"),Aur->GetTarget()->GetGUIDLow());
3757 delete Aur;
3758 return false;
3761 // m_auraname can be modified to SPELL_AURA_NONE for area auras, this expected for this value
3762 AuraType aurName = Aur->GetModifier()->m_auraname;
3764 spellEffectPair spair = spellEffectPair(Aur->GetId(), Aur->GetEffIndex());
3765 AuraMap::iterator i = m_Auras.find( spair );
3767 // take out same spell
3768 if (i != m_Auras.end())
3770 // passive and persistent auras can stack with themselves any number of times
3771 if (!Aur->IsPassive() && !Aur->IsPersistent())
3773 for(AuraMap::iterator i2 = m_Auras.lower_bound(spair); i2 != m_Auras.upper_bound(spair); ++i2)
3775 Aura* aur2 = i2->second;
3776 if(aur2->GetCasterGUID()==Aur->GetCasterGUID())
3778 // Aura can stack on self -> Stack it;
3779 if(aurSpellInfo->StackAmount)
3781 // can be created with >1 stack by some spell mods
3782 aur2->modStackAmount(Aur->GetStackAmount());
3783 delete Aur;
3784 return false;
3787 // Check for coexisting Weapon-proced Auras
3788 if (Aur->isWeaponBuffCoexistableWith(aur2))
3789 continue;
3791 // Carry over removed Aura's remaining damage if Aura still has ticks remaining
3792 if (aur2->GetSpellProto()->AttributesEx4 & SPELL_ATTR_EX4_STACK_DOT_MODIFIER && aurName == SPELL_AURA_PERIODIC_DAMAGE && aur2->GetAuraDuration() > 0)
3794 int32 remainingTicks = aur2->GetAuraMaxTicks() - aur2->GetAuraTicks();
3795 int32 remainingDamage = aur2->GetModifier()->m_amount * remainingTicks;
3797 Aur->GetModifier()->m_amount += int32(remainingDamage / Aur->GetAuraMaxTicks());
3799 // can be only single (this check done at _each_ aura add
3800 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3801 break;
3804 bool stop = false;
3806 // m_auraname can be modified to SPELL_AURA_NONE for area auras, use original
3807 AuraType aurNameReal = AuraType(aurSpellInfo->EffectApplyAuraName[Aur->GetEffIndex()]);
3809 switch(aurNameReal)
3811 // DoT/HoT/etc
3812 case SPELL_AURA_DUMMY: // allow stack
3813 case SPELL_AURA_PERIODIC_DAMAGE:
3814 case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
3815 case SPELL_AURA_PERIODIC_LEECH:
3816 case SPELL_AURA_PERIODIC_HEAL:
3817 case SPELL_AURA_OBS_MOD_HEALTH:
3818 case SPELL_AURA_PERIODIC_MANA_LEECH:
3819 case SPELL_AURA_OBS_MOD_MANA:
3820 case SPELL_AURA_POWER_BURN_MANA:
3821 break;
3822 case SPELL_AURA_PERIODIC_ENERGIZE: // all or self or clear non-stackable
3823 default: // not allow
3824 // can be only single (this check done at _each_ aura add
3825 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3826 stop = true;
3827 break;
3830 if(stop)
3831 break;
3836 // passive auras not stacable with other ranks
3837 if (!IsPassiveSpellStackableWithRanks(aurSpellInfo))
3839 if (!RemoveNoStackAurasDueToAura(Aur))
3841 delete Aur;
3842 return false; // couldn't remove conflicting aura with higher rank
3846 // update single target auras list (before aura add to aura list, to prevent unexpected remove recently added aura)
3847 if (Aur->IsSingleTarget() && Aur->GetTarget())
3849 // caster pointer can be deleted in time aura remove, find it by guid at each iteration
3850 for(;;)
3852 Unit* caster = Aur->GetCaster();
3853 if(!caster) // caster deleted and not required adding scAura
3854 break;
3856 bool restart = false;
3857 AuraList& scAuras = caster->GetSingleCastAuras();
3858 for(AuraList::const_iterator itr = scAuras.begin(); itr != scAuras.end(); ++itr)
3860 if( (*itr)->GetTarget() != Aur->GetTarget() &&
3861 IsSingleTargetSpells((*itr)->GetSpellProto(),aurSpellInfo) )
3863 if ((*itr)->IsInUse())
3865 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());
3866 continue;
3868 (*itr)->GetTarget()->RemoveAura((*itr)->GetId(), (*itr)->GetEffIndex());
3869 restart = true;
3870 break;
3874 if(!restart)
3876 // done
3877 scAuras.push_back(Aur);
3878 break;
3883 // add aura, register in lists and arrays
3884 Aur->_AddAura();
3885 m_Auras.insert(AuraMap::value_type(spellEffectPair(Aur->GetId(), Aur->GetEffIndex()), Aur));
3886 if (aurName < TOTAL_AURAS)
3888 m_modAuras[aurName].push_back(Aur);
3891 Aur->ApplyModifier(true,true);
3892 sLog.outDebug("Aura %u now is in use", aurName);
3894 // if aura deleted before boosts apply ignore
3895 // this can be possible it it removed indirectly by triggered spell effect at ApplyModifier
3896 if (Aur->IsDeleted())
3897 return false;
3899 if(IsSpellLastAuraEffect(aurSpellInfo,Aur->GetEffIndex()))
3900 Aur->HandleSpellSpecificBoosts(true);
3902 return true;
3905 void Unit::RemoveRankAurasDueToSpell(uint32 spellId)
3907 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
3908 if(!spellInfo)
3909 return;
3910 AuraMap::const_iterator i,next;
3911 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3913 next = i;
3914 ++next;
3915 uint32 i_spellId = (*i).second->GetId();
3916 if((*i).second && i_spellId && i_spellId != spellId)
3918 if(sSpellMgr.IsRankSpellDueToSpell(spellInfo,i_spellId))
3920 RemoveAurasDueToSpell(i_spellId);
3922 if( m_Auras.empty() )
3923 break;
3924 else
3925 next = m_Auras.begin();
3931 bool Unit::RemoveNoStackAurasDueToAura(Aura *Aur)
3933 if (!Aur)
3934 return false;
3936 SpellEntry const* spellProto = Aur->GetSpellProto();
3937 if (!spellProto)
3938 return false;
3940 uint32 spellId = Aur->GetId();
3941 SpellEffectIndex effIndex = Aur->GetEffIndex();
3943 // passive spell special case (only non stackable with ranks)
3944 if(IsPassiveSpell(spellId))
3946 if(IsPassiveSpellStackableWithRanks(spellProto))
3947 return true;
3950 SpellSpecific spellId_spec = GetSpellSpecific(spellId);
3952 AuraMap::iterator i,next;
3953 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3955 next = i;
3956 ++next;
3957 if (!(*i).second) continue;
3959 SpellEntry const* i_spellProto = (*i).second->GetSpellProto();
3961 if (!i_spellProto)
3962 continue;
3964 uint32 i_spellId = i_spellProto->Id;
3966 // early checks that spellId is passive non stackable spell
3967 if(IsPassiveSpell(i_spellId))
3969 // passive non-stackable spells not stackable only for same caster
3970 if(Aur->GetCasterGUID()!=i->second->GetCasterGUID())
3971 continue;
3973 // passive non-stackable spells not stackable only with another rank of same spell
3974 if (!sSpellMgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3975 continue;
3978 SpellEffectIndex i_effIndex = (*i).second->GetEffIndex();
3980 if(i_spellId == spellId) continue;
3982 bool is_triggered_by_spell = false;
3983 // prevent triggering aura of removing aura that triggered it
3984 for(int j = 0; j < MAX_EFFECT_INDEX; ++j)
3985 if (i_spellProto->EffectTriggerSpell[j] == spellId)
3986 is_triggered_by_spell = true;
3988 // prevent triggered aura of removing aura that triggering it (triggered effect early some aura of parent spell
3989 for(int j = 0; j < MAX_EFFECT_INDEX; ++j)
3990 if (spellProto->EffectTriggerSpell[j] == i_spellId)
3991 is_triggered_by_spell = true;
3993 if (is_triggered_by_spell)
3994 continue;
3996 SpellSpecific i_spellId_spec = GetSpellSpecific(i_spellId);
3998 // single allowed spell specific from same caster or from any caster at target
3999 bool is_spellSpecPerTargetPerCaster = IsSingleFromSpellSpecificPerTargetPerCaster(spellId_spec,i_spellId_spec);
4000 bool is_spellSpecPerTarget = IsSingleFromSpellSpecificPerTarget(spellId_spec,i_spellId_spec);
4001 if( is_spellSpecPerTarget || is_spellSpecPerTargetPerCaster && Aur->GetCasterGUID() == (*i).second->GetCasterGUID() )
4003 // cannot remove higher rank
4004 if (sSpellMgr.IsRankSpellDueToSpell(spellProto, i_spellId))
4005 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
4006 return false;
4008 // Its a parent aura (create this aura in ApplyModifier)
4009 if ((*i).second->IsInUse())
4011 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());
4012 continue;
4014 RemoveAurasDueToSpell(i_spellId);
4016 if( m_Auras.empty() )
4017 break;
4018 else
4019 next = m_Auras.begin();
4021 continue;
4024 // spell with spell specific that allow single ranks for spell from diff caster
4025 // same caster case processed or early or later
4026 bool is_spellPerTarget = IsSingleFromSpellSpecificSpellRanksPerTarget(spellId_spec,i_spellId_spec);
4027 if ( is_spellPerTarget && Aur->GetCasterGUID() != (*i).second->GetCasterGUID() && sSpellMgr.IsRankSpellDueToSpell(spellProto, i_spellId))
4029 // cannot remove higher rank
4030 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
4031 return false;
4033 // Its a parent aura (create this aura in ApplyModifier)
4034 if ((*i).second->IsInUse())
4036 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());
4037 continue;
4039 RemoveAurasDueToSpell(i_spellId);
4041 if( m_Auras.empty() )
4042 break;
4043 else
4044 next = m_Auras.begin();
4046 continue;
4049 // non single (per caster) per target spell specific (possible single spell per target at caster)
4050 if( !is_spellSpecPerTargetPerCaster && !is_spellSpecPerTarget && sSpellMgr.IsNoStackSpellDueToSpell(spellId, i_spellId) )
4052 // Its a parent aura (create this aura in ApplyModifier)
4053 if ((*i).second->IsInUse())
4055 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());
4056 continue;
4058 RemoveAurasDueToSpell(i_spellId);
4060 if( m_Auras.empty() )
4061 break;
4062 else
4063 next = m_Auras.begin();
4065 continue;
4068 // Potions stack aura by aura (elixirs/flask already checked)
4069 if( spellProto->SpellFamilyName == SPELLFAMILY_POTION && i_spellProto->SpellFamilyName == SPELLFAMILY_POTION )
4071 if (IsNoStackAuraDueToAura(spellId, effIndex, i_spellId, i_effIndex))
4073 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
4074 return false; // cannot remove higher rank
4076 // Its a parent aura (create this aura in ApplyModifier)
4077 if ((*i).second->IsInUse())
4079 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());
4080 continue;
4082 RemoveAura(i);
4083 next = i;
4087 return true;
4090 void Unit::RemoveAura(uint32 spellId, SpellEffectIndex effindex, Aura* except)
4092 spellEffectPair spair = spellEffectPair(spellId, effindex);
4093 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
4095 if(iter->second!=except)
4097 RemoveAura(iter);
4098 iter = m_Auras.lower_bound(spair);
4100 else
4101 ++iter;
4105 void Unit::RemoveAurasByCasterSpell(uint32 spellId, uint64 casterGUID)
4107 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
4109 Aura *aur = iter->second;
4110 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
4111 RemoveAura(iter);
4112 else
4113 ++iter;
4117 void Unit::RemoveAurasByCasterSpell(uint32 spellId, SpellEffectIndex effindex, uint64 casterGUID)
4119 spellEffectPair spair = spellEffectPair(spellId, effindex);
4120 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
4122 Aura *aur = iter->second;
4123 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
4125 RemoveAura(iter);
4126 iter = m_Auras.lower_bound(spair);
4128 else
4129 ++iter;
4133 void Unit::RemoveSingleAuraDueToSpellByDispel(uint32 spellId, uint64 casterGUID, Unit *dispeler)
4135 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellId);
4137 // Custom dispel cases
4138 // Unstable Affliction
4139 if(spellEntry->SpellFamilyName == SPELLFAMILY_WARLOCK && (spellEntry->SpellFamilyFlags & UI64LIT(0x010000000000)))
4141 if (Aura* dotAura = GetAura(SPELL_AURA_PERIODIC_DAMAGE,SPELLFAMILY_WARLOCK,UI64LIT(0x010000000000),0x00000000,casterGUID))
4143 int32 damage = dotAura->GetModifier()->m_amount*9;
4145 // Remove spell auras from stack
4146 RemoveSingleSpellAurasByCasterSpell(spellId, casterGUID, AURA_REMOVE_BY_DISPEL);
4148 // backfire damage and silence
4149 dispeler->CastCustomSpell(dispeler, 31117, &damage, NULL, NULL, true, NULL, NULL,casterGUID);
4150 return;
4153 // Flame Shock
4154 else if (spellEntry->SpellFamilyName == SPELLFAMILY_SHAMAN && (spellEntry->SpellFamilyFlags & UI64LIT(0x10000000)))
4156 Unit* caster = NULL;
4157 uint32 triggeredSpell = 0;
4159 if (Aura* dotAura = GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, UI64LIT(0x10000000), 0x00000000, casterGUID))
4160 caster = dotAura->GetCaster();
4162 if (caster && !caster->isDead())
4164 Unit::AuraList const& auras = caster->GetAurasByType(SPELL_AURA_DUMMY);
4165 for (Unit::AuraList::const_iterator i = auras.begin(); i != auras.end(); ++i)
4167 switch((*i)->GetId())
4169 case 51480: triggeredSpell=64694; break;// Lava Flows, Rank 1
4170 case 51481: triggeredSpell=65263; break;// Lava Flows, Rank 2
4171 case 51482: triggeredSpell=65264; break;// Lava Flows, Rank 3
4172 default: continue;
4174 break;
4178 // Remove spell auras from stack
4179 RemoveSingleSpellAurasByCasterSpell(spellId, casterGUID, AURA_REMOVE_BY_DISPEL);
4181 // Haste
4182 if (triggeredSpell)
4183 caster->CastSpell(caster, triggeredSpell, true);
4184 return;
4186 // Vampiric touch (first dummy aura)
4187 else if (spellEntry->SpellFamilyName == SPELLFAMILY_PRIEST && spellEntry->SpellFamilyFlags & UI64LIT(0x0000040000000000))
4189 if (Aura *dot = GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, UI64LIT(0x0000040000000000), 0x00000000, casterGUID))
4191 if(Unit* caster = dot->GetCaster())
4193 int32 bp0 = dot->GetModifier()->m_amount;
4194 bp0 = 8 * caster->SpellDamageBonus(this, spellEntry, bp0, DOT, 1);
4196 // Remove spell auras from stack
4197 RemoveSingleSpellAurasByCasterSpell(spellId, casterGUID, AURA_REMOVE_BY_DISPEL);
4199 CastCustomSpell(this, 64085, &bp0, NULL, NULL, true, NULL, NULL, casterGUID);
4200 return;
4205 RemoveSingleSpellAurasByCasterSpell(spellId, casterGUID, AURA_REMOVE_BY_DISPEL);
4208 void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit *stealer)
4210 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
4212 Aura *aur = iter->second;
4213 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
4215 int32 basePoints = aur->GetBasePoints();
4216 // construct the new aura for the attacker - will never return NULL, it's just a wrapper for
4217 // some different constructors
4218 Aura * new_aur = CreateAura(aur->GetSpellProto(), aur->GetEffIndex(), &basePoints, stealer, this);
4220 // set its duration and maximum duration
4221 // max duration 2 minutes (in msecs)
4222 int32 dur = aur->GetAuraDuration();
4223 int32 max_dur = 2*MINUTE*IN_MILISECONDS;
4224 int32 new_max_dur = max_dur > dur ? dur : max_dur;
4225 new_aur->SetAuraMaxDuration( new_max_dur );
4226 new_aur->SetAuraDuration( new_max_dur );
4228 // set periodic to do at least one tick (for case when original aura has been at last tick preparing)
4229 int32 periodic = aur->GetModifier()->periodictime;
4230 new_aur->GetModifier()->periodictime = periodic < new_max_dur ? periodic : new_max_dur;
4232 // Unregister _before_ adding to stealer
4233 aur->UnregisterSingleCastAura();
4235 // strange but intended behaviour: Stolen single target auras won't be treated as single targeted
4236 new_aur->SetIsSingleTarget(false);
4238 // add the new aura to stealer
4239 stealer->AddAura(new_aur);
4241 // Remove aura as dispel
4242 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
4244 else
4245 ++iter;
4249 void Unit::RemoveAurasDueToSpellByCancel(uint32 spellId)
4251 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
4253 if (iter->second->GetId() == spellId)
4254 RemoveAura(iter, AURA_REMOVE_BY_CANCEL);
4255 else
4256 ++iter;
4260 void Unit::RemoveAurasWithDispelType( DispelType type )
4262 // Create dispel mask by dispel type
4263 uint32 dispelMask = GetDispellMask(type);
4264 // Dispel all existing auras vs current dispel type
4265 AuraMap& auras = GetAuras();
4266 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
4268 SpellEntry const* spell = itr->second->GetSpellProto();
4269 if( (1<<spell->Dispel) & dispelMask )
4271 // Dispel aura
4272 RemoveAurasDueToSpell(spell->Id);
4273 itr = auras.begin();
4275 else
4276 ++itr;
4280 void Unit::RemoveSingleAuraFromStack(AuraMap::iterator &i, AuraRemoveMode mode)
4282 if (i->second->modStackAmount(-1))
4283 RemoveAura(i,mode);
4287 void Unit::RemoveSingleAuraFromStack(uint32 spellId, SpellEffectIndex effindex, AuraRemoveMode mode)
4289 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
4290 if(iter != m_Auras.end())
4291 RemoveSingleAuraFromStack(iter,mode);
4294 void Unit::RemoveSingleSpellAurasFromStack(uint32 spellId, AuraRemoveMode mode)
4296 for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
4297 RemoveSingleAuraFromStack(spellId, SpellEffectIndex(i), mode);
4300 void Unit::RemoveSingleSpellAurasByCasterSpell(uint32 spellId, uint64 casterGUID, AuraRemoveMode mode)
4302 for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
4303 RemoveSingleAuraByCasterSpell(spellId, SpellEffectIndex(i), casterGUID, mode);
4306 void Unit::RemoveSingleAuraByCasterSpell(uint32 spellId, SpellEffectIndex effindex, uint64 casterGUID, AuraRemoveMode mode)
4308 spellEffectPair spair = spellEffectPair(spellId, effindex);
4309 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
4311 Aura *aur = iter->second;
4312 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
4314 RemoveSingleAuraFromStack(iter,mode);
4315 break;
4321 void Unit::RemoveAurasDueToSpell(uint32 spellId, Aura* except)
4323 for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
4324 RemoveAura(spellId,SpellEffectIndex(i),except);
4327 void Unit::RemoveAurasDueToItemSpell(Item* castItem,uint32 spellId)
4329 for (int k=0; k < MAX_EFFECT_INDEX; ++k)
4331 spellEffectPair spair = spellEffectPair(spellId, SpellEffectIndex(k));
4332 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
4334 if (iter->second->GetCastItemGUID() == castItem->GetGUID())
4336 RemoveAura(iter);
4337 iter = m_Auras.upper_bound(spair); // overwrite by more appropriate
4339 else
4340 ++iter;
4345 void Unit::RemoveAurasWithInterruptFlags(uint32 flags)
4347 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
4349 if (iter->second->GetSpellProto()->AuraInterruptFlags & flags)
4350 RemoveAura(iter);
4351 else
4352 ++iter;
4356 void Unit::RemoveNotOwnSingleTargetAuras(uint32 newPhase)
4358 // single target auras from other casters
4359 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
4361 if (iter->second->GetCasterGUID()!=GetGUID() && IsSingleTargetSpell(iter->second->GetSpellProto()))
4363 if(!newPhase)
4364 RemoveAura(iter);
4365 else
4367 Unit* caster = iter->second->GetCaster();
4368 if(!caster || !caster->InSamePhase(newPhase))
4369 RemoveAura(iter);
4370 else
4371 ++iter;
4374 else
4375 ++iter;
4378 // single target auras at other targets
4379 AuraList& scAuras = GetSingleCastAuras();
4380 for (AuraList::iterator iter = scAuras.begin(); iter != scAuras.end(); )
4382 Aura* aura = *iter;
4383 if (aura->GetTarget() != this && !aura->GetTarget()->InSamePhase(newPhase))
4385 scAuras.erase(iter); // explicitly remove, instead waiting remove in RemoveAura
4386 aura->GetTarget()->RemoveAura(aura);
4387 iter = scAuras.begin();
4389 else
4390 ++iter;
4395 void Unit::RemoveAura(Aura* aura, AuraRemoveMode mode /*= AURA_REMOVE_BY_DEFAULT*/)
4397 AuraMap::iterator i = m_Auras.lower_bound(spellEffectPair(aura->GetId(), aura->GetEffIndex()));
4398 AuraMap::iterator upperBound = m_Auras.upper_bound(spellEffectPair(aura->GetId(), aura->GetEffIndex()));
4399 for (; i != upperBound; ++i)
4401 if (i->second == aura)
4403 RemoveAura(i,mode);
4404 return;
4407 sLog.outDebug("Trying to remove aura id %u effect %u by pointer but aura not found on target", aura->GetId(), aura->GetEffIndex());
4410 void Unit::RemoveAura(AuraMap::iterator &i, AuraRemoveMode mode)
4412 Aura* Aur = i->second;
4413 SpellEntry const* AurSpellInfo = Aur->GetSpellProto();
4415 Aur->UnregisterSingleCastAura();
4417 // remove from list before mods removing (prevent cyclic calls, mods added before including to aura list - use reverse order)
4418 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
4420 m_modAuras[Aur->GetModifier()->m_auraname].remove(Aur);
4423 // Set remove mode
4424 Aur->SetRemoveMode(mode);
4426 // if unit currently update aura list then make safe update iterator shift to next
4427 if (m_AurasUpdateIterator == i)
4428 ++m_AurasUpdateIterator;
4430 // some ShapeshiftBoosts at remove trigger removing other auras including parent Shapeshift aura
4431 // remove aura from list before to prevent deleting it before
4432 m_Auras.erase(i);
4434 // now aura removed from from list and can't be deleted by indirect call but can be referenced from callers
4436 // Statue unsummoned at aura remove
4437 Totem* statue = NULL;
4438 if(IsChanneledSpell(AurSpellInfo))
4439 if(Unit* caster = Aur->GetCaster())
4440 if(caster->GetTypeId()==TYPEID_UNIT && ((Creature*)caster)->isTotem() && ((Totem*)caster)->GetTotemType()==TOTEM_STATUE)
4441 statue = ((Totem*)caster);
4443 sLog.outDebug("Aura %u now is remove mode %d",Aur->GetModifier()->m_auraname, mode);
4444 if (mode != AURA_REMOVE_BY_DELETE) // not unapply if target will deleted
4445 Aur->ApplyModifier(false,true);
4447 if (Aur->_RemoveAura())
4449 // last aura in stack removed
4450 if (mode != AURA_REMOVE_BY_DELETE && IsSpellLastAuraEffect(Aur->GetSpellProto(),Aur->GetEffIndex()))
4451 Aur->HandleSpellSpecificBoosts(false);
4454 // If aura in use (removed from code that plan access to it data after return)
4455 // store it in aura list with delayed deletion
4456 if (Aur->IsInUse())
4457 m_deletedAuras.push_back(Aur);
4458 else
4459 delete Aur;
4461 if(statue)
4462 statue->UnSummon();
4464 // only way correctly remove all auras from list
4465 if( m_Auras.empty() )
4466 i = m_Auras.end();
4467 else
4468 i = m_Auras.begin();
4472 void Unit::RemoveAllAuras(AuraRemoveMode mode /*= AURA_REMOVE_BY_DEFAULT*/)
4474 while (!m_Auras.empty())
4476 AuraMap::iterator iter = m_Auras.begin();
4477 RemoveAura(iter,mode);
4481 void Unit::RemoveArenaAuras(bool onleave)
4483 // in join, remove positive buffs, on end, remove negative
4484 // used to remove positive visible auras in arenas
4485 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
4487 if (!(iter->second->GetSpellProto()->AttributesEx4 & SPELL_ATTR_EX4_UNK21) &&
4488 // don't remove stances, shadowform, pally/hunter auras
4489 !iter->second->IsPassive() && // don't remove passive auras
4490 (!(iter->second->GetSpellProto()->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY) ||
4491 !(iter->second->GetSpellProto()->Attributes & SPELL_ATTR_UNK8)) &&
4492 // not unaffected by invulnerability auras or not having that unknown flag (that seemed the most probable)
4493 (iter->second->IsPositive() != onleave)) // remove positive buffs on enter, negative buffs on leave
4494 RemoveAura(iter);
4495 else
4496 ++iter;
4500 void Unit::RemoveAllAurasOnDeath()
4502 // used just after dieing to remove all visible auras
4503 // and disable the mods for the passive ones
4504 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
4506 if (!iter->second->IsPassive() && !iter->second->IsDeathPersistent())
4507 RemoveAura(iter, AURA_REMOVE_BY_DEATH);
4508 else
4509 ++iter;
4513 void Unit::DelayAura(uint32 spellId, SpellEffectIndex effindex, int32 delaytime)
4515 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
4516 if (iter != m_Auras.end())
4518 if (iter->second->GetAuraDuration() < delaytime)
4519 iter->second->SetAuraDuration(0);
4520 else
4521 iter->second->SetAuraDuration(iter->second->GetAuraDuration() - delaytime);
4522 iter->second->SendAuraUpdate(false);
4523 sLog.outDebug("Aura %u partially interrupted on unit %u, new duration: %u ms",iter->second->GetModifier()->m_auraname, GetGUIDLow(), iter->second->GetAuraDuration());
4527 void Unit::_RemoveAllAuraMods()
4529 for (AuraMap::const_iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
4531 (*i).second->ApplyModifier(false);
4535 void Unit::_ApplyAllAuraMods()
4537 for (AuraMap::const_iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
4539 (*i).second->ApplyModifier(true);
4543 Aura* Unit::GetAura(uint32 spellId, SpellEffectIndex effindex)
4545 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
4546 if (iter != m_Auras.end())
4547 return iter->second;
4548 return NULL;
4551 Aura* Unit::GetAura(AuraType type, uint32 family, uint64 familyFlag, uint32 familyFlag2, uint64 casterGUID)
4553 AuraList const& auras = GetAurasByType(type);
4554 for(AuraList::const_iterator i = auras.begin();i != auras.end(); ++i)
4556 SpellEntry const *spell = (*i)->GetSpellProto();
4557 if (spell->SpellFamilyName == family && (spell->SpellFamilyFlags & familyFlag || spell->SpellFamilyFlags2 & familyFlag2))
4559 if (casterGUID && (*i)->GetCasterGUID()!=casterGUID)
4560 continue;
4561 return (*i);
4564 return NULL;
4567 bool Unit::HasAura(uint32 spellId) const
4569 for (int i = 0; i < MAX_EFFECT_INDEX ; ++i)
4571 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, SpellEffectIndex(i)));
4572 if (iter != m_Auras.end())
4573 return true;
4575 return false;
4578 void Unit::AddDynObject(DynamicObject* dynObj)
4580 m_dynObjGUIDs.push_back(dynObj->GetGUID());
4583 void Unit::RemoveDynObject(uint32 spellid)
4585 if(m_dynObjGUIDs.empty())
4586 return;
4587 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4589 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4590 if(!dynObj)
4592 i = m_dynObjGUIDs.erase(i);
4594 else if(spellid == 0 || dynObj->GetSpellId() == spellid)
4596 dynObj->Delete();
4597 i = m_dynObjGUIDs.erase(i);
4599 else
4600 ++i;
4604 void Unit::RemoveAllDynObjects()
4606 while(!m_dynObjGUIDs.empty())
4608 DynamicObject* dynObj = GetMap()->GetDynamicObject(*m_dynObjGUIDs.begin());
4609 if(dynObj)
4610 dynObj->Delete();
4611 m_dynObjGUIDs.erase(m_dynObjGUIDs.begin());
4615 DynamicObject * Unit::GetDynObject(uint32 spellId, SpellEffectIndex effIndex)
4617 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4619 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4620 if(!dynObj)
4622 i = m_dynObjGUIDs.erase(i);
4623 continue;
4626 if (dynObj->GetSpellId() == spellId && dynObj->GetEffIndex() == effIndex)
4627 return dynObj;
4628 ++i;
4630 return NULL;
4633 DynamicObject * Unit::GetDynObject(uint32 spellId)
4635 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4637 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4638 if(!dynObj)
4640 i = m_dynObjGUIDs.erase(i);
4641 continue;
4644 if (dynObj->GetSpellId() == spellId)
4645 return dynObj;
4646 ++i;
4648 return NULL;
4651 GameObject* Unit::GetGameObject(uint32 spellId) const
4653 for (GameObjectList::const_iterator i = m_gameObj.begin(); i != m_gameObj.end(); ++i)
4654 if ((*i)->GetSpellId() == spellId)
4655 return *i;
4657 return NULL;
4660 void Unit::AddGameObject(GameObject* gameObj)
4662 assert(gameObj && gameObj->GetOwnerGUID()==0);
4663 m_gameObj.push_back(gameObj);
4664 gameObj->SetOwnerGUID(GetGUID());
4666 if ( GetTypeId()==TYPEID_PLAYER && gameObj->GetSpellId() )
4668 SpellEntry const* createBySpell = sSpellStore.LookupEntry(gameObj->GetSpellId());
4669 // Need disable spell use for owner
4670 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4671 // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
4672 ((Player*)this)->AddSpellAndCategoryCooldowns(createBySpell,0,NULL,true);
4676 void Unit::RemoveGameObject(GameObject* gameObj, bool del)
4678 assert(gameObj && gameObj->GetOwnerGUID()==GetGUID());
4680 gameObj->SetOwnerGUID(0);
4682 // GO created by some spell
4683 if (uint32 spellid = gameObj->GetSpellId())
4685 RemoveAurasDueToSpell(spellid);
4687 if (GetTypeId()==TYPEID_PLAYER)
4689 SpellEntry const* createBySpell = sSpellStore.LookupEntry(spellid );
4690 // Need activate spell use for owner
4691 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4692 // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
4693 ((Player*)this)->SendCooldownEvent(createBySpell);
4697 m_gameObj.remove(gameObj);
4699 if(del)
4701 gameObj->SetRespawnTime(0);
4702 gameObj->Delete();
4706 void Unit::RemoveGameObject(uint32 spellid, bool del)
4708 if(m_gameObj.empty())
4709 return;
4710 GameObjectList::iterator i, next;
4711 for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next)
4713 next = i;
4714 if(spellid == 0 || (*i)->GetSpellId() == spellid)
4716 (*i)->SetOwnerGUID(0);
4717 if(del)
4719 (*i)->SetRespawnTime(0);
4720 (*i)->Delete();
4723 next = m_gameObj.erase(i);
4725 else
4726 ++next;
4730 void Unit::RemoveAllGameObjects()
4732 // remove references to unit
4733 for(GameObjectList::iterator i = m_gameObj.begin(); i != m_gameObj.end();)
4735 (*i)->SetOwnerGUID(0);
4736 (*i)->SetRespawnTime(0);
4737 (*i)->Delete();
4738 i = m_gameObj.erase(i);
4742 void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage *log)
4744 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+4+1+4+4+1+1+4+4+1)); // we guess size
4745 data << log->target->GetPackGUID();
4746 data << log->attacker->GetPackGUID();
4747 data << uint32(log->SpellID);
4748 data << uint32(log->damage); // damage amount
4749 data << uint32(log->overkill); // overkill
4750 data << uint8 (log->schoolMask); // damage school
4751 data << uint32(log->absorb); // AbsorbedDamage
4752 data << uint32(log->resist); // resist
4753 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
4754 data << uint8 (log->unused); // unused
4755 data << uint32(log->blocked); // blocked
4756 data << uint32(log->HitInfo);
4757 data << uint8 (0); // flag to use extend data
4758 SendMessageToSet( &data, true );
4761 void Unit::SendSpellNonMeleeDamageLog(Unit *target, uint32 SpellID, uint32 Damage, SpellSchoolMask damageSchoolMask, uint32 AbsorbedDamage, uint32 Resist, bool PhysicalDamage, uint32 Blocked, bool CriticalHit)
4763 SpellNonMeleeDamage log(this, target, SpellID, damageSchoolMask);
4764 log.damage = Damage - AbsorbedDamage - Resist - Blocked;
4765 log.absorb = AbsorbedDamage;
4766 log.resist = Resist;
4767 log.physicalLog = PhysicalDamage;
4768 log.blocked = Blocked;
4769 log.HitInfo = SPELL_HIT_TYPE_UNK1 | SPELL_HIT_TYPE_UNK3 | SPELL_HIT_TYPE_UNK6;
4770 if(CriticalHit)
4771 log.HitInfo |= SPELL_HIT_TYPE_CRIT;
4772 SendSpellNonMeleeDamageLog(&log);
4775 void Unit::SendPeriodicAuraLog(SpellPeriodicAuraLogInfo *pInfo)
4777 Aura *aura = pInfo->aura;
4778 Modifier *mod = aura->GetModifier();
4780 WorldPacket data(SMSG_PERIODICAURALOG, 30);
4781 data << aura->GetTarget()->GetPackGUID();
4782 data.appendPackGUID(aura->GetCasterGUID());
4783 data << uint32(aura->GetId()); // spellId
4784 data << uint32(1); // count
4785 data << uint32(mod->m_auraname); // auraId
4786 switch(mod->m_auraname)
4788 case SPELL_AURA_PERIODIC_DAMAGE:
4789 case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
4790 data << uint32(pInfo->damage); // damage
4791 data << uint32(pInfo->overDamage); // overkill?
4792 data << uint32(GetSpellSchoolMask(aura->GetSpellProto()));
4793 data << uint32(pInfo->absorb); // absorb
4794 data << uint32(pInfo->resist); // resist
4795 data << uint8(pInfo->critical ? 1 : 0); // new 3.1.2 critical flag
4796 break;
4797 case SPELL_AURA_PERIODIC_HEAL:
4798 case SPELL_AURA_OBS_MOD_HEALTH:
4799 data << uint32(pInfo->damage); // damage
4800 data << uint32(pInfo->overDamage); // overheal?
4801 data << uint8(pInfo->critical ? 1 : 0); // new 3.1.2 critical flag
4802 break;
4803 case SPELL_AURA_OBS_MOD_MANA:
4804 case SPELL_AURA_PERIODIC_ENERGIZE:
4805 data << uint32(mod->m_miscvalue); // power type
4806 data << uint32(pInfo->damage); // damage
4807 break;
4808 case SPELL_AURA_PERIODIC_MANA_LEECH:
4809 data << uint32(mod->m_miscvalue); // power type
4810 data << uint32(pInfo->damage); // amount
4811 data << float(pInfo->multiplier); // gain multiplier
4812 break;
4813 default:
4814 sLog.outError("Unit::SendPeriodicAuraLog: unknown aura %u", uint32(mod->m_auraname));
4815 return;
4818 aura->GetTarget()->SendMessageToSet(&data, true);
4821 void Unit::ProcDamageAndSpell(Unit *pVictim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellEntry const *procSpell)
4823 // Not much to do if no flags are set.
4824 if (procAttacker)
4825 ProcDamageAndSpellFor(false,pVictim,procAttacker, procExtra,attType, procSpell, amount);
4826 // Now go on with a victim's events'n'auras
4827 // Not much to do if no flags are set or there is no victim
4828 if(pVictim && pVictim->isAlive() && procVictim)
4829 pVictim->ProcDamageAndSpellFor(true,this,procVictim, procExtra, attType, procSpell, amount);
4832 void Unit::SendSpellMiss(Unit *target, uint32 spellID, SpellMissInfo missInfo)
4834 WorldPacket data(SMSG_SPELLLOGMISS, (4+8+1+4+8+1));
4835 data << uint32(spellID);
4836 data << uint64(GetGUID());
4837 data << uint8(0); // can be 0 or 1
4838 data << uint32(1); // target count
4839 // for(i = 0; i < target count; ++i)
4840 data << uint64(target->GetGUID()); // target GUID
4841 data << uint8(missInfo);
4842 // end loop
4843 SendMessageToSet(&data, true);
4846 void Unit::SendAttackStateUpdate(CalcDamageInfo *damageInfo)
4848 sLog.outDebug("WORLD: Sending SMSG_ATTACKERSTATEUPDATE");
4850 uint32 count = 1;
4851 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, 16 + 45); // we guess size
4852 data << uint32(damageInfo->HitInfo);
4853 data << damageInfo->attacker->GetPackGUID();
4854 data << damageInfo->target->GetPackGUID();
4855 data << uint32(damageInfo->damage); // Full damage
4856 data << uint32(0); // overkill value
4857 data << uint8(count); // Sub damage count
4859 for(uint32 i = 0; i < count; ++i)
4861 data << uint32(damageInfo->damageSchoolMask); // School of sub damage
4862 data << float(damageInfo->damage); // sub damage
4863 data << uint32(damageInfo->damage); // Sub Damage
4866 if(damageInfo->HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4868 for(uint32 i = 0; i < count; ++i)
4869 data << uint32(damageInfo->absorb); // Absorb
4872 if(damageInfo->HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4874 for(uint32 i = 0; i < count; ++i)
4875 data << uint32(damageInfo->resist); // Resist
4878 data << uint8(damageInfo->TargetState);
4879 data << uint32(0);
4880 data << uint32(0);
4882 if(damageInfo->HitInfo & HITINFO_BLOCK)
4883 data << uint32(damageInfo->blocked_amount);
4885 if(damageInfo->HitInfo & HITINFO_UNK3)
4886 data << uint32(0);
4888 if(damageInfo->HitInfo & HITINFO_UNK1)
4890 data << uint32(0);
4891 data << float(0);
4892 data << float(0);
4893 data << float(0);
4894 data << float(0);
4895 data << float(0);
4896 data << float(0);
4897 data << float(0);
4898 data << float(0);
4899 for(uint8 i = 0; i < 5; ++i)
4901 data << float(0);
4902 data << float(0);
4904 data << uint32(0);
4907 SendMessageToSet( &data, true );
4910 void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit *target, uint8 /*SwingType*/, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount)
4912 CalcDamageInfo dmgInfo;
4913 dmgInfo.HitInfo = HitInfo;
4914 dmgInfo.attacker = this;
4915 dmgInfo.target = target;
4916 dmgInfo.damage = Damage - AbsorbDamage - Resist - BlockedAmount;
4917 dmgInfo.damageSchoolMask = damageSchoolMask;
4918 dmgInfo.absorb = AbsorbDamage;
4919 dmgInfo.resist = Resist;
4920 dmgInfo.TargetState = TargetState;
4921 dmgInfo.blocked_amount = BlockedAmount;
4922 SendAttackStateUpdate(&dmgInfo);
4925 bool Unit::HandleHasteAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
4927 SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto();
4929 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4930 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4932 uint32 triggered_spell_id = 0;
4933 Unit* target = pVictim;
4934 int32 basepoints0 = 0;
4936 switch(hasteSpell->SpellFamilyName)
4938 case SPELLFAMILY_ROGUE:
4940 switch(hasteSpell->Id)
4942 // Blade Flurry
4943 case 13877:
4944 case 33735:
4946 target = SelectRandomUnfriendlyTarget(pVictim);
4947 if(!target)
4948 return false;
4949 basepoints0 = damage;
4950 triggered_spell_id = 22482;
4951 break;
4954 break;
4958 // processed charge only counting case
4959 if(!triggered_spell_id)
4960 return true;
4962 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
4964 if(!triggerEntry)
4966 sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",hasteSpell->Id,triggered_spell_id);
4967 return false;
4970 // default case
4971 if(!target || target!=this && !target->isAlive())
4972 return false;
4974 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
4975 return false;
4977 if(basepoints0)
4978 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
4979 else
4980 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
4982 if( cooldown && GetTypeId()==TYPEID_PLAYER )
4983 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
4985 return true;
4988 bool Unit::HandleSpellCritChanceAuraProc(Unit *pVictim, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
4990 SpellEntry const *triggeredByAuraSpell = triggeredByAura->GetSpellProto();
4992 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4993 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4995 uint32 triggered_spell_id = 0;
4996 Unit* target = pVictim;
4997 int32 basepoints0 = 0;
4999 switch(triggeredByAuraSpell->SpellFamilyName)
5001 case SPELLFAMILY_MAGE:
5003 switch(triggeredByAuraSpell->Id)
5005 // Focus Magic
5006 case 54646:
5008 Unit* caster = triggeredByAura->GetCaster();
5009 if(!caster)
5010 return false;
5012 triggered_spell_id = 54648;
5013 target = caster;
5014 break;
5020 // processed charge only counting case
5021 if(!triggered_spell_id)
5022 return true;
5024 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
5026 if(!triggerEntry)
5028 sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",triggeredByAuraSpell->Id,triggered_spell_id);
5029 return false;
5032 // default case
5033 if(!target || target!=this && !target->isAlive())
5034 return false;
5036 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
5037 return false;
5039 if(basepoints0)
5040 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5041 else
5042 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
5044 if( cooldown && GetTypeId()==TYPEID_PLAYER )
5045 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
5047 return true;
5050 bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
5052 SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
5053 SpellEffectIndex effIndex = triggeredByAura->GetEffIndex();
5054 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
5056 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
5057 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
5059 uint32 triggered_spell_id = 0;
5060 Unit* target = pVictim;
5061 int32 basepoints[MAX_EFFECT_INDEX] = {0, 0, 0};
5063 switch(dummySpell->SpellFamilyName)
5065 case SPELLFAMILY_GENERIC:
5067 switch (dummySpell->Id)
5069 // Eye for an Eye
5070 case 9799:
5071 case 25988:
5073 // return damage % to attacker but < 50% own total health
5074 basepoints[0] = triggerAmount*int32(damage)/100;
5075 if (basepoints[0] > (int32)GetMaxHealth()/2)
5076 basepoints[0] = (int32)GetMaxHealth()/2;
5078 triggered_spell_id = 25997;
5079 break;
5081 // Sweeping Strikes (NPC spells may be)
5082 case 18765:
5083 case 35429:
5085 // prevent chain of triggered spell from same triggered spell
5086 if (procSpell && procSpell->Id == 26654)
5087 return false;
5089 target = SelectRandomUnfriendlyTarget(pVictim);
5090 if(!target)
5091 return false;
5093 triggered_spell_id = 26654;
5094 break;
5096 // Twisted Reflection (boss spell)
5097 case 21063:
5098 triggered_spell_id = 21064;
5099 break;
5100 // Unstable Power
5101 case 24658:
5103 if (!procSpell || procSpell->Id == 24659)
5104 return false;
5105 // Need remove one 24659 aura
5106 RemoveSingleSpellAurasFromStack(24659);
5107 return true;
5109 // Restless Strength
5110 case 24661:
5112 // Need remove one 24662 aura
5113 RemoveSingleSpellAurasFromStack(24662);
5114 return true;
5116 // Adaptive Warding (Frostfire Regalia set)
5117 case 28764:
5119 if(!procSpell)
5120 return false;
5122 // find Mage Armor
5123 bool found = false;
5124 AuraList const& mRegenInterupt = GetAurasByType(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT);
5125 for(AuraList::const_iterator iter = mRegenInterupt.begin(); iter != mRegenInterupt.end(); ++iter)
5127 if(SpellEntry const* iterSpellProto = (*iter)->GetSpellProto())
5129 if(iterSpellProto->SpellFamilyName==SPELLFAMILY_MAGE && (iterSpellProto->SpellFamilyFlags & UI64LIT(0x10000000)))
5131 found=true;
5132 break;
5136 if(!found)
5137 return false;
5139 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
5141 case SPELL_SCHOOL_NORMAL:
5142 case SPELL_SCHOOL_HOLY:
5143 return false; // ignored
5144 case SPELL_SCHOOL_FIRE: triggered_spell_id = 28765; break;
5145 case SPELL_SCHOOL_NATURE: triggered_spell_id = 28768; break;
5146 case SPELL_SCHOOL_FROST: triggered_spell_id = 28766; break;
5147 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 28769; break;
5148 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 28770; break;
5149 default:
5150 return false;
5153 target = this;
5154 break;
5156 // Obsidian Armor (Justice Bearer`s Pauldrons shoulder)
5157 case 27539:
5159 if(!procSpell)
5160 return false;
5162 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
5164 case SPELL_SCHOOL_NORMAL:
5165 return false; // ignore
5166 case SPELL_SCHOOL_HOLY: triggered_spell_id = 27536; break;
5167 case SPELL_SCHOOL_FIRE: triggered_spell_id = 27533; break;
5168 case SPELL_SCHOOL_NATURE: triggered_spell_id = 27538; break;
5169 case SPELL_SCHOOL_FROST: triggered_spell_id = 27534; break;
5170 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 27535; break;
5171 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 27540; break;
5172 default:
5173 return false;
5176 target = this;
5177 break;
5179 // Mana Leech (Passive) (Priest Pet Aura)
5180 case 28305:
5182 // Cast on owner
5183 target = GetOwner();
5184 if(!target)
5185 return false;
5187 triggered_spell_id = 34650;
5188 break;
5190 // Divine purpose
5191 case 31871:
5192 case 31872:
5194 // Roll chane
5195 if (!roll_chance_i(triggerAmount))
5196 return false;
5198 // Remove any stun effect on target
5199 AuraMap& Auras = pVictim->GetAuras();
5200 for(AuraMap::const_iterator iter = Auras.begin(); iter != Auras.end();)
5202 SpellEntry const *spell = iter->second->GetSpellProto();
5203 if( spell->Mechanic == MECHANIC_STUN ||
5204 spell->EffectMechanic[iter->second->GetEffIndex()] == MECHANIC_STUN)
5206 pVictim->RemoveAurasDueToSpell(spell->Id);
5207 iter = Auras.begin();
5209 else
5210 ++iter;
5212 return true;
5214 // Mark of Malice
5215 case 33493:
5217 // Cast finish spell at last charge
5218 if (triggeredByAura->GetAuraCharges() > 1)
5219 return false;
5221 target = this;
5222 triggered_spell_id = 33494;
5223 break;
5225 // Vampiric Aura (boss spell)
5226 case 38196:
5228 basepoints[0] = 3 * damage; // 300%
5229 if (basepoints[0] < 0)
5230 return false;
5232 triggered_spell_id = 31285;
5233 target = this;
5234 break;
5236 // Aura of Madness (Darkmoon Card: Madness trinket)
5237 //=====================================================
5238 // 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior)
5239 // 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid)
5240 // 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid)
5241 // 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin)
5242 // 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes)
5243 // 41005 Manic: +35 haste (spell, melee and ranged) (All classes)
5244 // 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter)
5245 // 41011 Martyr Complex: +35 stamina (All classes)
5246 // 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
5247 // 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
5248 case 39446:
5250 if(GetTypeId() != TYPEID_PLAYER)
5251 return false;
5253 // Select class defined buff
5254 switch (getClass())
5256 case CLASS_PALADIN: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
5257 case CLASS_DRUID: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
5259 uint32 RandomSpell[]={39511,40997,40998,40999,41002,41005,41009,41011,41409};
5260 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
5261 break;
5263 case CLASS_ROGUE: // 39511,40997,40998,41002,41005,41011
5264 case CLASS_WARRIOR: // 39511,40997,40998,41002,41005,41011
5266 uint32 RandomSpell[]={39511,40997,40998,41002,41005,41011};
5267 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
5268 break;
5270 case CLASS_PRIEST: // 40999,41002,41005,41009,41011,41406,41409
5271 case CLASS_SHAMAN: // 40999,41002,41005,41009,41011,41406,41409
5272 case CLASS_MAGE: // 40999,41002,41005,41009,41011,41406,41409
5273 case CLASS_WARLOCK: // 40999,41002,41005,41009,41011,41406,41409
5275 uint32 RandomSpell[]={40999,41002,41005,41009,41011,41406,41409};
5276 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
5277 break;
5279 case CLASS_HUNTER: // 40997,40999,41002,41005,41009,41011,41406,41409
5281 uint32 RandomSpell[]={40997,40999,41002,41005,41009,41011,41406,41409};
5282 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
5283 break;
5285 default:
5286 return false;
5289 target = this;
5290 if (roll_chance_i(10))
5291 ((Player*)this)->Say("This is Madness!", LANG_UNIVERSAL);
5292 break;
5294 // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck)
5295 // cast 45479 Light's Wrath if Exalted by Aldor
5296 // cast 45429 Arcane Bolt if Exalted by Scryers
5297 case 45481:
5299 if(GetTypeId() != TYPEID_PLAYER)
5300 return false;
5302 // Get Aldor reputation rank
5303 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
5305 target = this;
5306 triggered_spell_id = 45479;
5307 break;
5309 // Get Scryers reputation rank
5310 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
5312 // triggered at positive/self casts also, current attack target used then
5313 if(IsFriendlyTo(target))
5315 target = getVictim();
5316 if(!target)
5318 uint64 selected_guid = ((Player *)this)->GetSelection();
5319 target = ObjectAccessor::GetUnit(*this,selected_guid);
5320 if(!target)
5321 return false;
5323 if(IsFriendlyTo(target))
5324 return false;
5327 triggered_spell_id = 45429;
5328 break;
5330 return false;
5332 // Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck)
5333 // cast 45480 Light's Strength if Exalted by Aldor
5334 // cast 45428 Arcane Strike if Exalted by Scryers
5335 case 45482:
5337 if(GetTypeId() != TYPEID_PLAYER)
5338 return false;
5340 // Get Aldor reputation rank
5341 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
5343 target = this;
5344 triggered_spell_id = 45480;
5345 break;
5347 // Get Scryers reputation rank
5348 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
5350 triggered_spell_id = 45428;
5351 break;
5353 return false;
5355 // Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck)
5356 // cast 45431 Arcane Insight if Exalted by Aldor
5357 // cast 45432 Light's Ward if Exalted by Scryers
5358 case 45483:
5360 if(GetTypeId() != TYPEID_PLAYER)
5361 return false;
5363 // Get Aldor reputation rank
5364 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
5366 target = this;
5367 triggered_spell_id = 45432;
5368 break;
5370 // Get Scryers reputation rank
5371 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
5373 target = this;
5374 triggered_spell_id = 45431;
5375 break;
5377 return false;
5379 // Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck)
5380 // cast 45478 Light's Salvation if Exalted by Aldor
5381 // cast 45430 Arcane Surge if Exalted by Scryers
5382 case 45484:
5384 if(GetTypeId() != TYPEID_PLAYER)
5385 return false;
5387 // Get Aldor reputation rank
5388 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
5390 target = this;
5391 triggered_spell_id = 45478;
5392 break;
5394 // Get Scryers reputation rank
5395 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
5397 triggered_spell_id = 45430;
5398 break;
5400 return false;
5403 // Sunwell Exalted Caster Neck (??? neck)
5404 // cast ??? Light's Wrath if Exalted by Aldor
5405 // cast ??? Arcane Bolt if Exalted by Scryers*/
5406 case 46569:
5407 return false; // old unused version
5408 // Living Seed
5409 case 48504:
5411 triggered_spell_id = 48503;
5412 basepoints[0] = triggerAmount;
5413 target = this;
5414 break;
5416 // Vampiric Touch (generic, used by some boss)
5417 case 52723:
5418 case 60501:
5420 triggered_spell_id = 52724;
5421 basepoints[0] = damage / 2;
5422 target = this;
5423 break;
5425 // Shadowfiend Death (Gain mana if pet dies with Glyph of Shadowfiend)
5426 case 57989:
5428 Unit *owner = GetOwner();
5429 if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
5430 return false;
5432 // Glyph of Shadowfiend (need cast as self cast for owner, no hidden cooldown)
5433 owner->CastSpell(owner,58227,true,castItem,triggeredByAura);
5434 return true;
5436 // Glyph of Life Tap
5437 case 63320:
5438 triggered_spell_id = 63321;
5439 break;
5440 // Item - Shadowmourne Legendary
5441 case 71903:
5443 if (!roll_chance_i(triggerAmount))
5444 return false;
5446 Aura *aur = GetAura(71905, EFFECT_INDEX_0);
5447 if (aur && uint32(aur->GetStackAmount() + 1) >= aur->GetSpellProto()->StackAmount)
5449 RemoveAurasDueToSpell(71905);
5450 CastSpell(this, 71904, true); // Chaos Bane
5451 return true;
5453 else
5454 triggered_spell_id = 71905;
5456 break;
5459 break;
5461 case SPELLFAMILY_MAGE:
5463 // Magic Absorption
5464 if (dummySpell->SpellIconID == 459) // only this spell have SpellIconID == 459 and dummy aura
5466 if (getPowerType() != POWER_MANA)
5467 return false;
5469 // mana reward
5470 basepoints[0] = (triggerAmount * GetMaxPower(POWER_MANA) / 100);
5471 target = this;
5472 triggered_spell_id = 29442;
5473 break;
5475 // Master of Elements
5476 if (dummySpell->SpellIconID == 1920)
5478 if(!procSpell)
5479 return false;
5481 // mana cost save
5482 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
5483 basepoints[0] = cost * triggerAmount/100;
5484 if (basepoints[0] <=0)
5485 return false;
5487 target = this;
5488 triggered_spell_id = 29077;
5489 break;
5492 // Arcane Potency
5493 if (dummySpell->SpellIconID == 2120)
5495 if(!procSpell)
5496 return false;
5498 target = this;
5499 switch (dummySpell->Id)
5501 case 31571: triggered_spell_id = 57529; break;
5502 case 31572: triggered_spell_id = 57531; break;
5503 default:
5504 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u",dummySpell->Id);
5505 return false;
5507 break;
5510 // Hot Streak
5511 if (dummySpell->SpellIconID == 2999)
5513 if (effIndex != EFFECT_INDEX_0)
5514 return true;
5515 Aura *counter = GetAura(triggeredByAura->GetId(), EFFECT_INDEX_1);
5516 if (!counter)
5517 return true;
5519 // Count spell criticals in a row in second aura
5520 Modifier *mod = counter->GetModifier();
5521 if (procEx & PROC_EX_CRITICAL_HIT)
5523 mod->m_amount *=2;
5524 if (mod->m_amount < 100) // not enough
5525 return true;
5526 // Crititcal counted -> roll chance
5527 if (roll_chance_i(triggerAmount))
5528 CastSpell(this, 48108, true, castItem, triggeredByAura);
5530 mod->m_amount = 25;
5531 return true;
5533 // Burnout
5534 if (dummySpell->SpellIconID == 2998)
5536 if(!procSpell)
5537 return false;
5539 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
5540 basepoints[0] = cost * triggerAmount/100;
5541 if (basepoints[0] <=0)
5542 return false;
5543 triggered_spell_id = 44450;
5544 target = this;
5545 break;
5547 // Incanter's Regalia set (add trigger chance to Mana Shield)
5548 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000000000008000))
5550 if (GetTypeId() != TYPEID_PLAYER)
5551 return false;
5553 target = this;
5554 triggered_spell_id = 37436;
5555 break;
5557 switch(dummySpell->Id)
5559 // Ignite
5560 case 11119:
5561 case 11120:
5562 case 12846:
5563 case 12847:
5564 case 12848:
5566 switch (dummySpell->Id)
5568 case 11119: basepoints[0] = int32(0.04f*damage); break;
5569 case 11120: basepoints[0] = int32(0.08f*damage); break;
5570 case 12846: basepoints[0] = int32(0.12f*damage); break;
5571 case 12847: basepoints[0] = int32(0.16f*damage); break;
5572 case 12848: basepoints[0] = int32(0.20f*damage); break;
5573 default:
5574 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (IG)",dummySpell->Id);
5575 return false;
5578 triggered_spell_id = 12654;
5579 break;
5581 // Combustion
5582 case 11129:
5584 //last charge and crit
5585 if (triggeredByAura->GetAuraCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT) )
5586 return true; // charge counting (will removed)
5588 CastSpell(this, 28682, true, castItem, triggeredByAura);
5589 return (procEx & PROC_EX_CRITICAL_HIT); // charge update only at crit hits, no hidden cooldowns
5591 // Glyph of Ice Block
5592 case 56372:
5594 if (GetTypeId() != TYPEID_PLAYER)
5595 return false;
5597 // not 100% safe with client version switches but for 3.1.3 no spells with cooldown that can have mage player except Frost Nova.
5598 ((Player*)this)->RemoveSpellCategoryCooldown(35, true);
5599 return true;
5601 // Glyph of Polymorph
5602 case 56375:
5604 if (!pVictim || !pVictim->isAlive())
5605 return false;
5607 pVictim->RemoveSpellsCausingAura(SPELL_AURA_PERIODIC_DAMAGE);
5608 pVictim->RemoveSpellsCausingAura(SPELL_AURA_PERIODIC_DAMAGE_PERCENT);
5609 return true;
5611 // Blessing of Ancient Kings
5612 case 64411:
5614 // for DOT procs
5615 if (!IsPositiveSpell(procSpell->Id))
5616 return false;
5618 triggered_spell_id = 64413;
5619 basepoints[0] = damage * 15 / 100;
5620 break;
5623 break;
5625 case SPELLFAMILY_WARRIOR:
5627 // Retaliation
5628 if (dummySpell->SpellFamilyFlags == UI64LIT(0x0000000800000000))
5630 // check attack comes not from behind
5631 if (!HasInArc(M_PI_F, pVictim))
5632 return false;
5634 triggered_spell_id = 22858;
5635 break;
5637 // Second Wind
5638 if (dummySpell->SpellIconID == 1697)
5640 // only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example)
5641 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
5642 return false;
5643 // Need stun or root mechanic
5644 if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_ROOT_AND_STUN_MASK))
5645 return false;
5647 switch (dummySpell->Id)
5649 case 29838: triggered_spell_id=29842; break;
5650 case 29834: triggered_spell_id=29841; break;
5651 case 42770: triggered_spell_id=42771; break;
5652 default:
5653 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)",dummySpell->Id);
5654 return false;
5657 target = this;
5658 break;
5660 // Damage Shield
5661 if (dummySpell->SpellIconID == 3214)
5663 triggered_spell_id = 59653;
5664 basepoints[0] = GetShieldBlockValue() * triggerAmount / 100;
5665 break;
5668 // Sweeping Strikes
5669 if (dummySpell->Id == 12328)
5671 // prevent chain of triggered spell from same triggered spell
5672 if(procSpell && procSpell->Id == 26654)
5673 return false;
5675 target = SelectRandomUnfriendlyTarget(pVictim);
5676 if(!target)
5677 return false;
5679 triggered_spell_id = 26654;
5680 break;
5682 break;
5684 case SPELLFAMILY_WARLOCK:
5686 // Seed of Corruption
5687 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000001000000000))
5689 Modifier* mod = triggeredByAura->GetModifier();
5690 // if damage is more than need or target die from damage deal finish spell
5691 if( mod->m_amount <= (int32)damage || GetHealth() <= damage )
5693 // remember guid before aura delete
5694 uint64 casterGuid = triggeredByAura->GetCasterGUID();
5696 // Remove aura (before cast for prevent infinite loop handlers)
5697 RemoveAurasDueToSpell(triggeredByAura->GetId());
5699 // Cast finish spell (triggeredByAura already not exist!)
5700 CastSpell(this, 27285, true, castItem, NULL, casterGuid);
5701 return true; // no hidden cooldown
5704 // Damage counting
5705 mod->m_amount-=damage;
5706 return true;
5708 // Seed of Corruption (Mobs cast) - no die req
5709 if (dummySpell->SpellFamilyFlags == UI64LIT(0x0) && dummySpell->SpellIconID == 1932)
5711 Modifier* mod = triggeredByAura->GetModifier();
5712 // if damage is more than need deal finish spell
5713 if( mod->m_amount <= (int32)damage )
5715 // remember guid before aura delete
5716 uint64 casterGuid = triggeredByAura->GetCasterGUID();
5718 // Remove aura (before cast for prevent infinite loop handlers)
5719 RemoveAurasDueToSpell(triggeredByAura->GetId());
5721 // Cast finish spell (triggeredByAura already not exist!)
5722 CastSpell(this, 32865, true, castItem, NULL, casterGuid);
5723 return true; // no hidden cooldown
5725 // Damage counting
5726 mod->m_amount-=damage;
5727 return true;
5729 // Fel Synergy
5730 if (dummySpell->SpellIconID == 3222)
5732 target = GetPet();
5733 if (!target)
5734 return false;
5735 basepoints[0] = damage * triggerAmount / 100;
5736 triggered_spell_id = 54181;
5737 break;
5739 switch(dummySpell->Id)
5741 // Nightfall & Glyph of Corruption
5742 case 18094:
5743 case 18095:
5744 case 56218:
5746 target = this;
5747 triggered_spell_id = 17941;
5748 break;
5750 //Soul Leech
5751 case 30293:
5752 case 30295:
5753 case 30296:
5755 // health
5756 basepoints[0] = int32(damage*triggerAmount/100);
5757 target = this;
5758 triggered_spell_id = 30294;
5759 break;
5761 // Shadowflame (Voidheart Raiment set bonus)
5762 case 37377:
5764 triggered_spell_id = 37379;
5765 break;
5767 // Pet Healing (Corruptor Raiment or Rift Stalker Armor)
5768 case 37381:
5770 target = GetPet();
5771 if (!target)
5772 return false;
5774 // heal amount
5775 basepoints[0] = damage * triggerAmount/100;
5776 triggered_spell_id = 37382;
5777 break;
5779 // Shadowflame Hellfire (Voidheart Raiment set bonus)
5780 case 39437:
5782 triggered_spell_id = 37378;
5783 break;
5785 // Siphon Life
5786 case 63108:
5788 basepoints[0] = int32(damage * triggerAmount / 100);
5789 triggered_spell_id = 63106;
5790 break;
5793 break;
5795 case SPELLFAMILY_PRIEST:
5797 // Vampiric Touch
5798 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000040000000000))
5800 if(!pVictim || !pVictim->isAlive())
5801 return false;
5803 // pVictim is caster of aura
5804 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5805 return false;
5807 // Energize 0.25% of max. mana
5808 pVictim->CastSpell(pVictim,57669,true,castItem,triggeredByAura);
5809 return true; // no hidden cooldown
5812 switch(dummySpell->SpellIconID)
5814 // Improved Shadowform
5815 case 217:
5817 if(!roll_chance_i(triggerAmount))
5818 return false;
5820 RemoveSpellsCausingAura(SPELL_AURA_MOD_ROOT);
5821 RemoveSpellsCausingAura(SPELL_AURA_MOD_DECREASE_SPEED);
5822 break;
5824 // Divine Aegis
5825 case 2820:
5827 basepoints[0] = damage * triggerAmount/100;
5828 triggered_spell_id = 47753;
5829 break;
5831 // Empowered Renew
5832 case 3021:
5834 if (!procSpell)
5835 return false;
5837 Aura* healingAura = pVictim->GetAura(procSpell->Id, EFFECT_INDEX_0);
5838 if (!healingAura)
5839 return false;
5841 int32 healingfromticks = SpellHealingBonus(pVictim, procSpell, (healingAura->GetModifier()->m_amount* GetSpellAuraMaxTicks(procSpell)), DOT);
5842 basepoints[0] = healingfromticks * triggerAmount / 100;
5843 triggered_spell_id = 63544;
5844 break;
5846 // Improved Devouring Plague
5847 case 3790:
5849 if (!procSpell)
5850 return false;
5852 Aura* leachAura = pVictim->GetAura(procSpell->Id, EFFECT_INDEX_0);
5853 if (!leachAura)
5854 return false;
5856 int32 damagefromticks = SpellDamageBonus(pVictim, procSpell, (leachAura->GetModifier()->m_amount* GetSpellAuraMaxTicks(procSpell)), DOT);
5857 basepoints[0] = damagefromticks * triggerAmount / 100;
5858 triggered_spell_id = 63675;
5859 break;
5863 switch(dummySpell->Id)
5865 // Vampiric Embrace
5866 case 15286:
5868 // Return if self damage
5869 if (this == pVictim)
5870 return false;
5872 // Heal amount - Self/Team
5873 int32 team = triggerAmount*damage/500;
5874 int32 self = triggerAmount*damage/100 - team;
5875 CastCustomSpell(this,15290,&team,&self,NULL,true,castItem,triggeredByAura);
5876 return true; // no hidden cooldown
5878 // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen)
5879 case 40438:
5881 // Shadow Word: Pain
5882 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000008000))
5883 triggered_spell_id = 40441;
5884 // Renew
5885 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000010))
5886 triggered_spell_id = 40440;
5887 else
5888 return false;
5890 target = this;
5891 break;
5893 // Oracle Healing Bonus ("Garments of the Oracle" set)
5894 case 26169:
5896 // heal amount
5897 basepoints[0] = int32(damage * 10/100);
5898 target = this;
5899 triggered_spell_id = 26170;
5900 break;
5902 // Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set
5903 case 39372:
5905 if(!procSpell || (GetSpellSchoolMask(procSpell) & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW))==0 )
5906 return false;
5908 // heal amount
5909 basepoints[0] = damage * triggerAmount/100;
5910 target = this;
5911 triggered_spell_id = 39373;
5912 break;
5914 // Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus)
5915 case 28809:
5917 triggered_spell_id = 28810;
5918 break;
5920 // Glyph of Dispel Magic
5921 case 55677:
5923 if(!target->IsFriendlyTo(this))
5924 return false;
5926 basepoints[0] = int32(target->GetMaxHealth() * triggerAmount / 100);
5927 triggered_spell_id = 56131;
5928 break;
5931 break;
5933 case SPELLFAMILY_DRUID:
5935 switch(dummySpell->Id)
5937 // Leader of the Pack
5938 case 24932:
5940 // dummy m_amount store health percent (!=0 if Improved Leader of the Pack applied)
5941 int32 heal_percent = triggeredByAura->GetModifier()->m_amount;
5942 if (!heal_percent)
5943 return false;
5945 // check explicitly only to prevent mana cast when halth cast cooldown
5946 if (cooldown && ((Player*)this)->HasSpellCooldown(34299))
5947 return false;
5949 // health
5950 triggered_spell_id = 34299;
5951 basepoints[0] = GetMaxHealth() * heal_percent / 100;
5952 target = this;
5954 // mana to caster
5955 if (triggeredByAura->GetCasterGUID() == GetGUID())
5957 if (SpellEntry const* manaCastEntry = sSpellStore.LookupEntry(60889))
5959 int32 mana_percent = manaCastEntry->CalculateSimpleValue(EFFECT_INDEX_0) * heal_percent;
5960 CastCustomSpell(this, manaCastEntry, &mana_percent, NULL, NULL, true, castItem, triggeredByAura);
5963 break;
5965 // Healing Touch (Dreamwalker Raiment set)
5966 case 28719:
5968 // mana back
5969 basepoints[0] = int32(procSpell->manaCost * 30 / 100);
5970 target = this;
5971 triggered_spell_id = 28742;
5972 break;
5974 // Healing Touch Refund (Idol of Longevity trinket)
5975 case 28847:
5977 target = this;
5978 triggered_spell_id = 28848;
5979 break;
5981 // Mana Restore (Malorne Raiment set / Malorne Regalia set)
5982 case 37288:
5983 case 37295:
5985 target = this;
5986 triggered_spell_id = 37238;
5987 break;
5989 // Druid Tier 6 Trinket
5990 case 40442:
5992 float chance;
5994 // Starfire
5995 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000004))
5997 triggered_spell_id = 40445;
5998 chance = 25.0f;
6000 // Rejuvenation
6001 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000010))
6003 triggered_spell_id = 40446;
6004 chance = 25.0f;
6006 // Mangle (Bear) and Mangle (Cat)
6007 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000044000000000))
6009 triggered_spell_id = 40452;
6010 chance = 40.0f;
6012 else
6013 return false;
6015 if (!roll_chance_f(chance))
6016 return false;
6018 target = this;
6019 break;
6021 // Maim Interrupt
6022 case 44835:
6024 // Deadly Interrupt Effect
6025 triggered_spell_id = 32747;
6026 break;
6028 // Glyph of Rejuvenation
6029 case 54754:
6031 // less 50% health
6032 if (pVictim->GetMaxHealth() < 2 * pVictim->GetHealth())
6033 return false;
6034 basepoints[0] = triggerAmount * damage / 100;
6035 triggered_spell_id = 54755;
6036 break;
6038 // Item - Druid T10 Restoration 4P Bonus (Rejuvenation)
6039 case 70664:
6041 if (!procSpell || GetTypeId() != TYPEID_PLAYER)
6042 return false;
6044 float radius;
6045 if (procSpell->EffectRadiusIndex[EFFECT_INDEX_0])
6046 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(procSpell->EffectRadiusIndex[EFFECT_INDEX_0]));
6047 else
6048 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(procSpell->rangeIndex));
6050 ((Player*)this)->ApplySpellMod(procSpell->Id, SPELLMOD_RADIUS, radius,NULL);
6052 Unit *second = pVictim->SelectRandomFriendlyTarget(pVictim, radius);
6054 if (!second)
6055 return false;
6057 pVictim->CastSpell(second, procSpell, true, NULL, triggeredByAura, GetGUID());
6058 return true;
6061 // Eclipse
6062 if (dummySpell->SpellIconID == 2856)
6064 if (!procSpell)
6065 return false;
6066 // Only 0 aura can proc
6067 if (effIndex != EFFECT_INDEX_0)
6068 return true;
6069 // Wrath crit
6070 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000001))
6072 if (HasAura(48517))
6073 return false;
6074 if (!roll_chance_i(60))
6075 return false;
6076 triggered_spell_id = 48518;
6077 target = this;
6078 break;
6080 // Starfire crit
6081 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000004))
6083 if (HasAura(48518))
6084 return false;
6085 triggered_spell_id = 48517;
6086 target = this;
6087 break;
6089 return false;
6091 // Living Seed
6092 else if (dummySpell->SpellIconID == 2860)
6094 triggered_spell_id = 48504;
6095 basepoints[0] = triggerAmount * damage / 100;
6096 break;
6098 break;
6100 case SPELLFAMILY_ROGUE:
6102 switch(dummySpell->Id)
6104 // Deadly Throw Interrupt
6105 case 32748:
6107 // Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw
6108 if (this == pVictim)
6109 return false;
6111 triggered_spell_id = 32747;
6112 break;
6115 // Cut to the Chase
6116 if (dummySpell->SpellIconID == 2909)
6118 // "refresh your Slice and Dice duration to its 5 combo point maximum"
6119 // lookup Slice and Dice
6120 AuraList const& sd = GetAurasByType(SPELL_AURA_MOD_HASTE);
6121 for(AuraList::const_iterator itr = sd.begin(); itr != sd.end(); ++itr)
6123 SpellEntry const *spellProto = (*itr)->GetSpellProto();
6124 if (spellProto->SpellFamilyName == SPELLFAMILY_ROGUE &&
6125 (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000040000)))
6127 (*itr)->SetAuraMaxDuration(GetSpellMaxDuration(spellProto));
6128 (*itr)->RefreshAura();
6129 return true;
6132 return false;
6134 // Deadly Brew
6135 if (dummySpell->SpellIconID == 2963)
6137 triggered_spell_id = 44289;
6138 break;
6140 // Quick Recovery
6141 if (dummySpell->SpellIconID == 2116)
6143 if(!procSpell)
6144 return false;
6146 // energy cost save
6147 basepoints[0] = procSpell->manaCost * triggerAmount/100;
6148 if (basepoints[0] <= 0)
6149 return false;
6151 target = this;
6152 triggered_spell_id = 31663;
6153 break;
6155 break;
6157 case SPELLFAMILY_HUNTER:
6159 // Aspect of the Viper
6160 if (dummySpell->SpellFamilyFlags & UI64LIT(0x4000000000000))
6162 uint32 maxmana = GetMaxPower(POWER_MANA);
6163 basepoints[0] = int32(maxmana* GetAttackTime(RANGED_ATTACK)/1000.0f/100.0f);
6165 target = this;
6166 triggered_spell_id = 34075;
6167 break;
6169 // Thrill of the Hunt
6170 if (dummySpell->SpellIconID == 2236)
6172 if (!procSpell)
6173 return false;
6175 // mana cost save
6176 int32 mana = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
6177 basepoints[0] = mana * 40/100;
6178 if (basepoints[0] <= 0)
6179 return false;
6181 target = this;
6182 triggered_spell_id = 34720;
6183 break;
6185 // Hunting Party
6186 if (dummySpell->SpellIconID == 3406)
6188 triggered_spell_id = 57669;
6189 target = this;
6190 break;
6192 // Lock and Load
6193 if ( dummySpell->SpellIconID == 3579 )
6195 // Proc only from periodic (from trap activation proc another aura of this spell)
6196 if (!(procFlag & PROC_FLAG_ON_DO_PERIODIC) || !roll_chance_i(triggerAmount))
6197 return false;
6198 triggered_spell_id = 56453;
6199 target = this;
6200 break;
6202 // Rapid Recuperation
6203 if ( dummySpell->SpellIconID == 3560 )
6205 // This effect only from Rapid Killing (mana regen)
6206 if (!(procSpell->SpellFamilyFlags & UI64LIT(0x0100000000000000)))
6207 return false;
6209 target = this;
6211 switch(dummySpell->Id)
6213 case 53228: // Rank 1
6214 triggered_spell_id = 56654;
6215 break;
6216 case 53232: // Rank 2
6217 triggered_spell_id = 58882;
6218 break;
6220 break;
6222 // Glyph of Mend Pet
6223 if(dummySpell->Id == 57870)
6225 pVictim->CastSpell(pVictim, 57894, true, NULL, NULL, GetGUID());
6226 return true;
6228 break;
6230 case SPELLFAMILY_PALADIN:
6232 // Seal of Righteousness - melee proc dummy (addition ${$MWS*(0.022*$AP+0.044*$SPH)} damage)
6233 if ((dummySpell->SpellFamilyFlags & UI64LIT(0x000000008000000)) && effIndex == EFFECT_INDEX_0)
6235 triggered_spell_id = 25742;
6236 float ap = GetTotalAttackPowerValue(BASE_ATTACK);
6237 int32 holy = SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
6238 SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, pVictim);
6239 basepoints[0] = GetAttackTime(BASE_ATTACK) * int32(ap*0.022f + 0.044f * holy) / 1000;
6240 break;
6242 // Righteous Vengeance
6243 if (dummySpell->SpellIconID == 3025)
6245 // 4 damage tick
6246 basepoints[0] = triggerAmount*damage/400;
6247 triggered_spell_id = 61840;
6248 break;
6250 // Sheath of Light
6251 if (dummySpell->SpellIconID == 3030)
6253 // 4 healing tick
6254 basepoints[0] = triggerAmount*damage/400;
6255 triggered_spell_id = 54203;
6256 break;
6258 switch(dummySpell->Id)
6260 // Judgement of Light
6261 case 20185:
6263 basepoints[0] = int32( pVictim->GetMaxHealth() * triggeredByAura->GetModifier()->m_amount / 100 );
6264 pVictim->CastCustomSpell(pVictim, 20267, &basepoints[0], NULL, NULL, true, NULL, triggeredByAura);
6265 return true;
6267 // Judgement of Wisdom
6268 case 20186:
6270 if (pVictim->getPowerType() == POWER_MANA)
6272 // 2% of maximum base mana
6273 basepoints[0] = int32(pVictim->GetCreateMana() * 2 / 100);
6274 pVictim->CastCustomSpell(pVictim, 20268, &basepoints[0], NULL, NULL, true, NULL, triggeredByAura);
6276 return true;
6278 // Heart of the Crusader (Rank 1)
6279 case 20335:
6280 triggered_spell_id = 21183;
6281 break;
6282 // Heart of the Crusader (Rank 2)
6283 case 20336:
6284 triggered_spell_id = 54498;
6285 break;
6286 // Heart of the Crusader (Rank 3)
6287 case 20337:
6288 triggered_spell_id = 54499;
6289 break;
6290 case 20911: // Blessing of Sanctuary
6291 case 25899: // Greater Blessing of Sanctuary
6293 target = this;
6294 switch (target->getPowerType())
6296 case POWER_MANA:
6297 triggered_spell_id = 57319;
6298 break;
6299 default:
6300 return false;
6302 break;
6304 // Holy Power (Redemption Armor set)
6305 case 28789:
6307 if(!pVictim)
6308 return false;
6310 // Set class defined buff
6311 switch (pVictim->getClass())
6313 case CLASS_PALADIN:
6314 case CLASS_PRIEST:
6315 case CLASS_SHAMAN:
6316 case CLASS_DRUID:
6317 triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
6318 break;
6319 case CLASS_MAGE:
6320 case CLASS_WARLOCK:
6321 triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
6322 break;
6323 case CLASS_HUNTER:
6324 case CLASS_ROGUE:
6325 triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d.
6326 break;
6327 case CLASS_WARRIOR:
6328 triggered_spell_id = 28790; // Increases the friendly target's armor
6329 break;
6330 default:
6331 return false;
6333 break;
6335 // Spiritual Attunement
6336 case 31785:
6337 case 33776:
6339 // if healed by another unit (pVictim)
6340 if (this == pVictim)
6341 return false;
6343 // heal amount
6344 basepoints[0] = triggerAmount*damage/100;
6345 target = this;
6346 triggered_spell_id = 31786;
6347 break;
6349 // Seal of Vengeance (damage calc on apply aura)
6350 case 31801:
6352 if (effIndex != EFFECT_INDEX_0) // effect 1,2 used by seal unleashing code
6353 return false;
6355 // At melee attack or Hammer of the Righteous spell damage considered as melee attack
6356 if ((procFlag & PROC_FLAG_SUCCESSFUL_MELEE_HIT) || (procSpell && procSpell->Id == 53595) )
6357 triggered_spell_id = 31803; // Holy Vengeance
6359 // Add 5-stack effect from Holy Vengeance
6360 int8 stacks = 0;
6361 AuraList const& auras = target->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
6362 for(AuraList::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr)
6364 if( ((*itr)->GetId() == 31803) && (*itr)->GetCasterGUID()==GetGUID())
6366 stacks = (*itr)->GetStackAmount();
6367 break;
6370 if(stacks >= 5)
6371 CastSpell(target,42463,true,NULL,triggeredByAura);
6372 break;
6374 // Judgements of the Wise
6375 case 31876:
6376 case 31877:
6377 case 31878:
6378 // triggered only at casted Judgement spells, not at additional Judgement effects
6379 if(!procSpell || procSpell->Category != 1210)
6380 return false;
6382 target = this;
6383 triggered_spell_id = 31930;
6385 // Replenishment
6386 CastSpell(this, 57669, true, NULL, triggeredByAura);
6387 break;
6388 // Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal)
6389 case 40470:
6391 if (!procSpell)
6392 return false;
6394 float chance;
6396 // Flash of light/Holy light
6397 if (procSpell->SpellFamilyFlags & UI64LIT(0x00000000C0000000))
6399 triggered_spell_id = 40471;
6400 chance = 15.0f;
6402 // Judgement (any)
6403 else if (GetSpellSpecific(procSpell->Id)==SPELL_JUDGEMENT)
6405 triggered_spell_id = 40472;
6406 chance = 50.0f;
6408 else
6409 return false;
6411 if (!roll_chance_f(chance))
6412 return false;
6414 break;
6416 // Light's Beacon (heal target area aura)
6417 case 53651:
6419 // not do bonus heal for explicit beacon focus healing
6420 if (GetGUID() == triggeredByAura->GetCasterGUID())
6421 return false;
6423 // beacon
6424 Unit* beacon = triggeredByAura->GetCaster();
6425 if (!beacon)
6426 return false;
6428 // find caster main aura at beacon
6429 Aura* dummy = NULL;
6430 Unit::AuraList const& baa = beacon->GetAurasByType(SPELL_AURA_PERIODIC_TRIGGER_SPELL);
6431 for(Unit::AuraList::const_iterator i = baa.begin(); i != baa.end(); ++i)
6433 if ((*i)->GetId() == 53563 && (*i)->GetCasterGUID() == pVictim->GetGUID())
6435 dummy = (*i);
6436 break;
6440 // original heal must be form beacon caster
6441 if (!dummy)
6442 return false;
6444 triggered_spell_id = 53652; // Beacon of Light
6445 basepoints[0] = triggeredByAura->GetModifier()->m_amount*damage/100;
6447 // cast with original caster set but beacon to beacon for apply caster mods and avoid LoS check
6448 beacon->CastCustomSpell(beacon,triggered_spell_id,&basepoints[0],NULL,NULL,true,castItem,triggeredByAura,pVictim->GetGUID());
6449 return true;
6451 // Seal of Corruption (damage calc on apply aura)
6452 case 53736:
6454 if (effIndex != EFFECT_INDEX_0) // effect 1,2 used by seal unleashing code
6455 return false;
6457 // At melee attack or Hammer of the Righteous spell damage considered as melee attack
6458 if ((procFlag & PROC_FLAG_SUCCESSFUL_MELEE_HIT) || (procSpell && procSpell->Id == 53595))
6459 triggered_spell_id = 53742; // Blood Corruption
6461 // Add 5-stack effect from Blood Corruption
6462 int8 stacks = 0;
6463 AuraList const& auras = target->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
6464 for(AuraList::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr)
6466 if( ((*itr)->GetId() == 53742) && (*itr)->GetCasterGUID()==GetGUID())
6468 stacks = (*itr)->GetStackAmount();
6469 break;
6472 if(stacks >= 5)
6473 CastSpell(target,53739,true,NULL,triggeredByAura);
6474 break;
6476 // Glyph of Flash of Light
6477 case 54936:
6479 triggered_spell_id = 54957;
6480 basepoints[0] = triggerAmount*damage/100;
6481 break;
6483 // Glyph of Holy Light
6484 case 54937:
6486 triggered_spell_id = 54968;
6487 basepoints[0] = triggerAmount*damage/100;
6488 break;
6490 // Glyph of Divinity
6491 case 54939:
6493 // Lookup base amount mana restore
6494 for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
6496 if (procSpell->Effect[i] == SPELL_EFFECT_ENERGIZE)
6498 int32 mana = procSpell->EffectBasePoints[i];
6499 CastCustomSpell(this, 54986, NULL, &mana, NULL, true, castItem, triggeredByAura);
6500 break;
6503 return true;
6505 // Sacred Shield (buff)
6506 case 58597:
6508 triggered_spell_id = 66922;
6509 SpellEntry const* triggeredEntry = sSpellStore.LookupEntry(triggered_spell_id);
6510 if (!triggeredEntry)
6511 return false;
6513 basepoints[0] = int32(damage / (GetSpellDuration(triggeredEntry) / triggeredEntry->EffectAmplitude[EFFECT_INDEX_0]));
6514 target = this;
6515 break;
6517 // Sacred Shield (talent rank)
6518 case 53601:
6520 triggered_spell_id = 58597;
6521 target = this;
6522 break;
6525 break;
6527 case SPELLFAMILY_SHAMAN:
6529 switch(dummySpell->Id)
6531 // Totemic Power (The Earthshatterer set)
6532 case 28823:
6534 if( !pVictim )
6535 return false;
6537 // Set class defined buff
6538 switch (pVictim->getClass())
6540 case CLASS_PALADIN:
6541 case CLASS_PRIEST:
6542 case CLASS_SHAMAN:
6543 case CLASS_DRUID:
6544 triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
6545 break;
6546 case CLASS_MAGE:
6547 case CLASS_WARLOCK:
6548 triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
6549 break;
6550 case CLASS_HUNTER:
6551 case CLASS_ROGUE:
6552 triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d.
6553 break;
6554 case CLASS_WARRIOR:
6555 triggered_spell_id = 28827; // Increases the friendly target's armor
6556 break;
6557 default:
6558 return false;
6560 break;
6562 // Lesser Healing Wave (Totem of Flowing Water Relic)
6563 case 28849:
6565 target = this;
6566 triggered_spell_id = 28850;
6567 break;
6569 // Windfury Weapon (Passive) 1-5 Ranks
6570 case 33757:
6572 if(GetTypeId()!=TYPEID_PLAYER)
6573 return false;
6575 if(!castItem || !castItem->IsEquipped())
6576 return false;
6578 // custom cooldown processing case
6579 if( cooldown && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
6580 return false;
6582 // Now amount of extra power stored in 1 effect of Enchant spell
6583 // Get it by item enchant id
6584 uint32 spellId;
6585 switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)))
6587 case 283: spellId = 8232; break; // 1 Rank
6588 case 284: spellId = 8235; break; // 2 Rank
6589 case 525: spellId = 10486; break; // 3 Rank
6590 case 1669:spellId = 16362; break; // 4 Rank
6591 case 2636:spellId = 25505; break; // 5 Rank
6592 case 3785:spellId = 58801; break; // 6 Rank
6593 case 3786:spellId = 58803; break; // 7 Rank
6594 case 3787:spellId = 58804; break; // 8 Rank
6595 default:
6597 sLog.outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)",
6598 castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)),dummySpell->Id);
6599 return false;
6603 SpellEntry const* windfurySpellEntry = sSpellStore.LookupEntry(spellId);
6604 if(!windfurySpellEntry)
6606 sLog.outError("Unit::HandleDummyAuraProc: non existed spell id: %u (Windfury)",spellId);
6607 return false;
6610 int32 extra_attack_power = CalculateSpellDamage(windfurySpellEntry, EFFECT_INDEX_1, windfurySpellEntry->EffectBasePoints[EFFECT_INDEX_1], pVictim);
6612 // Off-Hand case
6613 if (castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
6615 // Value gained from additional AP
6616 basepoints[0] = int32(extra_attack_power/14.0f * GetAttackTime(OFF_ATTACK)/1000/2);
6617 triggered_spell_id = 33750;
6619 // Main-Hand case
6620 else
6622 // Value gained from additional AP
6623 basepoints[0] = int32(extra_attack_power/14.0f * GetAttackTime(BASE_ATTACK)/1000);
6624 triggered_spell_id = 25504;
6627 // apply cooldown before cast to prevent processing itself
6628 if( cooldown )
6629 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
6631 // Attack Twice
6632 for ( uint32 i = 0; i<2; ++i )
6633 CastCustomSpell(pVictim,triggered_spell_id,&basepoints[0],NULL,NULL,true,castItem,triggeredByAura);
6635 return true;
6637 // Shaman Tier 6 Trinket
6638 case 40463:
6640 if( !procSpell )
6641 return false;
6643 float chance;
6644 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000001))
6646 triggered_spell_id = 40465; // Lightning Bolt
6647 chance = 15.0f;
6649 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080))
6651 triggered_spell_id = 40465; // Lesser Healing Wave
6652 chance = 10.0f;
6654 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000001000000000))
6656 triggered_spell_id = 40466; // Stormstrike
6657 chance = 50.0f;
6659 else
6660 return false;
6662 if (!roll_chance_f(chance))
6663 return false;
6665 target = this;
6666 break;
6668 // Glyph of Healing Wave
6669 case 55440:
6671 // Not proc from self heals
6672 if (this==pVictim)
6673 return false;
6674 basepoints[0] = triggerAmount * damage / 100;
6675 target = this;
6676 triggered_spell_id = 55533;
6677 break;
6679 // Spirit Hunt
6680 case 58877:
6682 // Cast on owner
6683 target = GetOwner();
6684 if (!target)
6685 return false;
6686 basepoints[0] = triggerAmount * damage / 100;
6687 triggered_spell_id = 58879;
6688 break;
6690 // Glyph of Totem of Wrath
6691 case 63280:
6693 Totem* totem = GetTotem(TOTEM_SLOT_FIRE);
6694 if (!totem)
6695 return false;
6697 // find totem aura bonus
6698 AuraList const& spellPower = totem->GetAurasByType(SPELL_AURA_NONE);
6699 for(AuraList::const_iterator i = spellPower.begin();i != spellPower.end(); ++i)
6701 // select proper aura for format aura type in spell proto
6702 if ((*i)->GetTarget()==totem && (*i)->GetSpellProto()->EffectApplyAuraName[(*i)->GetEffIndex()] == SPELL_AURA_MOD_HEALING_DONE &&
6703 (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN && (*i)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000004000000))
6705 basepoints[0] = triggerAmount * (*i)->GetModifier()->m_amount / 100;
6706 break;
6710 if (!basepoints[0])
6711 return false;
6713 basepoints[1] = basepoints[0];
6714 triggered_spell_id = 63283; // Totem of Wrath, caster bonus
6715 target = this;
6716 break;
6718 // Shaman T8 Elemental 4P Bonus
6719 case 64928:
6721 basepoints[0] = int32( triggerAmount * damage / 100 );
6722 triggered_spell_id = 64930; // Electrified
6723 break;
6725 // Shaman T9 Elemental 4P Bonus
6726 case 67228:
6728 basepoints[0] = int32( triggerAmount * damage / 100 );
6729 triggered_spell_id = 71824;
6730 break;
6733 // Storm, Earth and Fire
6734 if (dummySpell->SpellIconID == 3063)
6736 // Earthbind Totem summon only
6737 if(procSpell->Id != 2484)
6738 return false;
6740 if (!roll_chance_i(triggerAmount))
6741 return false;
6743 triggered_spell_id = 64695;
6744 break;
6746 // Ancestral Awakening
6747 if (dummySpell->SpellIconID == 3065)
6749 triggered_spell_id = 52759;
6750 basepoints[0] = triggerAmount * damage / 100;
6751 target = this;
6752 break;
6754 // Earth Shield
6755 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000040000000000))
6757 target = this;
6758 basepoints[0] = triggerAmount;
6760 // Glyph of Earth Shield
6761 if (Aura* aur = GetDummyAura(63279))
6763 int32 aur_mod = aur->GetModifier()->m_amount;
6764 basepoints[0] = int32(basepoints[0] * (aur_mod + 100.0f) / 100.0f);
6767 triggered_spell_id = 379;
6768 break;
6770 // Improved Water Shield
6771 if (dummySpell->SpellIconID == 2287)
6773 // Lesser Healing Wave need aditional 60% roll
6774 if ((procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080)) && !roll_chance_i(60))
6775 return false;
6776 // lookup water shield
6777 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
6778 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
6780 if ((*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
6781 ((*itr)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000002000000000)))
6783 uint32 spell = (*itr)->GetSpellProto()->EffectTriggerSpell[(*itr)->GetEffIndex()];
6784 CastSpell(this, spell, true, castItem, triggeredByAura);
6785 if ((*itr)->DropAuraCharge())
6786 RemoveSingleSpellAurasFromStack((*itr)->GetId());
6787 return true;
6790 return false;
6791 break;
6793 // Lightning Overload
6794 if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura
6796 if(!procSpell || GetTypeId() != TYPEID_PLAYER || !pVictim )
6797 return false;
6799 // custom cooldown processing case
6800 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
6801 return false;
6803 uint32 spellId = 0;
6804 // Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost
6805 switch (procSpell->Id)
6807 // Lightning Bolt
6808 case 403: spellId = 45284; break; // Rank 1
6809 case 529: spellId = 45286; break; // Rank 2
6810 case 548: spellId = 45287; break; // Rank 3
6811 case 915: spellId = 45288; break; // Rank 4
6812 case 943: spellId = 45289; break; // Rank 5
6813 case 6041: spellId = 45290; break; // Rank 6
6814 case 10391: spellId = 45291; break; // Rank 7
6815 case 10392: spellId = 45292; break; // Rank 8
6816 case 15207: spellId = 45293; break; // Rank 9
6817 case 15208: spellId = 45294; break; // Rank 10
6818 case 25448: spellId = 45295; break; // Rank 11
6819 case 25449: spellId = 45296; break; // Rank 12
6820 case 49237: spellId = 49239; break; // Rank 13
6821 case 49238: spellId = 49240; break; // Rank 14
6822 // Chain Lightning
6823 case 421: spellId = 45297; break; // Rank 1
6824 case 930: spellId = 45298; break; // Rank 2
6825 case 2860: spellId = 45299; break; // Rank 3
6826 case 10605: spellId = 45300; break; // Rank 4
6827 case 25439: spellId = 45301; break; // Rank 5
6828 case 25442: spellId = 45302; break; // Rank 6
6829 case 49270: spellId = 49268; break; // Rank 7
6830 case 49271: spellId = 49269; break; // Rank 8
6831 default:
6832 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (LO)", procSpell->Id);
6833 return false;
6835 // No thread generated mod
6836 // TODO: exist special flag in spell attributes for this, need found and use!
6837 SpellModifier *mod = new SpellModifier(SPELLMOD_THREAT,SPELLMOD_PCT,-100,triggeredByAura);
6839 ((Player*)this)->AddSpellMod(mod, true);
6841 // Remove cooldown (Chain Lightning - have Category Recovery time)
6842 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000002))
6843 ((Player*)this)->RemoveSpellCooldown(spellId);
6845 CastSpell(pVictim, spellId, true, castItem, triggeredByAura);
6847 ((Player*)this)->AddSpellMod(mod, false);
6849 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6850 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
6852 return true;
6854 // Static Shock
6855 if(dummySpell->SpellIconID == 3059)
6857 // lookup Lightning Shield
6858 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
6859 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
6861 if ((*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
6862 ((*itr)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000000000400)))
6864 uint32 spell = 0;
6865 switch ((*itr)->GetId())
6867 case 324: spell = 26364; break;
6868 case 325: spell = 26365; break;
6869 case 905: spell = 26366; break;
6870 case 945: spell = 26367; break;
6871 case 8134: spell = 26369; break;
6872 case 10431: spell = 26370; break;
6873 case 10432: spell = 26363; break;
6874 case 25469: spell = 26371; break;
6875 case 25472: spell = 26372; break;
6876 case 49280: spell = 49278; break;
6877 case 49281: spell = 49279; break;
6878 default:
6879 return false;
6881 CastSpell(target, spell, true, castItem, triggeredByAura);
6882 if ((*itr)->DropAuraCharge())
6883 RemoveSingleSpellAurasFromStack((*itr)->GetId());
6884 return true;
6887 return false;
6889 // Frozen Power
6890 if (dummySpell->SpellIconID == 3780)
6892 Unit *caster = triggeredByAura->GetCaster();
6894 if (!procSpell || !caster)
6895 return false;
6897 float distance = caster->GetDistance(pVictim);
6898 int32 chance = triggerAmount;
6900 if (distance < 15.0f || !roll_chance_i(chance))
6901 return false;
6903 // make triggered cast apply after current damage spell processing for prevent remove by it
6904 if(Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
6905 spell->AddTriggeredSpell(63685);
6906 return true;
6908 break;
6910 case SPELLFAMILY_DEATHKNIGHT:
6912 // Butchery
6913 if (dummySpell->SpellIconID == 2664)
6915 basepoints[0] = triggerAmount;
6916 triggered_spell_id = 50163;
6917 target = this;
6918 break;
6920 // Dancing Rune Weapon
6921 if (dummySpell->Id == 49028)
6923 // 1 dummy aura for dismiss rune blade
6924 if (effIndex != EFFECT_INDEX_2)
6925 return false;
6926 // TODO: wite script for this "fights on its own, doing the same attacks"
6927 // NOTE: Trigger here on every attack and spell cast
6928 return false;
6930 // Mark of Blood
6931 if (dummySpell->Id == 49005)
6933 // TODO: need more info (cooldowns/PPM)
6934 triggered_spell_id = 61607;
6935 break;
6937 // Vendetta
6938 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000000000010000))
6940 basepoints[0] = triggerAmount * GetMaxHealth() / 100;
6941 triggered_spell_id = 50181;
6942 target = this;
6943 break;
6945 // Necrosis
6946 if (dummySpell->SpellIconID == 2709)
6948 basepoints[0] = triggerAmount * damage / 100;
6949 triggered_spell_id = 51460;
6950 break;
6952 // Threat of Thassarian
6953 if (dummySpell->SpellIconID == 2023)
6955 // Must Dual Wield
6956 if (!procSpell || !haveOffhandWeapon())
6957 return false;
6958 // Chance as basepoints for dummy aura
6959 if (!roll_chance_i(triggerAmount))
6960 return false;
6962 switch (procSpell->Id)
6964 // Obliterate
6965 case 49020: // Rank 1
6966 triggered_spell_id = 66198; break;
6967 case 51423: // Rank 2
6968 triggered_spell_id = 66972; break;
6969 case 51424: // Rank 3
6970 triggered_spell_id = 66973; break;
6971 case 51425: // Rank 4
6972 triggered_spell_id = 66974; break;
6973 // Frost Strike
6974 case 49143: // Rank 1
6975 triggered_spell_id = 66196; break;
6976 case 51416: // Rank 2
6977 triggered_spell_id = 66958; break;
6978 case 51417: // Rank 3
6979 triggered_spell_id = 66959; break;
6980 case 51418: // Rank 4
6981 triggered_spell_id = 66960; break;
6982 case 51419: // Rank 5
6983 triggered_spell_id = 66961; break;
6984 case 55268: // Rank 6
6985 triggered_spell_id = 66962; break;
6986 // Plague Strike
6987 case 45462: // Rank 1
6988 triggered_spell_id = 66216; break;
6989 case 49917: // Rank 2
6990 triggered_spell_id = 66988; break;
6991 case 49918: // Rank 3
6992 triggered_spell_id = 66989; break;
6993 case 49919: // Rank 4
6994 triggered_spell_id = 66990; break;
6995 case 49920: // Rank 5
6996 triggered_spell_id = 66991; break;
6997 case 49921: // Rank 6
6998 triggered_spell_id = 66992; break;
6999 // Death Strike
7000 case 49998: // Rank 1
7001 triggered_spell_id = 66188; break;
7002 case 49999: // Rank 2
7003 triggered_spell_id = 66950; break;
7004 case 45463: // Rank 3
7005 triggered_spell_id = 66951; break;
7006 case 49923: // Rank 4
7007 triggered_spell_id = 66952; break;
7008 case 49924: // Rank 5
7009 triggered_spell_id = 66953; break;
7010 // Rune Strike
7011 case 56815:
7012 triggered_spell_id = 66217; break;
7013 // Blood Strike
7014 case 45902: // Rank 1
7015 triggered_spell_id = 66215; break;
7016 case 49926: // Rank 2
7017 triggered_spell_id = 66975; break;
7018 case 49927: // Rank 3
7019 triggered_spell_id = 66976; break;
7020 case 49928: // Rank 4
7021 triggered_spell_id = 66977; break;
7022 case 49929: // Rank 5
7023 triggered_spell_id = 66978; break;
7024 case 49930: // Rank 6
7025 triggered_spell_id = 66979; break;
7026 default:
7027 return false;
7029 break;
7031 // Runic Power Back on Snare/Root
7032 if (dummySpell->Id == 61257)
7034 // only for spells and hit/crit (trigger start always) and not start from self casted spells
7035 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
7036 return false;
7037 // Need snare or root mechanic
7038 if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_ROOT_AND_SNARE_MASK))
7039 return false;
7040 triggered_spell_id = 61258;
7041 target = this;
7042 break;
7044 // Wandering Plague
7045 if (dummySpell->SpellIconID == 1614)
7047 if (!roll_chance_f(GetUnitCriticalChance(BASE_ATTACK, pVictim)))
7048 return false;
7049 basepoints[0] = triggerAmount * damage / 100;
7050 triggered_spell_id = 50526;
7051 break;
7053 // Blood-Caked Blade
7054 if (dummySpell->SpellIconID == 138)
7056 triggered_spell_id = dummySpell->EffectTriggerSpell[effIndex];
7057 break;
7059 break;
7061 default:
7062 break;
7065 // processed charge only counting case
7066 if(!triggered_spell_id)
7067 return true;
7069 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
7071 if(!triggerEntry)
7073 sLog.outError("Unit::HandleDummyAuraProc: Spell %u have not existed triggered spell %u",dummySpell->Id,triggered_spell_id);
7074 return false;
7077 // default case
7078 if(!target || target!=this && !target->isAlive())
7079 return false;
7081 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
7082 return false;
7084 if (basepoints[EFFECT_INDEX_0] || basepoints[EFFECT_INDEX_1] || basepoints[EFFECT_INDEX_2])
7085 CastCustomSpell(target, triggered_spell_id,
7086 basepoints[EFFECT_INDEX_0] ? &basepoints[EFFECT_INDEX_0] : NULL,
7087 basepoints[EFFECT_INDEX_1] ? &basepoints[EFFECT_INDEX_1] : NULL,
7088 basepoints[EFFECT_INDEX_2] ? &basepoints[EFFECT_INDEX_2] : NULL,
7089 true, castItem, triggeredByAura);
7090 else
7091 CastSpell(target, triggered_spell_id, true, castItem, triggeredByAura);
7093 if (cooldown && GetTypeId()==TYPEID_PLAYER)
7094 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
7096 return true;
7099 bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown)
7101 // Get triggered aura spell info
7102 SpellEntry const* auraSpellInfo = triggeredByAura->GetSpellProto();
7104 // Basepoints of trigger aura
7105 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
7107 // Set trigger spell id, target, custom basepoints
7108 uint32 trigger_spell_id = auraSpellInfo->EffectTriggerSpell[triggeredByAura->GetEffIndex()];
7109 Unit* target = NULL;
7110 int32 basepoints[MAX_EFFECT_INDEX] = {0, 0, 0};
7112 if(triggeredByAura->GetModifier()->m_auraname == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE)
7113 basepoints[0] = triggerAmount;
7115 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
7116 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
7118 // Try handle unknown trigger spells
7119 // Custom requirements (not listed in procEx) Warning! damage dealing after this
7120 // Custom triggered spells
7121 switch (auraSpellInfo->SpellFamilyName)
7123 case SPELLFAMILY_GENERIC:
7124 switch(auraSpellInfo->Id)
7126 //case 191: // Elemental Response
7127 // switch (procSpell->School)
7128 // {
7129 // case SPELL_SCHOOL_FIRE: trigger_spell_id = 34192; break;
7130 // case SPELL_SCHOOL_FROST: trigger_spell_id = 34193; break;
7131 // case SPELL_SCHOOL_ARCANE:trigger_spell_id = 34194; break;
7132 // case SPELL_SCHOOL_NATURE:trigger_spell_id = 34195; break;
7133 // case SPELL_SCHOOL_SHADOW:trigger_spell_id = 34196; break;
7134 // case SPELL_SCHOOL_HOLY: trigger_spell_id = 34197; break;
7135 // case SPELL_SCHOOL_NORMAL:trigger_spell_id = 34198; break;
7136 // }
7137 // break;
7138 //case 5301: break; // Defensive State (DND)
7139 //case 7137: break: // Shadow Charge (Rank 1)
7140 //case 7377: break: // Take Immune Periodic Damage <Not Working>
7141 //case 13358: break; // Defensive State (DND)
7142 //case 16092: break; // Defensive State (DND)
7143 //case 18943: break; // Double Attack
7144 //case 19194: break; // Double Attack
7145 //case 19817: break; // Double Attack
7146 //case 19818: break; // Double Attack
7147 //case 22835: break; // Drunken Rage
7148 // trigger_spell_id = 14822; break;
7149 case 23780: // Aegis of Preservation (Aegis of Preservation trinket)
7150 trigger_spell_id = 23781;
7151 break;
7152 //case 24949: break; // Defensive State 2 (DND)
7153 case 27522: // Mana Drain Trigger
7154 case 40336: // Mana Drain Trigger
7155 // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target.
7156 if (isAlive())
7157 CastSpell(this, 29471, true, castItem, triggeredByAura);
7158 if (pVictim && pVictim->isAlive())
7159 CastSpell(pVictim, 27526, true, castItem, triggeredByAura);
7160 return true;
7161 case 31255: // Deadly Swiftness (Rank 1)
7162 // whenever you deal damage to a target who is below 20% health.
7163 if (pVictim->GetHealth() > pVictim->GetMaxHealth() / 5)
7164 return false;
7166 target = this;
7167 trigger_spell_id = 22588;
7168 break;
7169 //case 33207: break; // Gossip NPC Periodic - Fidget
7170 case 33896: // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher)
7171 trigger_spell_id = 33898;
7172 break;
7173 //case 34082: break; // Advantaged State (DND)
7174 //case 34783: break: // Spell Reflection
7175 //case 35205: break: // Vanish
7176 //case 35321: break; // Gushing Wound
7177 //case 36096: break: // Spell Reflection
7178 //case 36207: break: // Steal Weapon
7179 //case 36576: break: // Shaleskin (Shaleskin Flayer, Shaleskin Ripper) 30023 trigger
7180 //case 37030: break; // Chaotic Temperament
7181 //case 38363: break; // Gushing Wound
7182 //case 39215: break; // Gushing Wound
7183 //case 40250: break; // Improved Duration
7184 //case 40329: break; // Demo Shout Sensor
7185 //case 40364: break; // Entangling Roots Sensor
7186 //case 41054: break; // Copy Weapon
7187 // trigger_spell_id = 41055; break;
7188 //case 41248: break; // Consuming Strikes
7189 // trigger_spell_id = 41249; break;
7190 //case 42730: break: // Woe Strike
7191 //case 43453: break: // Rune Ward
7192 //case 43504: break; // Alterac Valley OnKill Proc Aura
7193 //case 44326: break: // Pure Energy Passive
7194 //case 44526: break; // Hate Monster (Spar) (30 sec)
7195 //case 44527: break; // Hate Monster (Spar Buddy) (30 sec)
7196 //case 44819: break; // Hate Monster (Spar Buddy) (>30% Health)
7197 //case 44820: break; // Hate Monster (Spar) (<30%)
7198 case 45057: // Evasive Maneuvers (Commendation of Kael`thas trinket)
7199 // reduce you below $s1% health
7200 if (GetHealth() - damage > GetMaxHealth() * triggerAmount / 100)
7201 return false;
7202 break;
7203 //case 45903: break: // Offensive State
7204 //case 46146: break: // [PH] Ahune Spanky Hands
7205 //case 46939: break; // Black Bow of the Betrayer
7206 // trigger_spell_id = 29471; - gain mana
7207 // 27526; - drain mana if possible
7208 case 43820: // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket)
7209 // Pct value stored in dummy
7210 basepoints[0] = pVictim->GetCreateHealth() * auraSpellInfo->EffectBasePoints[EFFECT_INDEX_1] / 100;
7211 target = pVictim;
7212 break;
7213 //case 45205: break; // Copy Offhand Weapon
7214 //case 45343: break; // Dark Flame Aura
7215 //case 47300: break; // Dark Flame Aura
7216 //case 48876: break; // Beast's Mark
7217 // trigger_spell_id = 48877; break;
7218 //case 49059: break; // Horde, Hate Monster (Spar Buddy) (>30% Health)
7219 //case 50051: break; // Ethereal Pet Aura
7220 //case 50689: break; // Blood Presence (Rank 1)
7221 //case 50844: break; // Blood Mirror
7222 //case 52856: break; // Charge
7223 //case 54072: break; // Knockback Ball Passive
7224 //case 54476: break; // Blood Presence
7225 //case 54775: break; // Abandon Vehicle on Poly
7226 case 57345: // Darkmoon Card: Greatness
7228 float stat = 0.0f;
7229 // strength
7230 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); }
7231 // agility
7232 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); }
7233 // intellect
7234 if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);}
7235 // spirit
7236 if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235; }
7237 break;
7239 //case 55580: break: // Mana Link
7240 //case 57587: break: // Steal Ranged ()
7241 //case 57594: break; // Copy Ranged Weapon
7242 //case 59237: break; // Beast's Mark
7243 // trigger_spell_id = 59233; break;
7244 //case 59288: break; // Infra-Green Shield
7245 //case 59532: break; // Abandon Passengers on Poly
7246 //case 59735: break: // Woe Strike
7247 case 64415: // // Val'anyr Hammer of Ancient Kings - Equip Effect
7249 // for DOT procs
7250 if (!IsPositiveSpell(procSpell->Id))
7251 return false;
7252 break;
7254 case 67702: // Death's Choice, Item - Coliseum 25 Normal Melee Trinket
7256 float stat = 0.0f;
7257 // strength
7258 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67708;stat = GetStat(STAT_STRENGTH); }
7259 // agility
7260 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67703; }
7261 break;
7263 case 67771: // Death's Choice (heroic), Item - Coliseum 25 Heroic Melee Trinket
7265 float stat = 0.0f;
7266 // strength
7267 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67773;stat = GetStat(STAT_STRENGTH); }
7268 // agility
7269 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67772; }
7270 break;
7273 break;
7274 case SPELLFAMILY_MAGE:
7275 if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed
7277 switch (auraSpellInfo->Id)
7279 case 31641: // Rank 1
7280 case 31642: // Rank 2
7281 trigger_spell_id = 31643;
7282 break;
7283 default:
7284 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blazing Speed",auraSpellInfo->Id);
7285 return false;
7288 // Persistent Shield (Scarab Brooch trinket)
7289 else if(auraSpellInfo->Id == 26467)
7291 // This spell originally trigger 13567 - Dummy Trigger (vs dummy efect)
7292 basepoints[0] = damage * 15 / 100;
7293 target = pVictim;
7294 trigger_spell_id = 26470;
7296 break;
7297 case SPELLFAMILY_WARRIOR:
7298 // Deep Wounds (replace triggered spells to directly apply DoT), dot spell have finilyflags
7299 if (auraSpellInfo->SpellFamilyFlags == UI64LIT(0x0) && auraSpellInfo->SpellIconID == 243)
7301 float weaponDamage;
7302 // DW should benefit of attack power, damage percent mods etc.
7303 // TODO: check if using offhand damage is correct and if it should be divided by 2
7304 if (haveOffhandWeapon() && getAttackTimer(BASE_ATTACK) > getAttackTimer(OFF_ATTACK))
7305 weaponDamage = (GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE) + GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE))/2;
7306 else
7307 weaponDamage = (GetFloatValue(UNIT_FIELD_MINDAMAGE) + GetFloatValue(UNIT_FIELD_MAXDAMAGE))/2;
7309 switch (auraSpellInfo->Id)
7311 case 12834: basepoints[0] = int32(weaponDamage * 16 / 100); break;
7312 case 12849: basepoints[0] = int32(weaponDamage * 32 / 100); break;
7313 case 12867: basepoints[0] = int32(weaponDamage * 48 / 100); break;
7314 // Impossible case
7315 default:
7316 sLog.outError("Unit::HandleProcTriggerSpell: DW unknown spell rank %u",auraSpellInfo->Id);
7317 return false;
7320 // 1 tick/sec * 6 sec = 6 ticks
7321 basepoints[0] /= 6;
7323 trigger_spell_id = 12721;
7324 break;
7326 if (auraSpellInfo->Id == 50421) // Scent of Blood
7327 trigger_spell_id = 50422;
7328 break;
7329 case SPELLFAMILY_WARLOCK:
7331 // Drain Soul
7332 if (auraSpellInfo->SpellFamilyFlags & UI64LIT(0x0000000000004000))
7334 Unit::AuraList const& mAddFlatModifier = GetAurasByType(SPELL_AURA_ADD_FLAT_MODIFIER);
7335 for(Unit::AuraList::const_iterator i = mAddFlatModifier.begin(); i != mAddFlatModifier.end(); ++i)
7337 if ((*i)->GetModifier()->m_miscvalue == SPELLMOD_CHANCE_OF_SUCCESS && (*i)->GetSpellProto()->SpellIconID == 113)
7339 // Drain Soul
7340 CastCustomSpell(this, 18371, &basepoints[0], NULL, NULL, true, castItem, triggeredByAura);
7341 break;
7344 // Not remove charge (aura removed on death in any cases)
7345 // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura
7346 return false;
7348 // Nether Protection
7349 else if (auraSpellInfo->SpellIconID == 1985)
7351 if (!procSpell)
7352 return false;
7353 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
7355 case SPELL_SCHOOL_NORMAL:
7356 return false; // ignore
7357 case SPELL_SCHOOL_HOLY: trigger_spell_id = 54370; break;
7358 case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break;
7359 case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break;
7360 case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break;
7361 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break;
7362 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
7363 default:
7364 return false;
7367 // Cheat Death
7368 else if (auraSpellInfo->Id == 28845)
7370 // When your health drops below 20% ....
7371 if (GetHealth() - damage > GetMaxHealth() / 5 || GetHealth() < GetMaxHealth() / 5)
7372 return false;
7374 // Decimation
7375 else if (auraSpellInfo->Id == 63156 || auraSpellInfo->Id == 63158)
7377 // Looking for dummy effect
7378 Aura *aur = GetAura(auraSpellInfo->Id, EFFECT_INDEX_1);
7379 if (!aur)
7380 return false;
7382 // If target's health is not below equal certain value (35%) not proc
7383 if (int32(pVictim->GetHealth() * 100 / pVictim->GetMaxHealth()) > aur->GetModifier()->m_amount)
7384 return false;
7386 break;
7388 case SPELLFAMILY_PRIEST:
7390 // Greater Heal Refund (Avatar Raiment set)
7391 if (auraSpellInfo->Id==37594)
7393 // Not give if target already have full health
7394 if (pVictim->GetHealth() == pVictim->GetMaxHealth())
7395 return false;
7396 // If your Greater Heal brings the target to full health, you gain $37595s1 mana.
7397 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
7398 return false;
7399 trigger_spell_id = 37595;
7401 // Blessed Recovery
7402 else if (auraSpellInfo->SpellIconID == 1875)
7404 switch (auraSpellInfo->Id)
7406 case 27811: trigger_spell_id = 27813; break;
7407 case 27815: trigger_spell_id = 27817; break;
7408 case 27816: trigger_spell_id = 27818; break;
7409 default:
7410 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id);
7411 return false;
7413 basepoints[0] = damage * triggerAmount / 100 / 3;
7414 target = this;
7416 break;
7418 case SPELLFAMILY_DRUID:
7420 // Druid Forms Trinket
7421 if (auraSpellInfo->Id==37336)
7423 switch(m_form)
7425 case FORM_NONE: trigger_spell_id = 37344;break;
7426 case FORM_CAT: trigger_spell_id = 37341;break;
7427 case FORM_BEAR:
7428 case FORM_DIREBEAR: trigger_spell_id = 37340;break;
7429 case FORM_TREE: trigger_spell_id = 37342;break;
7430 case FORM_MOONKIN: trigger_spell_id = 37343;break;
7431 default:
7432 return false;
7435 // Druid T9 Feral Relic (Lacerate, Swipe, Mangle, and Shred)
7436 else if (auraSpellInfo->Id==67353)
7438 switch(m_form)
7440 case FORM_CAT: trigger_spell_id = 67355; break;
7441 case FORM_BEAR:
7442 case FORM_DIREBEAR: trigger_spell_id = 67354; break;
7443 default:
7444 return false;
7447 break;
7449 case SPELLFAMILY_HUNTER:
7450 // Piercing Shots
7451 if (auraSpellInfo->SpellIconID == 3247 && auraSpellInfo->SpellVisual[0] == 0)
7453 basepoints[0] = damage * triggerAmount / 100 / 8;
7454 trigger_spell_id = 63468;
7455 target = pVictim;
7457 // Rapid Recuperation
7458 else if (auraSpellInfo->Id == 53228 || auraSpellInfo->Id == 53232)
7460 // This effect only from Rapid Fire (ability cast)
7461 if (!(procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000020)))
7462 return false;
7464 break;
7465 case SPELLFAMILY_PALADIN:
7468 // Blessed Life
7469 if (auraSpellInfo->SpellIconID == 2137)
7471 switch (auraSpellInfo->Id)
7473 case 31828: // Rank 1
7474 case 31829: // Rank 2
7475 case 31830: // Rank 3
7476 break;
7477 default:
7478 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blessed Life", auraSpellInfo->Id);
7479 return false;
7483 // Healing Discount
7484 if (auraSpellInfo->Id==37705)
7486 trigger_spell_id = 37706;
7487 target = this;
7489 // Soul Preserver
7490 if (auraSpellInfo->Id==60510)
7492 trigger_spell_id = 60515;
7493 target = this;
7495 // Illumination
7496 else if (auraSpellInfo->SpellIconID==241)
7498 if(!procSpell)
7499 return false;
7500 // procspell is triggered spell but we need mana cost of original casted spell
7501 uint32 originalSpellId = procSpell->Id;
7502 // Holy Shock heal
7503 if (procSpell->SpellFamilyFlags & UI64LIT(0x0001000000000000))
7505 switch(procSpell->Id)
7507 case 25914: originalSpellId = 20473; break;
7508 case 25913: originalSpellId = 20929; break;
7509 case 25903: originalSpellId = 20930; break;
7510 case 27175: originalSpellId = 27174; break;
7511 case 33074: originalSpellId = 33072; break;
7512 case 48820: originalSpellId = 48824; break;
7513 case 48821: originalSpellId = 48825; break;
7514 default:
7515 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in HShock",procSpell->Id);
7516 return false;
7519 SpellEntry const *originalSpell = sSpellStore.LookupEntry(originalSpellId);
7520 if(!originalSpell)
7522 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu",originalSpellId);
7523 return false;
7525 // percent stored in effect 1 (class scripts) base points
7526 int32 cost = originalSpell->manaCost + originalSpell->ManaCostPercentage * GetCreateMana() / 100;
7527 basepoints[0] = cost*auraSpellInfo->CalculateSimpleValue(EFFECT_INDEX_1)/100;
7528 trigger_spell_id = 20272;
7529 target = this;
7531 // Lightning Capacitor
7532 else if (auraSpellInfo->Id==37657)
7534 if(!pVictim || !pVictim->isAlive())
7535 return false;
7536 // stacking
7537 CastSpell(this, 37658, true, NULL, triggeredByAura);
7539 Aura * dummy = GetDummyAura(37658);
7540 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
7541 if(!dummy || dummy->GetStackAmount() < triggerAmount)
7542 return false;
7544 RemoveAurasDueToSpell(37658);
7545 trigger_spell_id = 37661;
7546 target = pVictim;
7548 // Bonus Healing (Crystal Spire of Karabor mace)
7549 else if (auraSpellInfo->Id == 40971)
7551 // If your target is below $s1% health
7552 if (pVictim->GetHealth() > pVictim->GetMaxHealth() * triggerAmount / 100)
7553 return false;
7555 // Thunder Capacitor
7556 else if (auraSpellInfo->Id == 54841)
7558 if(!pVictim || !pVictim->isAlive())
7559 return false;
7560 // stacking
7561 CastSpell(this, 54842, true, NULL, triggeredByAura);
7563 // counting
7564 Aura * dummy = GetDummyAura(54842);
7565 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
7566 if(!dummy || dummy->GetStackAmount() < triggerAmount)
7567 return false;
7569 RemoveAurasDueToSpell(54842);
7570 trigger_spell_id = 54843;
7571 target = pVictim;
7573 break;
7575 case SPELLFAMILY_SHAMAN:
7577 // Lightning Shield (overwrite non existing triggered spell call in spell.dbc
7578 if (auraSpellInfo->SpellFamilyFlags & UI64LIT(0x0000000000000400))
7580 switch(auraSpellInfo->Id)
7582 case 324: // Rank 1
7583 trigger_spell_id = 26364; break;
7584 case 325: // Rank 2
7585 trigger_spell_id = 26365; break;
7586 case 905: // Rank 3
7587 trigger_spell_id = 26366; break;
7588 case 945: // Rank 4
7589 trigger_spell_id = 26367; break;
7590 case 8134: // Rank 5
7591 trigger_spell_id = 26369; break;
7592 case 10431: // Rank 6
7593 trigger_spell_id = 26370; break;
7594 case 10432: // Rank 7
7595 trigger_spell_id = 26363; break;
7596 case 25469: // Rank 8
7597 trigger_spell_id = 26371; break;
7598 case 25472: // Rank 9
7599 trigger_spell_id = 26372; break;
7600 case 49280: // Rank 10
7601 trigger_spell_id = 49278; break;
7602 case 49281: // Rank 11
7603 trigger_spell_id = 49279; break;
7604 default:
7605 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in LShield", auraSpellInfo->Id);
7606 return false;
7609 // Lightning Shield (The Ten Storms set)
7610 else if (auraSpellInfo->Id == 23551)
7612 trigger_spell_id = 23552;
7613 target = pVictim;
7615 // Damage from Lightning Shield (The Ten Storms set)
7616 else if (auraSpellInfo->Id == 23552)
7617 trigger_spell_id = 27635;
7618 // Mana Surge (The Earthfury set)
7619 else if (auraSpellInfo->Id == 23572)
7621 if(!procSpell)
7622 return false;
7623 basepoints[0] = procSpell->manaCost * 35 / 100;
7624 trigger_spell_id = 23571;
7625 target = this;
7627 // Nature's Guardian
7628 else if (auraSpellInfo->SpellIconID == 2013)
7630 // Check health condition - should drop to less 30% (damage deal after this!)
7631 if (!(10*(int32(GetHealth() - damage)) < int32(3 * GetMaxHealth())))
7632 return false;
7634 if(pVictim && pVictim->isAlive())
7635 pVictim->getThreatManager().modifyThreatPercent(this,-10);
7637 basepoints[0] = triggerAmount * GetMaxHealth() / 100;
7638 trigger_spell_id = 31616;
7639 target = this;
7641 break;
7643 case SPELLFAMILY_DEATHKNIGHT:
7645 // Acclimation
7646 if (auraSpellInfo->SpellIconID == 1930)
7648 if (!procSpell)
7649 return false;
7650 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
7652 case SPELL_SCHOOL_NORMAL:
7653 return false; // ignore
7654 case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break;
7655 case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break;
7656 case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break;
7657 case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break;
7658 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break;
7659 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 50486; break;
7660 default:
7661 return false;
7664 // Blade Barrier
7665 else if (auraSpellInfo->SpellIconID == 85)
7667 if (GetTypeId() != TYPEID_PLAYER || getClass() != CLASS_DEATH_KNIGHT ||
7668 !((Player*)this)->IsBaseRuneSlotsOnCooldown(RUNE_BLOOD))
7669 return false;
7671 // Improved Blood Presence
7672 else if (auraSpellInfo->Id == 63611)
7674 if (GetTypeId() != TYPEID_PLAYER || !((Player*)this)->isHonorOrXPTarget(pVictim) || !damage)
7675 return false;
7676 basepoints[0] = triggerAmount * damage / 100;
7677 trigger_spell_id = 50475;
7679 break;
7681 default:
7682 break;
7685 // All ok. Check current trigger spell
7686 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(trigger_spell_id);
7687 if (!triggerEntry)
7689 // Not cast unknown spell
7690 // sLog.outError("Unit::HandleProcTriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?",auraSpellInfo->Id,triggeredByAura->GetEffIndex());
7691 return false;
7694 // not allow proc extra attack spell at extra attack
7695 if (m_extraAttacks && IsSpellHaveEffect(triggerEntry, SPELL_EFFECT_ADD_EXTRA_ATTACKS))
7696 return false;
7698 // Custom basepoints/target for exist spell
7699 // dummy basepoints or other customs
7700 switch(trigger_spell_id)
7702 // Cast positive spell on enemy target
7703 case 7099: // Curse of Mending
7704 case 39647: // Curse of Mending
7705 case 29494: // Temptation
7706 case 20233: // Improved Lay on Hands (cast on target)
7708 target = pVictim;
7709 break;
7711 // Combo points add triggers (need add combopoint only for main target, and after possible combopoints reset)
7712 case 15250: // Rogue Setup
7714 if(!pVictim || pVictim != getVictim()) // applied only for main target
7715 return false;
7716 break; // continue normal case
7718 // Finish movies that add combo
7719 case 14189: // Seal Fate (Netherblade set)
7720 case 14157: // Ruthlessness
7722 // Need add combopoint AFTER finish movie (or they dropped in finish phase)
7723 break;
7725 // Bloodthirst (($m/100)% of max health)
7726 case 23880:
7728 basepoints[0] = int32(GetMaxHealth() * triggerAmount / 100);
7729 break;
7731 // Shamanistic Rage triggered spell
7732 case 30824:
7734 basepoints[0] = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
7735 break;
7737 // Enlightenment (trigger only from mana cost spells)
7738 case 35095:
7740 if(!procSpell || procSpell->powerType!=POWER_MANA || procSpell->manaCost==0 && procSpell->ManaCostPercentage==0 && procSpell->manaCostPerlevel==0)
7741 return false;
7742 break;
7744 // Demonic Pact
7745 case 48090:
7747 // As the spell is proced from pet's attack - find owner
7748 Unit* owner = GetOwner();
7749 if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
7750 return false;
7752 // This spell doesn't stack, but refreshes duration. So we receive current bonuses to minus them later.
7753 int32 curBonus = 0;
7754 if (Aura* aur = owner->GetAura(48090, EFFECT_INDEX_0))
7755 curBonus = aur->GetModifier()->m_amount;
7756 int32 spellDamage = owner->SpellBaseDamageBonus(SPELL_SCHOOL_MASK_MAGIC) - curBonus;
7757 if(spellDamage <= 0)
7758 return false;
7760 // percent stored in owner talent dummy
7761 AuraList const& dummyAuras = owner->GetAurasByType(SPELL_AURA_DUMMY);
7762 for (AuraList::const_iterator i = dummyAuras.begin(); i != dummyAuras.end(); ++i)
7764 if ((*i)->GetSpellProto()->SpellIconID == 3220)
7766 basepoints[0] = basepoints[1] = int32(spellDamage * (*i)->GetModifier()->m_amount / 100);
7767 break;
7770 break;
7772 // Sword and Board
7773 case 50227:
7775 // Remove cooldown on Shield Slam
7776 if (GetTypeId() == TYPEID_PLAYER)
7777 ((Player*)this)->RemoveSpellCategoryCooldown(1209, true);
7778 break;
7780 // Maelstrom Weapon
7781 case 53817:
7783 // have rank dependent proc chance, ignore too often cases
7784 // PPM = 2.5 * (rank of talent),
7785 uint32 rank = sSpellMgr.GetSpellRank(auraSpellInfo->Id);
7786 // 5 rank -> 100% 4 rank -> 80% and etc from full rate
7787 if(!roll_chance_i(20*rank))
7788 return false;
7789 break;
7791 // Brain Freeze
7792 case 57761:
7794 if(!procSpell)
7795 return false;
7796 // For trigger from Blizzard need exist Improved Blizzard
7797 if (procSpell->SpellFamilyName==SPELLFAMILY_MAGE && (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080)))
7799 bool found = false;
7800 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7801 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7803 int32 script = (*i)->GetModifier()->m_miscvalue;
7804 if(script==836 || script==988 || script==989)
7806 found=true;
7807 break;
7810 if(!found)
7811 return false;
7813 break;
7815 // Astral Shift
7816 case 52179:
7818 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
7819 return false;
7821 // Need stun, fear or silence mechanic
7822 if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_SILENCE_AND_STUN_AND_FEAR_MASK))
7823 return false;
7824 break;
7826 // Burning Determination
7827 case 54748:
7829 if(!procSpell)
7830 return false;
7831 // Need Interrupt or Silenced mechanic
7832 if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_INTERRUPT_AND_SILENCE_MASK))
7833 return false;
7834 break;
7836 // Lock and Load
7837 case 56453:
7839 // Proc only from trap activation (from periodic proc another aura of this spell)
7840 if (!(procFlags & PROC_FLAG_ON_TRAP_ACTIVATION) || !roll_chance_i(triggerAmount))
7841 return false;
7842 break;
7844 // Freezing Fog (Rime triggered)
7845 case 59052:
7847 // Howling Blast cooldown reset
7848 if (GetTypeId() == TYPEID_PLAYER)
7849 ((Player*)this)->RemoveSpellCategoryCooldown(1248, true);
7850 break;
7852 // Druid - Savage Defense
7853 case 62606:
7855 basepoints[0] = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
7856 break;
7860 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(trigger_spell_id))
7861 return false;
7863 // try detect target manually if not set
7864 if (target == NULL)
7865 target = !(procFlags & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) && IsPositiveSpell(trigger_spell_id) ? this : pVictim;
7867 // default case
7868 if (!target || target!=this && !target->isAlive())
7869 return false;
7871 if (basepoints[EFFECT_INDEX_0] || basepoints[EFFECT_INDEX_1] || basepoints[EFFECT_INDEX_2])
7872 CastCustomSpell(target,trigger_spell_id,
7873 basepoints[EFFECT_INDEX_0] ? &basepoints[EFFECT_INDEX_0] : NULL,
7874 basepoints[EFFECT_INDEX_1] ? &basepoints[EFFECT_INDEX_1] : NULL,
7875 basepoints[EFFECT_INDEX_2] ? &basepoints[EFFECT_INDEX_2] : NULL,
7876 true, castItem, triggeredByAura);
7877 else
7878 CastSpell(target,trigger_spell_id,true,castItem,triggeredByAura);
7880 if( cooldown && GetTypeId()==TYPEID_PLAYER )
7881 ((Player*)this)->AddSpellCooldown(trigger_spell_id,0,time(NULL) + cooldown);
7883 return true;
7886 bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, uint32 /*damage*/, Aura *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown)
7888 int32 scriptId = triggeredByAura->GetModifier()->m_miscvalue;
7890 if(!pVictim || !pVictim->isAlive())
7891 return false;
7893 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
7894 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
7896 // Basepoints of trigger aura
7897 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
7899 uint32 triggered_spell_id = 0;
7901 switch(scriptId)
7903 case 836: // Improved Blizzard (Rank 1)
7905 if (!procSpell || procSpell->SpellVisual[0]!=9487)
7906 return false;
7907 triggered_spell_id = 12484;
7908 break;
7910 case 988: // Improved Blizzard (Rank 2)
7912 if (!procSpell || procSpell->SpellVisual[0]!=9487)
7913 return false;
7914 triggered_spell_id = 12485;
7915 break;
7917 case 989: // Improved Blizzard (Rank 3)
7919 if (!procSpell || procSpell->SpellVisual[0]!=9487)
7920 return false;
7921 triggered_spell_id = 12486;
7922 break;
7924 case 4086: // Improved Mend Pet (Rank 1)
7925 case 4087: // Improved Mend Pet (Rank 2)
7927 if(!roll_chance_i(triggerAmount))
7928 return false;
7930 triggered_spell_id = 24406;
7931 break;
7933 case 4533: // Dreamwalker Raiment 2 pieces bonus
7935 // Chance 50%
7936 if (!roll_chance_i(50))
7937 return false;
7939 switch (pVictim->getPowerType())
7941 case POWER_MANA: triggered_spell_id = 28722; break;
7942 case POWER_RAGE: triggered_spell_id = 28723; break;
7943 case POWER_ENERGY: triggered_spell_id = 28724; break;
7944 default:
7945 return false;
7947 break;
7949 case 4537: // Dreamwalker Raiment 6 pieces bonus
7950 triggered_spell_id = 28750; // Blessing of the Claw
7951 break;
7952 case 5497: // Improved Mana Gems (Serpent-Coil Braid)
7953 triggered_spell_id = 37445; // Mana Surge
7954 break;
7955 case 6953: // Warbringer
7956 RemoveAurasAtMechanicImmunity(IMMUNE_TO_ROOT_AND_SNARE_MASK,0,true);
7957 return true;
7958 case 7010: // Revitalize (rank 1)
7959 case 7011: // Revitalize (rank 2)
7960 case 7012: // Revitalize (rank 3)
7962 if(!roll_chance_i(triggerAmount))
7963 return false;
7965 switch( pVictim->getPowerType() )
7967 case POWER_MANA: triggered_spell_id = 48542; break;
7968 case POWER_RAGE: triggered_spell_id = 48541; break;
7969 case POWER_ENERGY: triggered_spell_id = 48540; break;
7970 case POWER_RUNIC_POWER: triggered_spell_id = 48543; break;
7971 default: return false;
7973 break;
7977 // not processed
7978 if(!triggered_spell_id)
7979 return false;
7981 // standard non-dummy case
7982 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
7984 if(!triggerEntry)
7986 sLog.outError("Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u",triggered_spell_id,scriptId);
7987 return false;
7990 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
7991 return false;
7993 CastSpell(pVictim, triggered_spell_id, true, castItem, triggeredByAura);
7995 if( cooldown && GetTypeId()==TYPEID_PLAYER )
7996 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
7998 return true;
8001 void Unit::setPowerType(Powers new_powertype)
8003 SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype);
8005 if(GetTypeId() == TYPEID_PLAYER)
8007 if(((Player*)this)->GetGroup())
8008 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE);
8010 else if(((Creature*)this)->isPet())
8012 Pet *pet = ((Pet*)this);
8013 if(pet->isControlled())
8015 Unit *owner = GetOwner();
8016 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
8017 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE);
8021 switch(new_powertype)
8023 default:
8024 case POWER_MANA:
8025 break;
8026 case POWER_RAGE:
8027 SetMaxPower(POWER_RAGE,GetCreatePowers(POWER_RAGE));
8028 SetPower( POWER_RAGE,0);
8029 break;
8030 case POWER_FOCUS:
8031 SetMaxPower(POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
8032 SetPower( POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
8033 break;
8034 case POWER_ENERGY:
8035 SetMaxPower(POWER_ENERGY,GetCreatePowers(POWER_ENERGY));
8036 break;
8037 case POWER_HAPPINESS:
8038 SetMaxPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
8039 SetPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
8040 break;
8044 FactionTemplateEntry const* Unit::getFactionTemplateEntry() const
8046 FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry(getFaction());
8047 if(!entry)
8049 static uint64 guid = 0; // prevent repeating spam same faction problem
8051 if(GetGUID() != guid)
8053 if(GetTypeId() == TYPEID_PLAYER)
8054 sLog.outError("Player %s have invalid faction (faction template id) #%u", ((Player*)this)->GetName(), getFaction());
8055 else
8056 sLog.outError("Creature (template id: %u) have invalid faction (faction template id) #%u", ((Creature*)this)->GetCreatureInfo()->Entry, getFaction());
8057 guid = GetGUID();
8060 return entry;
8063 bool Unit::IsHostileTo(Unit const* unit) const
8065 // always non-hostile to self
8066 if(unit==this)
8067 return false;
8069 // always non-hostile to GM in GM mode
8070 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
8071 return false;
8073 // always hostile to enemy
8074 if(getVictim()==unit || unit->getVictim()==this)
8075 return true;
8077 // test pet/charm masters instead pers/charmeds
8078 Unit const* testerOwner = GetCharmerOrOwner();
8079 Unit const* targetOwner = unit->GetCharmerOrOwner();
8081 // always hostile to owner's enemy
8082 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
8083 return true;
8085 // always hostile to enemy owner
8086 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
8087 return true;
8089 // always hostile to owner of owner's enemy
8090 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
8091 return true;
8093 Unit const* tester = testerOwner ? testerOwner : this;
8094 Unit const* target = targetOwner ? targetOwner : unit;
8096 // always non-hostile to target with common owner, or to owner/pet
8097 if(tester==target)
8098 return false;
8100 // special cases (Duel, etc)
8101 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
8103 Player const* pTester = (Player const*)tester;
8104 Player const* pTarget = (Player const*)target;
8106 // Duel
8107 if(pTester->duel && pTester->duel->opponent == pTarget && pTester->duel->startTime != 0)
8108 return true;
8110 // Group
8111 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
8112 return false;
8114 // Sanctuary
8115 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
8116 return false;
8118 // PvP FFA state
8119 if(pTester->IsFFAPvP() && pTarget->IsFFAPvP())
8120 return true;
8122 //= PvP states
8123 // Green/Blue (can't attack)
8124 if(pTester->GetTeam()==pTarget->GetTeam())
8125 return false;
8127 // Red (can attack) if true, Blue/Yellow (can't attack) in another case
8128 return pTester->IsPvP() && pTarget->IsPvP();
8131 // faction base cases
8132 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
8133 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
8134 if(!tester_faction || !target_faction)
8135 return false;
8137 if(target->isAttackingPlayer() && tester->IsContestedGuard())
8138 return true;
8140 // PvC forced reaction and reputation case
8141 if(tester->GetTypeId()==TYPEID_PLAYER)
8143 // forced reaction
8144 if(target_faction->faction)
8146 if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
8147 return *force <= REP_HOSTILE;
8149 // if faction have reputation then hostile state for tester at 100% dependent from at_war state
8150 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
8151 if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
8152 return (factionState->Flags & FACTION_FLAG_AT_WAR);
8155 // CvP forced reaction and reputation case
8156 else if(target->GetTypeId()==TYPEID_PLAYER)
8158 // forced reaction
8159 if(tester_faction->faction)
8161 if(ReputationRank const* force = ((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
8162 return *force <= REP_HOSTILE;
8164 // apply reputation state
8165 FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction);
8166 if(raw_tester_faction && raw_tester_faction->reputationListID >=0 )
8167 return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) <= REP_HOSTILE;
8171 // common faction based case (CvC,PvC,CvP)
8172 return tester_faction->IsHostileTo(*target_faction);
8175 bool Unit::IsFriendlyTo(Unit const* unit) const
8177 // always friendly to self
8178 if(unit==this)
8179 return true;
8181 // always friendly to GM in GM mode
8182 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
8183 return true;
8185 // always non-friendly to enemy
8186 if(getVictim()==unit || unit->getVictim()==this)
8187 return false;
8189 // test pet/charm masters instead pers/charmeds
8190 Unit const* testerOwner = GetCharmerOrOwner();
8191 Unit const* targetOwner = unit->GetCharmerOrOwner();
8193 // always non-friendly to owner's enemy
8194 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
8195 return false;
8197 // always non-friendly to enemy owner
8198 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
8199 return false;
8201 // always non-friendly to owner of owner's enemy
8202 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
8203 return false;
8205 Unit const* tester = testerOwner ? testerOwner : this;
8206 Unit const* target = targetOwner ? targetOwner : unit;
8208 // always friendly to target with common owner, or to owner/pet
8209 if(tester==target)
8210 return true;
8212 // special cases (Duel)
8213 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
8215 Player const* pTester = (Player const*)tester;
8216 Player const* pTarget = (Player const*)target;
8218 // Duel
8219 if(pTester->duel && pTester->duel->opponent == target && pTester->duel->startTime != 0)
8220 return false;
8222 // Group
8223 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
8224 return true;
8226 // Sanctuary
8227 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
8228 return true;
8230 // PvP FFA state
8231 if(pTester->IsFFAPvP() && pTarget->IsFFAPvP())
8232 return false;
8234 //= PvP states
8235 // Green/Blue (non-attackable)
8236 if(pTester->GetTeam()==pTarget->GetTeam())
8237 return true;
8239 // Blue (friendly/non-attackable) if not PVP, or Yellow/Red in another case (attackable)
8240 return !pTarget->IsPvP();
8243 // faction base cases
8244 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
8245 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
8246 if(!tester_faction || !target_faction)
8247 return false;
8249 if(target->isAttackingPlayer() && tester->IsContestedGuard())
8250 return false;
8252 // PvC forced reaction and reputation case
8253 if(tester->GetTypeId()==TYPEID_PLAYER)
8255 // forced reaction
8256 if(target_faction->faction)
8258 if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
8259 return *force >= REP_FRIENDLY;
8261 // if faction have reputation then friendly state for tester at 100% dependent from at_war state
8262 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
8263 if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
8264 return !(factionState->Flags & FACTION_FLAG_AT_WAR);
8267 // CvP forced reaction and reputation case
8268 else if(target->GetTypeId()==TYPEID_PLAYER)
8270 // forced reaction
8271 if(tester_faction->faction)
8273 if(ReputationRank const* force =((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
8274 return *force >= REP_FRIENDLY;
8276 // apply reputation state
8277 if(FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction))
8278 if(raw_tester_faction->reputationListID >=0 )
8279 return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) >= REP_FRIENDLY;
8283 // common faction based case (CvC,PvC,CvP)
8284 return tester_faction->IsFriendlyTo(*target_faction);
8287 bool Unit::IsHostileToPlayers() const
8289 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
8290 if(!my_faction || !my_faction->faction)
8291 return false;
8293 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
8294 if(raw_faction && raw_faction->reputationListID >=0 )
8295 return false;
8297 return my_faction->IsHostileToPlayers();
8300 bool Unit::IsNeutralToAll() const
8302 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
8303 if(!my_faction || !my_faction->faction)
8304 return true;
8306 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
8307 if(raw_faction && raw_faction->reputationListID >=0 )
8308 return false;
8310 return my_faction->IsNeutralToAll();
8313 bool Unit::Attack(Unit *victim, bool meleeAttack)
8315 if(!victim || victim == this)
8316 return false;
8318 // dead units can neither attack nor be attacked
8319 if(!isAlive() || !victim->IsInWorld() || !victim->isAlive())
8320 return false;
8322 // player cannot attack in mount state
8323 if(GetTypeId()==TYPEID_PLAYER && IsMounted())
8324 return false;
8326 // nobody can attack GM in GM-mode
8327 if(victim->GetTypeId()==TYPEID_PLAYER)
8329 if(((Player*)victim)->isGameMaster())
8330 return false;
8332 else
8334 if(((Creature*)victim)->IsInEvadeMode())
8335 return false;
8338 // remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack)
8339 if(HasAuraType(SPELL_AURA_MOD_UNATTACKABLE))
8340 RemoveSpellsCausingAura(SPELL_AURA_MOD_UNATTACKABLE);
8342 // in fighting already
8343 if (m_attacking)
8345 if (m_attacking == victim)
8347 // switch to melee attack from ranged/magic
8348 if( meleeAttack && !hasUnitState(UNIT_STAT_MELEE_ATTACKING) )
8350 addUnitState(UNIT_STAT_MELEE_ATTACKING);
8351 SendMeleeAttackStart(victim);
8352 return true;
8354 return false;
8357 // remove old target data
8358 AttackStop(true);
8360 // new battle
8361 else
8363 // set position before any AI calls/assistance
8364 if(GetTypeId()==TYPEID_UNIT)
8365 ((Creature*)this)->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ());
8368 // Set our target
8369 SetTargetGUID(victim->GetGUID());
8371 if(meleeAttack)
8372 addUnitState(UNIT_STAT_MELEE_ATTACKING);
8374 m_attacking = victim;
8375 m_attacking->_addAttacker(this);
8377 if (GetTypeId() == TYPEID_UNIT)
8379 ((Creature*)this)->SendAIReaction(AI_REACTION_HOSTILE);
8380 ((Creature*)this)->CallAssistance();
8383 // delay offhand weapon attack to next attack time
8384 if(haveOffhandWeapon())
8385 resetAttackTimer(OFF_ATTACK);
8387 if(meleeAttack)
8388 SendMeleeAttackStart(victim);
8390 return true;
8393 bool Unit::AttackStop(bool targetSwitch /*=false*/)
8395 if (!m_attacking)
8396 return false;
8398 Unit* victim = m_attacking;
8400 m_attacking->_removeAttacker(this);
8401 m_attacking = NULL;
8403 // Clear our target
8404 SetTargetGUID(0);
8406 clearUnitState(UNIT_STAT_MELEE_ATTACKING);
8408 InterruptSpell(CURRENT_MELEE_SPELL);
8410 // reset only at real combat stop
8411 if(!targetSwitch && GetTypeId()==TYPEID_UNIT )
8413 ((Creature*)this)->SetNoCallAssistance(false);
8415 if (((Creature*)this)->HasSearchedAssistance())
8417 ((Creature*)this)->SetNoSearchAssistance(false);
8418 UpdateSpeed(MOVE_RUN, false);
8422 SendMeleeAttackStop(victim);
8424 return true;
8427 void Unit::CombatStop(bool includingCast)
8429 if (includingCast && IsNonMeleeSpellCasted(false))
8430 InterruptNonMeleeSpells(false);
8432 AttackStop();
8433 RemoveAllAttackers();
8434 if( GetTypeId()==TYPEID_PLAYER )
8435 ((Player*)this)->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel
8436 ClearInCombat();
8439 struct CombatStopWithPetsHelper
8441 explicit CombatStopWithPetsHelper(bool _includingCast) : includingCast(_includingCast) {}
8442 void operator()(Unit* unit) const { unit->CombatStop(includingCast); }
8443 bool includingCast;
8446 void Unit::CombatStopWithPets(bool includingCast)
8448 CombatStop(includingCast);
8449 CallForAllControlledUnits(CombatStopWithPetsHelper(includingCast),false,true,true);
8452 struct IsAttackingPlayerHelper
8454 explicit IsAttackingPlayerHelper() {}
8455 bool operator()(Unit* unit) const { return unit->isAttackingPlayer(); }
8458 bool Unit::isAttackingPlayer() const
8460 if(hasUnitState(UNIT_STAT_ATTACK_PLAYER))
8461 return true;
8463 return CheckAllControlledUnits(IsAttackingPlayerHelper(),true,true,true);
8466 void Unit::RemoveAllAttackers()
8468 while (!m_attackers.empty())
8470 AttackerSet::iterator iter = m_attackers.begin();
8471 if(!(*iter)->AttackStop())
8473 sLog.outError("WORLD: Unit has an attacker that isn't attacking it!");
8474 m_attackers.erase(iter);
8479 bool Unit::HasAuraStateForCaster(AuraState flag, uint64 caster) const
8481 if(!HasAuraState(flag))
8482 return false;
8484 // single per-caster aura state
8485 if(flag == AURA_STATE_CONFLAGRATE)
8487 Unit::AuraList const& dotList = GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
8488 for(Unit::AuraList::const_iterator i = dotList.begin(); i != dotList.end(); ++i)
8490 if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK &&
8491 (*i)->GetCasterGUID() == caster &&
8492 // Immolate
8493 (((*i)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000000000004)) ||
8494 // Shadowflame
8495 ((*i)->GetSpellProto()->SpellFamilyFlags2 & 0x00000002)))
8497 return true;
8501 return false;
8504 return true;
8507 void Unit::ModifyAuraState(AuraState flag, bool apply)
8509 if (apply)
8511 if (!HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)))
8513 SetFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
8514 if(GetTypeId() == TYPEID_PLAYER)
8516 const PlayerSpellMap& sp_list = ((Player*)this)->GetSpellMap();
8517 for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
8519 if(itr->second.state == PLAYERSPELL_REMOVED) continue;
8520 SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first);
8521 if (!spellInfo || !IsPassiveSpell(itr->first)) continue;
8522 if (spellInfo->CasterAuraState == flag)
8523 CastSpell(this, itr->first, true, NULL);
8528 else
8530 if (HasFlag(UNIT_FIELD_AURASTATE,1<<(flag-1)))
8532 RemoveFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
8534 if (flag != AURA_STATE_ENRAGE) // enrage aura state triggering continues auras
8536 Unit::AuraMap& tAuras = GetAuras();
8537 for (Unit::AuraMap::iterator itr = tAuras.begin(); itr != tAuras.end();)
8539 SpellEntry const* spellProto = (*itr).second->GetSpellProto();
8540 if (spellProto->CasterAuraState == flag)
8542 // exceptions (applied at state but not removed at state change)
8543 // Rampage
8544 if(spellProto->SpellIconID==2006 && spellProto->SpellFamilyName==SPELLFAMILY_WARRIOR && spellProto->SpellFamilyFlags==0x100000)
8546 ++itr;
8547 continue;
8550 RemoveAura(itr);
8552 else
8553 ++itr;
8560 Unit *Unit::GetOwner() const
8562 if(uint64 ownerid = GetOwnerGUID())
8563 return ObjectAccessor::GetUnit(*this, ownerid);
8564 return NULL;
8567 Unit *Unit::GetCharmer() const
8569 if(uint64 charmerid = GetCharmerGUID())
8570 return ObjectAccessor::GetUnit(*this, charmerid);
8571 return NULL;
8574 bool Unit::IsCharmerOrOwnerPlayerOrPlayerItself() const
8576 if (GetTypeId()==TYPEID_PLAYER)
8577 return true;
8579 return IS_PLAYER_GUID(GetCharmerOrOwnerGUID());
8582 Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself()
8584 uint64 guid = GetCharmerOrOwnerGUID();
8585 if(IS_PLAYER_GUID(guid))
8586 return ObjectAccessor::FindPlayer(guid);
8588 return GetTypeId()==TYPEID_PLAYER ? (Player*)this : NULL;
8591 Pet* Unit::GetPet() const
8593 if(uint64 pet_guid = GetPetGUID())
8595 if(Pet* pet = GetMap()->GetPet(pet_guid))
8596 return pet;
8598 sLog.outError("Unit::GetPet: Pet %u not exist.",GUID_LOPART(pet_guid));
8599 const_cast<Unit*>(this)->SetPet(0);
8602 return NULL;
8605 Unit* Unit::GetCharm() const
8607 if (uint64 charm_guid = GetCharmGUID())
8609 if(Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid))
8610 return pet;
8612 sLog.outError("Unit::GetCharm: Charmed creature %u not exist.",GUID_LOPART(charm_guid));
8613 const_cast<Unit*>(this)->SetCharm(NULL);
8616 return NULL;
8619 void Unit::Uncharm()
8621 if (Unit* charm = GetCharm())
8623 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
8624 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
8628 float Unit::GetCombatDistance( const Unit* target ) const
8630 float radius = target->GetFloatValue(UNIT_FIELD_COMBATREACH) + GetFloatValue(UNIT_FIELD_COMBATREACH);
8631 float dx = GetPositionX() - target->GetPositionX();
8632 float dy = GetPositionY() - target->GetPositionY();
8633 float dz = GetPositionZ() - target->GetPositionZ();
8634 float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - radius;
8635 return ( dist > 0 ? dist : 0);
8638 void Unit::SetPet(Pet* pet)
8640 SetPetGUID(pet ? pet->GetGUID() : 0);
8642 if(pet && GetTypeId() == TYPEID_PLAYER)
8643 ((Player*)this)->SendPetGUIDs();
8645 // FIXME: hack, speed must be set only at follow
8646 if(pet && GetTypeId()==TYPEID_PLAYER)
8647 for(int i = 0; i < MAX_MOVE_TYPE; ++i)
8648 pet->SetSpeedRate(UnitMoveType(i), m_speed_rate[i], true);
8651 void Unit::SetCharm(Unit* pet)
8653 SetCharmGUID(pet ? pet->GetGUID() : 0);
8656 void Unit::AddGuardian( Pet* pet )
8658 m_guardianPets.insert(pet->GetGUID());
8661 void Unit::RemoveGuardian( Pet* pet )
8663 m_guardianPets.erase(pet->GetGUID());
8666 void Unit::RemoveGuardians()
8668 while(!m_guardianPets.empty())
8670 uint64 guid = *m_guardianPets.begin();
8671 if(Pet* pet = GetMap()->GetPet(guid))
8672 pet->Remove(PET_SAVE_AS_DELETED);
8674 m_guardianPets.erase(guid);
8678 Pet* Unit::FindGuardianWithEntry(uint32 entry)
8680 // pet guid middle part is entry (and creature also)
8681 // and in guardian list must be guardians with same entry _always_
8682 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
8683 if(Pet* pet = GetMap()->GetPet(*itr))
8684 if (pet->GetEntry() == entry)
8685 return pet;
8687 return NULL;
8690 Unit* Unit::_GetTotem(TotemSlot slot) const
8692 return GetTotem(slot);
8695 Totem* Unit::GetTotem(TotemSlot slot ) const
8697 if(slot >= MAX_TOTEM_SLOT || !IsInWorld())
8698 return NULL;
8700 Creature *totem = GetMap()->GetCreature(m_TotemSlot[slot]);
8701 return totem && totem->isTotem() ? (Totem*)totem : NULL;
8704 bool Unit::IsAllTotemSlotsUsed() const
8706 for (int i = 0; i < MAX_TOTEM_SLOT; ++i)
8707 if (!m_TotemSlot[i])
8708 return false;
8709 return true;
8712 void Unit::_AddTotem(TotemSlot slot, Totem* totem)
8714 m_TotemSlot[slot] = totem->GetGUID();
8717 void Unit::_RemoveTotem(Totem* totem)
8719 for(int i = 0; i < MAX_TOTEM_SLOT; ++i)
8721 if (m_TotemSlot[i] == totem->GetGUID())
8723 m_TotemSlot[i] = 0;
8724 break;
8731 void Unit::UnsummonAllTotems()
8733 for (int i = 0; i < MAX_TOTEM_SLOT; ++i)
8734 if (Totem* totem = GetTotem(TotemSlot(i)))
8735 totem->UnSummon();
8738 int32 Unit::DealHeal(Unit *pVictim, uint32 addhealth, SpellEntry const *spellProto, bool critical)
8740 int32 gain = pVictim->ModifyHealth(int32(addhealth));
8742 Unit* unit = this;
8744 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
8745 unit = GetOwner();
8747 if (unit->GetTypeId()==TYPEID_PLAYER)
8749 // overheal = addhealth - gain
8750 unit->SendHealSpellLog(pVictim, spellProto->Id, addhealth, addhealth - gain, critical);
8752 if (BattleGround *bg = ((Player*)unit)->GetBattleGround())
8753 bg->UpdatePlayerScore((Player*)unit, SCORE_HEALING_DONE, gain);
8755 // use the actual gain, as the overheal shall not be counted, skip gain 0 (it ignored anyway in to criteria)
8756 if (gain)
8757 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE, gain, 0, pVictim);
8759 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED, addhealth);
8762 if (pVictim->GetTypeId()==TYPEID_PLAYER)
8764 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED, gain);
8765 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED, addhealth);
8768 return gain;
8771 Unit* Unit::SelectMagnetTarget(Unit *victim, SpellEntry const *spellInfo)
8773 if(!victim)
8774 return NULL;
8776 // Magic case
8777 if(spellInfo && (spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC))
8779 Unit::AuraList const& magnetAuras = victim->GetAurasByType(SPELL_AURA_SPELL_MAGNET);
8780 for(Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
8781 if(Unit* magnet = (*itr)->GetCaster())
8782 if(magnet->IsWithinLOSInMap(this) && magnet->isAlive())
8783 return magnet;
8785 // Melee && ranged case
8786 else
8788 AuraList const& hitTriggerAuras = victim->GetAurasByType(SPELL_AURA_ADD_CASTER_HIT_TRIGGER);
8789 for(AuraList::const_iterator i = hitTriggerAuras.begin(); i != hitTriggerAuras.end(); ++i)
8790 if(Unit* magnet = (*i)->GetCaster())
8791 if(magnet->isAlive() && magnet->IsWithinLOSInMap(this))
8792 if(roll_chance_i((*i)->GetModifier()->m_amount))
8793 return magnet;
8796 return victim;
8799 void Unit::SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, uint32 OverHeal, bool critical)
8801 // we guess size
8802 WorldPacket data(SMSG_SPELLHEALLOG, (8+8+4+4+1));
8803 data << pVictim->GetPackGUID();
8804 data << GetPackGUID();
8805 data << uint32(SpellID);
8806 data << uint32(Damage);
8807 data << uint32(OverHeal);
8808 data << uint8(critical ? 1 : 0);
8809 data << uint8(0); // unused in client?
8810 SendMessageToSet(&data, true);
8813 void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
8815 WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1));
8816 data << pVictim->GetPackGUID();
8817 data << GetPackGUID();
8818 data << uint32(SpellID);
8819 data << uint32(powertype);
8820 data << uint32(Damage);
8821 SendMessageToSet(&data, true);
8824 void Unit::EnergizeBySpell(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
8826 SendEnergizeSpellLog(pVictim, SpellID, Damage, powertype);
8827 // needs to be called after sending spell log
8828 pVictim->ModifyPower(powertype, Damage);
8831 uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack)
8833 if(!spellProto || !pVictim || damagetype==DIRECT_DAMAGE )
8834 return pdamage;
8836 // For totems get damage bonus from owner (statue isn't totem in fact)
8837 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
8839 if(Unit* owner = GetOwner())
8840 return owner->SpellDamageBonus(pVictim, spellProto, pdamage, damagetype);
8843 // Taken/Done total percent damage auras
8844 float DoneTotalMod = 1.0f;
8845 float TakenTotalMod = 1.0f;
8846 int32 DoneTotal = 0;
8847 int32 TakenTotal = 0;
8849 // ..done
8850 // Creature damage
8851 if( GetTypeId() == TYPEID_UNIT && !((Creature*)this)->isPet() )
8852 DoneTotalMod *= ((Creature*)this)->GetSpellDamageMod(((Creature*)this)->GetCreatureInfo()->rank);
8854 if (!(spellProto->AttributesEx6 & SPELL_ATTR_EX6_NO_DMG_PERCENT_MODS))
8856 AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
8857 for(AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
8859 if( ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto)) &&
8860 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
8861 // -1 == any item class (not wand then)
8862 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
8863 // 0 == any inventory type (not wand then)
8865 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8870 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8871 // Add flat bonus from spell damage versus
8872 DoneTotal += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask);
8873 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
8874 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
8875 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8876 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8878 // done scripted mod (take it from owner)
8879 Unit *owner = GetOwner();
8880 if (!owner) owner = this;
8881 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8882 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
8884 if (!(*i)->isAffectedOnSpell(spellProto))
8885 continue;
8886 switch((*i)->GetModifier()->m_miscvalue)
8888 case 4920: // Molten Fury
8889 case 4919:
8890 case 6917: // Death's Embrace
8891 case 6926:
8892 case 6928:
8894 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
8895 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
8896 break;
8898 // Soul Siphon
8899 case 4992:
8900 case 4993:
8902 // effect 1 m_amount
8903 int32 maxPercent = (*i)->GetModifier()->m_amount;
8904 // effect 0 m_amount
8905 int32 stepPercent = CalculateSpellDamage((*i)->GetSpellProto(), EFFECT_INDEX_0, (*i)->GetSpellProto()->EffectBasePoints[EFFECT_INDEX_0], this);
8906 // count affliction effects and calc additional damage in percentage
8907 int32 modPercent = 0;
8908 AuraMap const& victimAuras = pVictim->GetAuras();
8909 for (AuraMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
8911 SpellEntry const* m_spell = itr->second->GetSpellProto();
8912 if (m_spell->SpellFamilyName != SPELLFAMILY_WARLOCK || !(m_spell->SpellFamilyFlags & UI64LIT(0x0004071B8044C402)))
8913 continue;
8914 modPercent += stepPercent * itr->second->GetStackAmount();
8915 if (modPercent >= maxPercent)
8917 modPercent = maxPercent;
8918 break;
8921 DoneTotalMod *= (modPercent+100.0f)/100.0f;
8922 break;
8924 case 6916: // Death's Embrace
8925 case 6925:
8926 case 6927:
8927 if (HasAuraState(AURA_STATE_HEALTHLESS_20_PERCENT))
8928 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
8929 break;
8930 case 5481: // Starfire Bonus
8932 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, UI64LIT(0x0000000000200002)))
8933 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8934 break;
8936 case 4418: // Increased Shock Damage
8937 case 4554: // Increased Lightning Damage
8938 case 4555: // Improved Moonfire
8939 case 5142: // Increased Lightning Damage
8940 case 5147: // Improved Consecration / Libram of Resurgence
8941 case 5148: // Idol of the Shooting Star
8942 case 6008: // Increased Lightning Damage
8943 case 8627: // Totem of Hex
8945 DoneTotal+=(*i)->GetModifier()->m_amount;
8946 break;
8948 // Tundra Stalker
8949 // Merciless Combat
8950 case 7277:
8952 // Merciless Combat
8953 if ((*i)->GetSpellProto()->SpellIconID == 2656)
8955 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
8956 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
8958 else // Tundra Stalker
8960 // Frost Fever (target debuff)
8961 if (pVictim->GetAura(SPELL_AURA_MOD_HASTE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0000000000000000), 0x00000002))
8962 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8963 break;
8965 break;
8967 case 7293: // Rage of Rivendare
8969 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0200000000000000)))
8970 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8971 break;
8973 // Twisted Faith
8974 case 7377:
8976 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, UI64LIT(0x0000000000008000), 0, GetGUID()))
8977 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8978 break;
8980 // Marked for Death
8981 case 7598:
8982 case 7599:
8983 case 7600:
8984 case 7601:
8985 case 7602:
8987 if (pVictim->GetAura(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, UI64LIT(0x0000000000000400)))
8988 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8989 break;
8994 // Custom scripted damage
8995 switch(spellProto->SpellFamilyName)
8997 case SPELLFAMILY_MAGE:
8999 // Ice Lance
9000 if (spellProto->SpellIconID == 186)
9002 if (pVictim->isFrozen())
9004 float multiplier = 3.0f;
9006 // if target have higher level
9007 if (pVictim->getLevel() > getLevel())
9008 // Glyph of Ice Lance
9009 if (Aura* glyph = GetDummyAura(56377))
9010 multiplier = glyph->GetModifier()->m_amount;
9012 DoneTotalMod *= multiplier;
9015 // Torment the weak affected (Arcane Barrage, Arcane Blast, Frostfire Bolt, Arcane Missiles, Fireball)
9016 if ((spellProto->SpellFamilyFlags & UI64LIT(0x0000900020200021)) &&
9017 (pVictim->HasAuraType(SPELL_AURA_MOD_DECREASE_SPEED) || pVictim->HasAuraType(SPELL_AURA_MELEE_SLOW)))
9019 //Search for Torment the weak dummy aura
9020 Unit::AuraList const& ttw = GetAurasByType(SPELL_AURA_DUMMY);
9021 for(Unit::AuraList::const_iterator i = ttw.begin(); i != ttw.end(); ++i)
9023 if ((*i)->GetSpellProto()->SpellIconID == 3263)
9025 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f) / 100.0f;
9026 break;
9030 break;
9032 case SPELLFAMILY_WARLOCK:
9034 // Drain Soul
9035 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000004000))
9037 if (pVictim->GetHealth() * 100 / pVictim->GetMaxHealth() <= 25)
9038 DoneTotalMod *= 4;
9040 break;
9042 case SPELLFAMILY_PRIEST:
9044 // Glyph of Smite
9045 if (spellProto->SpellFamilyFlags & UI64LIT(0x00000080))
9047 // Holy Fire
9048 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, UI64LIT(0x00100000), NULL))
9049 if (Aura *aur = GetAura(55692, EFFECT_INDEX_0))
9050 DoneTotalMod *= (aur->GetModifier()->m_amount+100.0f) / 100.0f;
9052 break;
9054 case SPELLFAMILY_DEATHKNIGHT:
9056 // Icy Touch, Howling Blast and Frost Strike
9057 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000600000002))
9059 // search disease
9060 bool found = false;
9061 Unit::AuraMap const& auras = pVictim->GetAuras();
9062 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr)
9064 if(itr->second->GetSpellProto()->Dispel == DISPEL_DISEASE)
9066 found = true;
9067 break;
9070 if(!found)
9071 break;
9073 // search for Glacier Rot dummy aura
9074 Unit::AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
9075 for(Unit::AuraList::const_iterator i = dummyAuras.begin(); i != dummyAuras.end(); ++i)
9077 if ((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()] == 7244)
9079 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f) / 100.0f;
9080 break;
9084 break;
9086 default:
9087 break;
9091 // ..taken
9092 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
9093 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
9095 if ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto))
9096 TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
9099 // .. taken pct: dummy auras
9100 if (pVictim->GetTypeId() == TYPEID_PLAYER)
9102 //Cheat Death
9103 if (Aura *dummy = pVictim->GetDummyAura(45182))
9105 float mod = -((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2*4;
9106 if (mod < float(dummy->GetModifier()->m_amount))
9107 mod = float(dummy->GetModifier()->m_amount);
9108 TakenTotalMod *= (mod+100.0f)/100.0f;
9112 // From caster spells
9113 AuraList const& mOwnerTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_FROM_CASTER);
9114 for(AuraList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i)
9116 if ((*i)->GetCasterGUID() == GetGUID() && (*i)->isAffectedOnSpell(spellProto))
9117 TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
9120 // Mod damage from spell mechanic
9121 TakenTotalMod *= pVictim->GetTotalAuraMultiplierByMiscValueForMask(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT,GetAllSpellMechanicMask(spellProto));
9123 // Mod damage taken from AoE spells
9124 if(IsAreaOfEffectSpell(spellProto))
9126 AuraList const& avoidAuras = pVictim->GetAurasByType(SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE);
9127 for(AuraList::const_iterator itr = avoidAuras.begin(); itr != avoidAuras.end(); ++itr)
9128 TakenTotalMod *= ((*itr)->GetModifier()->m_amount + 100.0f) / 100.0f;
9131 // Taken/Done fixed damage bonus auras
9132 int32 DoneAdvertisedBenefit = SpellBaseDamageBonus(GetSpellSchoolMask(spellProto));
9133 int32 TakenAdvertisedBenefit = SpellBaseDamageBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
9135 // Pets just add their bonus damage to their spell damage
9136 // note that their spell damage is just gain of their own auras
9137 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
9138 DoneAdvertisedBenefit += ((Pet*)this)->GetBonusDamage();
9140 float LvlPenalty = CalculateLevelPenalty(spellProto);
9141 // Spellmod SpellDamage
9142 float SpellModSpellDamage = 100.0f;
9143 if(Player* modOwner = GetSpellModOwner())
9144 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_SPELL_BONUS_DAMAGE,SpellModSpellDamage);
9145 SpellModSpellDamage /= 100.0f;
9147 // Check for table values
9148 if (SpellBonusEntry const* bonus = sSpellMgr.GetSpellBonusData(spellProto->Id))
9150 float coeff;
9151 if (damagetype == DOT)
9152 coeff = bonus->dot_damage * LvlPenalty * stack;
9153 else
9154 coeff = bonus->direct_damage * LvlPenalty * stack;
9156 if (bonus->ap_bonus)
9157 DoneTotal += int32(bonus->ap_bonus * GetTotalAttackPowerValue(BASE_ATTACK) * stack);
9159 DoneTotal += int32(DoneAdvertisedBenefit * coeff * SpellModSpellDamage);
9160 TakenTotal += int32(TakenAdvertisedBenefit * coeff);
9162 // Default calculation
9163 else if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
9165 // Damage over Time spells bonus calculation
9166 float DotFactor = 1.0f;
9167 if (damagetype == DOT)
9169 if (!IsChanneledSpell(spellProto))
9170 DotFactor = GetSpellDuration(spellProto) / 15000.0f;
9172 if (uint16 DotTicks = GetSpellAuraMaxTicks(spellProto))
9174 DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
9175 TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
9178 // Distribute Damage over multiple effects, reduce by AoE
9179 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
9180 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
9181 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
9182 for(int j = 0; j < MAX_EFFECT_INDEX; ++j)
9184 if (spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
9185 (spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA &&
9186 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH))
9188 CastingTime /= 2;
9189 break;
9192 DoneTotal += int32(DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * SpellModSpellDamage);
9193 TakenTotal+= int32(TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty);
9196 float tmpDamage = (pdamage + DoneTotal) * DoneTotalMod;
9197 // apply spellmod to Done damage (flat and pct)
9198 if(Player* modOwner = GetSpellModOwner())
9199 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
9201 tmpDamage = (tmpDamage + TakenTotal) * TakenTotalMod;
9203 return tmpDamage > 0 ? uint32(tmpDamage) : 0;
9206 int32 Unit::SpellBaseDamageBonus(SpellSchoolMask schoolMask)
9208 int32 DoneAdvertisedBenefit = 0;
9210 // ..done
9211 AuraList const& mDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
9212 for(AuraList::const_iterator i = mDamageDone.begin();i != mDamageDone.end(); ++i)
9214 if (((*i)->GetModifier()->m_miscvalue & schoolMask) != 0 &&
9215 (*i)->GetSpellProto()->EquippedItemClass == -1 && // -1 == any item class (not wand then)
9216 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0) // 0 == any inventory type (not wand then)
9217 DoneAdvertisedBenefit += (*i)->GetModifier()->m_amount;
9220 if (GetTypeId() == TYPEID_PLAYER)
9222 // Base value
9223 DoneAdvertisedBenefit +=((Player*)this)->GetBaseSpellPowerBonus();
9225 // Damage bonus from stats
9226 AuraList const& mDamageDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT);
9227 for(AuraList::const_iterator i = mDamageDoneOfStatPercent.begin();i != mDamageDoneOfStatPercent.end(); ++i)
9229 if((*i)->GetModifier()->m_miscvalue & schoolMask)
9231 // stat used stored in miscValueB for this aura
9232 Stats usedStat = Stats((*i)->GetMiscBValue());
9233 DoneAdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
9236 // ... and attack power
9237 AuraList const& mDamageDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER);
9238 for(AuraList::const_iterator i =mDamageDonebyAP.begin();i != mDamageDonebyAP.end(); ++i)
9240 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
9241 DoneAdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
9245 return DoneAdvertisedBenefit;
9248 int32 Unit::SpellBaseDamageBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
9250 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
9252 int32 TakenAdvertisedBenefit = 0;
9253 // ..done (for creature type by mask) in taken
9254 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
9255 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
9257 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
9258 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
9261 // ..taken
9262 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
9263 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
9265 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
9266 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
9269 return TakenAdvertisedBenefit;
9272 bool Unit::isSpellCrit(Unit *pVictim, SpellEntry const *spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType)
9274 // not critting spell
9275 if((spellProto->AttributesEx2 & SPELL_ATTR_EX2_CANT_CRIT))
9276 return false;
9278 float crit_chance = 0.0f;
9279 switch(spellProto->DmgClass)
9281 case SPELL_DAMAGE_CLASS_NONE:
9282 return false;
9283 case SPELL_DAMAGE_CLASS_MAGIC:
9285 if (schoolMask & SPELL_SCHOOL_MASK_NORMAL)
9286 crit_chance = 0.0f;
9287 // For other schools
9288 else if (GetTypeId() == TYPEID_PLAYER)
9289 crit_chance = GetFloatValue( PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask));
9290 else
9292 crit_chance = float(m_baseSpellCritChance);
9293 crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
9295 // taken
9296 if (pVictim)
9298 if (!IsPositiveSpell(spellProto->Id))
9300 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE
9301 crit_chance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask);
9302 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE
9303 crit_chance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
9304 // Modify by player victim resilience
9305 crit_chance -= pVictim->GetSpellCritChanceReduction();
9308 // scripted (increase crit chance ... against ... target by x%)
9309 // scripted (Increases the critical effect chance of your .... by x% on targets ...)
9310 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
9311 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
9313 if (!((*i)->isAffectedOnSpell(spellProto)))
9314 continue;
9315 switch((*i)->GetModifier()->m_miscvalue)
9317 case 849: if (pVictim->isFrozen()) crit_chance+= 17.0f; break; //Shatter Rank 1
9318 case 910: if (pVictim->isFrozen()) crit_chance+= 34.0f; break; //Shatter Rank 2
9319 case 911: if (pVictim->isFrozen()) crit_chance+= 50.0f; break; //Shatter Rank 3
9320 case 7917: // Glyph of Shadowburn
9321 if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
9322 crit_chance+=(*i)->GetModifier()->m_amount;
9323 break;
9324 case 7997: // Renewed Hope
9325 case 7998:
9326 if (pVictim->HasAura(6788))
9327 crit_chance+=(*i)->GetModifier()->m_amount;
9328 break;
9329 default:
9330 break;
9333 // Custom crit by class
9334 switch(spellProto->SpellFamilyName)
9336 case SPELLFAMILY_PRIEST:
9337 // Flash Heal
9338 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000800))
9340 if (pVictim->GetHealth() > pVictim->GetMaxHealth()/2)
9341 break;
9342 AuraList const& mDummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
9343 for(AuraList::const_iterator i = mDummyAuras.begin(); i!= mDummyAuras.end(); ++i)
9345 // Improved Flash Heal
9346 if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_PRIEST &&
9347 (*i)->GetSpellProto()->SpellIconID == 2542)
9349 crit_chance+=(*i)->GetModifier()->m_amount;
9350 break;
9354 break;
9355 case SPELLFAMILY_PALADIN:
9356 // Sacred Shield
9357 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000040000000))
9359 Aura *aura = pVictim->GetDummyAura(58597);
9360 if (aura && aura->GetCasterGUID() == GetGUID())
9361 crit_chance+=aura->GetModifier()->m_amount;
9363 // Exorcism
9364 else if (spellProto->Category == 19)
9366 if (pVictim->GetCreatureTypeMask() & CREATURE_TYPEMASK_DEMON_OR_UNDEAD)
9367 return true;
9369 break;
9370 case SPELLFAMILY_SHAMAN:
9371 // Lava Burst
9372 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000100000000000))
9374 // Flame Shock
9375 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, UI64LIT(0x0000000010000000), 0, GetGUID()))
9376 return true;
9378 break;
9381 break;
9383 case SPELL_DAMAGE_CLASS_MELEE:
9384 case SPELL_DAMAGE_CLASS_RANGED:
9386 if (pVictim)
9387 crit_chance = GetUnitCriticalChance(attackType, pVictim);
9389 crit_chance+= GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
9390 break;
9392 default:
9393 return false;
9395 // percent done
9396 // only players use intelligence for critical chance computations
9397 if(Player* modOwner = GetSpellModOwner())
9398 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance);
9400 crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f;
9401 if (roll_chance_f(crit_chance))
9402 return true;
9403 return false;
9406 uint32 Unit::SpellCriticalDamageBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
9408 // Calculate critical bonus
9409 int32 crit_bonus;
9410 switch(spellProto->DmgClass)
9412 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
9413 case SPELL_DAMAGE_CLASS_RANGED:
9414 crit_bonus = damage;
9415 break;
9416 default:
9417 crit_bonus = damage / 2; // for spells is 50%
9418 break;
9421 // adds additional damage to crit_bonus (from talents)
9422 if(Player* modOwner = GetSpellModOwner())
9423 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
9425 if(!pVictim)
9426 return damage += crit_bonus;
9428 int32 critPctDamageMod = 0;
9429 if(spellProto->DmgClass >= SPELL_DAMAGE_CLASS_MELEE)
9431 if(GetWeaponAttackType(spellProto) == RANGED_ATTACK)
9432 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
9433 else
9434 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
9436 else
9437 critPctDamageMod += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_DAMAGE,GetSpellSchoolMask(spellProto));
9439 critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS, GetSpellSchoolMask(spellProto));
9441 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
9442 critPctDamageMod += GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask);
9444 if(critPctDamageMod!=0)
9445 crit_bonus = int32(crit_bonus * float((100.0f + critPctDamageMod)/100.0f));
9447 if(crit_bonus > 0)
9448 damage += crit_bonus;
9450 return damage;
9453 uint32 Unit::SpellCriticalHealingBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
9455 // Calculate critical bonus
9456 int32 crit_bonus;
9457 switch(spellProto->DmgClass)
9459 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
9460 case SPELL_DAMAGE_CLASS_RANGED:
9461 // TODO: write here full calculation for melee/ranged spells
9462 crit_bonus = damage;
9463 break;
9464 default:
9465 crit_bonus = damage / 2; // for spells is 50%
9466 break;
9469 if(pVictim)
9471 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
9472 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
9475 if(crit_bonus > 0)
9476 damage += crit_bonus;
9478 damage = int32(damage * GetTotalAuraMultiplier(SPELL_AURA_MOD_CRITICAL_HEALING_AMOUNT));
9480 return damage;
9483 int32 Unit::SpellHealingBonus(Unit *pVictim, SpellEntry const *spellProto, int32 healamount, DamageEffectType damagetype, uint32 stack)
9485 // For totems get healing bonus from owner (statue isn't totem in fact)
9486 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
9487 if(Unit* owner = GetOwner())
9488 return owner->SpellHealingBonus(pVictim, spellProto, healamount, damagetype, stack);
9490 float TakenTotalMod = 1.0f;
9492 // Healing taken percent
9493 float minval = float(pVictim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT));
9494 if(minval)
9495 TakenTotalMod *= (100.0f + minval) / 100.0f;
9497 float maxval = float(pVictim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT));
9498 if(maxval)
9499 TakenTotalMod *= (100.0f + maxval) / 100.0f;
9501 // No heal amount for this class spells
9502 if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE)
9504 healamount = int32(healamount * TakenTotalMod);
9505 return healamount < 0 ? 0 : healamount;
9508 // Healing Done
9509 // Taken/Done total percent damage auras
9510 float DoneTotalMod = 1.0f;
9511 int32 DoneTotal = 0;
9512 int32 TakenTotal = 0;
9514 // Healing done percent
9515 AuraList const& mHealingDonePct = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT);
9516 for(AuraList::const_iterator i = mHealingDonePct.begin();i != mHealingDonePct.end(); ++i)
9517 DoneTotalMod *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
9519 // done scripted mod (take it from owner)
9520 Unit *owner = GetOwner();
9521 if (!owner) owner = this;
9522 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
9523 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
9525 if (!(*i)->isAffectedOnSpell(spellProto))
9526 continue;
9527 switch((*i)->GetModifier()->m_miscvalue)
9529 case 4415: // Increased Rejuvenation Healing
9530 case 4953:
9531 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
9532 DoneTotal+=(*i)->GetModifier()->m_amount;
9533 break;
9534 case 7997: // Renewed Hope
9535 case 7998:
9536 if (pVictim->HasAura(6788))
9537 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
9538 break;
9539 case 21: // Test of Faith
9540 case 6935:
9541 case 6918:
9542 if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
9543 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
9544 break;
9545 case 7798: // Glyph of Regrowth
9547 if (pVictim->GetAura(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, UI64LIT(0x0000000000000040)))
9548 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9549 break;
9551 case 8477: // Nourish Heal Boost
9553 int32 stepPercent = (*i)->GetModifier()->m_amount;
9555 int ownHotCount = 0; // counted HoT types amount, not stacks
9557 Unit::AuraList const& RejorRegr = pVictim->GetAurasByType(SPELL_AURA_PERIODIC_HEAL);
9558 for(Unit::AuraList::const_iterator i = RejorRegr.begin(); i != RejorRegr.end(); ++i)
9559 if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_DRUID &&
9560 (*i)->GetCasterGUID() == GetGUID())
9561 ++ownHotCount;
9563 if (ownHotCount)
9564 TakenTotalMod *= (stepPercent * ownHotCount + 100.0f) / 100.0f;
9565 break;
9567 case 7871: // Glyph of Lesser Healing Wave
9569 if (pVictim->GetAura(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, UI64LIT(0x0000040000000000), 0, GetGUID()))
9570 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9571 break;
9573 default:
9574 break;
9578 // Taken/Done fixed damage bonus auras
9579 int32 DoneAdvertisedBenefit = SpellBaseHealingBonus(GetSpellSchoolMask(spellProto));
9580 int32 TakenAdvertisedBenefit = SpellBaseHealingBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
9582 float LvlPenalty = CalculateLevelPenalty(spellProto);
9583 // Spellmod SpellDamage
9584 float SpellModSpellDamage = 100.0f;
9585 if(Player* modOwner = GetSpellModOwner())
9586 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_SPELL_BONUS_DAMAGE, SpellModSpellDamage);
9587 SpellModSpellDamage /= 100.0f;
9589 // Check for table values
9590 SpellBonusEntry const* bonus = sSpellMgr.GetSpellBonusData(spellProto->Id);
9591 if (bonus)
9593 float coeff;
9594 if (damagetype == DOT)
9595 coeff = bonus->dot_damage * LvlPenalty * stack;
9596 else
9597 coeff = bonus->direct_damage * LvlPenalty * stack;
9599 if (bonus->ap_bonus)
9600 DoneTotal += int32(bonus->ap_bonus * GetTotalAttackPowerValue(BASE_ATTACK) * stack);
9602 DoneTotal += int32(DoneAdvertisedBenefit * coeff * SpellModSpellDamage);
9603 TakenTotal += int32(TakenAdvertisedBenefit * coeff);
9605 // Default calculation
9606 else if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
9608 // Damage over Time spells bonus calculation
9609 float DotFactor = 1.0f;
9610 if(damagetype == DOT)
9612 if(!IsChanneledSpell(spellProto))
9613 DotFactor = GetSpellDuration(spellProto) / 15000.0f;
9614 uint16 DotTicks = GetSpellAuraMaxTicks(spellProto);
9615 if(DotTicks)
9617 DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
9618 TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
9621 // Distribute Damage over multiple effects, reduce by AoE
9622 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
9623 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
9624 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
9625 for(int j = 0; j < MAX_EFFECT_INDEX; ++j)
9627 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
9628 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
9630 CastingTime /= 2;
9631 break;
9634 DoneTotal += int32(DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * SpellModSpellDamage * 1.88f);
9635 TakenTotal += int32(TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * 1.88f);
9638 // use float as more appropriate for negative values and percent applying
9639 float heal = (healamount + DoneTotal)*DoneTotalMod;
9640 // apply spellmod to Done amount
9641 if(Player* modOwner = GetSpellModOwner())
9642 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal);
9644 // Taken mods
9645 // Healing Wave cast
9646 if (spellProto->SpellFamilyName == SPELLFAMILY_SHAMAN && (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000040)))
9648 // Search for Healing Way on Victim
9649 Unit::AuraList const& auraDummy = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
9650 for(Unit::AuraList::const_iterator itr = auraDummy.begin(); itr!=auraDummy.end(); ++itr)
9651 if((*itr)->GetId() == 29203)
9652 TakenTotalMod *= ((*itr)->GetModifier()->m_amount+100.0f) / 100.0f;
9654 // Nourish 20% of heal increase if target is affected by Druids HOTs
9655 else if (spellProto->SpellFamilyName == SPELLFAMILY_DRUID && (spellProto->SpellFamilyFlags & UI64LIT(0x0200000000000000)))
9657 int ownHotCount = 0; // counted HoT types amount, not stacks
9658 Unit::AuraList const& RejorRegr = pVictim->GetAurasByType(SPELL_AURA_PERIODIC_HEAL);
9659 for(Unit::AuraList::const_iterator i = RejorRegr.begin(); i != RejorRegr.end(); ++i)
9660 if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_DRUID &&
9661 (*i)->GetCasterGUID() == GetGUID())
9662 ++ownHotCount;
9664 if (ownHotCount)
9666 TakenTotalMod *= 1.2f; // base bonus at HoTs
9668 if (Aura* glyph = GetAura(62971, EFFECT_INDEX_0))// Glyph of Nourish
9669 TakenTotalMod *= (glyph->GetModifier()->m_amount * ownHotCount + 100.0f) / 100.0f;
9674 AuraList const& mHealingGet= pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING_RECEIVED);
9675 for(AuraList::const_iterator i = mHealingGet.begin(); i != mHealingGet.end(); ++i)
9676 if ((*i)->isAffectedOnSpell(spellProto))
9677 TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
9679 heal = (heal + TakenTotal) * TakenTotalMod;
9681 return heal < 0 ? 0 : uint32(heal);
9684 int32 Unit::SpellBaseHealingBonus(SpellSchoolMask schoolMask)
9686 int32 AdvertisedBenefit = 0;
9688 AuraList const& mHealingDone = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE);
9689 for(AuraList::const_iterator i = mHealingDone.begin();i != mHealingDone.end(); ++i)
9690 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
9691 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
9693 // Healing bonus of spirit, intellect and strength
9694 if (GetTypeId() == TYPEID_PLAYER)
9696 // Base value
9697 AdvertisedBenefit +=((Player*)this)->GetBaseSpellPowerBonus();
9699 // Healing bonus from stats
9700 AuraList const& mHealingDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT);
9701 for(AuraList::const_iterator i = mHealingDoneOfStatPercent.begin();i != mHealingDoneOfStatPercent.end(); ++i)
9703 // stat used dependent from misc value (stat index)
9704 Stats usedStat = Stats((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()]);
9705 AdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
9708 // ... and attack power
9709 AuraList const& mHealingDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER);
9710 for(AuraList::const_iterator i = mHealingDonebyAP.begin();i != mHealingDonebyAP.end(); ++i)
9711 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
9712 AdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
9714 return AdvertisedBenefit;
9717 int32 Unit::SpellBaseHealingBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
9719 int32 AdvertisedBenefit = 0;
9720 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING);
9721 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
9722 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
9723 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
9725 return AdvertisedBenefit;
9728 bool Unit::IsImmunedToDamage(SpellSchoolMask shoolMask)
9730 //If m_immuneToSchool type contain this school type, IMMUNE damage.
9731 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
9732 for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
9733 if (itr->type & shoolMask)
9734 return true;
9736 //If m_immuneToDamage type contain magic, IMMUNE damage.
9737 SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
9738 for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
9739 if (itr->type & shoolMask)
9740 return true;
9742 return false;
9745 bool Unit::IsImmunedToSpell(SpellEntry const* spellInfo)
9747 if (!spellInfo)
9748 return false;
9750 //TODO add spellEffect immunity checks!, player with flag in bg is imune to imunity buffs from other friendly players!
9751 //SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_EFFECT];
9753 SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_DISPEL];
9754 for(SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr)
9755 if (itr->type == spellInfo->Dispel)
9756 return true;
9758 if (!(spellInfo->AttributesEx & SPELL_ATTR_EX_UNAFFECTED_BY_SCHOOL_IMMUNE) && // unaffected by school immunity
9759 !(spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)) // can remove immune (by dispell or immune it)
9761 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
9762 for(SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
9763 if (!(IsPositiveSpell(itr->spellId) && IsPositiveSpell(spellInfo->Id)) &&
9764 (itr->type & GetSpellSchoolMask(spellInfo)))
9765 return true;
9768 if(uint32 mechanic = spellInfo->Mechanic)
9770 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
9771 for(SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
9772 if (itr->type == mechanic)
9773 return true;
9775 AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MECHANIC_IMMUNITY_MASK);
9776 for(AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
9777 if ((*iter)->GetModifier()->m_miscvalue & (1 << (mechanic-1)))
9778 return true;
9781 return false;
9784 bool Unit::IsImmunedToSpellEffect(SpellEntry const* spellInfo, SpellEffectIndex index) const
9786 //If m_immuneToEffect type contain this effect type, IMMUNE effect.
9787 uint32 effect = spellInfo->Effect[index];
9788 SpellImmuneList const& effectList = m_spellImmune[IMMUNITY_EFFECT];
9789 for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr)
9790 if (itr->type == effect)
9791 return true;
9793 if(uint32 mechanic = spellInfo->EffectMechanic[index])
9795 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
9796 for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
9797 if (itr->type == mechanic)
9798 return true;
9800 AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MECHANIC_IMMUNITY_MASK);
9801 for(AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
9802 if ((*iter)->GetModifier()->m_miscvalue & (1 << (mechanic-1)))
9803 return true;
9806 if(uint32 aura = spellInfo->EffectApplyAuraName[index])
9808 SpellImmuneList const& list = m_spellImmune[IMMUNITY_STATE];
9809 for(SpellImmuneList::const_iterator itr = list.begin(); itr != list.end(); ++itr)
9810 if (itr->type == aura)
9811 return true;
9813 // Check for immune to application of harmful magical effects
9814 AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MOD_IMMUNE_AURA_APPLY_SCHOOL);
9815 for(AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
9816 if (spellInfo->Dispel == DISPEL_MAGIC && // Magic debuff
9817 ((*iter)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellInfo)) && // Check school
9818 !IsPositiveEffect(spellInfo->Id, index)) // Harmful
9819 return true;
9822 return false;
9825 bool Unit::IsDamageToThreatSpell(SpellEntry const * spellInfo) const
9827 if (!spellInfo)
9828 return false;
9830 uint32 family = spellInfo->SpellFamilyName;
9831 uint64 flags = spellInfo->SpellFamilyFlags;
9833 if ((family == 5 && flags == 256) || //Searing Pain
9834 (family == 6 && flags == 8192) || //Mind Blast
9835 (family == 11 && flags == 1048576)) //Earth Shock
9836 return true;
9838 return false;
9841 uint32 Unit::MeleeDamageBonus(Unit *pVictim, uint32 pdamage,WeaponAttackType attType, SpellEntry const *spellProto, DamageEffectType damagetype, uint32 stack)
9843 if (!pVictim)
9844 return pdamage;
9846 if (pdamage == 0)
9847 return pdamage;
9849 // differentiate for weapon damage based spells
9850 bool isWeaponDamageBasedSpell = !(spellProto && (damagetype == DOT || IsSpellHaveEffect(spellProto, SPELL_EFFECT_SCHOOL_DAMAGE)));
9851 Item* pWeapon = GetTypeId() == TYPEID_PLAYER ? ((Player*)this)->GetWeaponForAttack(attType,true,false) : NULL;
9852 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
9853 uint32 schoolMask = spellProto ? spellProto->SchoolMask : GetMeleeDamageSchoolMask();
9854 uint32 mechanicMask = spellProto ? GetAllSpellMechanicMask(spellProto) : 0;
9856 // Shred also have bonus as MECHANIC_BLEED damages
9857 if (spellProto && spellProto->SpellFamilyName==SPELLFAMILY_DRUID && spellProto->SpellFamilyFlags & UI64LIT(0x00008000))
9858 mechanicMask |= (1 << (MECHANIC_BLEED-1));
9861 // FLAT damage bonus auras
9862 // =======================
9863 int32 DoneFlat = 0;
9864 int32 TakenFlat = 0;
9865 int32 APbonus = 0;
9867 // ..done flat, already included in wepon damage based spells
9868 if (!isWeaponDamageBasedSpell)
9870 AuraList const& mModDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
9871 for(AuraList::const_iterator i = mModDamageDone.begin(); i != mModDamageDone.end(); ++i)
9873 if ((*i)->GetModifier()->m_miscvalue & schoolMask && // schoolmask has to fit with the intrinsic spell school
9874 (*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask() && // AND schoolmask has to fit with weapon damage school (essential for non-physical spells)
9875 ((*i)->GetSpellProto()->EquippedItemClass == -1 || // general, weapon independent
9876 pWeapon && pWeapon->IsFitToSpellRequirements((*i)->GetSpellProto()))) // OR used weapon fits aura requirements
9878 DoneFlat += (*i)->GetModifier()->m_amount;
9882 // Pets just add their bonus damage to their melee damage
9883 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
9884 DoneFlat += ((Pet*)this)->GetBonusDamage();
9887 // ..done flat (by creature type mask)
9888 DoneFlat += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE, creatureTypeMask);
9890 // ..done flat (base at attack power for marked target and base at attack power for creature type)
9891 if (attType == RANGED_ATTACK)
9893 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS);
9894 APbonus += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS, creatureTypeMask);
9895 TakenFlat += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN);
9897 else
9899 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS);
9900 APbonus += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS, creatureTypeMask);
9901 TakenFlat += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN);
9904 // ..taken flat (by school mask)
9905 TakenFlat += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_DAMAGE_TAKEN, schoolMask);
9907 // PERCENT damage auras
9908 // ====================
9909 float DonePercent = 1.0f;
9910 float TakenPercent = 1.0f;
9912 // ..done pct, already included in weapon damage based spells
9913 if(!isWeaponDamageBasedSpell)
9915 AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
9916 for(AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
9918 if ((*i)->GetModifier()->m_miscvalue & schoolMask && // schoolmask has to fit with the intrinsic spell school
9919 (*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask() && // AND schoolmask has to fit with weapon damage school (essential for non-physical spells)
9920 ((*i)->GetSpellProto()->EquippedItemClass == -1 || // general, weapon independent
9921 pWeapon && pWeapon->IsFitToSpellRequirements((*i)->GetSpellProto()))) // OR used weapon fits aura requirements
9923 DonePercent *= ((*i)->GetModifier()->m_amount+100.0f) / 100.0f;
9927 if (attType == OFF_ATTACK)
9928 DonePercent *= GetModifierValue(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_PCT); // no school check required
9931 // ..done pct (by creature type mask)
9932 DonePercent *= GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS, creatureTypeMask);
9934 // ..taken pct (by school mask)
9935 TakenPercent *= pVictim->GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN, schoolMask);
9937 // ..taken pct (by mechanic mask)
9938 TakenPercent *= pVictim->GetTotalAuraMultiplierByMiscValueForMask(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT,mechanicMask);
9940 // ..taken pct (melee/ranged)
9941 if(attType == RANGED_ATTACK)
9942 TakenPercent *= pVictim->GetTotalAuraMultiplier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT);
9943 else
9944 TakenPercent *= pVictim->GetTotalAuraMultiplier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT);
9946 // ..taken pct (aoe avoidance)
9947 if(spellProto && IsAreaOfEffectSpell(spellProto))
9948 TakenPercent *= pVictim->GetTotalAuraMultiplier(SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE);
9951 // special dummys/class sripts and other effects
9952 // =============================================
9953 Unit *owner = GetOwner();
9954 if (!owner)
9955 owner = this;
9957 // ..done (class scripts)
9958 if(spellProto)
9960 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
9961 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
9963 if (!(*i)->isAffectedOnSpell(spellProto))
9964 continue;
9966 switch((*i)->GetModifier()->m_miscvalue)
9968 // Tundra Stalker
9969 // Merciless Combat
9970 case 7277:
9972 // Merciless Combat
9973 if ((*i)->GetSpellProto()->SpellIconID == 2656)
9975 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
9976 DonePercent *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
9978 else // Tundra Stalker
9980 // Frost Fever (target debuff)
9981 if (pVictim->GetAura(SPELL_AURA_MOD_HASTE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0000000000000000), 0x00000002))
9982 DonePercent *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9983 break;
9985 break;
9987 case 7293: // Rage of Rivendare
9989 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0200000000000000)))
9990 DonePercent *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9991 break;
9993 // Marked for Death
9994 case 7598:
9995 case 7599:
9996 case 7600:
9997 case 7601:
9998 case 7602:
10000 if (pVictim->GetAura(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, UI64LIT(0x0000000000000400)))
10001 DonePercent *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
10002 break;
10008 // .. taken (dummy auras)
10009 AuraList const& mDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
10010 for(AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
10012 switch((*i)->GetSpellProto()->SpellIconID)
10014 //Cheat Death
10015 case 2109:
10016 if((*i)->GetModifier()->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)
10018 if(pVictim->GetTypeId() != TYPEID_PLAYER)
10019 continue;
10021 float mod = ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f);
10022 if (mod < float((*i)->GetModifier()->m_amount))
10023 mod = float((*i)->GetModifier()->m_amount);
10025 TakenPercent *= (mod + 100.0f) / 100.0f;
10027 break;
10031 // .. taken (class scripts)
10032 AuraList const& mclassScritAuras = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
10033 for(AuraList::const_iterator i = mclassScritAuras.begin(); i != mclassScritAuras.end(); ++i)
10035 switch((*i)->GetMiscValue())
10037 // Dirty Deeds
10038 case 6427:
10039 case 6428:
10040 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
10042 Aura* eff0 = GetAura((*i)->GetId(), EFFECT_INDEX_0);
10043 if (!eff0 || (*i)->GetEffIndex() != EFFECT_INDEX_1)
10045 sLog.outError("Spell structure of DD (%u) changed.",(*i)->GetId());
10046 continue;
10049 // effect 0 have expected value but in negative state
10050 TakenPercent *= (-eff0->GetModifier()->m_amount + 100.0f) / 100.0f;
10052 break;
10057 // final calculation
10058 // =================
10060 // scaling of non weapon based spells
10061 if (!isWeaponDamageBasedSpell)
10063 float LvlPenalty = CalculateLevelPenalty(spellProto);
10065 // Check for table values
10066 if (SpellBonusEntry const* bonus = sSpellMgr.GetSpellBonusData(spellProto->Id))
10068 float coeff;
10069 if (damagetype == DOT)
10070 coeff = bonus->dot_damage * LvlPenalty * stack;
10071 else
10072 coeff = bonus->direct_damage * LvlPenalty * stack;
10074 if (bonus->ap_bonus)
10075 DoneFlat += bonus->ap_bonus * (GetTotalAttackPowerValue(BASE_ATTACK) + APbonus) * stack;
10077 DoneFlat *= coeff;
10078 TakenFlat *= coeff;
10080 // Default calculation
10081 else if (DoneFlat || TakenFlat)
10083 // Damage over Time spells bonus calculation
10084 float DotFactor = 1.0f;
10085 if(damagetype == DOT)
10087 if(!IsChanneledSpell(spellProto))
10088 DotFactor = GetSpellDuration(spellProto) / 15000.0f;
10089 uint16 DotTicks = GetSpellAuraMaxTicks(spellProto);
10090 if(DotTicks)
10092 DoneFlat = DoneFlat * int32(stack) / DotTicks;
10093 TakenFlat = TakenFlat * int32(stack) / DotTicks;
10096 // Distribute Damage over multiple effects, reduce by AoE
10097 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
10098 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
10099 DoneFlat *= (CastingTime / 3500.0f) * DotFactor * LvlPenalty;
10100 TakenFlat*= (CastingTime / 3500.0f) * DotFactor * LvlPenalty;
10103 // weapon damage based spells
10104 else if( APbonus || DoneFlat )
10106 bool normalized = spellProto ? IsSpellHaveEffect(spellProto, SPELL_EFFECT_NORMALIZED_WEAPON_DMG) : false;
10107 DoneFlat += int32(APbonus / 14.0f * GetAPMultiplier(attType,normalized));
10109 // for weapon damage based spells we still have to apply damage done percent mods
10110 // (that are already included into pdamage) to not-yet included DoneFlat
10111 // e.g. from doneVersusCreature, apBonusVs...
10112 UnitMods unitMod;
10113 switch(attType)
10115 default:
10116 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
10117 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
10118 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
10121 DoneFlat *= GetModifierValue(unitMod, TOTAL_PCT);
10124 float tmpDamage = float(int32(pdamage) + DoneFlat) * DonePercent;
10126 // apply spellmod to Done damage
10127 if(spellProto)
10129 if(Player* modOwner = GetSpellModOwner())
10130 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
10133 tmpDamage = (tmpDamage + TakenFlat) * TakenPercent;
10135 // bonus result can be negative
10136 return tmpDamage > 0 ? uint32(tmpDamage) : 0;
10139 void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply)
10141 if (apply)
10143 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(), next; itr != m_spellImmune[op].end(); itr = next)
10145 next = itr; ++next;
10146 if(itr->type == type)
10148 m_spellImmune[op].erase(itr);
10149 next = m_spellImmune[op].begin();
10152 SpellImmune Immune;
10153 Immune.spellId = spellId;
10154 Immune.type = type;
10155 m_spellImmune[op].push_back(Immune);
10157 else
10159 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(); itr != m_spellImmune[op].end(); ++itr)
10161 if(itr->spellId == spellId)
10163 m_spellImmune[op].erase(itr);
10164 break;
10171 void Unit::ApplySpellDispelImmunity(const SpellEntry * spellProto, DispelType type, bool apply)
10173 ApplySpellImmune(spellProto->Id,IMMUNITY_DISPEL, type, apply);
10175 if (apply && spellProto->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)
10176 RemoveAurasWithDispelType(type);
10179 float Unit::GetWeaponProcChance() const
10181 // normalized proc chance for weapon attack speed
10182 // (odd formula...)
10183 if (isAttackReady(BASE_ATTACK))
10184 return (GetAttackTime(BASE_ATTACK) * 1.8f / 1000.0f);
10185 else if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
10186 return (GetAttackTime(OFF_ATTACK) * 1.6f / 1000.0f);
10188 return 0.0f;
10191 float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM) const
10193 // proc per minute chance calculation
10194 if (PPM <= 0.0f)
10195 return 0.0f;
10196 return WeaponSpeed * PPM / 600.0f; // result is chance in percents (probability = Speed_in_sec * (PPM / 60))
10199 void Unit::Mount(uint32 mount, uint32 spellId)
10201 if (!mount)
10202 return;
10204 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNTING);
10206 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount);
10208 SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
10210 if (GetTypeId() == TYPEID_PLAYER)
10212 // Called by Taxi system / GM command
10213 if (!spellId)
10214 ((Player*)this)->UnsummonPetTemporaryIfAny();
10215 // Called by mount aura
10216 else if (SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellId))
10218 // Flying case (Unsummon any pet)
10219 if (IsSpellHaveAura(spellInfo, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED))
10220 ((Player*)this)->UnsummonPetTemporaryIfAny();
10221 // Normal case (Unsummon only permanent pet)
10222 else if (Pet* pet = GetPet())
10224 if (pet->IsPermanentPetFor((Player*)this) && !((Player*)this)->InArena())
10225 ((Player*)this)->UnsummonPetTemporaryIfAny();
10226 else
10227 pet->ApplyModeFlags(PET_MODE_DISABLE_ACTIONS,true);
10233 void Unit::Unmount()
10235 if (!IsMounted())
10236 return;
10238 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED);
10240 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
10241 RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
10243 // only resummon old pet if the player is already added to a map
10244 // this prevents adding a pet to a not created map which would otherwise cause a crash
10245 // (it could probably happen when logging in after a previous crash)
10246 if(GetTypeId() == TYPEID_PLAYER)
10248 if(Pet* pet = GetPet())
10249 pet->ApplyModeFlags(PET_MODE_DISABLE_ACTIONS,false);
10250 else
10251 ((Player*)this)->ResummonPetTemporaryUnSummonedIfAny();
10255 void Unit::SetInCombatWith(Unit* enemy)
10257 Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf();
10258 if (eOwner->IsPvP())
10260 SetInCombatState(true,enemy);
10261 return;
10264 //check for duel
10265 if (eOwner->GetTypeId() == TYPEID_PLAYER && ((Player*)eOwner)->duel)
10267 Unit const* myOwner = GetCharmerOrOwnerOrSelf();
10268 if(((Player const*)eOwner)->duel->opponent == myOwner)
10270 SetInCombatState(true,enemy);
10271 return;
10275 SetInCombatState(false,enemy);
10278 void Unit::SetInCombatState(bool PvP, Unit* enemy)
10280 // only alive units can be in combat
10281 if (!isAlive())
10282 return;
10284 if (PvP)
10285 m_CombatTimer = 5000;
10287 bool creatureNotInCombat = GetTypeId()==TYPEID_UNIT && !HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
10289 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
10291 if (isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
10292 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
10294 if (creatureNotInCombat)
10296 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
10298 if (((Creature*)this)->AI())
10299 ((Creature*)this)->AI()->EnterCombat(enemy);
10303 void Unit::ClearInCombat()
10305 m_CombatTimer = 0;
10306 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
10308 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
10309 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
10311 // Player's state will be cleared in Player::UpdateContestedPvP
10312 if (GetTypeId() != TYPEID_PLAYER)
10314 Creature* creature = (Creature*)this;
10315 if (creature->GetCreatureInfo() && creature->GetCreatureInfo()->unit_flags & UNIT_FLAG_OOC_NOT_ATTACKABLE)
10316 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
10318 clearUnitState(UNIT_STAT_ATTACK_PLAYER);
10320 else
10321 ((Player*)this)->UpdatePotionCooldown();
10324 bool Unit::isTargetableForAttack(bool inverseAlive /*=false*/) const
10326 if (GetTypeId()==TYPEID_PLAYER && ((Player *)this)->isGameMaster())
10327 return false;
10329 if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE))
10330 return false;
10332 // to be removed if unit by any reason enter combat
10333 if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE))
10334 return false;
10336 // inversealive is needed for some spells which need to be casted at dead targets (aoe)
10337 if (isAlive() == inverseAlive)
10338 return false;
10340 return IsInWorld() && !hasUnitState(UNIT_STAT_DIED) && !isInFlight();
10343 int32 Unit::ModifyHealth(int32 dVal)
10345 int32 gain = 0;
10347 if(dVal==0)
10348 return 0;
10350 int32 curHealth = (int32)GetHealth();
10352 int32 val = dVal + curHealth;
10353 if(val <= 0)
10355 SetHealth(0);
10356 return -curHealth;
10359 int32 maxHealth = (int32)GetMaxHealth();
10361 if(val < maxHealth)
10363 SetHealth(val);
10364 gain = val - curHealth;
10366 else if(curHealth != maxHealth)
10368 SetHealth(maxHealth);
10369 gain = maxHealth - curHealth;
10372 return gain;
10375 int32 Unit::ModifyPower(Powers power, int32 dVal)
10377 int32 gain = 0;
10379 if(dVal==0)
10380 return 0;
10382 int32 curPower = (int32)GetPower(power);
10384 int32 val = dVal + curPower;
10385 if(val <= 0)
10387 SetPower(power,0);
10388 return -curPower;
10391 int32 maxPower = (int32)GetMaxPower(power);
10393 if(val < maxPower)
10395 SetPower(power,val);
10396 gain = val - curPower;
10398 else if(curPower != maxPower)
10400 SetPower(power,maxPower);
10401 gain = maxPower - curPower;
10404 return gain;
10407 bool Unit::isVisibleForOrDetect(Unit const* u, WorldObject const* viewPoint, bool detect, bool inVisibleList, bool is3dDistance) const
10409 if(!u || !IsInMap(u))
10410 return false;
10412 // Always can see self
10413 if (u==this)
10414 return true;
10416 // player visible for other player if not logout and at same transport
10417 // including case when player is out of world
10418 bool at_same_transport =
10419 GetTypeId() == TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER &&
10420 !((Player*)this)->GetSession()->PlayerLogout() && !((Player*)u)->GetSession()->PlayerLogout() &&
10421 !((Player*)this)->GetSession()->PlayerLoading() && !((Player*)u)->GetSession()->PlayerLoading() &&
10422 ((Player*)this)->GetTransport() && ((Player*)this)->GetTransport() == ((Player*)u)->GetTransport();
10424 // not in world
10425 if(!at_same_transport && (!IsInWorld() || !u->IsInWorld()))
10426 return false;
10428 // forbidden to seen (at GM respawn command)
10429 if(m_Visibility==VISIBILITY_RESPAWN)
10430 return false;
10432 Map& _map = *u->GetMap();
10433 // Grid dead/alive checks
10434 if (u->GetTypeId()==TYPEID_PLAYER)
10436 // non visible at grid for any stealth state
10437 if(!IsVisibleInGridForPlayer((Player *)u))
10438 return false;
10440 // if player is dead then he can't detect anyone in any cases
10441 if(!u->isAlive())
10442 detect = false;
10444 else
10446 // all dead creatures/players not visible for any creatures
10447 if(!u->isAlive() || !isAlive())
10448 return false;
10451 // always seen by far sight caster
10452 if (u->GetTypeId()==TYPEID_PLAYER && ((Player*)u)->GetFarSight()==GetGUID())
10453 return true;
10455 // different visible distance checks
10456 if (u->isInFlight()) // what see player in flight
10458 // use object grey distance for all (only see objects any way)
10459 if (!IsWithinDistInMap(viewPoint,World::GetMaxVisibleDistanceInFlight()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
10460 return false;
10462 else if(!isAlive()) // distance for show body
10464 if (!IsWithinDistInMap(viewPoint,World::GetMaxVisibleDistanceForObject()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
10465 return false;
10467 else if(GetTypeId()==TYPEID_PLAYER) // distance for show player
10469 if(u->GetTypeId()==TYPEID_PLAYER)
10471 // Players far than max visible distance for player or not in our map are not visible too
10472 if (!at_same_transport && !IsWithinDistInMap(viewPoint, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
10473 return false;
10475 else
10477 // Units far than max visible distance for creature or not in our map are not visible too
10478 if (!IsWithinDistInMap(viewPoint, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
10479 return false;
10482 else if(GetCharmerOrOwnerGUID()) // distance for show pet/charmed
10484 // Pet/charmed far than max visible distance for player or not in our map are not visible too
10485 if (!IsWithinDistInMap(viewPoint, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
10486 return false;
10488 else // distance for show creature
10490 // Units far than max visible distance for creature or not in our map are not visible too
10491 if (!IsWithinDistInMap(viewPoint, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
10492 return false;
10495 // always seen by owner
10496 if (GetCharmerOrOwnerGUID()==u->GetGUID())
10497 return true;
10499 // isInvisibleForAlive() those units can only be seen by dead or if other
10500 // unit is also invisible for alive.. if an isinvisibleforalive unit dies we
10501 // should be able to see it too
10502 if (u->isAlive() && isAlive() && isInvisibleForAlive() != u->isInvisibleForAlive())
10503 if (u->GetTypeId() != TYPEID_PLAYER || !((Player *)u)->isGameMaster())
10504 return false;
10506 // Visible units, always are visible for all units, except for units under invisibility and phases
10507 if (m_Visibility == VISIBILITY_ON && u->m_invisibilityMask==0 && InSamePhase(u))
10508 return true;
10510 // GMs see any players, not higher GMs and all units in any phase
10511 if (u->GetTypeId() == TYPEID_PLAYER && ((Player *)u)->isGameMaster())
10513 if(GetTypeId() == TYPEID_PLAYER)
10514 return ((Player *)this)->GetSession()->GetSecurity() <= ((Player *)u)->GetSession()->GetSecurity();
10515 else
10516 return true;
10519 // non faction visibility non-breakable for non-GMs
10520 if (m_Visibility == VISIBILITY_OFF)
10521 return false;
10523 // phased visibility (both must phased in same way)
10524 if(!InSamePhase(u))
10525 return false;
10527 // raw invisibility
10528 bool invisible = (m_invisibilityMask != 0 || u->m_invisibilityMask !=0);
10530 // detectable invisibility case
10531 if( invisible && (
10532 // Invisible units, always are visible for units under same invisibility type
10533 (m_invisibilityMask & u->m_invisibilityMask)!=0 ||
10534 // Invisible units, always are visible for unit that can detect this invisibility (have appropriate level for detect)
10535 u->canDetectInvisibilityOf(this) ||
10536 // Units that can detect invisibility always are visible for units that can be detected
10537 canDetectInvisibilityOf(u) ))
10539 invisible = false;
10542 // special cases for always overwrite invisibility/stealth
10543 if(invisible || m_Visibility == VISIBILITY_GROUP_STEALTH)
10545 // non-hostile case
10546 if (!u->IsHostileTo(this))
10548 // 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)
10549 if(GetTypeId()==TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER)
10551 if(((Player*)this)->IsGroupVisibleFor(((Player*)u)))
10552 return true;
10554 // else apply same rules as for hostile case (detecting check for stealth)
10557 // hostile case
10558 else
10560 // Hunter mark functionality
10561 AuraList const& auras = GetAurasByType(SPELL_AURA_MOD_STALKED);
10562 for(AuraList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
10563 if((*iter)->GetCasterGUID()==u->GetGUID())
10564 return true;
10566 // else apply detecting check for stealth
10569 // none other cases for detect invisibility, so invisible
10570 if(invisible)
10571 return false;
10573 // else apply stealth detecting check
10576 // unit got in stealth in this moment and must ignore old detected state
10577 if (m_Visibility == VISIBILITY_GROUP_NO_DETECT)
10578 return false;
10580 // GM invisibility checks early, invisibility if any detectable, so if not stealth then visible
10581 if (m_Visibility != VISIBILITY_GROUP_STEALTH)
10582 return true;
10584 // NOW ONLY STEALTH CASE
10586 //if in non-detect mode then invisible for unit
10587 //mobs always detect players (detect == true)... return 'false' for those mobs which have (detect == false)
10588 //players detect players only in Player::HandleStealthedUnitsDetection()
10589 if (!detect)
10590 return (u->GetTypeId() == TYPEID_PLAYER) ? ((Player*)u)->HaveAtClient(this) : false;
10592 // Special cases
10594 // If is attacked then stealth is lost, some creature can use stealth too
10595 if( !getAttackers().empty() )
10596 return true;
10598 // If there is collision rogue is seen regardless of level difference
10599 if (IsWithinDist(u,0.24f))
10600 return true;
10602 //If a mob or player is stunned he will not be able to detect stealth
10603 if (u->hasUnitState(UNIT_STAT_STUNNED) && (u != this))
10604 return false;
10606 // set max ditance
10607 float visibleDistance = (u->GetTypeId() == TYPEID_PLAYER) ? MAX_PLAYER_STEALTH_DETECT_RANGE : ((Creature const*)u)->GetAttackDistance(this);
10609 //Always invisible from back (when stealth detection is on), also filter max distance cases
10610 bool isInFront = viewPoint->isInFrontInMap(this, visibleDistance);
10611 if(!isInFront)
10612 return false;
10614 // if doesn't have stealth detection (Shadow Sight), then check how stealthy the unit is, otherwise just check los
10615 if(!u->HasAuraType(SPELL_AURA_DETECT_STEALTH))
10617 //Calculation if target is in front
10619 //Visible distance based on stealth value (stealth rank 4 300MOD, 10.5 - 3 = 7.5)
10620 visibleDistance = 10.5f - (GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH)/100.0f);
10622 //Visible distance is modified by
10623 //-Level Diff (every level diff = 1.0f in visible distance)
10624 visibleDistance += int32(u->getLevelForTarget(this)) - int32(getLevelForTarget(u));
10626 //This allows to check talent tree and will add addition stealth dependent on used points)
10627 int32 stealthMod = GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_LEVEL);
10628 if(stealthMod < 0)
10629 stealthMod = 0;
10631 //-Stealth Mod(positive like Master of Deception) and Stealth Detection(negative like paranoia)
10632 //based on wowwiki every 5 mod we have 1 more level diff in calculation
10633 visibleDistance += (int32(u->GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_DETECT)) - stealthMod)/5.0f;
10634 visibleDistance = visibleDistance > MAX_PLAYER_STEALTH_DETECT_RANGE ? MAX_PLAYER_STEALTH_DETECT_RANGE : visibleDistance;
10636 // recheck new distance
10637 if(visibleDistance <= 0 || !IsWithinDist(viewPoint,visibleDistance))
10638 return false;
10641 // Now check is target visible with LoS
10642 float ox,oy,oz;
10643 viewPoint->GetPosition(ox,oy,oz);
10644 return IsWithinLOS(ox,oy,oz);
10647 void Unit::SetVisibility(UnitVisibility x)
10649 m_Visibility = x;
10651 if(IsInWorld())
10653 Map *m = GetMap();
10655 if(GetTypeId()==TYPEID_PLAYER)
10656 m->PlayerRelocation((Player*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
10657 else
10658 m->CreatureRelocation((Creature*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
10662 bool Unit::canDetectInvisibilityOf(Unit const* u) const
10664 if(uint32 mask = (m_detectInvisibilityMask & u->m_invisibilityMask))
10666 for(uint32 i = 0; i < 10; ++i)
10668 if(((1 << i) & mask)==0)
10669 continue;
10671 // find invisibility level
10672 int32 invLevel = 0;
10673 Unit::AuraList const& iAuras = u->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY);
10674 for(Unit::AuraList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr)
10675 if(((*itr)->GetModifier()->m_miscvalue)==i && invLevel < (*itr)->GetModifier()->m_amount)
10676 invLevel = (*itr)->GetModifier()->m_amount;
10678 // find invisibility detect level
10679 int32 detectLevel = 0;
10680 Unit::AuraList const& dAuras = GetAurasByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION);
10681 for(Unit::AuraList::const_iterator itr = dAuras.begin(); itr != dAuras.end(); ++itr)
10682 if(((*itr)->GetModifier()->m_miscvalue)==i && detectLevel < (*itr)->GetModifier()->m_amount)
10683 detectLevel = (*itr)->GetModifier()->m_amount;
10685 if(i==6 && GetTypeId()==TYPEID_PLAYER) // special drunk detection case
10687 detectLevel = ((Player*)this)->GetDrunkValue();
10690 if(invLevel <= detectLevel)
10691 return true;
10695 return false;
10698 struct UpdateWalkModeHelper
10700 explicit UpdateWalkModeHelper(Unit* _source) : source(_source) {}
10701 void operator()(Unit* unit) const { unit->UpdateWalkMode(source, true); }
10702 Unit* source;
10705 void Unit::UpdateWalkMode(Unit* source, bool self)
10707 if (GetTypeId() == TYPEID_PLAYER)
10708 ((Player*)this)->CallForAllControlledUnits(UpdateWalkModeHelper(source), false, true, true, true);
10709 else if (self)
10711 bool on = source->GetTypeId() == TYPEID_PLAYER
10712 ? ((Player*)source)->HasMovementFlag(MOVEFLAG_WALK_MODE)
10713 : ((Creature*)source)->HasSplineFlag(SPLINEFLAG_WALKMODE);
10715 if (on)
10717 if (((Creature*)this)->isPet() && hasUnitState(UNIT_STAT_FOLLOW))
10718 ((Creature*)this)->AddSplineFlag(SPLINEFLAG_WALKMODE);
10720 else
10722 if (((Creature*)this)->isPet())
10723 ((Creature*)this)->RemoveSplineFlag(SPLINEFLAG_WALKMODE);
10726 else
10727 CallForAllControlledUnits(UpdateWalkModeHelper(source), false, true, true);
10730 void Unit::UpdateSpeed(UnitMoveType mtype, bool forced)
10732 // not in combat pet have same speed as owner
10733 switch(mtype)
10735 case MOVE_RUN:
10736 case MOVE_WALK:
10737 case MOVE_SWIM:
10738 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet() && hasUnitState(UNIT_STAT_FOLLOW))
10740 if(Unit* owner = GetOwner())
10742 SetSpeedRate(mtype, owner->GetSpeedRate(mtype), forced);
10743 return;
10746 break;
10749 int32 main_speed_mod = 0;
10750 float stack_bonus = 1.0f;
10751 float non_stack_bonus = 1.0f;
10753 switch(mtype)
10755 case MOVE_WALK:
10756 return;
10757 case MOVE_RUN:
10759 if (IsMounted()) // Use on mount auras
10761 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED);
10762 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS);
10763 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK))/100.0f;
10765 else
10767 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED);
10768 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS);
10769 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK))/100.0f;
10771 break;
10773 case MOVE_RUN_BACK:
10774 return;
10775 case MOVE_SWIM:
10777 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SWIM_SPEED);
10778 break;
10780 case MOVE_SWIM_BACK:
10781 return;
10782 case MOVE_FLIGHT:
10784 if (IsMounted()) // Use on mount auras
10785 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
10786 else // Use not mount (shapeshift for example) auras (should stack)
10787 main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_SPEED_FLIGHT);
10788 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_FLIGHT_SPEED_ALWAYS);
10789 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK))/100.0f;
10790 break;
10792 case MOVE_FLIGHT_BACK:
10793 return;
10794 default:
10795 sLog.outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype);
10796 return;
10799 float bonus = non_stack_bonus > stack_bonus ? non_stack_bonus : stack_bonus;
10800 // now we ready for speed calculation
10801 float speed = main_speed_mod ? bonus*(100.0f + main_speed_mod)/100.0f : bonus;
10803 switch(mtype)
10805 case MOVE_RUN:
10806 case MOVE_SWIM:
10807 case MOVE_FLIGHT:
10809 // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need
10810 // TODO: possible affect only on MOVE_RUN
10811 if(int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED))
10813 // Use speed from aura
10814 float max_speed = normalization / baseMoveSpeed[mtype];
10815 if (speed > max_speed)
10816 speed = max_speed;
10818 break;
10820 default:
10821 break;
10824 // for creature case, we check explicit if mob searched for assistance
10825 if (GetTypeId() == TYPEID_UNIT)
10827 if (((Creature*)this)->HasSearchedAssistance())
10828 speed *= 0.66f; // best guessed value, so this will be 33% reduction. Based off initial speed, mob can then "run", "walk fast" or "walk".
10831 // Apply strongest slow aura mod to speed
10832 int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED);
10833 if (slow)
10835 speed *=(100.0f + slow)/100.0f;
10836 float min_speed = (float)GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MINIMUM_SPEED) / 100.0f;
10837 if (speed < min_speed)
10838 speed = min_speed;
10840 SetSpeedRate(mtype, speed, forced);
10843 float Unit::GetSpeed( UnitMoveType mtype ) const
10845 return m_speed_rate[mtype]*baseMoveSpeed[mtype];
10848 struct SetSpeedRateHelper
10850 explicit SetSpeedRateHelper(UnitMoveType _mtype, bool _forced) : mtype(_mtype), forced(_forced) {}
10851 void operator()(Unit* unit) const { unit->UpdateSpeed(mtype,forced); }
10852 UnitMoveType mtype;
10853 bool forced;
10856 void Unit::SetSpeedRate(UnitMoveType mtype, float rate, bool forced)
10858 if (rate < 0)
10859 rate = 0.0f;
10861 // Update speed only on change
10862 if (m_speed_rate[mtype] == rate)
10863 return;
10865 m_speed_rate[mtype] = rate;
10867 propagateSpeedChange();
10869 WorldPacket data;
10870 if(!forced)
10872 switch(mtype)
10874 case MOVE_WALK:
10875 data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8+4+2+4+4+4+4+4+4+4);
10876 break;
10877 case MOVE_RUN:
10878 data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8+4+2+4+4+4+4+4+4+4);
10879 break;
10880 case MOVE_RUN_BACK:
10881 data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
10882 break;
10883 case MOVE_SWIM:
10884 data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8+4+2+4+4+4+4+4+4+4);
10885 break;
10886 case MOVE_SWIM_BACK:
10887 data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
10888 break;
10889 case MOVE_TURN_RATE:
10890 data.Initialize(MSG_MOVE_SET_TURN_RATE, 8+4+2+4+4+4+4+4+4+4);
10891 break;
10892 case MOVE_FLIGHT:
10893 data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8+4+2+4+4+4+4+4+4+4);
10894 break;
10895 case MOVE_FLIGHT_BACK:
10896 data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
10897 break;
10898 case MOVE_PITCH_RATE:
10899 data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8+4+2+4+4+4+4+4+4+4);
10900 break;
10901 default:
10902 sLog.outError("Unit::SetSpeedRate: Unsupported move type (%d), data not sent to client.",mtype);
10903 return;
10906 data << GetPackGUID();
10907 data << uint32(0); // movement flags
10908 data << uint16(0); // unk flags
10909 data << uint32(getMSTime());
10910 data << float(GetPositionX());
10911 data << float(GetPositionY());
10912 data << float(GetPositionZ());
10913 data << float(GetOrientation());
10914 data << uint32(0); // fall time
10915 data << float(GetSpeed(mtype));
10916 SendMessageToSet( &data, true );
10918 else
10920 if(GetTypeId() == TYPEID_PLAYER)
10922 // register forced speed changes for WorldSession::HandleForceSpeedChangeAck
10923 // and do it only for real sent packets and use run for run/mounted as client expected
10924 ++((Player*)this)->m_forced_speed_changes[mtype];
10927 switch(mtype)
10929 case MOVE_WALK:
10930 data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE, 16);
10931 break;
10932 case MOVE_RUN:
10933 data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE, 17);
10934 break;
10935 case MOVE_RUN_BACK:
10936 data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE, 16);
10937 break;
10938 case MOVE_SWIM:
10939 data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE, 16);
10940 break;
10941 case MOVE_SWIM_BACK:
10942 data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, 16);
10943 break;
10944 case MOVE_TURN_RATE:
10945 data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE, 16);
10946 break;
10947 case MOVE_FLIGHT:
10948 data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE, 16);
10949 break;
10950 case MOVE_FLIGHT_BACK:
10951 data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, 16);
10952 break;
10953 case MOVE_PITCH_RATE:
10954 data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE, 16);
10955 break;
10956 default:
10957 sLog.outError("Unit::SetSpeedRate: Unsupported move type (%d), data not sent to client.",mtype);
10958 return;
10960 data << GetPackGUID();
10961 data << (uint32)0; // moveEvent, NUM_PMOVE_EVTS = 0x39
10962 if (mtype == MOVE_RUN)
10963 data << uint8(0); // new 2.1.0
10964 data << float(GetSpeed(mtype));
10965 SendMessageToSet( &data, true );
10968 if (GetTypeId() == TYPEID_PLAYER) // need include minpet
10969 ((Player*)this)->CallForAllControlledUnits(SetSpeedRateHelper(mtype,forced),false,true,true,true);
10970 else
10971 CallForAllControlledUnits(SetSpeedRateHelper(mtype,forced),false,true,true);
10974 void Unit::SetHover(bool on)
10976 if(on)
10977 CastSpell(this, 11010, true);
10978 else
10979 RemoveAurasDueToSpell(11010);
10982 void Unit::setDeathState(DeathState s)
10984 if (s != ALIVE && s!= JUST_ALIVED)
10986 CombatStop();
10987 DeleteThreatList();
10988 ClearComboPointHolders(); // any combo points pointed to unit lost at it death
10990 if(IsNonMeleeSpellCasted(false))
10991 InterruptNonMeleeSpells(false);
10994 if (s == JUST_DIED)
10996 RemoveAllAurasOnDeath();
10997 RemoveGuardians();
10998 UnsummonAllTotems();
11000 // after removing a Fearaura (in RemoveAllAurasOnDeath)
11001 // Unit::SetFeared is called and makes that creatures attack player again
11002 StopMoving();
11004 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false);
11005 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, false);
11006 // remove aurastates allowing special moves
11007 ClearAllReactives();
11008 ClearDiminishings();
11010 else if(s == JUST_ALIVED)
11012 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground)
11015 if (m_deathState != ALIVE && s == ALIVE)
11017 //_ApplyAllAuraMods();
11019 m_deathState = s;
11022 /*########################################
11023 ######## ########
11024 ######## AGGRO SYSTEM ########
11025 ######## ########
11026 ########################################*/
11027 bool Unit::CanHaveThreatList() const
11029 // only creatures can have threat list
11030 if( GetTypeId() != TYPEID_UNIT )
11031 return false;
11033 // only alive units can have threat list
11034 if( !isAlive() )
11035 return false;
11037 // totems can not have threat list
11038 if( ((Creature*)this)->isTotem() )
11039 return false;
11041 // vehicles can not have threat list
11042 if( ((Creature*)this)->isVehicle() )
11043 return false;
11045 // pets can not have a threat list, unless they are controlled by a creature
11046 if( ((Creature*)this)->isPet() && IS_PLAYER_GUID(((Pet*)this)->GetOwnerGUID()) )
11047 return false;
11049 return true;
11052 //======================================================================
11054 float Unit::ApplyTotalThreatModifier(float threat, SpellSchoolMask schoolMask)
11056 if (!HasAuraType(SPELL_AURA_MOD_THREAT))
11057 return threat;
11059 if (schoolMask == SPELL_SCHOOL_MASK_NONE)
11060 return threat;
11062 SpellSchools school = GetFirstSchoolInMask(schoolMask);
11064 return threat * m_threatModifier[school];
11067 //======================================================================
11069 void Unit::AddThreat(Unit* pVictim, float threat /*= 0.0f*/, bool crit /*= false*/, SpellSchoolMask schoolMask /*= SPELL_SCHOOL_MASK_NONE*/, SpellEntry const *threatSpell /*= NULL*/)
11071 // Only mobs can manage threat lists
11072 if(CanHaveThreatList())
11073 m_ThreatManager.addThreat(pVictim, threat, crit, schoolMask, threatSpell);
11076 //======================================================================
11078 void Unit::DeleteThreatList()
11080 if(CanHaveThreatList() && !m_ThreatManager.isThreatListEmpty())
11081 SendThreatClear();
11082 m_ThreatManager.clearReferences();
11085 //======================================================================
11087 void Unit::TauntApply(Unit* taunter)
11089 assert(GetTypeId()== TYPEID_UNIT);
11091 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
11092 return;
11094 if(!CanHaveThreatList())
11095 return;
11097 Unit *target = getVictim();
11098 if(target && target == taunter)
11099 return;
11101 SetInFront(taunter);
11102 if (((Creature*)this)->AI())
11103 ((Creature*)this)->AI()->AttackStart(taunter);
11105 m_ThreatManager.tauntApply(taunter);
11108 //======================================================================
11110 void Unit::TauntFadeOut(Unit *taunter)
11112 assert(GetTypeId()== TYPEID_UNIT);
11114 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
11115 return;
11117 if(!CanHaveThreatList())
11118 return;
11120 Unit *target = getVictim();
11121 if(!target || target != taunter)
11122 return;
11124 if(m_ThreatManager.isThreatListEmpty())
11126 if(((Creature*)this)->AI())
11127 ((Creature*)this)->AI()->EnterEvadeMode();
11128 return;
11131 m_ThreatManager.tauntFadeOut(taunter);
11132 target = m_ThreatManager.getHostileTarget();
11134 if (target && target != taunter)
11136 SetInFront(target);
11137 if (((Creature*)this)->AI())
11138 ((Creature*)this)->AI()->AttackStart(target);
11142 //======================================================================
11144 bool Unit::SelectHostileTarget()
11146 //function provides main threat functionality
11147 //next-victim-selection algorithm and evade mode are called
11148 //threat list sorting etc.
11150 assert(GetTypeId()== TYPEID_UNIT);
11152 if (!this->isAlive())
11153 return false;
11154 //This function only useful once AI has been initialized
11155 if (!((Creature*)this)->AI())
11156 return false;
11158 Unit* target = NULL;
11160 // First checking if we have some taunt on us
11161 const AuraList& tauntAuras = GetAurasByType(SPELL_AURA_MOD_TAUNT);
11162 if ( !tauntAuras.empty() )
11164 Unit* caster;
11166 // The last taunt aura caster is alive an we are happy to attack him
11167 if ( (caster = tauntAuras.back()->GetCaster()) && caster->isAlive() )
11168 return true;
11169 else if (tauntAuras.size() > 1)
11171 // We do not have last taunt aura caster but we have more taunt auras,
11172 // so find first available target
11174 // Auras are pushed_back, last caster will be on the end
11175 AuraList::const_iterator aura = --tauntAuras.end();
11178 --aura;
11179 if ( (caster = (*aura)->GetCaster()) &&
11180 caster->IsInMap(this) && caster->isTargetableForAttack() && caster->isInAccessablePlaceFor((Creature*)this) )
11182 target = caster;
11183 break;
11185 }while (aura != tauntAuras.begin());
11189 if ( !target && !m_ThreatManager.isThreatListEmpty() )
11190 // No taunt aura or taunt aura caster is dead standart target selection
11191 target = m_ThreatManager.getHostileTarget();
11193 if(target)
11195 if(!hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_DIED))
11196 SetInFront(target);
11197 ((Creature*)this)->AI()->AttackStart(target);
11198 return true;
11201 // no target but something prevent go to evade mode
11202 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_TAUNT) )
11203 return false;
11205 // last case when creature don't must go to evade mode:
11206 // it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list
11207 // for example at owner command to pet attack some far away creature
11208 // Note: creature not have targeted movement generator but have attacker in this case
11209 if (GetMotionMaster()->GetCurrentMovementGeneratorType() != CHASE_MOTION_TYPE)
11211 for(AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr)
11213 if ((*itr)->IsInMap(this) && (*itr)->isTargetableForAttack() && (*itr)->isInAccessablePlaceFor((Creature*)this))
11214 return false;
11218 // enter in evade mode in other case
11219 ((Creature*)this)->AI()->EnterEvadeMode();
11221 return false;
11224 //======================================================================
11225 //======================================================================
11226 //======================================================================
11228 int32 Unit::CalculateSpellDamage(SpellEntry const* spellProto, SpellEffectIndex effect_index, int32 effBasePoints, Unit const* target)
11230 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
11232 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
11234 int32 level = int32(getLevel());
11235 if (level > (int32)spellProto->maxLevel && spellProto->maxLevel > 0)
11236 level = (int32)spellProto->maxLevel;
11237 else if (level < (int32)spellProto->baseLevel)
11238 level = (int32)spellProto->baseLevel;
11239 level-= (int32)spellProto->spellLevel;
11241 float basePointsPerLevel = spellProto->EffectRealPointsPerLevel[effect_index];
11242 float randomPointsPerLevel = spellProto->EffectDicePerLevel[effect_index];
11243 int32 basePoints = int32(effBasePoints + level * basePointsPerLevel);
11244 int32 randomPoints = int32(spellProto->EffectDieSides[effect_index] + level * randomPointsPerLevel);
11245 float comboDamage = spellProto->EffectPointsPerComboPoint[effect_index];
11247 // range can have possitive and negative values, so order its for irand
11248 int32 randvalue = int32(spellProto->EffectBaseDice[effect_index]) >= randomPoints
11249 ? irand(randomPoints, int32(spellProto->EffectBaseDice[effect_index]))
11250 : irand(int32(spellProto->EffectBaseDice[effect_index]), randomPoints);
11252 int32 value = basePoints + randvalue;
11253 //random damage
11254 if(comboDamage != 0 && unitPlayer && target && (target->GetGUID() == unitPlayer->GetComboTarget()))
11255 value += (int32)(comboDamage * comboPoints);
11257 if(Player* modOwner = GetSpellModOwner())
11259 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_ALL_EFFECTS, value);
11260 switch(effect_index)
11262 case 0:
11263 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT1, value);
11264 break;
11265 case 1:
11266 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT2, value);
11267 break;
11268 case 2:
11269 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT3, value);
11270 break;
11274 if(spellProto->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION && spellProto->spellLevel &&
11275 spellProto->Effect[effect_index] != SPELL_EFFECT_WEAPON_PERCENT_DAMAGE &&
11276 spellProto->Effect[effect_index] != SPELL_EFFECT_KNOCK_BACK &&
11277 (spellProto->Effect[effect_index] != SPELL_EFFECT_APPLY_AURA || spellProto->EffectApplyAuraName[effect_index] != SPELL_AURA_MOD_DECREASE_SPEED))
11278 value = int32(value*0.25f*exp(getLevel()*(70-spellProto->spellLevel)/1000.0f));
11280 return value;
11283 int32 Unit::CalculateSpellDuration(SpellEntry const* spellProto, SpellEffectIndex effect_index, Unit const* target)
11285 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
11287 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
11289 int32 minduration = GetSpellDuration(spellProto);
11290 int32 maxduration = GetSpellMaxDuration(spellProto);
11292 int32 duration;
11294 if( minduration != -1 && minduration != maxduration )
11295 duration = minduration + int32((maxduration - minduration) * comboPoints / 5);
11296 else
11297 duration = minduration;
11299 if (duration > 0)
11301 int32 mechanic = GetEffectMechanic(spellProto, effect_index);
11302 // Find total mod value (negative bonus)
11303 int32 durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD, mechanic);
11304 // Modify from SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL aura for negatve effects (stack always ?)
11305 if (!IsPositiveEffect(spellProto->Id, effect_index))
11306 durationMod_always+=target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL, spellProto->Dispel);
11307 // Find max mod (negative bonus)
11308 int32 durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK, mechanic);
11310 if (!IsPositiveSpell(spellProto->Id))
11311 durationMod_always += target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DURATION_OF_MAGIC_EFFECTS, spellProto->DmgClass);
11313 int32 durationMod = 0;
11314 // Select strongest negative mod
11315 if (durationMod_always > durationMod_not_stack)
11316 durationMod = durationMod_not_stack;
11317 else
11318 durationMod = durationMod_always;
11320 if (durationMod != 0)
11321 duration = int32(int64(duration) * (100+durationMod) /100);
11323 if (duration < 0) duration = 0;
11326 return duration;
11329 DiminishingLevels Unit::GetDiminishing(DiminishingGroup group)
11331 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
11333 if(i->DRGroup != group)
11334 continue;
11336 if(!i->hitCount)
11337 return DIMINISHING_LEVEL_1;
11339 if(!i->hitTime)
11340 return DIMINISHING_LEVEL_1;
11342 // If last spell was casted more than 15 seconds ago - reset the count.
11343 if(i->stack==0 && getMSTimeDiff(i->hitTime,getMSTime()) > 15000)
11345 i->hitCount = DIMINISHING_LEVEL_1;
11346 return DIMINISHING_LEVEL_1;
11348 // or else increase the count.
11349 else
11351 return DiminishingLevels(i->hitCount);
11354 return DIMINISHING_LEVEL_1;
11357 void Unit::IncrDiminishing(DiminishingGroup group)
11359 // Checking for existing in the table
11360 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
11362 if(i->DRGroup != group)
11363 continue;
11364 if(i->hitCount < DIMINISHING_LEVEL_IMMUNE)
11365 i->hitCount += 1;
11366 return;
11368 m_Diminishing.push_back(DiminishingReturn(group,getMSTime(),DIMINISHING_LEVEL_2));
11371 void Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration,Unit* caster,DiminishingLevels Level, int32 limitduration)
11373 if(duration == -1 || group == DIMINISHING_NONE || caster->IsFriendlyTo(this) )
11374 return;
11376 // Duration of crowd control abilities on pvp target is limited by 10 sec. (2.2.0)
11377 if(limitduration > 0 && duration > limitduration)
11379 // test pet/charm masters instead pets/charmeds
11380 Unit const* targetOwner = GetCharmerOrOwner();
11381 Unit const* casterOwner = caster->GetCharmerOrOwner();
11383 Unit const* target = targetOwner ? targetOwner : this;
11384 Unit const* source = casterOwner ? casterOwner : caster;
11386 if(target->GetTypeId() == TYPEID_PLAYER && source->GetTypeId() == TYPEID_PLAYER)
11387 duration = limitduration;
11390 float mod = 1.0f;
11392 // Some diminishings applies to mobs too (for example, Stun)
11393 if((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER && GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL)
11395 DiminishingLevels diminish = Level;
11396 switch(diminish)
11398 case DIMINISHING_LEVEL_1: break;
11399 case DIMINISHING_LEVEL_2: mod = 0.5f; break;
11400 case DIMINISHING_LEVEL_3: mod = 0.25f; break;
11401 case DIMINISHING_LEVEL_IMMUNE: mod = 0.0f;break;
11402 default: break;
11406 duration = int32(duration * mod);
11409 void Unit::ApplyDiminishingAura( DiminishingGroup group, bool apply )
11411 // Checking for existing in the table
11412 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
11414 if(i->DRGroup != group)
11415 continue;
11417 if(apply)
11418 i->stack += 1;
11419 else if(i->stack)
11421 i->stack -= 1;
11422 // Remember time after last aura from group removed
11423 if (i->stack == 0)
11424 i->hitTime = getMSTime();
11426 break;
11430 Unit* Unit::GetUnit(WorldObject const& object, uint64 guid)
11432 return ObjectAccessor::GetUnit(object,guid);
11435 bool Unit::isVisibleForInState( Player const* u, WorldObject const* viewPoint, bool inVisibleList ) const
11437 return isVisibleForOrDetect(u, viewPoint, false, inVisibleList, false);
11440 /// returns true if creature can't be seen by alive units
11441 bool Unit::isInvisibleForAlive() const
11443 if (m_AuraFlags & UNIT_AURAFLAG_ALIVE_INVISIBLE)
11444 return true;
11445 // TODO: maybe spiritservices also have just an aura
11446 return isSpiritService();
11449 uint32 Unit::GetCreatureType() const
11451 if(GetTypeId() == TYPEID_PLAYER)
11453 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
11454 if(ssEntry && ssEntry->creatureType > 0)
11455 return ssEntry->creatureType;
11456 else
11457 return CREATURE_TYPE_HUMANOID;
11459 else
11460 return ((Creature*)this)->GetCreatureInfo()->type;
11463 /*#######################################
11464 ######## ########
11465 ######## STAT SYSTEM ########
11466 ######## ########
11467 #######################################*/
11469 bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply)
11471 if(unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
11473 sLog.outError("ERROR in HandleStatModifier(): non existed UnitMods or wrong UnitModifierType!");
11474 return false;
11477 float val = 1.0f;
11479 switch(modifierType)
11481 case BASE_VALUE:
11482 case TOTAL_VALUE:
11483 m_auraModifiersGroup[unitMod][modifierType] += apply ? amount : -amount;
11484 break;
11485 case BASE_PCT:
11486 case TOTAL_PCT:
11487 if(amount <= -100.0f) //small hack-fix for -100% modifiers
11488 amount = -200.0f;
11490 val = (100.0f + amount) / 100.0f;
11491 m_auraModifiersGroup[unitMod][modifierType] *= apply ? val : (1.0f/val);
11492 break;
11494 default:
11495 break;
11498 if(!CanModifyStats())
11499 return false;
11501 switch(unitMod)
11503 case UNIT_MOD_STAT_STRENGTH:
11504 case UNIT_MOD_STAT_AGILITY:
11505 case UNIT_MOD_STAT_STAMINA:
11506 case UNIT_MOD_STAT_INTELLECT:
11507 case UNIT_MOD_STAT_SPIRIT: UpdateStats(GetStatByAuraGroup(unitMod)); break;
11509 case UNIT_MOD_ARMOR: UpdateArmor(); break;
11510 case UNIT_MOD_HEALTH: UpdateMaxHealth(); break;
11512 case UNIT_MOD_MANA:
11513 case UNIT_MOD_RAGE:
11514 case UNIT_MOD_FOCUS:
11515 case UNIT_MOD_ENERGY:
11516 case UNIT_MOD_HAPPINESS:
11517 case UNIT_MOD_RUNE:
11518 case UNIT_MOD_RUNIC_POWER: UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); break;
11520 case UNIT_MOD_RESISTANCE_HOLY:
11521 case UNIT_MOD_RESISTANCE_FIRE:
11522 case UNIT_MOD_RESISTANCE_NATURE:
11523 case UNIT_MOD_RESISTANCE_FROST:
11524 case UNIT_MOD_RESISTANCE_SHADOW:
11525 case UNIT_MOD_RESISTANCE_ARCANE: UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); break;
11527 case UNIT_MOD_ATTACK_POWER: UpdateAttackPowerAndDamage(); break;
11528 case UNIT_MOD_ATTACK_POWER_RANGED: UpdateAttackPowerAndDamage(true); break;
11530 case UNIT_MOD_DAMAGE_MAINHAND: UpdateDamagePhysical(BASE_ATTACK); break;
11531 case UNIT_MOD_DAMAGE_OFFHAND: UpdateDamagePhysical(OFF_ATTACK); break;
11532 case UNIT_MOD_DAMAGE_RANGED: UpdateDamagePhysical(RANGED_ATTACK); break;
11534 default:
11535 break;
11538 return true;
11541 float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const
11543 if( unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
11545 sLog.outError("trial to access non existed modifier value from UnitMods!");
11546 return 0.0f;
11549 if(modifierType == TOTAL_PCT && m_auraModifiersGroup[unitMod][modifierType] <= 0.0f)
11550 return 0.0f;
11552 return m_auraModifiersGroup[unitMod][modifierType];
11555 float Unit::GetTotalStatValue(Stats stat) const
11557 UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat);
11559 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
11560 return 0.0f;
11562 // value = ((base_value * base_pct) + total_value) * total_pct
11563 float value = m_auraModifiersGroup[unitMod][BASE_VALUE] + GetCreateStat(stat);
11564 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
11565 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
11566 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
11568 return value;
11571 float Unit::GetTotalAuraModValue(UnitMods unitMod) const
11573 if(unitMod >= UNIT_MOD_END)
11575 sLog.outError("trial to access non existed UnitMods in GetTotalAuraModValue()!");
11576 return 0.0f;
11579 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
11580 return 0.0f;
11582 float value = m_auraModifiersGroup[unitMod][BASE_VALUE];
11583 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
11584 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
11585 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
11587 return value;
11590 SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const
11592 SpellSchools school = SPELL_SCHOOL_NORMAL;
11594 switch(unitMod)
11596 case UNIT_MOD_RESISTANCE_HOLY: school = SPELL_SCHOOL_HOLY; break;
11597 case UNIT_MOD_RESISTANCE_FIRE: school = SPELL_SCHOOL_FIRE; break;
11598 case UNIT_MOD_RESISTANCE_NATURE: school = SPELL_SCHOOL_NATURE; break;
11599 case UNIT_MOD_RESISTANCE_FROST: school = SPELL_SCHOOL_FROST; break;
11600 case UNIT_MOD_RESISTANCE_SHADOW: school = SPELL_SCHOOL_SHADOW; break;
11601 case UNIT_MOD_RESISTANCE_ARCANE: school = SPELL_SCHOOL_ARCANE; break;
11603 default:
11604 break;
11607 return school;
11610 Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const
11612 Stats stat = STAT_STRENGTH;
11614 switch(unitMod)
11616 case UNIT_MOD_STAT_STRENGTH: stat = STAT_STRENGTH; break;
11617 case UNIT_MOD_STAT_AGILITY: stat = STAT_AGILITY; break;
11618 case UNIT_MOD_STAT_STAMINA: stat = STAT_STAMINA; break;
11619 case UNIT_MOD_STAT_INTELLECT: stat = STAT_INTELLECT; break;
11620 case UNIT_MOD_STAT_SPIRIT: stat = STAT_SPIRIT; break;
11622 default:
11623 break;
11626 return stat;
11629 Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const
11631 switch(unitMod)
11633 case UNIT_MOD_MANA: return POWER_MANA;
11634 case UNIT_MOD_RAGE: return POWER_RAGE;
11635 case UNIT_MOD_FOCUS: return POWER_FOCUS;
11636 case UNIT_MOD_ENERGY: return POWER_ENERGY;
11637 case UNIT_MOD_HAPPINESS: return POWER_HAPPINESS;
11638 case UNIT_MOD_RUNE: return POWER_RUNE;
11639 case UNIT_MOD_RUNIC_POWER:return POWER_RUNIC_POWER;
11640 default: return POWER_MANA;
11643 return POWER_MANA;
11646 float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const
11648 if (attType == RANGED_ATTACK)
11650 int32 ap = GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS);
11651 if (ap < 0)
11652 return 0.0f;
11653 return ap * (1.0f + GetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER));
11655 else
11657 int32 ap = GetInt32Value(UNIT_FIELD_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS);
11658 if (ap < 0)
11659 return 0.0f;
11660 return ap * (1.0f + GetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER));
11664 float Unit::GetWeaponDamageRange(WeaponAttackType attType ,WeaponDamageRange type) const
11666 if (attType == OFF_ATTACK && !haveOffhandWeapon())
11667 return 0.0f;
11669 return m_weaponDamage[attType][type];
11672 void Unit::SetLevel(uint32 lvl)
11674 SetUInt32Value(UNIT_FIELD_LEVEL, lvl);
11676 // group update
11677 if ((GetTypeId() == TYPEID_PLAYER) && ((Player*)this)->GetGroup())
11678 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL);
11681 void Unit::SetHealth(uint32 val)
11683 uint32 maxHealth = GetMaxHealth();
11684 if(maxHealth < val)
11685 val = maxHealth;
11687 SetUInt32Value(UNIT_FIELD_HEALTH, val);
11689 // group update
11690 if(GetTypeId() == TYPEID_PLAYER)
11692 if(((Player*)this)->GetGroup())
11693 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP);
11695 else if(((Creature*)this)->isPet())
11697 Pet *pet = ((Pet*)this);
11698 if(pet->isControlled())
11700 Unit *owner = GetOwner();
11701 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11702 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP);
11707 void Unit::SetMaxHealth(uint32 val)
11709 uint32 health = GetHealth();
11710 SetUInt32Value(UNIT_FIELD_MAXHEALTH, val);
11712 // group update
11713 if(GetTypeId() == TYPEID_PLAYER)
11715 if(((Player*)this)->GetGroup())
11716 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP);
11718 else if(((Creature*)this)->isPet())
11720 Pet *pet = ((Pet*)this);
11721 if(pet->isControlled())
11723 Unit *owner = GetOwner();
11724 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11725 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP);
11729 if(val < health)
11730 SetHealth(val);
11733 void Unit::SetHealthPercent(float percent)
11735 uint32 newHealth = GetMaxHealth() * percent/100.0f;
11736 SetHealth(newHealth);
11739 void Unit::SetPower(Powers power, uint32 val)
11741 if(GetPower(power) == val)
11742 return;
11744 uint32 maxPower = GetMaxPower(power);
11745 if(maxPower < val)
11746 val = maxPower;
11748 SetStatInt32Value(UNIT_FIELD_POWER1 + power, val);
11750 WorldPacket data(SMSG_POWER_UPDATE);
11751 data << GetPackGUID();
11752 data << uint8(power);
11753 data << uint32(val);
11754 SendMessageToSet(&data, GetTypeId() == TYPEID_PLAYER ? true : false);
11756 // group update
11757 if(GetTypeId() == TYPEID_PLAYER)
11759 if(((Player*)this)->GetGroup())
11760 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
11762 else if(((Creature*)this)->isPet())
11764 Pet *pet = ((Pet*)this);
11765 if(pet->isControlled())
11767 Unit *owner = GetOwner();
11768 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11769 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
11772 // Update the pet's character sheet with happiness damage bonus
11773 if(pet->getPetType() == HUNTER_PET && power == POWER_HAPPINESS)
11775 pet->UpdateDamagePhysical(BASE_ATTACK);
11780 void Unit::SetMaxPower(Powers power, uint32 val)
11782 uint32 cur_power = GetPower(power);
11783 SetStatInt32Value(UNIT_FIELD_MAXPOWER1 + power, val);
11785 // group update
11786 if(GetTypeId() == TYPEID_PLAYER)
11788 if(((Player*)this)->GetGroup())
11789 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
11791 else if(((Creature*)this)->isPet())
11793 Pet *pet = ((Pet*)this);
11794 if(pet->isControlled())
11796 Unit *owner = GetOwner();
11797 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11798 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
11802 if(val < cur_power)
11803 SetPower(power, val);
11806 void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply)
11808 ApplyModUInt32Value(UNIT_FIELD_POWER1+power, val, apply);
11810 // group update
11811 if(GetTypeId() == TYPEID_PLAYER)
11813 if(((Player*)this)->GetGroup())
11814 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
11816 else if(((Creature*)this)->isPet())
11818 Pet *pet = ((Pet*)this);
11819 if(pet->isControlled())
11821 Unit *owner = GetOwner();
11822 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11823 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
11828 void Unit::ApplyMaxPowerMod(Powers power, uint32 val, bool apply)
11830 ApplyModUInt32Value(UNIT_FIELD_MAXPOWER1+power, val, apply);
11832 // group update
11833 if(GetTypeId() == TYPEID_PLAYER)
11835 if(((Player*)this)->GetGroup())
11836 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
11838 else if(((Creature*)this)->isPet())
11840 Pet *pet = ((Pet*)this);
11841 if(pet->isControlled())
11843 Unit *owner = GetOwner();
11844 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11845 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
11850 void Unit::ApplyAuraProcTriggerDamage( Aura* aura, bool apply )
11852 AuraList& tAuraProcTriggerDamage = m_modAuras[SPELL_AURA_PROC_TRIGGER_DAMAGE];
11853 if(apply)
11854 tAuraProcTriggerDamage.push_back(aura);
11855 else
11856 tAuraProcTriggerDamage.remove(aura);
11859 uint32 Unit::GetCreatePowers( Powers power ) const
11861 // POWER_FOCUS and POWER_HAPPINESS only have hunter pet
11862 switch(power)
11864 case POWER_MANA: return GetCreateMana();
11865 case POWER_RAGE: return 1000;
11866 case POWER_FOCUS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 100);
11867 case POWER_ENERGY: return 100;
11868 case POWER_HAPPINESS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 1050000);
11869 case POWER_RUNIC_POWER: return 1000;
11870 case POWER_RUNE: return 0;
11871 case POWER_HEALTH: return 0;
11874 return 0;
11877 void Unit::AddToWorld()
11879 Object::AddToWorld();
11882 void Unit::RemoveFromWorld()
11884 // cleanup
11885 if (IsInWorld())
11887 Uncharm();
11888 RemoveNotOwnSingleTargetAuras();
11889 RemoveGuardians();
11890 RemoveAllGameObjects();
11891 RemoveAllDynObjects();
11892 CleanupDeletedAuras();
11895 Object::RemoveFromWorld();
11898 void Unit::CleanupsBeforeDelete()
11900 if(m_uint32Values) // only for fully created object
11902 InterruptNonMeleeSpells(true);
11903 m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList
11904 CombatStop();
11905 ClearComboPointHolders();
11906 DeleteThreatList();
11907 getHostileRefManager().setOnlineOfflineState(false);
11908 RemoveAllAuras(AURA_REMOVE_BY_DELETE);
11909 GetMotionMaster()->Clear(false); // remove different non-standard movement generators.
11911 WorldObject::CleanupsBeforeDelete();
11914 CharmInfo* Unit::InitCharmInfo(Unit *charm)
11916 if(!m_charmInfo)
11917 m_charmInfo = new CharmInfo(charm);
11918 return m_charmInfo;
11921 CharmInfo::CharmInfo(Unit* unit)
11922 : m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_reactState(REACT_PASSIVE), m_petnumber(0)
11924 for(int i = 0; i < CREATURE_MAX_SPELLS; ++i)
11925 m_charmspells[i].SetActionAndType(0,ACT_DISABLED);
11928 void CharmInfo::InitPetActionBar()
11930 // the first 3 SpellOrActions are attack, follow and stay
11931 for(uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_START - ACTION_BAR_INDEX_START; ++i)
11932 SetActionBar(ACTION_BAR_INDEX_START + i,COMMAND_ATTACK - i,ACT_COMMAND);
11934 // middle 4 SpellOrActions are spells/special attacks/abilities
11935 for(uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_END-ACTION_BAR_INDEX_PET_SPELL_START; ++i)
11936 SetActionBar(ACTION_BAR_INDEX_PET_SPELL_START + i,0,ACT_DISABLED);
11938 // last 3 SpellOrActions are reactions
11939 for(uint32 i = 0; i < ACTION_BAR_INDEX_END - ACTION_BAR_INDEX_PET_SPELL_END; ++i)
11940 SetActionBar(ACTION_BAR_INDEX_PET_SPELL_END + i,COMMAND_ATTACK - i,ACT_REACTION);
11943 void CharmInfo::InitEmptyActionBar()
11945 SetActionBar(ACTION_BAR_INDEX_START,COMMAND_ATTACK,ACT_COMMAND);
11946 for(uint32 x = ACTION_BAR_INDEX_START+1; x < ACTION_BAR_INDEX_END; ++x)
11947 SetActionBar(x,0,ACT_PASSIVE);
11950 void CharmInfo::InitPossessCreateSpells()
11952 InitEmptyActionBar(); //charm action bar
11954 if(m_unit->GetTypeId() == TYPEID_PLAYER) //possessed players don't have spells, keep the action bar empty
11955 return;
11957 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
11959 if (IsPassiveSpell(((Creature*)m_unit)->m_spells[x]))
11960 m_unit->CastSpell(m_unit, ((Creature*)m_unit)->m_spells[x], true);
11961 else
11962 AddSpellToActionBar(((Creature*)m_unit)->m_spells[x], ACT_PASSIVE);
11966 void CharmInfo::InitCharmCreateSpells()
11968 if(m_unit->GetTypeId() == TYPEID_PLAYER) //charmed players don't have spells
11970 InitEmptyActionBar();
11971 return;
11974 InitPetActionBar();
11976 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
11978 uint32 spellId = ((Creature*)m_unit)->m_spells[x];
11980 if(!spellId)
11982 m_charmspells[x].SetActionAndType(spellId,ACT_DISABLED);
11983 continue;
11986 if (IsPassiveSpell(spellId))
11988 m_unit->CastSpell(m_unit, spellId, true);
11989 m_charmspells[x].SetActionAndType(spellId,ACT_PASSIVE);
11991 else
11993 m_charmspells[x].SetActionAndType(spellId,ACT_DISABLED);
11995 ActiveStates newstate;
11996 bool onlyselfcast = true;
11997 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
11999 if(!spellInfo) onlyselfcast = false;
12000 for(uint32 i = 0;i<3 && onlyselfcast;++i) //non existent spell will not make any problems as onlyselfcast would be false -> break right away
12002 if(spellInfo->EffectImplicitTargetA[i] != TARGET_SELF && spellInfo->EffectImplicitTargetA[i] != 0)
12003 onlyselfcast = false;
12006 if(onlyselfcast || !IsPositiveSpell(spellId)) //only self cast and spells versus enemies are autocastable
12007 newstate = ACT_DISABLED;
12008 else
12009 newstate = ACT_PASSIVE;
12011 AddSpellToActionBar(spellId, newstate);
12016 bool CharmInfo::AddSpellToActionBar(uint32 spell_id, ActiveStates newstate)
12018 uint32 first_id = sSpellMgr.GetFirstSpellInChain(spell_id);
12020 // new spell rank can be already listed
12021 for(uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
12023 if (uint32 action = PetActionBar[i].GetAction())
12025 if (PetActionBar[i].IsActionBarForSpell() && sSpellMgr.GetFirstSpellInChain(action) == first_id)
12027 PetActionBar[i].SetAction(spell_id);
12028 return true;
12033 // or use empty slot in other case
12034 for(uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
12036 if (!PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell())
12038 SetActionBar(i,spell_id,newstate == ACT_DECIDE ? ACT_DISABLED : newstate);
12039 return true;
12042 return false;
12045 bool CharmInfo::RemoveSpellFromActionBar(uint32 spell_id)
12047 uint32 first_id = sSpellMgr.GetFirstSpellInChain(spell_id);
12049 for(uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
12051 if (uint32 action = PetActionBar[i].GetAction())
12053 if (PetActionBar[i].IsActionBarForSpell() && sSpellMgr.GetFirstSpellInChain(action) == first_id)
12055 SetActionBar(i,0,ACT_DISABLED);
12056 return true;
12061 return false;
12064 void CharmInfo::ToggleCreatureAutocast(uint32 spellid, bool apply)
12066 if(IsPassiveSpell(spellid))
12067 return;
12069 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
12070 if(spellid == m_charmspells[x].GetAction())
12071 m_charmspells[x].SetType(apply ? ACT_ENABLED : ACT_DISABLED);
12074 void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow)
12076 m_petnumber = petnumber;
12077 if(statwindow)
12078 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber);
12079 else
12080 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0);
12083 void CharmInfo::LoadPetActionBar(const std::string& data )
12085 InitPetActionBar();
12087 Tokens tokens = StrSplit(data, " ");
12089 if (tokens.size() != (ACTION_BAR_INDEX_END-ACTION_BAR_INDEX_START)*2)
12090 return; // non critical, will reset to default
12092 int index;
12093 Tokens::iterator iter;
12094 for(iter = tokens.begin(), index = ACTION_BAR_INDEX_START; index < ACTION_BAR_INDEX_END; ++iter, ++index )
12096 // use unsigned cast to avoid sign negative format use at long-> ActiveStates (int) conversion
12097 uint8 type = (uint8)atol((*iter).c_str());
12098 ++iter;
12099 uint32 action = atol((*iter).c_str());
12101 PetActionBar[index].SetActionAndType(action,ActiveStates(type));
12103 // check correctness
12104 if(PetActionBar[index].IsActionBarForSpell() && !sSpellStore.LookupEntry(PetActionBar[index].GetAction()))
12105 SetActionBar(index,0,ACT_DISABLED);
12109 void CharmInfo::BuildActionBar( WorldPacket* data )
12111 for(uint32 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
12112 *data << uint32(PetActionBar[i].packedData);
12115 void CharmInfo::SetSpellAutocast( uint32 spell_id, bool state )
12117 for(int i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
12119 if(spell_id == PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell())
12121 PetActionBar[i].SetType(state ? ACT_ENABLED : ACT_DISABLED);
12122 break;
12127 bool Unit::isFrozen() const
12129 return HasAuraState(AURA_STATE_FROZEN);
12132 struct ProcTriggeredData
12134 ProcTriggeredData(SpellProcEventEntry const * _spellProcEvent, Aura* _triggeredByAura)
12135 : spellProcEvent(_spellProcEvent), triggeredByAura(_triggeredByAura),
12136 triggeredByAura_SpellPair(Unit::spellEffectPair(triggeredByAura->GetId(),triggeredByAura->GetEffIndex()))
12138 SpellProcEventEntry const *spellProcEvent;
12139 Aura* triggeredByAura;
12140 Unit::spellEffectPair triggeredByAura_SpellPair;
12143 typedef std::list< ProcTriggeredData > ProcTriggeredList;
12144 typedef std::list< uint32> RemoveSpellList;
12146 // List of auras that CAN be trigger but may not exist in spell_proc_event
12147 // in most case need for drop charges
12148 // in some types of aura need do additional check
12149 // for example SPELL_AURA_MECHANIC_IMMUNITY - need check for mechanic
12150 bool InitTriggerAuraData()
12152 for (int i=0;i<TOTAL_AURAS;++i)
12154 isTriggerAura[i]=false;
12155 isNonTriggerAura[i] = false;
12157 isTriggerAura[SPELL_AURA_DUMMY] = true;
12158 isTriggerAura[SPELL_AURA_MOD_CONFUSE] = true;
12159 isTriggerAura[SPELL_AURA_MOD_THREAT] = true;
12160 isTriggerAura[SPELL_AURA_MOD_STUN] = true; // Aura not have charges but need remove him on trigger
12161 isTriggerAura[SPELL_AURA_MOD_DAMAGE_DONE] = true;
12162 isTriggerAura[SPELL_AURA_MOD_DAMAGE_TAKEN] = true;
12163 isTriggerAura[SPELL_AURA_MOD_RESISTANCE] = true;
12164 isTriggerAura[SPELL_AURA_MOD_ROOT] = true;
12165 isTriggerAura[SPELL_AURA_REFLECT_SPELLS] = true;
12166 isTriggerAura[SPELL_AURA_DAMAGE_IMMUNITY] = true;
12167 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL] = true;
12168 isTriggerAura[SPELL_AURA_PROC_TRIGGER_DAMAGE] = true;
12169 isTriggerAura[SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK] = true;
12170 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT] = true;
12171 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL] = true;
12172 isTriggerAura[SPELL_AURA_REFLECT_SPELLS_SCHOOL] = true;
12173 isTriggerAura[SPELL_AURA_MECHANIC_IMMUNITY] = true;
12174 isTriggerAura[SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN] = true;
12175 isTriggerAura[SPELL_AURA_SPELL_MAGNET] = true;
12176 isTriggerAura[SPELL_AURA_MOD_ATTACK_POWER] = true;
12177 isTriggerAura[SPELL_AURA_ADD_CASTER_HIT_TRIGGER] = true;
12178 isTriggerAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true;
12179 isTriggerAura[SPELL_AURA_MOD_MECHANIC_RESISTANCE] = true;
12180 isTriggerAura[SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS] = true;
12181 isTriggerAura[SPELL_AURA_MOD_HASTE] = true;
12182 isTriggerAura[SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE]=true;
12183 isTriggerAura[SPELL_AURA_PRAYER_OF_MENDING] = true;
12184 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE] = true;
12185 isTriggerAura[SPELL_AURA_MOD_DAMAGE_FROM_CASTER] = true;
12186 isTriggerAura[SPELL_AURA_MOD_SPELL_CRIT_CHANCE] = true;
12187 isTriggerAura[SPELL_AURA_MAELSTROM_WEAPON] = true;
12189 isNonTriggerAura[SPELL_AURA_MOD_POWER_REGEN]=true;
12190 isNonTriggerAura[SPELL_AURA_REDUCE_PUSHBACK]=true;
12192 return true;
12195 uint32 createProcExtendMask(SpellNonMeleeDamage *damageInfo, SpellMissInfo missCondition)
12197 uint32 procEx = PROC_EX_NONE;
12198 // Check victim state
12199 if (missCondition!=SPELL_MISS_NONE)
12200 switch (missCondition)
12202 case SPELL_MISS_MISS: procEx|=PROC_EX_MISS; break;
12203 case SPELL_MISS_RESIST: procEx|=PROC_EX_RESIST; break;
12204 case SPELL_MISS_DODGE: procEx|=PROC_EX_DODGE; break;
12205 case SPELL_MISS_PARRY: procEx|=PROC_EX_PARRY; break;
12206 case SPELL_MISS_BLOCK: procEx|=PROC_EX_BLOCK; break;
12207 case SPELL_MISS_EVADE: procEx|=PROC_EX_EVADE; break;
12208 case SPELL_MISS_IMMUNE: procEx|=PROC_EX_IMMUNE; break;
12209 case SPELL_MISS_IMMUNE2: procEx|=PROC_EX_IMMUNE; break;
12210 case SPELL_MISS_DEFLECT: procEx|=PROC_EX_DEFLECT;break;
12211 case SPELL_MISS_ABSORB: procEx|=PROC_EX_ABSORB; break;
12212 case SPELL_MISS_REFLECT: procEx|=PROC_EX_REFLECT;break;
12213 default:
12214 break;
12216 else
12218 // On block
12219 if (damageInfo->blocked)
12220 procEx|=PROC_EX_BLOCK;
12221 // On absorb
12222 if (damageInfo->absorb)
12223 procEx|=PROC_EX_ABSORB;
12224 // On crit
12225 if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT)
12226 procEx|=PROC_EX_CRITICAL_HIT;
12227 else
12228 procEx|=PROC_EX_NORMAL_HIT;
12230 return procEx;
12233 void Unit::ProcDamageAndSpellFor( bool isVictim, Unit * pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const * procSpell, uint32 damage )
12235 // For melee/ranged based attack need update skills and set some Aura states
12236 if (procFlag & MELEE_BASED_TRIGGER_MASK)
12238 // Update skills here for players
12239 if (GetTypeId() == TYPEID_PLAYER)
12241 // On melee based hit/miss/resist need update skill (for victim and attacker)
12242 if (procExtra&(PROC_EX_NORMAL_HIT|PROC_EX_MISS|PROC_EX_RESIST))
12244 if (pTarget->GetTypeId() != TYPEID_PLAYER && pTarget->GetCreatureType() != CREATURE_TYPE_CRITTER)
12245 ((Player*)this)->UpdateCombatSkills(pTarget, attType, isVictim);
12247 // Update defence if player is victim and parry/dodge/block
12248 if (isVictim && procExtra&(PROC_EX_DODGE|PROC_EX_PARRY|PROC_EX_BLOCK))
12249 ((Player*)this)->UpdateDefense();
12251 // If exist crit/parry/dodge/block need update aura state (for victim and attacker)
12252 if (procExtra & (PROC_EX_CRITICAL_HIT|PROC_EX_PARRY|PROC_EX_DODGE|PROC_EX_BLOCK))
12254 // for victim
12255 if (isVictim)
12257 // if victim and dodge attack
12258 if (procExtra&PROC_EX_DODGE)
12260 //Update AURA_STATE on dodge
12261 if (getClass() != CLASS_ROGUE) // skip Rogue Riposte
12263 ModifyAuraState(AURA_STATE_DEFENSE, true);
12264 StartReactiveTimer( REACTIVE_DEFENSE );
12267 // if victim and parry attack
12268 if (procExtra & PROC_EX_PARRY)
12270 // For Hunters only Counterattack (skip Mongoose bite)
12271 if (getClass() == CLASS_HUNTER)
12273 ModifyAuraState(AURA_STATE_HUNTER_PARRY, true);
12274 StartReactiveTimer( REACTIVE_HUNTER_PARRY );
12276 else
12278 ModifyAuraState(AURA_STATE_DEFENSE, true);
12279 StartReactiveTimer( REACTIVE_DEFENSE );
12282 // if and victim block attack
12283 if (procExtra & PROC_EX_BLOCK)
12285 ModifyAuraState(AURA_STATE_DEFENSE,true);
12286 StartReactiveTimer( REACTIVE_DEFENSE );
12289 else //For attacker
12291 // Overpower on victim dodge
12292 if (procExtra&PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR)
12294 ((Player*)this)->AddComboPoints(pTarget, 1);
12295 StartReactiveTimer( REACTIVE_OVERPOWER );
12301 RemoveSpellList removedSpells;
12302 ProcTriggeredList procTriggered;
12303 // Fill procTriggered list
12304 for(AuraMap::const_iterator itr = GetAuras().begin(); itr!= GetAuras().end(); ++itr)
12306 // skip deleted auras (possible at recursive triggered call
12307 if(itr->second->IsDeleted())
12308 continue;
12310 SpellProcEventEntry const* spellProcEvent = NULL;
12311 if(!IsTriggeredAtSpellProcEvent(pTarget, itr->second, procSpell, procFlag, procExtra, attType, isVictim, (damage > 0), spellProcEvent))
12312 continue;
12314 itr->second->SetInUse(true); // prevent aura deletion
12315 procTriggered.push_back( ProcTriggeredData(spellProcEvent, itr->second) );
12318 // Nothing found
12319 if (procTriggered.empty())
12320 return;
12322 // Handle effects proceed this time
12323 for(ProcTriggeredList::const_iterator i = procTriggered.begin(); i != procTriggered.end(); ++i)
12325 // Some auras can be deleted in function called in this loop (except first, ofc)
12326 Aura *triggeredByAura = i->triggeredByAura;
12327 if(triggeredByAura->IsDeleted())
12328 continue;
12330 SpellProcEventEntry const *spellProcEvent = i->spellProcEvent;
12331 Modifier *auraModifier = triggeredByAura->GetModifier();
12332 SpellEntry const *spellInfo = triggeredByAura->GetSpellProto();
12333 bool useCharges = triggeredByAura->GetAuraCharges() > 0;
12334 // For players set spell cooldown if need
12335 uint32 cooldown = 0;
12336 if (GetTypeId() == TYPEID_PLAYER && spellProcEvent && spellProcEvent->cooldown)
12337 cooldown = spellProcEvent->cooldown;
12339 switch(auraModifier->m_auraname)
12341 case SPELL_AURA_PROC_TRIGGER_SPELL:
12343 sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
12344 // Don`t drop charge or add cooldown for not started trigger
12345 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
12347 triggeredByAura->SetInUse(false);
12348 continue;
12350 break;
12352 case SPELL_AURA_PROC_TRIGGER_DAMAGE:
12354 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());
12355 SpellNonMeleeDamage damageInfo(this, pTarget, spellInfo->Id, spellInfo->SchoolMask);
12356 CalculateSpellDamage(&damageInfo, auraModifier->m_amount, spellInfo);
12357 DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb);
12358 SendSpellNonMeleeDamageLog(&damageInfo);
12359 DealSpellDamage(&damageInfo, true);
12360 break;
12362 case SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN:
12363 case SPELL_AURA_MANA_SHIELD:
12364 case SPELL_AURA_OBS_MOD_MANA:
12365 case SPELL_AURA_ADD_PCT_MODIFIER:
12366 case SPELL_AURA_DUMMY:
12368 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());
12369 if (!HandleDummyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
12371 triggeredByAura->SetInUse(false);
12372 continue;
12374 break;
12376 case SPELL_AURA_MOD_HASTE:
12378 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());
12379 if (!HandleHasteAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
12381 triggeredByAura->SetInUse(false);
12382 continue;
12384 break;
12386 case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
12388 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());
12389 if (!HandleOverrideClassScriptAuraProc(pTarget, damage, triggeredByAura, procSpell, cooldown))
12391 triggeredByAura->SetInUse(false);
12392 continue;
12394 break;
12396 case SPELL_AURA_PRAYER_OF_MENDING:
12398 sLog.outDebug("ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
12399 (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
12401 HandleMendingAuraProc(triggeredByAura);
12402 break;
12404 case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE:
12406 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());
12408 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
12410 triggeredByAura->SetInUse(false);
12411 continue;
12413 break;
12415 case SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK:
12416 // Skip melee hits or instant cast spells
12417 if (procSpell == NULL || GetSpellCastTime(procSpell) == 0)
12419 triggeredByAura->SetInUse(false);
12420 continue;
12422 break;
12423 case SPELL_AURA_REFLECT_SPELLS_SCHOOL:
12424 // Skip Melee hits and spells ws wrong school
12425 if (procSpell == NULL || (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0)
12427 triggeredByAura->SetInUse(false);
12428 continue;
12430 break;
12431 case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT:
12432 case SPELL_AURA_MOD_POWER_COST_SCHOOL:
12433 // Skip melee hits and spells ws wrong school or zero cost
12434 if (procSpell == NULL ||
12435 (procSpell->manaCost == 0 && procSpell->ManaCostPercentage == 0) || // Cost check
12436 (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0) // School check
12438 triggeredByAura->SetInUse(false);
12439 continue;
12441 break;
12442 case SPELL_AURA_MECHANIC_IMMUNITY:
12443 // Compare mechanic
12444 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
12446 triggeredByAura->SetInUse(false);
12447 continue;
12449 break;
12450 case SPELL_AURA_MOD_MECHANIC_RESISTANCE:
12451 // Compare mechanic
12452 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
12454 triggeredByAura->SetInUse(false);
12455 continue;
12457 break;
12458 case SPELL_AURA_MOD_DAMAGE_FROM_CASTER:
12459 // Compare casters
12460 if (triggeredByAura->GetCasterGUID() != pTarget->GetGUID())
12462 triggeredByAura->SetInUse(false);
12463 continue;
12465 break;
12466 case SPELL_AURA_MOD_SPELL_CRIT_CHANCE:
12467 if (!procSpell)
12469 triggeredByAura->SetInUse(false);
12470 continue;
12472 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());
12473 if (!HandleSpellCritChanceAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
12475 triggeredByAura->SetInUse(false);
12476 continue;
12478 break;
12479 case SPELL_AURA_MAELSTROM_WEAPON:
12480 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());
12482 // remove all stack;
12483 RemoveSpellsCausingAura(SPELL_AURA_MAELSTROM_WEAPON);
12484 triggeredByAura->SetInUse(false); // this safe, aura locked
12485 continue; // avoid re-remove attempts
12486 default:
12487 // nothing do, just charges counter
12488 break;
12491 // Remove charge (aura can be removed by triggers)
12492 if(useCharges && !triggeredByAura->IsDeleted())
12494 // If last charge dropped add spell to remove list
12495 if(triggeredByAura->DropAuraCharge())
12496 removedSpells.push_back(triggeredByAura->GetId());
12499 triggeredByAura->SetInUse(false);
12501 if (!removedSpells.empty())
12503 // Sort spells and remove dublicates
12504 removedSpells.sort();
12505 removedSpells.unique();
12506 // Remove auras from removedAuras
12507 for(RemoveSpellList::const_iterator i = removedSpells.begin(); i != removedSpells.end();++i)
12508 RemoveSingleSpellAurasFromStack(*i);
12512 SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const
12514 return SPELL_SCHOOL_MASK_NORMAL;
12517 Player* Unit::GetSpellModOwner()
12519 if(GetTypeId()==TYPEID_PLAYER)
12520 return (Player*)this;
12521 if(((Creature*)this)->isPet() || ((Creature*)this)->isTotem())
12523 Unit* owner = GetOwner();
12524 if(owner && owner->GetTypeId()==TYPEID_PLAYER)
12525 return (Player*)owner;
12527 return NULL;
12530 ///----------Pet responses methods-----------------
12531 void Unit::SendPetCastFail(uint32 spellid, SpellCastResult msg)
12533 if(msg == SPELL_CAST_OK)
12534 return;
12536 Unit *owner = GetCharmerOrOwner();
12537 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
12538 return;
12540 WorldPacket data(SMSG_PET_CAST_FAILED, 1 + 4 + 1);
12541 data << uint8(0); // cast count?
12542 data << uint32(spellid);
12543 data << uint8(msg);
12544 // uint32 for some reason
12545 // uint32 for some reason
12546 ((Player*)owner)->GetSession()->SendPacket(&data);
12549 void Unit::SendPetActionFeedback (uint8 msg)
12551 Unit* owner = GetOwner();
12552 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
12553 return;
12555 WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1);
12556 data << uint8(msg);
12557 ((Player*)owner)->GetSession()->SendPacket(&data);
12560 void Unit::SendPetTalk (uint32 pettalk)
12562 Unit* owner = GetOwner();
12563 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
12564 return;
12566 WorldPacket data(SMSG_PET_ACTION_SOUND, 8 + 4);
12567 data << uint64(GetGUID());
12568 data << uint32(pettalk);
12569 ((Player*)owner)->GetSession()->SendPacket(&data);
12572 void Unit::SendPetAIReaction(uint64 guid)
12574 Unit* owner = GetOwner();
12575 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
12576 return;
12578 WorldPacket data(SMSG_AI_REACTION, 8 + 4);
12579 data << uint64(guid);
12580 data << uint32(AI_REACTION_HOSTILE);
12581 ((Player*)owner)->GetSession()->SendPacket(&data);
12584 ///----------End of Pet responses methods----------
12586 void Unit::StopMoving()
12588 clearUnitState(UNIT_STAT_MOVING);
12590 // send explicit stop packet
12591 // player expected for correct work SPLINEFLAG_WALKMODE
12592 SendMonsterMove(GetPositionX(), GetPositionY(), GetPositionZ(), SPLINETYPE_NORMAL, GetTypeId() == TYPEID_PLAYER ? SPLINEFLAG_WALKMODE : SPLINEFLAG_NONE, 0);
12594 // update position and orientation for near players
12595 WorldPacket data;
12596 BuildHeartBeatMsg(&data);
12597 SendMessageToSet(&data, false);
12600 void Unit::SetFeared(bool apply, uint64 const& casterGUID, uint32 spellID, uint32 time)
12602 if( apply )
12604 if(HasAuraType(SPELL_AURA_PREVENTS_FLEEING))
12605 return;
12607 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
12609 GetMotionMaster()->MovementExpired(false);
12610 CastStop(GetGUID() == casterGUID ? spellID : 0);
12612 Unit* caster = ObjectAccessor::GetUnit(*this,casterGUID);
12614 GetMotionMaster()->MoveFleeing(caster, time); // caster==NULL processed in MoveFleeing
12616 else
12618 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
12620 GetMotionMaster()->MovementExpired(false);
12622 if( GetTypeId() != TYPEID_PLAYER && isAlive() )
12624 // restore appropriate movement generator
12625 if(getVictim())
12626 GetMotionMaster()->MoveChase(getVictim());
12627 else
12628 GetMotionMaster()->Initialize();
12630 // attack caster if can
12631 Unit* caster = Unit::GetUnit(*this, casterGUID);
12632 if(caster && ((Creature*)this)->AI())
12633 ((Creature*)this)->AI()->AttackedBy(caster);
12637 if (GetTypeId() == TYPEID_PLAYER)
12638 ((Player*)this)->SetClientControl(this, !apply);
12641 void Unit::SetConfused(bool apply, uint64 const& casterGUID, uint32 spellID)
12643 if( apply )
12645 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
12647 CastStop(GetGUID()==casterGUID ? spellID : 0);
12649 GetMotionMaster()->MoveConfused();
12651 else
12653 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
12655 GetMotionMaster()->MovementExpired(false);
12657 if (GetTypeId() != TYPEID_PLAYER && isAlive())
12659 // restore appropriate movement generator
12660 if(getVictim())
12661 GetMotionMaster()->MoveChase(getVictim());
12662 else
12663 GetMotionMaster()->Initialize();
12667 if(GetTypeId() == TYPEID_PLAYER)
12668 ((Player*)this)->SetClientControl(this, !apply);
12671 void Unit::SetFeignDeath(bool apply, uint64 const& casterGUID, uint32 /*spellID*/)
12673 if( apply )
12676 WorldPacket data(SMSG_FEIGN_DEATH_RESISTED, 9);
12677 data<<GetGUID();
12678 data<<uint8(0);
12679 SendMessageToSet(&data,true);
12682 if(GetTypeId() != TYPEID_PLAYER)
12683 StopMoving();
12684 else
12685 ((Player*)this)->m_movementInfo.SetMovementFlags(MOVEFLAG_NONE);
12687 // blizz like 2.0.x
12688 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29);
12689 // blizz like 2.0.x
12690 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH);
12691 // blizz like 2.0.x
12692 SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_DEAD);
12694 addUnitState(UNIT_STAT_DIED);
12695 CombatStop();
12696 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION);
12698 // prevent interrupt message
12699 if (casterGUID == GetGUID())
12700 FinishSpell(CURRENT_GENERIC_SPELL,false);
12701 InterruptNonMeleeSpells(true);
12702 getHostileRefManager().deleteReferences();
12704 else
12707 WorldPacket data(SMSG_FEIGN_DEATH_RESISTED, 9);
12708 data<<GetGUID();
12709 data<<uint8(1);
12710 SendMessageToSet(&data,true);
12712 // blizz like 2.0.x
12713 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29);
12714 // blizz like 2.0.x
12715 RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH);
12716 // blizz like 2.0.x
12717 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_DEAD);
12719 clearUnitState(UNIT_STAT_DIED);
12721 if (GetTypeId() != TYPEID_PLAYER && isAlive())
12723 // restore appropriate movement generator
12724 if(getVictim())
12725 GetMotionMaster()->MoveChase(getVictim());
12726 else
12727 GetMotionMaster()->Initialize();
12733 bool Unit::IsSitState() const
12735 uint8 s = getStandState();
12736 return
12737 s == UNIT_STAND_STATE_SIT_CHAIR || s == UNIT_STAND_STATE_SIT_LOW_CHAIR ||
12738 s == UNIT_STAND_STATE_SIT_MEDIUM_CHAIR || s == UNIT_STAND_STATE_SIT_HIGH_CHAIR ||
12739 s == UNIT_STAND_STATE_SIT;
12742 bool Unit::IsStandState() const
12744 uint8 s = getStandState();
12745 return !IsSitState() && s != UNIT_STAND_STATE_SLEEP && s != UNIT_STAND_STATE_KNEEL;
12748 void Unit::SetStandState(uint8 state)
12750 SetByteValue(UNIT_FIELD_BYTES_1, 0, state);
12752 if (IsStandState())
12753 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED);
12755 if(GetTypeId()==TYPEID_PLAYER)
12757 WorldPacket data(SMSG_STANDSTATE_UPDATE, 1);
12758 data << (uint8)state;
12759 ((Player*)this)->GetSession()->SendPacket(&data);
12763 bool Unit::IsPolymorphed() const
12765 return GetSpellSpecific(getTransForm())==SPELL_MAGE_POLYMORPH;
12768 void Unit::SetDisplayId(uint32 modelId)
12770 SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId);
12772 if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
12774 Pet *pet = ((Pet*)this);
12775 if(!pet->isControlled())
12776 return;
12777 Unit *owner = GetOwner();
12778 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
12779 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID);
12783 void Unit::ClearComboPointHolders()
12785 while(!m_ComboPointHolders.empty())
12787 uint32 lowguid = *m_ComboPointHolders.begin();
12789 Player* plr = sObjectMgr.GetPlayer(ObjectGuid(HIGHGUID_PLAYER, lowguid));
12790 if(plr && plr->GetComboTarget()==GetGUID()) // recheck for safe
12791 plr->ClearComboPoints(); // remove also guid from m_ComboPointHolders;
12792 else
12793 m_ComboPointHolders.erase(lowguid); // or remove manually
12797 void Unit::ClearAllReactives()
12799 for(int i=0; i < MAX_REACTIVE; ++i)
12800 m_reactiveTimer[i] = 0;
12802 if (HasAuraState( AURA_STATE_DEFENSE))
12803 ModifyAuraState(AURA_STATE_DEFENSE, false);
12804 if (getClass() == CLASS_HUNTER && HasAuraState( AURA_STATE_HUNTER_PARRY))
12805 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
12806 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
12807 ((Player*)this)->ClearComboPoints();
12810 void Unit::UpdateReactives( uint32 p_time )
12812 for(int i = 0; i < MAX_REACTIVE; ++i)
12814 ReactiveType reactive = ReactiveType(i);
12816 if(!m_reactiveTimer[reactive])
12817 continue;
12819 if ( m_reactiveTimer[reactive] <= p_time)
12821 m_reactiveTimer[reactive] = 0;
12823 switch ( reactive )
12825 case REACTIVE_DEFENSE:
12826 if (HasAuraState(AURA_STATE_DEFENSE))
12827 ModifyAuraState(AURA_STATE_DEFENSE, false);
12828 break;
12829 case REACTIVE_HUNTER_PARRY:
12830 if ( getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
12831 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
12832 break;
12833 case REACTIVE_OVERPOWER:
12834 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
12835 ((Player*)this)->ClearComboPoints();
12836 break;
12837 default:
12838 break;
12841 else
12843 m_reactiveTimer[reactive] -= p_time;
12848 Unit* Unit::SelectRandomUnfriendlyTarget(Unit* except /*= NULL*/, float radius /*= ATTACK_DISTANCE*/) const
12850 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
12851 Cell cell(p);
12852 cell.data.Part.reserved = ALL_DISTRICT;
12853 cell.SetNoCreate();
12855 std::list<Unit *> targets;
12857 MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, radius);
12858 MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> searcher(this, targets, u_check);
12860 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
12861 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
12863 cell.Visit(p, world_unit_searcher, *GetMap(), *this, radius);
12864 cell.Visit(p, grid_unit_searcher, *GetMap(), *this, radius);
12866 // remove current target
12867 if(except)
12868 targets.remove(except);
12870 // remove not LoS targets
12871 for(std::list<Unit *>::iterator tIter = targets.begin(); tIter != targets.end();)
12873 if(!IsWithinLOSInMap(*tIter))
12875 std::list<Unit *>::iterator tIter2 = tIter;
12876 ++tIter;
12877 targets.erase(tIter2);
12879 else
12880 ++tIter;
12883 // no appropriate targets
12884 if(targets.empty())
12885 return NULL;
12887 // select random
12888 uint32 rIdx = urand(0,targets.size()-1);
12889 std::list<Unit *>::const_iterator tcIter = targets.begin();
12890 for(uint32 i = 0; i < rIdx; ++i)
12891 ++tcIter;
12893 return *tcIter;
12896 Unit* Unit::SelectRandomFriendlyTarget(Unit* except /*= NULL*/, float radius /*= ATTACK_DISTANCE*/) const
12898 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
12899 Cell cell(p);
12900 cell.data.Part.reserved = ALL_DISTRICT;
12901 cell.SetNoCreate();
12903 std::list<Unit *> targets;
12905 MaNGOS::AnyFriendlyUnitInObjectRangeCheck u_check(this, radius);
12906 MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck> searcher(this, targets, u_check);
12908 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
12909 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
12911 cell.Visit(p, world_unit_searcher, *GetMap(), *this, radius);
12912 cell.Visit(p, grid_unit_searcher, *GetMap(), *this, radius);
12914 // remove current target
12915 if(except)
12916 targets.remove(except);
12918 // remove not LoS targets
12919 for(std::list<Unit *>::iterator tIter = targets.begin(); tIter != targets.end();)
12921 if(!IsWithinLOSInMap(*tIter))
12923 std::list<Unit *>::iterator tIter2 = tIter;
12924 ++tIter;
12925 targets.erase(tIter2);
12927 else
12928 ++tIter;
12931 // no appropriate targets
12932 if(targets.empty())
12933 return NULL;
12935 // select random
12936 uint32 rIdx = urand(0,targets.size()-1);
12937 std::list<Unit *>::const_iterator tcIter = targets.begin();
12938 for(uint32 i = 0; i < rIdx; ++i)
12939 ++tcIter;
12941 return *tcIter;
12944 bool Unit::hasNegativeAuraWithInterruptFlag(uint32 flag)
12946 for (AuraMap::const_iterator iter = m_Auras.begin(); iter != m_Auras.end(); ++iter)
12948 if (!iter->second->IsPositive() && iter->second->GetSpellProto()->AuraInterruptFlags & flag)
12949 return true;
12951 return false;
12954 void Unit::ApplyAttackTimePercentMod( WeaponAttackType att,float val, bool apply )
12956 if(val > 0)
12958 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply);
12959 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,val,!apply);
12961 else
12963 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply);
12964 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,-val,apply);
12968 void Unit::ApplyCastTimePercentMod(float val, bool apply )
12970 if(val > 0)
12971 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,val,!apply);
12972 else
12973 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,-val,apply);
12976 uint32 Unit::GetCastingTimeForBonus( SpellEntry const *spellProto, DamageEffectType damagetype, uint32 CastingTime )
12978 // Not apply this to creature casted spells with casttime==0
12979 if(CastingTime==0 && GetTypeId()==TYPEID_UNIT && !((Creature*)this)->isPet())
12980 return 3500;
12982 if (CastingTime > 7000) CastingTime = 7000;
12983 if (CastingTime < 1500) CastingTime = 1500;
12985 if(damagetype == DOT && !IsChanneledSpell(spellProto))
12986 CastingTime = 3500;
12988 int32 overTime = 0;
12989 uint8 effects = 0;
12990 bool DirectDamage = false;
12991 bool AreaEffect = false;
12993 for (uint32 i = 0; i < MAX_EFFECT_INDEX; ++i)
12995 switch (spellProto->Effect[i])
12997 case SPELL_EFFECT_SCHOOL_DAMAGE:
12998 case SPELL_EFFECT_POWER_DRAIN:
12999 case SPELL_EFFECT_HEALTH_LEECH:
13000 case SPELL_EFFECT_ENVIRONMENTAL_DAMAGE:
13001 case SPELL_EFFECT_POWER_BURN:
13002 case SPELL_EFFECT_HEAL:
13003 DirectDamage = true;
13004 break;
13005 case SPELL_EFFECT_APPLY_AURA:
13006 switch (spellProto->EffectApplyAuraName[i])
13008 case SPELL_AURA_PERIODIC_DAMAGE:
13009 case SPELL_AURA_PERIODIC_HEAL:
13010 case SPELL_AURA_PERIODIC_LEECH:
13011 if ( GetSpellDuration(spellProto) )
13012 overTime = GetSpellDuration(spellProto);
13013 break;
13014 default:
13015 // -5% per additional effect
13016 ++effects;
13017 break;
13019 default:
13020 break;
13023 if (IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetA[i])) || IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetB[i])))
13024 AreaEffect = true;
13027 // Combined Spells with Both Over Time and Direct Damage
13028 if (overTime > 0 && CastingTime > 0 && DirectDamage)
13030 // mainly for DoTs which are 3500 here otherwise
13031 uint32 OriginalCastTime = GetSpellCastTime(spellProto);
13032 if (OriginalCastTime > 7000) OriginalCastTime = 7000;
13033 if (OriginalCastTime < 1500) OriginalCastTime = 1500;
13034 // Portion to Over Time
13035 float PtOT = (overTime / 15000.0f) / ((overTime / 15000.0f) + (OriginalCastTime / 3500.0f));
13037 if (damagetype == DOT)
13038 CastingTime = uint32(CastingTime * PtOT);
13039 else if (PtOT < 1.0f)
13040 CastingTime = uint32(CastingTime * (1 - PtOT));
13041 else
13042 CastingTime = 0;
13045 // Area Effect Spells receive only half of bonus
13046 if (AreaEffect)
13047 CastingTime /= 2;
13049 // -5% of total per any additional effect
13050 for (uint8 i = 0; i < effects; ++i)
13052 if (CastingTime > 175)
13054 CastingTime -= 175;
13056 else
13058 CastingTime = 0;
13059 break;
13063 return CastingTime;
13066 void Unit::UpdateAuraForGroup(uint8 slot)
13068 if(GetTypeId() == TYPEID_PLAYER)
13070 Player* player = (Player*)this;
13071 if(player->GetGroup())
13073 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_AURAS);
13074 player->SetAuraUpdateMask(slot);
13077 else if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
13079 Pet *pet = ((Pet*)this);
13080 if(pet->isControlled())
13082 Unit *owner = GetOwner();
13083 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
13085 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_AURAS);
13086 pet->SetAuraUpdateMask(slot);
13092 float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized)
13094 if (!normalized || GetTypeId() != TYPEID_PLAYER)
13095 return float(GetAttackTime(attType))/1000.0f;
13097 Item *Weapon = ((Player*)this)->GetWeaponForAttack(attType, true, false);
13098 if (!Weapon)
13099 return 2.4f; // fist attack
13101 switch (Weapon->GetProto()->InventoryType)
13103 case INVTYPE_2HWEAPON:
13104 return 3.3f;
13105 case INVTYPE_RANGED:
13106 case INVTYPE_RANGEDRIGHT:
13107 case INVTYPE_THROWN:
13108 return 2.8f;
13109 case INVTYPE_WEAPON:
13110 case INVTYPE_WEAPONMAINHAND:
13111 case INVTYPE_WEAPONOFFHAND:
13112 default:
13113 return Weapon->GetProto()->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7f : 2.4f;
13117 Aura* Unit::GetDummyAura( uint32 spell_id ) const
13119 Unit::AuraList const& mDummy = GetAurasByType(SPELL_AURA_DUMMY);
13120 for(Unit::AuraList::const_iterator itr = mDummy.begin(); itr != mDummy.end(); ++itr)
13121 if ((*itr)->GetId() == spell_id)
13122 return *itr;
13124 return NULL;
13127 void Unit::SetContestedPvP(Player *attackedPlayer)
13129 Player* player = GetCharmerOrOwnerPlayerOrPlayerItself();
13131 if(!player || attackedPlayer && (attackedPlayer == player || player->duel && player->duel->opponent == attackedPlayer))
13132 return;
13134 player->SetContestedPvPTimer(30000);
13135 if(!player->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
13137 player->addUnitState(UNIT_STAT_ATTACK_PLAYER);
13138 player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
13139 // call MoveInLineOfSight for nearby contested guards
13140 SetVisibility(GetVisibility());
13142 if(!hasUnitState(UNIT_STAT_ATTACK_PLAYER))
13144 addUnitState(UNIT_STAT_ATTACK_PLAYER);
13145 // call MoveInLineOfSight for nearby contested guards
13146 SetVisibility(GetVisibility());
13150 void Unit::AddPetAura(PetAura const* petSpell)
13152 m_petAuras.insert(petSpell);
13153 if(Pet* pet = GetPet())
13154 pet->CastPetAura(petSpell);
13157 void Unit::RemovePetAura(PetAura const* petSpell)
13159 m_petAuras.erase(petSpell);
13160 if(Pet* pet = GetPet())
13161 pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry()));
13164 Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget,uint32 spell_id)
13166 Pet* pet = new Pet(HUNTER_PET);
13168 if(!pet->CreateBaseAtCreature(creatureTarget))
13170 delete pet;
13171 return NULL;
13174 pet->SetOwnerGUID(GetGUID());
13175 pet->SetCreatorGUID(GetGUID());
13176 pet->setFaction(getFaction());
13177 pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id);
13179 if(GetTypeId()==TYPEID_PLAYER)
13180 pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
13182 if(IsPvP())
13183 pet->SetPvP(true);
13185 if(IsFFAPvP())
13186 pet->SetFFAPvP(true);
13188 uint32 level = (creatureTarget->getLevel() < (getLevel() - 5)) ? (getLevel() - 5) : creatureTarget->getLevel();
13190 if(!pet->InitStatsForLevel(level))
13192 sLog.outError("Pet::InitStatsForLevel() failed for creature (Entry: %u)!",creatureTarget->GetEntry());
13193 delete pet;
13194 return NULL;
13197 pet->GetCharmInfo()->SetPetNumber(sObjectMgr.GeneratePetNumber(), true);
13198 // this enables pet details window (Shift+P)
13199 pet->AIM_Initialize();
13200 pet->InitPetCreateSpells();
13201 pet->InitLevelupSpellsForLevel();
13202 pet->InitTalentForLevel();
13203 pet->SetHealth(pet->GetMaxHealth());
13205 return pet;
13208 bool Unit::IsTriggeredAtSpellProcEvent(Unit *pVictim, Aura* aura, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const*& spellProcEvent )
13210 SpellEntry const* spellProto = aura->GetSpellProto ();
13212 // Get proc Event Entry
13213 spellProcEvent = sSpellMgr.GetSpellProcEvent(spellProto->Id);
13215 // Aura info stored here
13216 Modifier *mod = aura->GetModifier();
13217 // Skip this auras
13218 if (isNonTriggerAura[mod->m_auraname])
13219 return false;
13220 // If not trigger by default and spellProcEvent==NULL - skip
13221 if (!isTriggerAura[mod->m_auraname] && spellProcEvent==NULL)
13222 return false;
13224 // Get EventProcFlag
13225 uint32 EventProcFlag;
13226 if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags
13227 EventProcFlag = spellProcEvent->procFlags;
13228 else
13229 EventProcFlag = spellProto->procFlags; // else get from spell proto
13230 // Continue if no trigger exist
13231 if (!EventProcFlag)
13232 return false;
13234 // Check spellProcEvent data requirements
13235 if(!SpellMgr::IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active))
13236 return false;
13238 // In most cases req get honor or XP from kill
13239 if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER)
13241 bool allow = ((Player*)this)->isHonorOrXPTarget(pVictim);
13242 // Shadow Word: Death - can trigger from every kill
13243 if (aura->GetId() == 32409)
13244 allow = true;
13245 if (!allow)
13246 return false;
13248 // Aura added by spell can`t trogger from self (prevent drop charges/do triggers)
13249 // But except periodic triggers (can triggered from self)
13250 if(procSpell && procSpell->Id == spellProto->Id && !(spellProto->procFlags & PROC_FLAG_ON_TAKE_PERIODIC))
13251 return false;
13253 // Check if current equipment allows aura to proc
13254 if(!isVictim && GetTypeId() == TYPEID_PLAYER)
13256 if(spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
13258 Item *item = NULL;
13259 if(attType == BASE_ATTACK)
13260 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
13261 else if (attType == OFF_ATTACK)
13262 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
13263 else
13264 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
13266 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
13267 return false;
13269 else if(spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
13271 // Check if player is wearing shield
13272 Item *item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
13273 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
13274 return false;
13277 // Get chance from spell
13278 float chance = (float)spellProto->procChance;
13279 // If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance;
13280 if(spellProcEvent && spellProcEvent->customChance)
13281 chance = spellProcEvent->customChance;
13282 // If PPM exist calculate chance from PPM
13283 if(!isVictim && spellProcEvent && spellProcEvent->ppmRate != 0)
13285 uint32 WeaponSpeed = GetAttackTime(attType);
13286 chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate);
13288 // Apply chance modifer aura
13289 if(Player* modOwner = GetSpellModOwner())
13291 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
13292 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_FREQUENCY_OF_SUCCESS,chance);
13295 return roll_chance_f(chance);
13298 bool Unit::HandleMendingAuraProc( Aura* triggeredByAura )
13300 // aura can be deleted at casts
13301 SpellEntry const* spellProto = triggeredByAura->GetSpellProto();
13302 SpellEffectIndex effIdx = triggeredByAura->GetEffIndex();
13303 int32 heal = triggeredByAura->GetModifier()->m_amount;
13304 uint64 caster_guid = triggeredByAura->GetCasterGUID();
13306 // jumps
13307 int32 jumps = triggeredByAura->GetAuraCharges()-1;
13309 // current aura expire
13310 triggeredByAura->SetAuraCharges(1); // will removed at next charges decrease
13312 // next target selection
13313 if(jumps > 0 && GetTypeId()==TYPEID_PLAYER && IS_PLAYER_GUID(caster_guid))
13315 float radius;
13316 if (spellProto->EffectRadiusIndex[effIdx])
13317 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
13318 else
13319 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
13321 if(Player* caster = ((Player*)triggeredByAura->GetCaster()))
13323 caster->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius,NULL);
13325 if(Player* target = ((Player*)this)->GetNextRandomRaidMember(radius))
13327 // aura will applied from caster, but spell casted from current aura holder
13328 SpellModifier *mod = new SpellModifier(SPELLMOD_CHARGES,SPELLMOD_FLAT,jumps-5,spellProto->Id,spellProto->SpellFamilyFlags,spellProto->SpellFamilyFlags2);
13330 // remove before apply next (locked against deleted)
13331 triggeredByAura->SetInUse(true);
13332 RemoveAurasByCasterSpell(spellProto->Id,caster->GetGUID());
13334 caster->AddSpellMod(mod, true);
13335 CastCustomSpell(target,spellProto->Id,&heal,NULL,NULL,true,NULL,triggeredByAura,caster->GetGUID());
13336 caster->AddSpellMod(mod, false);
13337 triggeredByAura->SetInUse(false);
13342 // heal
13343 CastCustomSpell(this,33110,&heal,NULL,NULL,true,NULL,NULL,caster_guid);
13344 return true;
13347 void Unit::RemoveAurasAtMechanicImmunity(uint32 mechMask, uint32 exceptSpellId, bool non_positive /*= false*/)
13349 Unit::AuraMap& auras = GetAuras();
13350 for(Unit::AuraMap::iterator iter = auras.begin(); iter != auras.end();)
13352 SpellEntry const *spell = iter->second->GetSpellProto();
13353 if (spell->Id == exceptSpellId)
13354 ++iter;
13355 else if (non_positive && iter->second->IsPositive())
13356 ++iter;
13357 else if (spell->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY)
13358 ++iter;
13359 else if (GetSpellMechanicMask(spell, iter->second->GetEffIndex()) & mechMask)
13361 RemoveAurasDueToSpell(spell->Id);
13362 if(auras.empty())
13363 break;
13364 else
13365 iter = auras.begin();
13367 else
13368 ++iter;
13372 void Unit::SetPhaseMask(uint32 newPhaseMask, bool update)
13374 if(newPhaseMask==GetPhaseMask())
13375 return;
13377 if(IsInWorld())
13378 RemoveNotOwnSingleTargetAuras(newPhaseMask); // we can lost access to caster or target
13380 WorldObject::SetPhaseMask(newPhaseMask,update);
13382 if(IsInWorld())
13383 if(Pet* pet = GetPet())
13384 pet->SetPhaseMask(newPhaseMask,true);
13387 void Unit::NearTeleportTo( float x, float y, float z, float orientation, bool casting /*= false*/ )
13389 if(GetTypeId() == TYPEID_PLAYER)
13390 ((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));
13391 else
13393 Creature* c = (Creature*)this;
13394 // Creature relocation acts like instant movement generator, so current generator expects interrupt/reset calls to react properly
13395 if (!c->GetMotionMaster()->empty())
13396 if (MovementGenerator *movgen = c->GetMotionMaster()->top())
13397 movgen->Interrupt(*c);
13399 GetMap()->CreatureRelocation((Creature*)this, x, y, z, orientation);
13401 WorldPacket data;
13402 BuildHeartBeatMsg(&data);
13403 SendMessageToSet(&data, false);
13404 // finished relocation, movegen can different from top before creature relocation,
13405 // but apply Reset expected to be safe in any case
13406 if (!c->GetMotionMaster()->empty())
13407 if (MovementGenerator *movgen = c->GetMotionMaster()->top())
13408 movgen->Reset(*c);
13412 void Unit::MonsterMove(float x, float y, float z, uint32 transitTime)
13414 SplineFlags flags = GetTypeId() == TYPEID_PLAYER ? SPLINEFLAG_WALKMODE : ((Creature*)this)->GetSplineFlags();
13415 SendMonsterMove(x, y, z, SPLINETYPE_NORMAL, flags, transitTime);
13417 if (GetTypeId() != TYPEID_PLAYER)
13419 Creature* c = (Creature*)this;
13420 // Creature relocation acts like instant movement generator, so current generator expects interrupt/reset calls to react properly
13421 if (!c->GetMotionMaster()->empty())
13422 if (MovementGenerator *movgen = c->GetMotionMaster()->top())
13423 movgen->Interrupt(*c);
13425 GetMap()->CreatureRelocation((Creature*)this, x, y, z, 0.0f);
13427 // finished relocation, movegen can different from top before creature relocation,
13428 // but apply Reset expected to be safe in any case
13429 if (!c->GetMotionMaster()->empty())
13430 if (MovementGenerator *movgen = c->GetMotionMaster()->top())
13431 movgen->Reset(*c);
13435 void Unit::MonsterMoveWithSpeed(float x, float y, float z, uint32 transitTime)
13437 SendMonsterMoveWithSpeed(x, y, z, transitTime );
13439 if (GetTypeId() != TYPEID_PLAYER)
13441 Creature* c = (Creature*)this;
13442 // Creature relocation acts like instant movement generator, so current generator expects interrupt/reset calls to react properly
13443 if (!c->GetMotionMaster()->empty())
13444 if (MovementGenerator *movgen = c->GetMotionMaster()->top())
13445 movgen->Interrupt(*c);
13447 GetMap()->CreatureRelocation((Creature*)this, x, y, z, 0.0f);
13449 // finished relocation, movegen can different from top before creature relocation,
13450 // but apply Reset expected to be safe in any case
13451 if (!c->GetMotionMaster()->empty())
13452 if (MovementGenerator *movgen = c->GetMotionMaster()->top())
13453 movgen->Reset(*c);
13457 struct SetPvPHelper
13459 explicit SetPvPHelper(bool _state) : state(_state) {}
13460 void operator()(Unit* unit) const { unit->SetPvP(state); }
13461 bool state;
13464 void Unit::SetPvP( bool state )
13466 if(state)
13467 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP);
13468 else
13469 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP);
13471 CallForAllControlledUnits(SetPvPHelper(state),true,true,true);
13474 struct SetFFAPvPHelper
13476 explicit SetFFAPvPHelper(bool _state) : state(_state) {}
13477 void operator()(Unit* unit) const { unit->SetFFAPvP(state); }
13478 bool state;
13481 void Unit::SetFFAPvP( bool state )
13483 if(state)
13484 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
13485 else
13486 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
13488 CallForAllControlledUnits(SetFFAPvPHelper(state),true,true,true);
13491 void Unit::KnockBackFrom(Unit* target, float horizontalSpeed, float verticalSpeed)
13493 float angle = this == target ? GetOrientation() + M_PI_F : target->GetAngle(this);
13494 float vsin = sin(angle);
13495 float vcos = cos(angle);
13497 // Effect propertly implemented only for players
13498 if(GetTypeId()==TYPEID_PLAYER)
13500 WorldPacket data(SMSG_MOVE_KNOCK_BACK, 8+4+4+4+4+4);
13501 data << GetPackGUID();
13502 data << uint32(0); // Sequence
13503 data << float(vcos); // x direction
13504 data << float(vsin); // y direction
13505 data << float(horizontalSpeed); // Horizontal speed
13506 data << float(-verticalSpeed); // Z Movement speed (vertical)
13507 ((Player*)this)->GetSession()->SendPacket(&data);
13509 else
13511 float dis = horizontalSpeed;
13513 float ox, oy, oz;
13514 GetPosition(ox, oy, oz);
13516 float fx = ox + dis * vcos;
13517 float fy = oy + dis * vsin;
13518 float fz = oz;
13520 float fx2, fy2, fz2; // getObjectHitPos overwrite last args in any result case
13521 if(VMAP::VMapFactory::createOrGetVMapManager()->getObjectHitPos(GetMapId(), ox,oy,oz+0.5f, fx,fy,oz+0.5f,fx2,fy2,fz2, -0.5f))
13523 fx = fx2;
13524 fy = fy2;
13525 fz = fz2;
13528 UpdateGroundPositionZ(fx, fy, fz);
13530 //FIXME: this mostly hack, must exist some packet for proper creature move at client side
13531 // with CreatureRelocation at server side
13532 NearTeleportTo(fx, fy, fz, GetOrientation(), this == target);
13536 float Unit::GetCombatRatingReduction(CombatRating cr) const
13538 if (GetTypeId() == TYPEID_PLAYER)
13539 return ((Player const*)this)->GetRatingBonusValue(cr);
13540 else if (((Creature const*)this)->isPet())
13542 // Player's pet have 0.4 resilience from owner
13543 if (Unit* owner = GetOwner())
13544 if(owner->GetTypeId() == TYPEID_PLAYER)
13545 return ((Player*)owner)->GetRatingBonusValue(cr) * 0.4f;
13548 return 0.0f;
13551 uint32 Unit::GetCombatRatingDamageReduction(CombatRating cr, float rate, float cap, uint32 damage) const
13553 float percent = GetCombatRatingReduction(cr) * rate;
13554 if (percent > cap)
13555 percent = cap;
13556 return uint32 (percent * damage / 100.0f);
13559 void Unit::SendThreatUpdate()
13561 ThreatList const& tlist = getThreatManager().getThreatList();
13562 if (uint32 count = tlist.size())
13564 sLog.outDebug( "WORLD: Send SMSG_THREAT_UPDATE Message" );
13565 WorldPacket data(SMSG_THREAT_UPDATE, 8 + count * 8);
13566 data << GetPackGUID();
13567 data << uint32(count);
13568 for (ThreatList::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr)
13570 data.appendPackGUID((*itr)->getUnitGuid());
13571 data << uint32((*itr)->getThreat());
13573 SendMessageToSet(&data, false);
13577 void Unit::SendHighestThreatUpdate(HostileReference* pHostilReference)
13579 ThreatList const& tlist = getThreatManager().getThreatList();
13580 if (uint32 count = tlist.size())
13582 sLog.outDebug( "WORLD: Send SMSG_HIGHEST_THREAT_UPDATE Message" );
13583 WorldPacket data(SMSG_HIGHEST_THREAT_UPDATE, 8 + 8 + count * 8);
13584 data << GetPackGUID();
13585 data.appendPackGUID(pHostilReference->getUnitGuid());
13586 data << uint32(count);
13587 for (ThreatList::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr)
13589 data.appendPackGUID((*itr)->getUnitGuid());
13590 data << uint32((*itr)->getThreat());
13592 SendMessageToSet(&data, false);
13596 void Unit::SendThreatClear()
13598 sLog.outDebug( "WORLD: Send SMSG_THREAT_CLEAR Message" );
13599 WorldPacket data(SMSG_THREAT_CLEAR, 8);
13600 data << GetPackGUID();
13601 SendMessageToSet(&data, false);
13604 void Unit::SendThreatRemove(HostileReference* pHostileReference)
13606 sLog.outDebug( "WORLD: Send SMSG_THREAT_REMOVE Message" );
13607 WorldPacket data(SMSG_THREAT_REMOVE, 8 + 8);
13608 data << GetPackGUID();
13609 data.appendPackGUID(pHostileReference->getUnitGuid());
13610 SendMessageToSet(&data, false);
13613 struct StopAttackFactionHelper
13615 explicit StopAttackFactionHelper(uint32 _faction_id) : faction_id(_faction_id) {}
13616 void operator()(Unit* unit) const { unit->StopAttackFaction(faction_id); }
13617 uint32 faction_id;
13620 void Unit::StopAttackFaction(uint32 faction_id)
13622 if (Unit* victim = getVictim())
13624 if (victim->getFactionTemplateEntry()->faction==faction_id)
13626 AttackStop();
13627 if (IsNonMeleeSpellCasted(false))
13628 InterruptNonMeleeSpells(false);
13630 // melee and ranged forced attack cancel
13631 if (GetTypeId() == TYPEID_PLAYER)
13632 ((Player*)this)->SendAttackSwingCancelAttack();
13636 AttackerSet const& attackers = getAttackers();
13637 for(AttackerSet::const_iterator itr = attackers.begin(); itr != attackers.end();)
13639 if ((*itr)->getFactionTemplateEntry()->faction==faction_id)
13641 (*itr)->AttackStop();
13642 itr = attackers.begin();
13644 else
13645 ++itr;
13648 getHostileRefManager().deleteReferencesForFaction(faction_id);
13650 CallForAllControlledUnits(StopAttackFactionHelper(faction_id),false,true,true);
13653 void Unit::CleanupDeletedAuras()
13655 // really delete auras "deleted" while processing its ApplyModify code
13656 for(AuraList::const_iterator itr = m_deletedAuras.begin(); itr != m_deletedAuras.end(); ++itr)
13657 delete *itr;
13658 m_deletedAuras.clear();
13661 bool Unit::CheckAndIncreaseCastCounter()
13663 uint32 maxCasts = sWorld.getConfig(CONFIG_UINT32_MAX_SPELL_CASTS_IN_CHAIN);
13665 if (maxCasts && m_castCounter >= maxCasts)
13666 return false;
13668 ++m_castCounter;
13669 return true;