[7916] Fixed pet action bar setup.
[getmangos.git] / src / game / Unit.cpp
blob21371820c4a29bfa157e187def3a55e773a42cef
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Log.h"
21 #include "Opcodes.h"
22 #include "WorldPacket.h"
23 #include "WorldSession.h"
24 #include "World.h"
25 #include "ObjectMgr.h"
26 #include "SpellMgr.h"
27 #include "Unit.h"
28 #include "QuestDef.h"
29 #include "Player.h"
30 #include "Creature.h"
31 #include "Spell.h"
32 #include "Group.h"
33 #include "SpellAuras.h"
34 #include "MapManager.h"
35 #include "ObjectAccessor.h"
36 #include "CreatureAI.h"
37 #include "Formulas.h"
38 #include "Pet.h"
39 #include "Util.h"
40 #include "Totem.h"
41 #include "BattleGround.h"
42 #include "InstanceSaveMgr.h"
43 #include "GridNotifiersImpl.h"
44 #include "CellImpl.h"
45 #include "Path.h"
46 #include "Traveller.h"
48 #include <math.h>
50 float baseMoveSpeed[MAX_MOVE_TYPE] =
52 2.5f, // MOVE_WALK
53 7.0f, // MOVE_RUN
54 1.25f, // MOVE_RUN_BACK
55 4.722222f, // MOVE_SWIM
56 4.5f, // MOVE_SWIM_BACK
57 3.141594f, // MOVE_TURN_RATE
58 7.0f, // MOVE_FLIGHT
59 4.5f, // MOVE_FLIGHT_BACK
60 3.14f // MOVE_PITCH_RATE
63 // Used for prepare can/can`t triggr aura
64 static bool InitTriggerAuraData();
65 // Define can trigger auras
66 static bool isTriggerAura[TOTAL_AURAS];
67 // Define can`t trigger auras (need for disable second trigger)
68 static bool isNonTriggerAura[TOTAL_AURAS];
69 // Prepare lists
70 static bool procPrepared = InitTriggerAuraData();
72 Unit::Unit()
73 : WorldObject(), i_motionMaster(this), m_ThreatManager(this), m_HostilRefManager(this)
75 m_objectType |= TYPEMASK_UNIT;
76 m_objectTypeId = TYPEID_UNIT;
77 // 2.3.2 - 0x70
78 m_updateFlag = (UPDATEFLAG_LOWGUID | UPDATEFLAG_HIGHGUID | UPDATEFLAG_LIVING | UPDATEFLAG_HAS_POSITION);
80 m_attackTimer[BASE_ATTACK] = 0;
81 m_attackTimer[OFF_ATTACK] = 0;
82 m_attackTimer[RANGED_ATTACK] = 0;
83 m_modAttackSpeedPct[BASE_ATTACK] = 1.0f;
84 m_modAttackSpeedPct[OFF_ATTACK] = 1.0f;
85 m_modAttackSpeedPct[RANGED_ATTACK] = 1.0f;
87 m_extraAttacks = 0;
89 m_state = 0;
90 m_form = FORM_NONE;
91 m_deathState = ALIVE;
93 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
94 m_currentSpells[i] = NULL;
96 m_addDmgOnce = 0;
98 for(int i = 0; i < MAX_TOTEM; ++i)
99 m_TotemSlot[i] = 0;
101 m_ObjectSlot[0] = m_ObjectSlot[1] = m_ObjectSlot[2] = m_ObjectSlot[3] = 0;
102 //m_Aura = NULL;
103 //m_AurasCheck = 2000;
104 //m_removeAuraTimer = 4;
105 //tmpAura = NULL;
107 m_Visibility = VISIBILITY_ON;
109 m_detectInvisibilityMask = 0;
110 m_invisibilityMask = 0;
111 m_transform = 0;
112 m_ShapeShiftFormSpellId = 0;
113 m_canModifyStats = false;
115 for (int i = 0; i < MAX_SPELL_IMMUNITY; ++i)
116 m_spellImmune[i].clear();
117 for (int i = 0; i < UNIT_MOD_END; ++i)
119 m_auraModifiersGroup[i][BASE_VALUE] = 0.0f;
120 m_auraModifiersGroup[i][BASE_PCT] = 1.0f;
121 m_auraModifiersGroup[i][TOTAL_VALUE] = 0.0f;
122 m_auraModifiersGroup[i][TOTAL_PCT] = 1.0f;
124 // implement 50% base damage from offhand
125 m_auraModifiersGroup[UNIT_MOD_DAMAGE_OFFHAND][TOTAL_PCT] = 0.5f;
127 for (int i = 0; i < MAX_ATTACK; ++i)
129 m_weaponDamage[i][MINDAMAGE] = BASE_MINDAMAGE;
130 m_weaponDamage[i][MAXDAMAGE] = BASE_MAXDAMAGE;
132 for (int i = 0; i < MAX_STATS; ++i)
133 m_createStats[i] = 0.0f;
135 m_attacking = NULL;
136 m_modMeleeHitChance = 0.0f;
137 m_modRangedHitChance = 0.0f;
138 m_modSpellHitChance = 0.0f;
139 m_baseSpellCritChance = 5;
141 m_CombatTimer = 0;
142 m_lastManaUse = 0;
144 //m_victimThreat = 0.0f;
145 for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
146 m_threatModifier[i] = 1.0f;
147 m_isSorted = true;
148 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
149 m_speed_rate[i] = 1.0f;
151 m_removedAuras = 0;
152 m_charmInfo = NULL;
153 m_unit_movement_flags = 0;
155 // remove aurastates allowing special moves
156 for(int i=0; i < MAX_REACTIVE; ++i)
157 m_reactiveTimer[i] = 0;
160 Unit::~Unit()
162 // set current spells as deletable
163 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
165 if (m_currentSpells[i])
167 m_currentSpells[i]->SetReferencedFromCurrent(false);
168 m_currentSpells[i] = NULL;
172 RemoveAllGameObjects();
173 RemoveAllDynObjects();
175 if(m_charmInfo) delete m_charmInfo;
178 void Unit::Update( uint32 p_time )
180 /*if(p_time > m_AurasCheck)
182 m_AurasCheck = 2000;
183 _UpdateAura();
184 }else
185 m_AurasCheck -= p_time;*/
187 // WARNING! Order of execution here is important, do not change.
188 // Spells must be processed with event system BEFORE they go to _UpdateSpells.
189 // Or else we may have some SPELL_STATE_FINISHED spells stalled in pointers, that is bad.
190 m_Events.Update( p_time );
191 _UpdateSpells( p_time );
193 // update combat timer only for players and pets
194 if (isInCombat() && (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet() || ((Creature*)this)->isCharmed()))
196 // Check UNIT_STAT_MELEE_ATTACKING or UNIT_STAT_CHASE (without UNIT_STAT_FOLLOW in this case) so pets can reach far away
197 // targets without stopping half way there and running off.
198 // These flags are reset after target dies or another command is given.
199 if( m_HostilRefManager.isEmpty() )
201 // m_CombatTimer set at aura start and it will be freeze until aura removing
202 if ( m_CombatTimer <= p_time )
203 ClearInCombat();
204 else
205 m_CombatTimer -= p_time;
209 if(uint32 base_att = getAttackTimer(BASE_ATTACK))
211 setAttackTimer(BASE_ATTACK, (p_time >= base_att ? 0 : base_att - p_time) );
214 // update abilities available only for fraction of time
215 UpdateReactives( p_time );
217 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, GetHealth() < GetMaxHealth()*0.20f);
218 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, GetHealth() < GetMaxHealth()*0.35f);
219 ModifyAuraState(AURA_STATE_HEALTH_ABOVE_75_PERCENT, GetHealth() > GetMaxHealth()*0.75f);
221 i_motionMaster.UpdateMotion(p_time);
224 bool Unit::haveOffhandWeapon() const
226 if(GetTypeId() == TYPEID_PLAYER)
227 return ((Player*)this)->GetWeaponForAttack(OFF_ATTACK,true);
228 else
229 return false;
232 void Unit::SendMonsterMoveWithSpeedToCurrentDestination(Player* player)
234 float x, y, z;
235 if(GetMotionMaster()->GetDestination(x, y, z))
236 SendMonsterMoveWithSpeed(x, y, z, 0, player);
239 void Unit::SendMonsterMoveWithSpeed(float x, float y, float z, uint32 transitTime, Player* player)
241 if (!transitTime)
243 if(GetTypeId()==TYPEID_PLAYER)
245 Traveller<Player> traveller(*(Player*)this);
246 transitTime = traveller.GetTotalTrevelTimeTo(x,y,z);
248 else
250 Traveller<Creature> traveller(*(Creature*)this);
251 transitTime = traveller.GetTotalTrevelTimeTo(x,y,z);
254 //float orientation = (float)atan2((double)dy, (double)dx);
255 SendMonsterMove(x, y, z, 0, GetUnitMovementFlags(), transitTime, player);
258 void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint8 type, uint32 MovementFlags, uint32 Time, Player* player)
260 WorldPacket data( SMSG_MONSTER_MOVE, (41 + GetPackGUID().size()) );
261 data.append(GetPackGUID());
263 data << GetPositionX() << GetPositionY() << GetPositionZ();
264 data << uint32(getMSTime());
266 data << uint8(type); // unknown
267 switch(type)
269 case 0: // normal packet
270 break;
271 case 1: // stop packet (raw pos?)
272 SendMessageToSet( &data, true );
273 return;
274 case 2: // facing spot, not used currently
275 data << float(0);
276 data << float(0);
277 data << float(0);
278 break;
279 case 3: // not used currently
280 data << uint64(0); // probably target guid (facing target?)
281 break;
282 case 4: // not used currently
283 data << float(0); // facing angle
284 break;
287 data << uint32(MovementFlags);
289 data << uint32(Time); // Time in between points
290 data << uint32(1); // 1 single waypoint
291 data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B
293 if(player)
294 player->GetSession()->SendPacket(&data);
295 else
296 SendMessageToSet( &data, true );
299 void Unit::SendMonsterMoveByPath(Path const& path, uint32 start, uint32 end, uint32 MovementFlags)
301 uint32 traveltime = uint32(path.GetTotalLength(start, end) * 32);
303 uint32 pathSize = end - start;
305 WorldPacket data( SMSG_MONSTER_MOVE, (GetPackGUID().size()+4+4+4+4+1+4+4+4+pathSize*4*3) );
306 data.append(GetPackGUID());
307 data << GetPositionX();
308 data << GetPositionY();
309 data << GetPositionZ();
310 data << uint32(getMSTime());
311 data << uint8( 0 );
312 data << uint32( MovementFlags );
313 data << uint32( traveltime );
314 data << uint32( pathSize );
315 data.append( (char*)path.GetNodes(start), pathSize * 4 * 3 );
316 SendMessageToSet(&data, true);
319 void Unit::resetAttackTimer(WeaponAttackType type)
321 m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]);
324 bool Unit::canReachWithAttack(Unit *pVictim) const
326 assert(pVictim);
327 float reach = GetFloatValue(UNIT_FIELD_COMBATREACH);
328 if( reach <= 0.0f )
329 reach = 1.0f;
330 return IsWithinDistInMap(pVictim, reach);
333 void Unit::RemoveSpellsCausingAura(AuraType auraType)
335 if (auraType >= TOTAL_AURAS) return;
336 AuraList::const_iterator iter, next;
337 for (iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end(); iter = next)
339 next = iter;
340 ++next;
342 if (*iter)
344 RemoveAurasDueToSpell((*iter)->GetId());
345 if (!m_modAuras[auraType].empty())
346 next = m_modAuras[auraType].begin();
347 else
348 return;
353 bool Unit::HasAuraType(AuraType auraType) const
355 return (!m_modAuras[auraType].empty());
358 /* Called by DealDamage for auras that have a chance to be dispelled on damage taken. */
359 void Unit::RemoveSpellbyDamageTaken(AuraType auraType, uint32 damage)
361 if(!HasAuraType(auraType))
362 return;
364 // The chance to dispel an aura depends on the damage taken with respect to the casters level.
365 uint32 max_dmg = getLevel() > 8 ? 25 * getLevel() - 150 : 50;
366 float chance = float(damage) / max_dmg * 100.0f;
367 if (roll_chance_f(chance))
368 RemoveSpellsCausingAura(auraType);
371 void Unit::DealDamageMods(Unit *pVictim, uint32 &damage, uint32* absorb)
373 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
375 if(absorb)
376 absorb += damage;
377 damage = 0;
378 return;
381 //You don't lose health from damage taken from another player while in a sanctuary
382 //You still see it in the combat log though
383 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
385 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
386 if(area && area->flags & AREA_FLAG_SANCTUARY) //sanctuary
388 if(absorb)
389 absorb += damage;
390 damage = 0;
394 uint32 originalDamage = damage;
396 //Script Event damage Deal
397 if( GetTypeId()== TYPEID_UNIT && ((Creature *)this)->AI())
398 ((Creature *)this)->AI()->DamageDeal(pVictim, damage);
399 //Script Event damage taken
400 if( pVictim->GetTypeId()== TYPEID_UNIT && ((Creature *)pVictim)->AI() )
401 ((Creature *)pVictim)->AI()->DamageTaken(this, damage);
403 if(absorb && originalDamage > damage)
404 absorb += (originalDamage - damage);
407 uint32 Unit::DealDamage(Unit *pVictim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellEntry const *spellProto, bool durabilityLoss)
409 // remove affects from victim (including from 0 damage and DoTs)
410 if(pVictim != this)
411 pVictim->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
413 // remove affects from attacker at any non-DoT damage (including 0 damage)
414 if( damagetype != DOT)
416 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
417 RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
419 if(pVictim != this)
420 RemoveSpellsCausingAura(SPELL_AURA_MOD_INVISIBILITY);
422 if(pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->IsStandState() && !pVictim->hasUnitState(UNIT_STAT_STUNNED))
423 pVictim->SetStandState(UNIT_STAND_STATE_STAND);
426 if(!damage)
428 // Rage from physical damage received .
429 if(cleanDamage && cleanDamage->damage && (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL) && pVictim->GetTypeId() == TYPEID_PLAYER && (pVictim->getPowerType() == POWER_RAGE))
430 ((Player*)pVictim)->RewardRage(cleanDamage->damage, 0, false);
432 return 0;
434 if (!spellProto || !IsAuraAddedBySpell(SPELL_AURA_MOD_FEAR, spellProto->Id))
435 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_FEAR, damage);
436 // root type spells do not dispel the root effect
437 if (!spellProto || !(spellProto->Mechanic == MECHANIC_ROOT || IsAuraAddedBySpell(SPELL_AURA_MOD_ROOT, spellProto->Id)))
438 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_ROOT, damage);
440 // no xp,health if type 8 /critters/
441 if(pVictim->GetTypeId() != TYPEID_PLAYER && pVictim->GetCreatureType() == CREATURE_TYPE_CRITTER)
443 pVictim->setDeathState(JUST_DIED);
444 pVictim->SetHealth(0);
446 // allow loot only if has loot_id in creature_template
447 CreatureInfo const* cInfo = ((Creature*)pVictim)->GetCreatureInfo();
448 if(cInfo && cInfo->lootid)
449 pVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
451 // some critters required for quests
452 if(GetTypeId() == TYPEID_PLAYER)
453 ((Player*)this)->KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
455 return damage;
458 DEBUG_LOG("DealDamageStart");
460 uint32 health = pVictim->GetHealth();
461 sLog.outDetail("deal dmg:%d to health:%d ",damage,health);
463 // duel ends when player has 1 or less hp
464 bool duel_hasEnded = false;
465 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->duel && damage >= (health-1))
467 // prevent kill only if killed in duel and killed by opponent or opponent controlled creature
468 if(((Player*)pVictim)->duel->opponent==this || ((Player*)pVictim)->duel->opponent->GetGUID() == GetOwnerGUID())
469 damage = health-1;
471 duel_hasEnded = true;
473 //Get in CombatState
474 if(pVictim != this && damagetype != DOT)
476 SetInCombatWith(pVictim);
477 pVictim->SetInCombatWith(this);
479 if(Player* attackedPlayer = pVictim->GetCharmerOrOwnerPlayerOrPlayerItself())
480 SetContestedPvP(attackedPlayer);
483 // Rage from Damage made (only from direct weapon damage)
484 if( cleanDamage && damagetype==DIRECT_DAMAGE && this != pVictim && GetTypeId() == TYPEID_PLAYER && (getPowerType() == POWER_RAGE))
486 uint32 weaponSpeedHitFactor;
488 switch(cleanDamage->attackType)
490 case BASE_ATTACK:
492 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
493 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 7);
494 else
495 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
497 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
499 break;
501 case OFF_ATTACK:
503 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
504 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
505 else
506 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 1.75f);
508 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
510 break;
512 case RANGED_ATTACK:
513 break;
517 if (GetTypeId() == TYPEID_PLAYER && this != pVictim)
519 Player *killer = ((Player*)this);
521 // in bg, count dmg if victim is also a player
522 if (pVictim->GetTypeId()==TYPEID_PLAYER)
524 if (BattleGround *bg = killer->GetBattleGround())
526 // FIXME: kept by compatibility. don't know in BG if the restriction apply.
527 bg->UpdatePlayerScore(killer, SCORE_DAMAGE_DONE, damage);
531 killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE, damage, 0, pVictim);
532 killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT, damage);
535 if (pVictim->GetTypeId() == TYPEID_PLAYER)
536 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED, damage);
538 if (pVictim->GetTypeId() == TYPEID_UNIT && !((Creature*)pVictim)->isPet() && !((Creature*)pVictim)->hasLootRecipient())
539 ((Creature*)pVictim)->SetLootRecipient(this);
541 if (health <= damage)
543 DEBUG_LOG("DealDamage: victim just died");
545 if (pVictim->GetTypeId() == TYPEID_PLAYER)
546 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, health);
548 // find player: owner of controlled `this` or `this` itself maybe
549 Player *player = GetCharmerOrOwnerPlayerOrPlayerItself();
551 if(pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->GetLootRecipient())
552 player = ((Creature*)pVictim)->GetLootRecipient();
553 // Reward player, his pets, and group/raid members
554 // call kill spell proc event (before real die and combat stop to triggering auras removed at death/combat stop)
555 if(player && player!=pVictim)
557 player->RewardPlayerAndGroupAtKill(pVictim);
558 player->ProcDamageAndSpell(pVictim, PROC_FLAG_KILL, PROC_FLAG_KILLED, PROC_EX_NONE, 0);
561 DEBUG_LOG("DealDamageAttackStop");
563 // stop combat
564 pVictim->CombatStop();
565 pVictim->getHostilRefManager().deleteReferences();
567 bool damageFromSpiritOfRedemtionTalent = spellProto && spellProto->Id == 27795;
569 // if talent known but not triggered (check priest class for speedup check)
570 Aura* spiritOfRedemtionTalentReady = NULL;
571 if( !damageFromSpiritOfRedemtionTalent && // not called from SPELL_AURA_SPIRIT_OF_REDEMPTION
572 pVictim->GetTypeId()==TYPEID_PLAYER && pVictim->getClass()==CLASS_PRIEST )
574 AuraList const& vDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
575 for(AuraList::const_iterator itr = vDummyAuras.begin(); itr != vDummyAuras.end(); ++itr)
577 if((*itr)->GetSpellProto()->SpellIconID==1654)
579 spiritOfRedemtionTalentReady = *itr;
580 break;
585 DEBUG_LOG("SET JUST_DIED");
586 if(!spiritOfRedemtionTalentReady)
587 pVictim->setDeathState(JUST_DIED);
589 DEBUG_LOG("DealDamageHealth1");
591 if(spiritOfRedemtionTalentReady)
593 // save value before aura remove
594 uint32 ressSpellId = pVictim->GetUInt32Value(PLAYER_SELF_RES_SPELL);
595 if(!ressSpellId)
596 ressSpellId = ((Player*)pVictim)->GetResurrectionSpellId();
598 //Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers)
599 pVictim->RemoveAllAurasOnDeath();
601 // restore for use at real death
602 pVictim->SetUInt32Value(PLAYER_SELF_RES_SPELL,ressSpellId);
604 // FORM_SPIRITOFREDEMPTION and related auras
605 pVictim->CastSpell(pVictim,27827,true,NULL,spiritOfRedemtionTalentReady);
607 else
608 pVictim->SetHealth(0);
610 // remember victim PvP death for corpse type and corpse reclaim delay
611 // at original death (not at SpiritOfRedemtionTalent timeout)
612 if( pVictim->GetTypeId()==TYPEID_PLAYER && !damageFromSpiritOfRedemtionTalent )
613 ((Player*)pVictim)->SetPvPDeath(player!=NULL);
615 // Call KilledUnit for creatures
616 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->AI())
617 ((Creature*)this)->AI()->KilledUnit(pVictim);
619 // achievement stuff
620 if (pVictim->GetTypeId() == TYPEID_PLAYER)
622 if (GetTypeId() == TYPEID_UNIT)
623 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE, GetEntry());
624 else if(GetTypeId() == TYPEID_PLAYER && pVictim != this)
625 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER, 1, ((Player*)this)->GetTeam());
628 // 10% durability loss on death
629 // clean InHateListOf
630 if (pVictim->GetTypeId() == TYPEID_PLAYER)
632 // only if not player and not controlled by player pet. And not at BG
633 if (durabilityLoss && !player && !((Player*)pVictim)->InBattleGround())
635 DEBUG_LOG("We are dead, loosing 10 percents durability");
636 ((Player*)pVictim)->DurabilityLossAll(0.10f,false);
637 // durability lost message
638 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
639 ((Player*)pVictim)->GetSession()->SendPacket(&data);
642 else // creature died
644 DEBUG_LOG("DealDamageNotPlayer");
645 Creature *cVictim = (Creature*)pVictim;
647 if(!cVictim->isPet())
649 cVictim->DeleteThreatList();
650 cVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
652 // Call creature just died function
653 if (cVictim->AI())
654 cVictim->AI()->JustDied(this);
656 // Dungeon specific stuff, only applies to players killing creatures
657 if(cVictim->GetInstanceId())
659 Map *m = cVictim->GetMap();
660 Player *creditedPlayer = GetCharmerOrOwnerPlayerOrPlayerItself();
661 // TODO: do instance binding anyway if the charmer/owner is offline
663 if(m->IsDungeon() && creditedPlayer)
665 if(m->IsRaid() || m->IsHeroic())
667 if(cVictim->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
668 ((InstanceMap *)m)->PermBindAllPlayers(creditedPlayer);
670 else
672 // the reset time is set but not added to the scheduler
673 // until the players leave the instance
674 time_t resettime = cVictim->GetRespawnTimeEx() + 2 * HOUR;
675 if(InstanceSave *save = sInstanceSaveManager.GetInstanceSave(cVictim->GetInstanceId()))
676 if(save->GetResetTime() < resettime) save->SetResetTime(resettime);
682 // last damage from non duel opponent or opponent controlled creature
683 if(duel_hasEnded)
685 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
686 Player *he = (Player*)pVictim;
688 assert(he->duel);
690 he->duel->opponent->CombatStopWithPets(true);
691 he->CombatStopWithPets(true);
693 he->DuelComplete(DUEL_INTERUPTED);
696 // battleground things (do this at the end, so the death state flag will be properly set to handle in the bg->handlekill)
697 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->InBattleGround())
699 Player *killed = ((Player*)pVictim);
700 if(BattleGround *bg = killed->GetBattleGround())
701 if(player)
702 bg->HandleKillPlayer(killed, player);
703 //later we can add support for creature->player kills here i'm
704 //not sure, but i guess those kills also get counted in av
705 //else if(GetTypeId() == TYPEID_UNIT)
706 // bg->HandleKillPlayer(killed,(Creature*)this);
709 else // if (health <= damage)
711 DEBUG_LOG("DealDamageAlive");
713 if (pVictim->GetTypeId() == TYPEID_PLAYER)
714 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, damage);
716 pVictim->ModifyHealth(- (int32)damage);
718 if(damagetype != DOT)
720 if(!getVictim())
722 // if not have main target then attack state with target (including AI call)
723 //start melee attacks only after melee hit
724 Attack(pVictim,(damagetype == DIRECT_DAMAGE));
727 // if damage pVictim call AI reaction
728 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
729 ((Creature*)pVictim)->AI()->AttackedBy(this);
732 // polymorphed and other negative transformed cases
733 if(pVictim->getTransForm() && pVictim->hasUnitState(UNIT_STAT_CONFUSED))
734 pVictim->RemoveAurasDueToSpell(pVictim->getTransForm());
736 if(damagetype == DIRECT_DAMAGE || damagetype == SPELL_DIRECT_DAMAGE)
738 if (!spellProto || !(spellProto->AuraInterruptFlags&AURA_INTERRUPT_FLAG_DIRECT_DAMAGE))
739 pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DIRECT_DAMAGE);
741 if (pVictim->GetTypeId() != TYPEID_PLAYER)
743 if(spellProto && IsDamageToThreatSpell(spellProto))
744 pVictim->AddThreat(this, damage*2, damageSchoolMask, spellProto);
745 else
746 pVictim->AddThreat(this, damage, damageSchoolMask, spellProto);
748 else // victim is a player
750 // Rage from damage received
751 if(this != pVictim && pVictim->getPowerType() == POWER_RAGE)
753 uint32 rage_damage = damage + (cleanDamage ? cleanDamage->damage : 0);
754 ((Player*)pVictim)->RewardRage(rage_damage, 0, false);
757 // random durability for items (HIT TAKEN)
758 if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
760 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
761 ((Player*)pVictim)->DurabilityPointLossForEquipSlot(slot);
765 if(GetTypeId()==TYPEID_PLAYER)
767 // random durability for items (HIT DONE)
768 if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
770 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
771 ((Player*)this)->DurabilityPointLossForEquipSlot(slot);
775 // TODO: Store auras by interrupt flag to speed this up.
776 AuraMap& vAuras = pVictim->GetAuras();
777 for (AuraMap::const_iterator i = vAuras.begin(), next; i != vAuras.end(); i = next)
779 const SpellEntry *se = i->second->GetSpellProto();
780 next = i; ++next;
781 if (spellProto && spellProto->Id == se->Id) // Not drop auras added by self
782 continue;
783 if( se->AuraInterruptFlags & AURA_INTERRUPT_FLAG_DAMAGE )
785 bool remove = true;
786 if (se->procFlags & (1<<3))
788 if (!roll_chance_i(se->procChance))
789 remove = false;
791 if (remove)
793 pVictim->RemoveAurasDueToSpell(i->second->GetId());
794 // FIXME: this may cause the auras with proc chance to be rerolled several times
795 next = vAuras.begin();
800 if (damagetype != NODAMAGE && damage && pVictim->GetTypeId() == TYPEID_PLAYER)
802 if( damagetype != DOT )
804 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
806 // skip channeled spell (processed differently below)
807 if (i == CURRENT_CHANNELED_SPELL)
808 continue;
810 if(Spell* spell = pVictim->m_currentSpells[i])
811 if(spell->getState() == SPELL_STATE_PREPARING)
813 if(spell->m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_ABORT_ON_DMG)
814 pVictim->InterruptSpell(i);
815 else
816 spell->Delayed();
821 if(Spell* spell = pVictim->m_currentSpells[CURRENT_CHANNELED_SPELL])
823 if (spell->getState() == SPELL_STATE_CASTING)
825 uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags;
826 if( channelInterruptFlags & CHANNEL_FLAG_DELAY )
828 if(pVictim!=this) //don't shorten the duration of channeling if you damage yourself
829 spell->DelayedChannel();
831 else if( (channelInterruptFlags & (CHANNEL_FLAG_DAMAGE | CHANNEL_FLAG_DAMAGE2)) )
833 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
834 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
837 else if (spell->getState() == SPELL_STATE_DELAYED)
838 // break channeled spell in delayed state on damage
840 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
841 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
846 // last damage from duel opponent
847 if(duel_hasEnded)
849 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
850 Player *he = (Player*)pVictim;
852 assert(he->duel);
854 he->SetHealth(1);
856 he->duel->opponent->CombatStopWithPets(true);
857 he->CombatStopWithPets(true);
859 he->CastSpell(he, 7267, true); // beg
860 he->DuelComplete(DUEL_WON);
864 DEBUG_LOG("DealDamageEnd returned %d damage", damage);
866 return damage;
869 void Unit::CastStop(uint32 except_spellid)
871 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
872 if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id!=except_spellid)
873 InterruptSpell(i,false);
876 void Unit::CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
878 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
880 if(!spellInfo)
882 sLog.outError("CastSpell: unknown spell id %i by caster: %s %u)", spellId,(GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
883 return;
886 CastSpell(Victim,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
889 void Unit::CastSpell(Unit* Victim,SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
891 if(!spellInfo)
893 sLog.outError("CastSpell: unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
894 return;
897 if (castItem)
898 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
900 if(!originalCaster && triggeredByAura)
901 originalCaster = triggeredByAura->GetCasterGUID();
903 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
905 SpellCastTargets targets;
906 targets.setUnitTarget( Victim );
907 spell->m_CastItem = castItem;
908 spell->prepare(&targets, triggeredByAura);
911 void Unit::CastCustomSpell(Unit* Victim,uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
913 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
915 if(!spellInfo)
917 sLog.outError("CastCustomSpell: unknown spell id %i", spellId);
918 return;
921 CastCustomSpell(Victim,spellInfo,bp0,bp1,bp2,triggered,castItem,triggeredByAura, originalCaster);
924 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)
926 if(!spellInfo)
928 sLog.outError("CastCustomSpell: unknown spell");
929 return;
932 if (castItem)
933 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
935 if(!originalCaster && triggeredByAura)
936 originalCaster = triggeredByAura->GetCasterGUID();
938 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster);
940 if(bp0)
941 spell->m_currentBasePoints[0] = *bp0-int32(spellInfo->EffectBaseDice[0]);
943 if(bp1)
944 spell->m_currentBasePoints[1] = *bp1-int32(spellInfo->EffectBaseDice[1]);
946 if(bp2)
947 spell->m_currentBasePoints[2] = *bp2-int32(spellInfo->EffectBaseDice[2]);
949 SpellCastTargets targets;
950 targets.setUnitTarget( Victim );
951 spell->m_CastItem = castItem;
952 spell->prepare(&targets, triggeredByAura);
955 // used for scripting
956 void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
958 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
960 if(!spellInfo)
962 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()));
963 return;
966 CastSpell(x, y, z,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
969 // used for scripting
970 void Unit::CastSpell(float x, float y, float z, SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
972 if(!spellInfo)
974 sLog.outError("CastSpell(x,y,z): unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
975 return;
978 if (castItem)
979 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
981 if(!originalCaster && triggeredByAura)
982 originalCaster = triggeredByAura->GetCasterGUID();
984 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
986 SpellCastTargets targets;
987 targets.setDestination(x, y, z);
988 spell->m_CastItem = castItem;
989 spell->prepare(&targets, triggeredByAura);
992 // Obsolete func need remove, here only for comotability vs another patches
993 uint32 Unit::SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage)
995 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellID);
996 SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, spellInfo->SchoolMask);
997 CalculateSpellDamage(&damageInfo, damage, spellInfo);
998 DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb);
999 SendSpellNonMeleeDamageLog(&damageInfo);
1000 DealSpellDamage(&damageInfo, true);
1001 return damageInfo.damage;
1004 void Unit::CalculateSpellDamage(SpellNonMeleeDamage *damageInfo, int32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType)
1006 SpellSchoolMask damageSchoolMask = SpellSchoolMask(damageInfo->schoolMask);
1007 Unit *pVictim = damageInfo->target;
1009 if (damage < 0)
1010 return;
1012 if(!this || !pVictim)
1013 return;
1014 if(!this->isAlive() || !pVictim->isAlive())
1015 return;
1017 uint32 crTypeMask = pVictim->GetCreatureTypeMask();
1018 // Check spell crit chance
1019 bool crit = isSpellCrit(pVictim, spellInfo, damageSchoolMask, attackType);
1020 bool blocked = false;
1021 // Per-school calc
1022 switch (spellInfo->DmgClass)
1024 // Melee and Ranged Spells
1025 case SPELL_DAMAGE_CLASS_RANGED:
1026 case SPELL_DAMAGE_CLASS_MELEE:
1028 // Physical Damage
1029 if ( damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL )
1031 //Calculate armor mitigation
1032 damage = CalcArmorReducedDamage(pVictim, damage);
1033 // Get blocked status
1034 blocked = isSpellBlocked(pVictim, spellInfo, attackType);
1036 // Magical Damage
1037 else
1039 // Calculate damage bonus
1040 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1042 if (crit)
1044 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1046 // Calculate crit bonus
1047 uint32 crit_bonus = damage;
1048 // Apply crit_damage bonus for melee spells
1049 if(Player* modOwner = GetSpellModOwner())
1050 modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
1051 damage += crit_bonus;
1053 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1054 int32 critPctDamageMod=0;
1055 if(attackType == RANGED_ATTACK)
1056 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1057 else
1059 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1060 critPctDamageMod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1062 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1063 critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1065 if (critPctDamageMod!=0)
1066 damage = int32((damage) * float((100.0f + critPctDamageMod)/100.0f));
1068 // Resilience - reduce crit damage
1069 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1070 damage -= ((Player*)pVictim)->GetMeleeCritDamageReduction(damage);
1072 // Spell weapon based damage CAN BE crit & blocked at same time
1073 if (blocked)
1075 damageInfo->blocked = uint32(pVictim->GetShieldBlockValue());
1076 if (damage < damageInfo->blocked)
1077 damageInfo->blocked = damage;
1078 damage-=damageInfo->blocked;
1081 break;
1082 // Magical Attacks
1083 case SPELL_DAMAGE_CLASS_NONE:
1084 case SPELL_DAMAGE_CLASS_MAGIC:
1086 // Calculate damage bonus
1087 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1088 // If crit add critical bonus
1089 if (crit)
1091 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1092 damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim);
1093 // Resilience - reduce crit damage
1094 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1095 damage -= ((Player*)pVictim)->GetSpellCritDamageReduction(damage);
1098 break;
1101 // Calculate absorb resist
1102 if(damage > 0)
1104 // lookup absorb/resist ignore auras on caster for spell
1105 bool ignore = false;
1106 Unit::AuraList const& ignoreAbsorb = GetAurasByType(SPELL_AURA_MOD_IGNORE_ABSORB_FOR_SPELL);
1107 for(Unit::AuraList::const_iterator i = ignoreAbsorb.begin(); i != ignoreAbsorb.end(); ++i)
1108 if ((*i)->isAffectedOnSpell(spellInfo))
1110 ignore = true;
1111 break;
1114 if (!ignore)
1116 CalcAbsorbResist(pVictim, damageSchoolMask, SPELL_DIRECT_DAMAGE, damage, &damageInfo->absorb, &damageInfo->resist);
1117 damage-= damageInfo->absorb + damageInfo->resist;
1120 else
1121 damage = 0;
1122 damageInfo->damage = damage;
1125 void Unit::DealSpellDamage(SpellNonMeleeDamage *damageInfo, bool durabilityLoss)
1127 if (damageInfo==0)
1128 return;
1130 Unit *pVictim = damageInfo->target;
1132 if(!this || !pVictim)
1133 return;
1135 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1136 return;
1138 SpellEntry const *spellProto = sSpellStore.LookupEntry(damageInfo->SpellID);
1139 if (spellProto == NULL)
1141 sLog.outDebug("Unit::DealSpellDamage have wrong damageInfo->SpellID: %u", damageInfo->SpellID);
1142 return;
1145 //You don't lose health from damage taken from another player while in a sanctuary
1146 //You still see it in the combat log though
1147 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1149 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1150 if(area && area->flags & AREA_FLAG_SANCTUARY) // sanctuary
1151 return;
1154 // Call default DealDamage
1155 CleanDamage cleanDamage(damageInfo->cleanDamage, BASE_ATTACK, MELEE_HIT_NORMAL);
1156 DealDamage(pVictim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, SpellSchoolMask(damageInfo->schoolMask), spellProto, durabilityLoss);
1159 //TODO for melee need create structure as in
1160 void Unit::CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType)
1162 damageInfo->attacker = this;
1163 damageInfo->target = pVictim;
1164 damageInfo->damageSchoolMask = GetMeleeDamageSchoolMask();
1165 damageInfo->attackType = attackType;
1166 damageInfo->damage = 0;
1167 damageInfo->cleanDamage = 0;
1168 damageInfo->absorb = 0;
1169 damageInfo->resist = 0;
1170 damageInfo->blocked_amount = 0;
1172 damageInfo->TargetState = 0;
1173 damageInfo->HitInfo = 0;
1174 damageInfo->procAttacker = PROC_FLAG_NONE;
1175 damageInfo->procVictim = PROC_FLAG_NONE;
1176 damageInfo->procEx = PROC_EX_NONE;
1177 damageInfo->hitOutCome = MELEE_HIT_EVADE;
1179 if(!this || !pVictim)
1180 return;
1181 if(!this->isAlive() || !pVictim->isAlive())
1182 return;
1184 // Select HitInfo/procAttacker/procVictim flag based on attack type
1185 switch (attackType)
1187 case BASE_ATTACK:
1188 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MILEE_HIT;
1189 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;
1190 damageInfo->HitInfo = HITINFO_NORMALSWING2;
1191 break;
1192 case OFF_ATTACK:
1193 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MILEE_HIT | PROC_FLAG_SUCCESSFUL_OFFHAND_HIT;
1194 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;//|PROC_FLAG_TAKEN_OFFHAND_HIT // not used
1195 damageInfo->HitInfo = HITINFO_LEFTSWING;
1196 break;
1197 case RANGED_ATTACK:
1198 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
1199 damageInfo->procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
1200 damageInfo->HitInfo = 0x08;// test
1201 break;
1202 default:
1203 break;
1206 // Physical Immune check
1207 if(damageInfo->target->IsImmunedToDamage(SpellSchoolMask(damageInfo->damageSchoolMask)))
1209 damageInfo->HitInfo |= HITINFO_NORMALSWING;
1210 damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE;
1212 damageInfo->procEx |=PROC_EX_IMMUNE;
1213 damageInfo->damage = 0;
1214 damageInfo->cleanDamage = 0;
1215 return;
1217 damage += CalculateDamage (damageInfo->attackType, false);
1218 // Add melee damage bonus
1219 MeleeDamageBonus(damageInfo->target, &damage, damageInfo->attackType);
1220 // Calculate armor reduction
1221 damageInfo->damage = CalcArmorReducedDamage(damageInfo->target, damage);
1222 damageInfo->cleanDamage += damage - damageInfo->damage;
1224 damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType);
1226 // Disable parry or dodge for ranged attack
1227 if(damageInfo->attackType == RANGED_ATTACK)
1229 if (damageInfo->hitOutCome == MELEE_HIT_PARRY) damageInfo->hitOutCome = MELEE_HIT_NORMAL;
1230 if (damageInfo->hitOutCome == MELEE_HIT_DODGE) damageInfo->hitOutCome = MELEE_HIT_MISS;
1233 switch(damageInfo->hitOutCome)
1235 case MELEE_HIT_EVADE:
1237 damageInfo->HitInfo |= HITINFO_MISS|HITINFO_SWINGNOHITSOUND;
1238 damageInfo->TargetState = VICTIMSTATE_EVADES;
1240 damageInfo->procEx|=PROC_EX_EVADE;
1241 damageInfo->damage = 0;
1242 damageInfo->cleanDamage = 0;
1243 return;
1245 case MELEE_HIT_MISS:
1247 damageInfo->HitInfo |= HITINFO_MISS;
1248 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1250 damageInfo->procEx|=PROC_EX_MISS;
1251 damageInfo->damage = 0;
1252 damageInfo->cleanDamage = 0;
1253 break;
1255 case MELEE_HIT_NORMAL:
1256 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1257 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1258 break;
1259 case MELEE_HIT_CRIT:
1261 damageInfo->HitInfo |= HITINFO_CRITICALHIT;
1262 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1264 damageInfo->procEx|=PROC_EX_CRITICAL_HIT;
1265 // Crit bonus calc
1266 damageInfo->damage += damageInfo->damage;
1267 int32 mod=0;
1268 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1269 if(damageInfo->attackType == RANGED_ATTACK)
1270 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1271 else
1273 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1274 mod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1277 uint32 crTypeMask = damageInfo->target->GetCreatureTypeMask();
1279 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1280 mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1281 if (mod!=0)
1282 damageInfo->damage = int32((damageInfo->damage) * float((100.0f + mod)/100.0f));
1284 // Resilience - reduce crit damage
1285 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1287 uint32 resilienceReduction = ((Player*)pVictim)->GetMeleeCritDamageReduction(damageInfo->damage);
1288 damageInfo->damage -= resilienceReduction;
1289 damageInfo->cleanDamage += resilienceReduction;
1291 break;
1293 case MELEE_HIT_PARRY:
1294 damageInfo->TargetState = VICTIMSTATE_PARRY;
1295 damageInfo->procEx|=PROC_EX_PARRY;
1296 damageInfo->cleanDamage += damageInfo->damage;
1297 damageInfo->damage = 0;
1298 break;
1300 case MELEE_HIT_DODGE:
1301 damageInfo->TargetState = VICTIMSTATE_DODGE;
1302 damageInfo->procEx|=PROC_EX_DODGE;
1303 damageInfo->cleanDamage += damageInfo->damage;
1304 damageInfo->damage = 0;
1305 break;
1306 case MELEE_HIT_BLOCK:
1308 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1309 damageInfo->HitInfo |= HITINFO_BLOCK;
1310 damageInfo->procEx|=PROC_EX_BLOCK;
1311 damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue();
1312 if (damageInfo->blocked_amount >= damageInfo->damage)
1314 damageInfo->TargetState = VICTIMSTATE_BLOCKS;
1315 damageInfo->blocked_amount = damageInfo->damage;
1317 damageInfo->damage -= damageInfo->blocked_amount;
1318 damageInfo->cleanDamage += damageInfo->blocked_amount;
1319 break;
1321 case MELEE_HIT_GLANCING:
1323 damageInfo->HitInfo |= HITINFO_GLANCING;
1324 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1325 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1326 float reducePercent = 1.0f; //damage factor
1327 // calculate base values and mods
1328 float baseLowEnd = 1.3f;
1329 float baseHighEnd = 1.2f;
1330 switch(getClass()) // lowering base values for casters
1332 case CLASS_SHAMAN:
1333 case CLASS_PRIEST:
1334 case CLASS_MAGE:
1335 case CLASS_WARLOCK:
1336 case CLASS_DRUID:
1337 baseLowEnd -= 0.7f;
1338 baseHighEnd -= 0.3f;
1339 break;
1342 float maxLowEnd = 0.6f;
1343 switch(getClass()) // upper for melee classes
1345 case CLASS_WARRIOR:
1346 case CLASS_ROGUE:
1347 maxLowEnd = 0.91f; //If the attacker is a melee class then instead the lower value of 0.91
1350 // calculate values
1351 int32 diff = damageInfo->target->GetDefenseSkillValue() - GetWeaponSkillValue(damageInfo->attackType);
1352 float lowEnd = baseLowEnd - ( 0.05f * diff );
1353 float highEnd = baseHighEnd - ( 0.03f * diff );
1355 // apply max/min bounds
1356 if ( lowEnd < 0.01f ) //the low end must not go bellow 0.01f
1357 lowEnd = 0.01f;
1358 else if ( lowEnd > maxLowEnd ) //the smaller value of this and 0.6 is kept as the low end
1359 lowEnd = maxLowEnd;
1361 if ( highEnd < 0.2f ) //high end limits
1362 highEnd = 0.2f;
1363 if ( highEnd > 0.99f )
1364 highEnd = 0.99f;
1366 if(lowEnd > highEnd) // prevent negative range size
1367 lowEnd = highEnd;
1369 reducePercent = lowEnd + rand_norm() * ( highEnd - lowEnd );
1371 damageInfo->cleanDamage += damageInfo->damage-uint32(reducePercent * damageInfo->damage);
1372 damageInfo->damage = uint32(reducePercent * damageInfo->damage);
1373 break;
1375 case MELEE_HIT_CRUSHING:
1377 damageInfo->HitInfo |= HITINFO_CRUSHING;
1378 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1379 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1380 // 150% normal damage
1381 damageInfo->damage += (damageInfo->damage / 2);
1382 break;
1384 default:
1386 break;
1389 // Calculate absorb resist
1390 if(int32(damageInfo->damage) > 0)
1392 damageInfo->procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1393 // Calculate absorb & resists
1394 CalcAbsorbResist(damageInfo->target, SpellSchoolMask(damageInfo->damageSchoolMask), DIRECT_DAMAGE, damageInfo->damage, &damageInfo->absorb, &damageInfo->resist);
1395 damageInfo->damage-=damageInfo->absorb + damageInfo->resist;
1396 if (damageInfo->absorb)
1398 damageInfo->HitInfo|=HITINFO_ABSORB;
1399 damageInfo->procEx|=PROC_EX_ABSORB;
1401 if (damageInfo->resist)
1402 damageInfo->HitInfo|=HITINFO_RESIST;
1405 else // Umpossible get negative result but....
1406 damageInfo->damage = 0;
1409 void Unit::DealMeleeDamage(CalcDamageInfo *damageInfo, bool durabilityLoss)
1411 if (damageInfo==0) return;
1412 Unit *pVictim = damageInfo->target;
1414 if(!this || !pVictim)
1415 return;
1417 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1418 return;
1420 //You don't lose health from damage taken from another player while in a sanctuary
1421 //You still see it in the combat log though
1422 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1424 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1425 if(area && area->flags & AREA_FLAG_SANCTUARY) // sanctuary
1426 return;
1429 // Hmmmm dont like this emotes client must by self do all animations
1430 if (damageInfo->HitInfo&HITINFO_CRITICALHIT)
1431 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_WOUNDCRITICAL);
1432 if(damageInfo->blocked_amount && damageInfo->TargetState!=VICTIMSTATE_BLOCKS)
1433 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_PARRYSHIELD);
1435 if(damageInfo->TargetState == VICTIMSTATE_PARRY)
1437 // Get attack timers
1438 float offtime = float(pVictim->getAttackTimer(OFF_ATTACK));
1439 float basetime = float(pVictim->getAttackTimer(BASE_ATTACK));
1440 // Reduce attack time
1441 if (pVictim->haveOffhandWeapon() && offtime < basetime)
1443 float percent20 = pVictim->GetAttackTime(OFF_ATTACK) * 0.20f;
1444 float percent60 = 3.0f * percent20;
1445 if(offtime > percent20 && offtime <= percent60)
1447 pVictim->setAttackTimer(OFF_ATTACK, uint32(percent20));
1449 else if(offtime > percent60)
1451 offtime -= 2.0f * percent20;
1452 pVictim->setAttackTimer(OFF_ATTACK, uint32(offtime));
1455 else
1457 float percent20 = pVictim->GetAttackTime(BASE_ATTACK) * 0.20;
1458 float percent60 = 3.0f * percent20;
1459 if(basetime > percent20 && basetime <= percent60)
1461 pVictim->setAttackTimer(BASE_ATTACK, uint32(percent20));
1463 else if(basetime > percent60)
1465 basetime -= 2.0f * percent20;
1466 pVictim->setAttackTimer(BASE_ATTACK, uint32(basetime));
1471 // Call default DealDamage
1472 CleanDamage cleanDamage(damageInfo->cleanDamage,damageInfo->attackType,damageInfo->hitOutCome);
1473 DealDamage(pVictim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->damageSchoolMask), NULL, durabilityLoss);
1475 // If this is a creature and it attacks from behind it has a probability to daze it's victim
1476 if( (damageInfo->hitOutCome==MELEE_HIT_CRIT || damageInfo->hitOutCome==MELEE_HIT_CRUSHING || damageInfo->hitOutCome==MELEE_HIT_NORMAL || damageInfo->hitOutCome==MELEE_HIT_GLANCING) &&
1477 GetTypeId() != TYPEID_PLAYER && !((Creature*)this)->GetCharmerOrOwnerGUID() && !pVictim->HasInArc(M_PI, this) )
1479 // -probability is between 0% and 40%
1480 // 20% base chance
1481 float Probability = 20.0f;
1483 //there is a newbie protection, at level 10 just 7% base chance; assuming linear function
1484 if( pVictim->getLevel() < 30 )
1485 Probability = 0.65f*pVictim->getLevel()+0.5f;
1487 uint32 VictimDefense=pVictim->GetDefenseSkillValue();
1488 uint32 AttackerMeleeSkill=GetUnitMeleeSkill();
1490 Probability *= AttackerMeleeSkill/(float)VictimDefense;
1492 if(Probability > 40.0f)
1493 Probability = 40.0f;
1495 if(roll_chance_f(Probability))
1496 CastSpell(pVictim, 1604, true);
1499 // If not miss
1500 if (!(damageInfo->HitInfo & HITINFO_MISS))
1502 if(GetTypeId() == TYPEID_PLAYER && pVictim->isAlive())
1504 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
1505 ((Player*)this)->CastItemCombatSpell(((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0,i), pVictim, damageInfo->attackType);
1508 // victim's damage shield
1509 std::set<Aura*> alreadyDone;
1510 uint32 removedAuras = pVictim->m_removedAuras;
1511 AuraList const& vDamageShields = pVictim->GetAurasByType(SPELL_AURA_DAMAGE_SHIELD);
1512 for(AuraList::const_iterator i = vDamageShields.begin(), next = vDamageShields.begin(); i != vDamageShields.end(); i = next)
1514 next++;
1515 if (alreadyDone.find(*i) == alreadyDone.end())
1517 alreadyDone.insert(*i);
1518 uint32 damage=(*i)->GetModifier()->m_amount;
1519 SpellEntry const *spellProto = sSpellStore.LookupEntry((*i)->GetId());
1520 if(!spellProto)
1521 continue;
1522 //Calculate absorb resist ??? no data in opcode for this possibly unable to absorb or resist?
1523 //uint32 absorb;
1524 //uint32 resist;
1525 //CalcAbsorbResist(pVictim, SpellSchools(spellProto->School), SPELL_DIRECT_DAMAGE, damage, &absorb, &resist);
1526 //damage-=absorb + resist;
1528 pVictim->DealDamageMods(this,damage,NULL);
1530 WorldPacket data(SMSG_SPELLDAMAGESHIELD,(8+8+4+4+4+4));
1531 data << uint64(pVictim->GetGUID());
1532 data << uint64(GetGUID());
1533 data << uint32(spellProto->Id);
1534 data << uint32(damage); // Damage
1535 data << uint32(0); // Overkill
1536 data << uint32(spellProto->SchoolMask);
1537 pVictim->SendMessageToSet(&data, true );
1539 pVictim->DealDamage(this, damage, 0, SPELL_DIRECT_DAMAGE, GetSpellSchoolMask(spellProto), spellProto, true);
1541 if (pVictim->m_removedAuras > removedAuras)
1543 removedAuras = pVictim->m_removedAuras;
1544 next = vDamageShields.begin();
1552 void Unit::HandleEmoteCommand(uint32 anim_id)
1554 WorldPacket data( SMSG_EMOTE, 4 + 8 );
1555 data << uint32(anim_id);
1556 data << uint64(GetGUID());
1557 SendMessageToSet(&data, true);
1560 uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage)
1562 uint32 newdamage = 0;
1563 float armor = pVictim->GetArmor();
1564 // Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura
1565 armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL);
1567 // Apply Player CR_ARMOR_PENETRATION rating
1568 if (GetTypeId()==TYPEID_PLAYER)
1569 armor *= 1.0f - ((Player*)this)->GetRatingBonusValue(CR_ARMOR_PENETRATION) / 100.0f;
1571 if (armor < 0.0f) armor=0.0f;
1573 float levelModifier = getLevel();
1574 if ( levelModifier > 59 )
1575 levelModifier = levelModifier + (4.5f * (levelModifier-59));
1577 float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40);
1578 tmpvalue = tmpvalue/(1.0f + tmpvalue);
1580 if(tmpvalue < 0.0f)
1581 tmpvalue = 0.0f;
1582 if(tmpvalue > 0.75f)
1583 tmpvalue = 0.75f;
1584 newdamage = uint32(damage - (damage * tmpvalue));
1586 return (newdamage > 1) ? newdamage : 1;
1589 void Unit::CalcAbsorbResist(Unit *pVictim,SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist)
1591 if(!pVictim || !pVictim->isAlive() || !damage)
1592 return;
1594 // Magic damage, check for resists
1595 if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL)==0)
1597 // Get base victim resistance for school
1598 float tmpvalue2 = (float)pVictim->GetResistance(GetFirstSchoolInMask(schoolMask));
1599 // Ignore resistance by self SPELL_AURA_MOD_TARGET_RESISTANCE aura
1600 tmpvalue2 += (float)GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask);
1602 tmpvalue2 *= (float)(0.15f / getLevel());
1603 if (tmpvalue2 < 0.0f)
1604 tmpvalue2 = 0.0f;
1605 if (tmpvalue2 > 0.75f)
1606 tmpvalue2 = 0.75f;
1607 uint32 ran = urand(0, 100);
1608 uint32 faq[4] = {24,6,4,6};
1609 uint8 m = 0;
1610 float Binom = 0.0f;
1611 for (uint8 i = 0; i < 4; ++i)
1613 Binom += 2400 *( powf(tmpvalue2, i) * powf( (1-tmpvalue2), (4-i)))/faq[i];
1614 if (ran > Binom )
1615 ++m;
1616 else
1617 break;
1619 if (damagetype == DOT && m == 4)
1620 *resist += uint32(damage - 1);
1621 else
1622 *resist += uint32(damage * m / 4);
1623 if(*resist > damage)
1624 *resist = damage;
1626 else
1627 *resist = 0;
1629 int32 RemainingDamage = damage - *resist;
1631 // Get unit state (need for some absorb check)
1632 uint32 unitflag = pVictim->GetUInt32Value(UNIT_FIELD_FLAGS);
1633 // Reflect damage spells (not cast any damage spell in aura lookup)
1634 uint32 reflectSpell = 0;
1635 int32 reflectDamage = 0;
1636 // Death Prevention Aura
1637 SpellEntry const* preventDeathSpell = NULL;
1638 int32 preventDeathAmount = 0;
1639 // Need remove expired auras after
1640 bool existExpired = false;
1641 // absorb without mana cost
1642 AuraList const& vSchoolAbsorb = pVictim->GetAurasByType(SPELL_AURA_SCHOOL_ABSORB);
1643 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end() && RemainingDamage > 0; ++i)
1645 Modifier* mod = (*i)->GetModifier();
1646 if (!(mod->m_miscvalue & schoolMask))
1647 continue;
1649 SpellEntry const* spellProto = (*i)->GetSpellProto();
1651 // Max Amount can be absorbed by this aura
1652 int32 currentAbsorb = mod->m_amount;
1654 // Found empty aura (impossible but..)
1655 if (currentAbsorb <=0)
1657 existExpired = true;
1658 continue;
1660 // Handle custom absorb auras
1661 // TODO: try find better way
1662 switch(spellProto->SpellFamilyName)
1664 case SPELLFAMILY_GENERIC:
1666 // Astral Shift
1667 if (spellProto->SpellIconID == 3066)
1669 //reduces all damage taken while stun, fear or silence
1670 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1671 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1672 continue;
1674 // Nerves of Steel
1675 if (spellProto->SpellIconID == 2115)
1677 // while affected by Stun and Fear
1678 if (unitflag&(UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING))
1679 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1680 continue;
1682 // Spell Deflection
1683 if (spellProto->SpellIconID == 3006)
1685 // You have a chance equal to your Parry chance
1686 if (damagetype == DIRECT_DAMAGE && // Only for direct damage
1687 roll_chance_f(pVictim->GetUnitParryChance())) // Roll chance
1688 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1689 continue;
1691 // Reflective Shield (Lady Malande boss)
1692 if (spellProto->Id == 41475)
1694 if(RemainingDamage < currentAbsorb)
1695 reflectDamage = RemainingDamage / 2;
1696 else
1697 reflectDamage = currentAbsorb / 2;
1698 reflectSpell = 33619;
1699 break;
1701 if (spellProto->Id == 39228 || // Argussian Compass
1702 spellProto->Id == 60218) // Essence of Gossamer
1704 // Max absorb stored in 1 dummy effect
1705 if (spellProto->EffectBasePoints[1] < currentAbsorb)
1706 currentAbsorb = spellProto->EffectBasePoints[1];
1707 break;
1709 break;
1711 case SPELLFAMILY_DRUID:
1713 // Primal Tenacity
1714 if (spellProto->SpellIconID == 2253)
1716 //reduces all damage taken while Stunned
1717 if (unitflag & UNIT_FLAG_STUNNED)
1718 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1719 continue;
1721 break;
1723 case SPELLFAMILY_ROGUE:
1725 // Cheat Death (make less prio with Guardian Spirit case)
1726 if (!preventDeathSpell && spellProto->SpellIconID == 2109 &&
1727 pVictim->GetTypeId()==TYPEID_PLAYER && // Only players
1728 !((Player*)pVictim)->HasSpellCooldown(31231) &&
1729 // Only if no cooldown
1730 roll_chance_i((*i)->GetModifier()->m_amount))
1731 // Only if roll
1733 preventDeathSpell = (*i)->GetSpellProto();
1734 continue;
1736 break;
1738 case SPELLFAMILY_PRIEST:
1740 // Guardian Spirit
1741 if (spellProto->SpellIconID == 2873)
1743 preventDeathSpell = (*i)->GetSpellProto();
1744 preventDeathAmount = (*i)->GetModifier()->m_amount;
1745 continue;
1748 // Reflective Shield
1749 if (spellProto->SpellFamilyFlags == 0x1)
1751 if (pVictim == this)
1752 break;
1753 Unit* caster = (*i)->GetCaster();
1754 if (!caster)
1755 break;
1756 AuraList const& vOverRideCS = caster->GetAurasByType(SPELL_AURA_DUMMY);
1757 for(AuraList::const_iterator k = vOverRideCS.begin(); k != vOverRideCS.end(); ++k)
1759 switch((*k)->GetModifier()->m_miscvalue)
1761 case 5065: // Rank 1
1762 case 5064: // Rank 2
1763 case 5063: // Rank 3
1765 if(RemainingDamage >= currentAbsorb)
1766 reflectDamage = (*k)->GetModifier()->m_amount * currentAbsorb/100;
1767 else
1768 reflectDamage = (*k)->GetModifier()->m_amount * RemainingDamage/100;
1769 reflectSpell = 33619;
1770 } break;
1771 default: break;
1774 break;
1776 break;
1778 case SPELLFAMILY_SHAMAN:
1780 // Astral Shift
1781 if (spellProto->SpellIconID == 3066)
1783 //reduces all damage taken while stun, fear or silence
1784 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1785 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1786 continue;
1788 break;
1790 case SPELLFAMILY_DEATHKNIGHT:
1792 // Shadow of Death
1793 if (spellProto->SpellIconID == 1958)
1795 // TODO: absorb only while transform
1796 continue;
1798 // Anti-Magic Shell (on self)
1799 if (spellProto->Id == 48707)
1801 // damage absorbed by Anti-Magic Shell energizes the DK with additional runic power.
1802 // This, if I'm not mistaken, shows that we get back ~2% of the absorbed damage as runic power.
1803 int32 absorbed = RemainingDamage * currentAbsorb / 100;
1804 int32 regen = absorbed * 2 / 10;
1805 pVictim->CastCustomSpell(pVictim, 49088, &regen, 0, 0, true, 0, *i);
1806 RemainingDamage -= absorbed;
1807 continue;
1809 // Anti-Magic Shell (on single party/raid member)
1810 if (spellProto->Id == 50462)
1812 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1813 continue;
1815 // Anti-Magic Zone
1816 if (spellProto->Id == 50461)
1818 Unit* caster = (*i)->GetCaster();
1819 if (!caster)
1820 continue;
1821 int32 absorbed = RemainingDamage * currentAbsorb / 100;
1822 int32 canabsorb = caster->GetHealth();
1823 if (canabsorb < absorbed)
1824 absorbed = canabsorb;
1826 RemainingDamage -= absorbed;
1828 uint32 ab_damage = absorbed;
1829 DealDamageMods(caster,ab_damage,NULL);
1830 DealDamage(caster, ab_damage, NULL, damagetype, schoolMask, 0, false);
1831 continue;
1833 break;
1835 default:
1836 break;
1839 // currentAbsorb - damage can be absorbed by shield
1840 // If need absorb less damage
1841 if (RemainingDamage < currentAbsorb)
1842 currentAbsorb = RemainingDamage;
1844 RemainingDamage -= currentAbsorb;
1846 // Reduce shield amount
1847 mod->m_amount-=currentAbsorb;
1848 // Need remove it later
1849 if (mod->m_amount<=0)
1850 existExpired = true;
1853 // Remove all expired absorb auras
1854 if (existExpired)
1856 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end();)
1858 if ((*i)->GetModifier()->m_amount<=0)
1860 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1861 i = vSchoolAbsorb.begin();
1863 else
1864 ++i;
1868 // Cast back reflect damage spell
1869 if (reflectSpell)
1870 pVictim->CastCustomSpell(this, reflectSpell, &reflectDamage, NULL, NULL, true);
1872 // absorb by mana cost
1873 AuraList const& vManaShield = pVictim->GetAurasByType(SPELL_AURA_MANA_SHIELD);
1874 for(AuraList::const_iterator i = vManaShield.begin(), next; i != vManaShield.end() && RemainingDamage > 0; i = next)
1876 next = i; ++next;
1878 // check damage school mask
1879 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1880 continue;
1882 int32 currentAbsorb;
1883 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1884 currentAbsorb = (*i)->GetModifier()->m_amount;
1885 else
1886 currentAbsorb = RemainingDamage;
1888 float manaMultiplier = (*i)->GetSpellProto()->EffectMultipleValue[(*i)->GetEffIndex()];
1889 if(Player *modOwner = pVictim->GetSpellModOwner())
1890 modOwner->ApplySpellMod((*i)->GetId(), SPELLMOD_MULTIPLE_VALUE, manaMultiplier);
1892 int32 maxAbsorb = int32(pVictim->GetPower(POWER_MANA) / manaMultiplier);
1893 if (currentAbsorb > maxAbsorb)
1894 currentAbsorb = maxAbsorb;
1896 (*i)->GetModifier()->m_amount -= currentAbsorb;
1897 if((*i)->GetModifier()->m_amount <= 0)
1899 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1900 next = vManaShield.begin();
1903 int32 manaReduction = int32(currentAbsorb * manaMultiplier);
1904 pVictim->ApplyPowerMod(POWER_MANA, manaReduction, false);
1906 RemainingDamage -= currentAbsorb;
1909 // only split damage if not damaging yourself
1910 if(pVictim != this)
1912 AuraList const& vSplitDamageFlat = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_FLAT);
1913 for(AuraList::const_iterator i = vSplitDamageFlat.begin(), next; i != vSplitDamageFlat.end() && RemainingDamage >= 0; i = next)
1915 next = i; ++next;
1917 // check damage school mask
1918 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1919 continue;
1921 // Damage can be splitted only if aura has an alive caster
1922 Unit *caster = (*i)->GetCaster();
1923 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1924 continue;
1926 int32 currentAbsorb;
1927 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1928 currentAbsorb = (*i)->GetModifier()->m_amount;
1929 else
1930 currentAbsorb = RemainingDamage;
1932 RemainingDamage -= currentAbsorb;
1935 uint32 splitted = currentAbsorb;
1936 uint32 splitted_absorb = 0;
1937 DealDamageMods(caster,splitted,&splitted_absorb);
1939 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, splitted_absorb, 0, false, 0, false);
1941 CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL);
1942 DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
1945 AuraList const& vSplitDamagePct = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_PCT);
1946 for(AuraList::const_iterator i = vSplitDamagePct.begin(), next; i != vSplitDamagePct.end() && RemainingDamage >= 0; i = next)
1948 next = i; ++next;
1950 // check damage school mask
1951 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1952 continue;
1954 // Damage can be splitted only if aura has an alive caster
1955 Unit *caster = (*i)->GetCaster();
1956 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1957 continue;
1959 uint32 splitted = uint32(RemainingDamage * (*i)->GetModifier()->m_amount / 100.0f);
1961 RemainingDamage -= int32(splitted);
1963 uint32 split_absorb = 0;
1964 DealDamageMods(caster,splitted,&split_absorb);
1966 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, split_absorb, 0, false, 0, false);
1968 CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL);
1969 DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
1973 // Apply death prevention spells effects
1974 if (preventDeathSpell && RemainingDamage >= pVictim->GetHealth())
1976 switch(preventDeathSpell->SpellFamilyName)
1978 // Cheat Death
1979 case SPELLFAMILY_ROGUE:
1981 // Cheat Death
1982 if (preventDeathSpell->SpellIconID == 2109)
1984 pVictim->CastSpell(pVictim,31231,true);
1985 ((Player*)pVictim)->AddSpellCooldown(31231,0,time(NULL)+60);
1986 // with health > 10% lost health until health==10%, in other case no losses
1987 uint32 health10 = pVictim->GetMaxHealth()/10;
1988 RemainingDamage = pVictim->GetHealth() > health10 ? pVictim->GetHealth() - health10 : 0;
1990 break;
1992 // Guardian Spirit
1993 case SPELLFAMILY_PRIEST:
1995 // Guardian Spirit
1996 if (preventDeathSpell->SpellIconID == 2873)
1998 int32 healAmount = pVictim->GetMaxHealth() * preventDeathAmount / 100;
1999 pVictim->CastCustomSpell(pVictim, 48153, &healAmount, NULL, NULL, true);
2000 pVictim->RemoveAurasDueToSpell(preventDeathSpell->Id);
2001 RemainingDamage = 0;
2003 break;
2008 *absorb = damage - RemainingDamage - *resist;
2011 void Unit::AttackerStateUpdate (Unit *pVictim, WeaponAttackType attType, bool extra )
2013 if(hasUnitState(UNIT_STAT_CONFUSED | UNIT_STAT_STUNNED | UNIT_STAT_FLEEING) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) )
2014 return;
2016 if (!pVictim->isAlive())
2017 return;
2019 if(IsNonMeleeSpellCasted(false))
2020 return;
2022 uint32 hitInfo;
2023 if (attType == BASE_ATTACK)
2024 hitInfo = HITINFO_NORMALSWING2;
2025 else if (attType == OFF_ATTACK)
2026 hitInfo = HITINFO_LEFTSWING;
2027 else
2028 return; // ignore ranged case
2030 uint32 extraAttacks = m_extraAttacks;
2032 // melee attack spell casted at main hand attack only
2033 if (attType == BASE_ATTACK && m_currentSpells[CURRENT_MELEE_SPELL])
2035 m_currentSpells[CURRENT_MELEE_SPELL]->cast();
2037 // not recent extra attack only at any non extra attack (melee spell case)
2038 if(!extra && extraAttacks)
2040 while(m_extraAttacks)
2042 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
2043 if(m_extraAttacks > 0)
2044 --m_extraAttacks;
2047 return;
2050 // attack can be redirected to another target
2051 pVictim = SelectMagnetTarget(pVictim);
2053 CalcDamageInfo damageInfo;
2054 CalculateMeleeDamage(pVictim, 0, &damageInfo, attType);
2055 // Send log damage message to client
2056 DealDamageMods(pVictim,damageInfo.damage,&damageInfo.absorb);
2057 SendAttackStateUpdate(&damageInfo);
2058 ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.damage, damageInfo.attackType);
2059 DealMeleeDamage(&damageInfo,true);
2061 if (GetTypeId() == TYPEID_PLAYER)
2062 DEBUG_LOG("AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
2063 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
2064 else
2065 DEBUG_LOG("AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
2066 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
2068 // if damage pVictim call AI reaction
2069 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
2070 ((Creature*)pVictim)->AI()->AttackedBy(this);
2072 // extra attack only at any non extra attack (normal case)
2073 if(!extra && extraAttacks)
2075 while(m_extraAttacks)
2077 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
2078 if(m_extraAttacks > 0)
2079 --m_extraAttacks;
2084 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType) const
2086 // This is only wrapper
2088 // Miss chance based on melee
2089 float miss_chance = MeleeMissChanceCalc(pVictim, attType);
2091 // Critical hit chance
2092 float crit_chance = GetUnitCriticalChance(attType, pVictim);
2094 // stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case)
2095 float dodge_chance = pVictim->GetUnitDodgeChance();
2096 float block_chance = pVictim->GetUnitBlockChance();
2097 float parry_chance = pVictim->GetUnitParryChance();
2099 // Useful if want to specify crit & miss chances for melee, else it could be removed
2100 DEBUG_LOG("MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance,crit_chance,dodge_chance,parry_chance,block_chance);
2102 return RollMeleeOutcomeAgainst(pVictim, attType, int32(crit_chance*100), int32(miss_chance*100), int32(dodge_chance*100),int32(parry_chance*100),int32(block_chance*100));
2105 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst (const Unit *pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const
2107 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2108 return MELEE_HIT_EVADE;
2110 int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(pVictim);
2111 int32 victimMaxSkillValueForLevel = pVictim->GetMaxSkillValueForLevel(this);
2113 int32 attackerWeaponSkill = GetWeaponSkillValue(attType,pVictim);
2114 int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this);
2116 // bonus from skills is 0.04%
2117 int32 skillBonus = 4 * ( attackerWeaponSkill - victimMaxSkillValueForLevel );
2118 int32 sum = 0, tmp = 0;
2119 int32 roll = urand (0, 10000);
2121 DEBUG_LOG ("RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus);
2122 DEBUG_LOG ("RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d",
2123 roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance);
2125 tmp = miss_chance;
2127 if (tmp > 0 && roll < (sum += tmp ))
2129 DEBUG_LOG ("RollMeleeOutcomeAgainst: MISS");
2130 return MELEE_HIT_MISS;
2133 // always crit against a sitting target (except 0 crit chance)
2134 if( pVictim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !pVictim->IsStandState() )
2136 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT (sitting victim)");
2137 return MELEE_HIT_CRIT;
2140 // Dodge chance
2142 // only players can't dodge if attacker is behind
2143 if (pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->HasInArc(M_PI,this))
2145 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind and victim was a player.");
2147 else
2149 // Reduce dodge chance by attacker expertise rating
2150 if (GetTypeId() == TYPEID_PLAYER)
2151 dodge_chance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2153 // Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2154 dodge_chance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE);
2156 tmp = dodge_chance;
2157 if ( (tmp > 0) // check if unit _can_ dodge
2158 && ((tmp -= skillBonus) > 0)
2159 && roll < (sum += tmp))
2161 DEBUG_LOG ("RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum-tmp, sum);
2162 return MELEE_HIT_DODGE;
2166 // parry & block chances
2168 // check if attack comes from behind, nobody can parry or block if attacker is behind
2169 if (!pVictim->HasInArc(M_PI,this))
2171 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind.");
2173 else
2175 // Reduce parry chance by attacker expertise rating
2176 if (GetTypeId() == TYPEID_PLAYER)
2177 parry_chance-= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2179 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY) )
2181 int32 tmp2 = int32(parry_chance);
2182 if ( (tmp2 > 0) // check if unit _can_ parry
2183 && ((tmp2 -= skillBonus) > 0)
2184 && (roll < (sum += tmp2)))
2186 DEBUG_LOG ("RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum-tmp2, sum);
2187 return MELEE_HIT_PARRY;
2191 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) )
2193 tmp = block_chance;
2194 if ( (tmp > 0) // check if unit _can_ block
2195 && ((tmp -= skillBonus) > 0)
2196 && (roll < (sum += tmp)))
2198 DEBUG_LOG ("RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum-tmp, sum);
2199 return MELEE_HIT_BLOCK;
2204 // Critical chance
2205 tmp = crit_chance;
2207 if (tmp > 0 && roll < (sum += tmp))
2209 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum-tmp, sum);
2210 return MELEE_HIT_CRIT;
2213 // 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)
2214 if( attType != RANGED_ATTACK &&
2215 (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet()) &&
2216 pVictim->GetTypeId() != TYPEID_PLAYER && !((Creature*)pVictim)->isPet() &&
2217 getLevel() < pVictim->getLevelForTarget(this) )
2219 // cap possible value (with bonuses > max skill)
2220 int32 skill = attackerWeaponSkill;
2221 int32 maxskill = attackerMaxSkillValueForLevel;
2222 skill = (skill > maxskill) ? maxskill : skill;
2224 tmp = (10 + (victimDefenseSkill - skill)) * 100;
2225 tmp = tmp > 4000 ? 4000 : tmp;
2226 if (roll < (sum += tmp))
2228 DEBUG_LOG ("RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum-4000, sum);
2229 return MELEE_HIT_GLANCING;
2233 // mobs can score crushing blows if they're 4 or more levels above victim
2234 if (getLevelForTarget(pVictim) >= pVictim->getLevelForTarget(this) + 4 &&
2235 // can be from by creature (if can) or from controlled player that considered as creature
2236 (GetTypeId()!=TYPEID_PLAYER && !((Creature*)this)->isPet() &&
2237 !(((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH) ||
2238 GetTypeId()==TYPEID_PLAYER && GetCharmerOrOwnerGUID()))
2240 // when their weapon skill is 15 or more above victim's defense skill
2241 tmp = victimDefenseSkill;
2242 int32 tmpmax = victimMaxSkillValueForLevel;
2243 // having defense above your maximum (from items, talents etc.) has no effect
2244 tmp = tmp > tmpmax ? tmpmax : tmp;
2245 // tmp = mob's level * 5 - player's current defense skill
2246 tmp = attackerMaxSkillValueForLevel - tmp;
2247 if(tmp >= 15)
2249 // add 2% chance per lacking skill point, min. is 15%
2250 tmp = tmp * 200 - 1500;
2251 if (roll < (sum += tmp))
2253 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum-tmp, sum);
2254 return MELEE_HIT_CRUSHING;
2259 DEBUG_LOG ("RollMeleeOutcomeAgainst: NORMAL");
2260 return MELEE_HIT_NORMAL;
2263 uint32 Unit::CalculateDamage (WeaponAttackType attType, bool normalized)
2265 float min_damage, max_damage;
2267 if (normalized && GetTypeId()==TYPEID_PLAYER)
2268 ((Player*)this)->CalculateMinMaxDamage(attType,normalized,min_damage, max_damage);
2269 else
2271 switch (attType)
2273 case RANGED_ATTACK:
2274 min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE);
2275 max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE);
2276 break;
2277 case BASE_ATTACK:
2278 min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE);
2279 max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE);
2280 break;
2281 case OFF_ATTACK:
2282 min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE);
2283 max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE);
2284 break;
2285 // Just for good manner
2286 default:
2287 min_damage = 0.0f;
2288 max_damage = 0.0f;
2289 break;
2293 if (min_damage > max_damage)
2295 std::swap(min_damage,max_damage);
2298 if(max_damage == 0.0f)
2299 max_damage = 5.0f;
2301 return urand((uint32)min_damage, (uint32)max_damage);
2304 float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const
2306 if(spellProto->spellLevel <= 0)
2307 return 1.0f;
2309 float LvlPenalty = 0.0f;
2311 if(spellProto->spellLevel < 20)
2312 LvlPenalty = 20.0f - spellProto->spellLevel * 3.75f;
2313 float LvlFactor = (float(spellProto->spellLevel) + 6.0f) / float(getLevel());
2314 if(LvlFactor > 1.0f)
2315 LvlFactor = 1.0f;
2317 return (100.0f - LvlPenalty) * LvlFactor / 100.0f;
2320 void Unit::SendAttackStart(Unit* pVictim)
2322 WorldPacket data( SMSG_ATTACKSTART, 8 + 8 );
2323 data << uint64(GetGUID());
2324 data << uint64(pVictim->GetGUID());
2326 SendMessageToSet(&data, true);
2327 DEBUG_LOG( "WORLD: Sent SMSG_ATTACKSTART" );
2330 void Unit::SendAttackStop(Unit* victim)
2332 if(!victim)
2333 return;
2335 WorldPacket data( SMSG_ATTACKSTOP, (4+16) ); // we guess size
2336 data.append(GetPackGUID());
2337 data.append(victim->GetPackGUID()); // can be 0x00...
2338 data << uint32(0); // can be 0x1
2339 SendMessageToSet(&data, true);
2340 sLog.outDetail("%s %u stopped attacking %s %u", (GetTypeId()==TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), (victim->GetTypeId()==TYPEID_PLAYER ? "player" : "creature"),victim->GetGUIDLow());
2342 /*if(victim->GetTypeId() == TYPEID_UNIT)
2343 ((Creature*)victim)->AI().EnterEvadeMode(this);*/
2346 bool Unit::isSpellBlocked(Unit *pVictim, SpellEntry const * /*spellProto*/, WeaponAttackType attackType)
2348 if (pVictim->HasInArc(M_PI,this))
2350 /* Currently not exist spells with ignore block
2351 // Ignore combat result aura (parry/dodge check on prepare)
2352 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2353 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2355 if (!(*i)->isAffectedOnSpell(spellProto))
2356 continue;
2357 if ((*i)->GetModifier()->m_miscvalue == )
2358 return false;
2362 // Check creatures flags_extra for disable block
2363 if(pVictim->GetTypeId()==TYPEID_UNIT &&
2364 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK )
2365 return false;
2367 float blockChance = pVictim->GetUnitBlockChance();
2368 blockChance += (int32(GetWeaponSkillValue(attackType)) - int32(pVictim->GetMaxSkillValueForLevel()))*0.04f;
2369 if (roll_chance_f(blockChance))
2370 return true;
2372 return false;
2375 // Melee based spells can be miss, parry or dodge on this step
2376 // Crit or block - determined on damage calculation phase! (and can be both in some time)
2377 float Unit::MeleeSpellMissChance(Unit *pVictim, WeaponAttackType attType, int32 skillDiff, SpellEntry const *spell)
2379 // Calculate hit chance (more correct for chance mod)
2380 int32 HitChance;
2382 // PvP - PvE melee chances
2383 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2384 int32 leveldif = pVictim->getLevelForTarget(this) - getLevelForTarget(pVictim);
2385 if(leveldif < 3)
2386 HitChance = 95 - leveldif;
2387 else
2388 HitChance = 93 - (leveldif - 2) * lchance;
2390 // Hit chance depends from victim auras
2391 if(attType == RANGED_ATTACK)
2392 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2393 else
2394 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2396 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2397 if(Player *modOwner = GetSpellModOwner())
2398 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, HitChance);
2400 // Miss = 100 - hit
2401 float miss_chance= 100.0f - HitChance;
2403 // Bonuses from attacker aura and ratings
2404 if (attType == RANGED_ATTACK)
2405 miss_chance -= m_modRangedHitChance;
2406 else
2407 miss_chance -= m_modMeleeHitChance;
2409 // bonus from skills is 0.04%
2410 miss_chance -= skillDiff * 0.04f;
2412 // Limit miss chance from 0 to 60%
2413 if (miss_chance < 0.0f)
2414 return 0.0f;
2415 if (miss_chance > 60.0f)
2416 return 60.0f;
2417 return miss_chance;
2420 // Melee based spells hit result calculations
2421 SpellMissInfo Unit::MeleeSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2423 WeaponAttackType attType = BASE_ATTACK;
2425 if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED)
2426 attType = RANGED_ATTACK;
2428 // bonus from skills is 0.04% per skill Diff
2429 int32 attackerWeaponSkill = int32(GetWeaponSkillValue(attType,pVictim));
2430 int32 skillDiff = attackerWeaponSkill - int32(pVictim->GetMaxSkillValueForLevel(this));
2431 int32 fullSkillDiff = attackerWeaponSkill - int32(pVictim->GetDefenseSkillValue(this));
2433 uint32 roll = urand (0, 10000);
2435 uint32 missChance = uint32(MeleeSpellMissChance(pVictim, attType, fullSkillDiff, spell)*100.0f);
2436 // Roll miss
2437 uint32 tmp = missChance;
2438 if (roll < tmp)
2439 return SPELL_MISS_MISS;
2441 // Chance resist mechanic (select max value from every mechanic spell effect)
2442 int32 resist_mech = 0;
2443 // Get effects mechanic and chance
2444 for(int eff = 0; eff < 3; ++eff)
2446 int32 effect_mech = GetEffectMechanic(spell, eff);
2447 if (effect_mech)
2449 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2450 if (resist_mech < temp*100)
2451 resist_mech = temp*100;
2454 // Roll chance
2455 tmp += resist_mech;
2456 if (roll < tmp)
2457 return SPELL_MISS_RESIST;
2459 bool canDodge = true;
2460 bool canParry = true;
2462 // Same spells cannot be parry/dodge
2463 if (spell->Attributes & SPELL_ATTR_IMPOSSIBLE_DODGE_PARRY_BLOCK)
2464 return SPELL_MISS_NONE;
2466 // Ranged attack cannot be parry/dodge only deflect
2467 if (attType == RANGED_ATTACK)
2469 // only if in front
2470 if (pVictim->HasInArc(M_PI,this))
2472 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2473 tmp+=deflect_chance;
2474 if (roll < tmp)
2475 return SPELL_MISS_DEFLECT;
2477 return SPELL_MISS_NONE;
2480 // Check for attack from behind
2481 if (!pVictim->HasInArc(M_PI,this))
2483 // Can`t dodge from behind in PvP (but its possible in PvE)
2484 if (GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
2485 canDodge = false;
2486 // Can`t parry
2487 canParry = false;
2489 // Check creatures flags_extra for disable parry
2490 if(pVictim->GetTypeId()==TYPEID_UNIT)
2492 uint32 flagEx = ((Creature*)pVictim)->GetCreatureInfo()->flags_extra;
2493 if( flagEx & CREATURE_FLAG_EXTRA_NO_PARRY )
2494 canParry = false;
2496 // Ignore combat result aura
2497 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2498 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2500 if (!(*i)->isAffectedOnSpell(spell))
2501 continue;
2502 switch((*i)->GetModifier()->m_miscvalue)
2504 case MELEE_HIT_DODGE: canDodge = false; break;
2505 case MELEE_HIT_BLOCK: break; // Block check in hit step
2506 case MELEE_HIT_PARRY: canParry = false; break;
2507 default:
2508 DEBUG_LOG("Spell %u SPELL_AURA_IGNORE_COMBAT_RESULT have unhandled state %d", (*i)->GetId(), (*i)->GetModifier()->m_miscvalue);
2509 break;
2513 if (canDodge)
2515 // Roll dodge
2516 int32 dodgeChance = int32(pVictim->GetUnitDodgeChance()*100.0f) - skillDiff * 4;
2517 // Reduce enemy dodge chance by SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2518 dodgeChance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE)*100;
2519 // Reduce dodge chance by attacker expertise rating
2520 if (GetTypeId() == TYPEID_PLAYER)
2521 dodgeChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2522 if (dodgeChance < 0)
2523 dodgeChance = 0;
2525 tmp += dodgeChance;
2526 if (roll < tmp)
2527 return SPELL_MISS_DODGE;
2530 if (canParry)
2532 // Roll parry
2533 int32 parryChance = int32(pVictim->GetUnitParryChance()*100.0f) - skillDiff * 4;
2534 // Reduce parry chance by attacker expertise rating
2535 if (GetTypeId() == TYPEID_PLAYER)
2536 parryChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2537 if (parryChance < 0)
2538 parryChance = 0;
2540 tmp += parryChance;
2541 if (roll < tmp)
2542 return SPELL_MISS_PARRY;
2545 return SPELL_MISS_NONE;
2548 // TODO need use unit spell resistances in calculations
2549 SpellMissInfo Unit::MagicSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2551 // Can`t miss on dead target (on skinning for example)
2552 if (!pVictim->isAlive())
2553 return SPELL_MISS_NONE;
2555 SpellSchoolMask schoolMask = GetSpellSchoolMask(spell);
2556 // PvP - PvE spell misschances per leveldif > 2
2557 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 7 : 11;
2558 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2560 // Base hit chance from attacker and victim levels
2561 int32 modHitChance;
2562 if(leveldif < 3)
2563 modHitChance = 96 - leveldif;
2564 else
2565 modHitChance = 94 - (leveldif - 2) * lchance;
2567 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2568 if(Player *modOwner = GetSpellModOwner())
2569 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance);
2570 // Increase from attacker SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT auras
2571 modHitChance+=GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT, schoolMask);
2572 // Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras
2573 modHitChance+= pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask);
2574 // Reduce spell hit chance for Area of effect spells from victim SPELL_AURA_MOD_AOE_AVOIDANCE aura
2575 if (IsAreaOfEffectSpell(spell))
2576 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE);
2577 // Reduce spell hit chance for dispel mechanic spells from victim SPELL_AURA_MOD_DISPEL_RESIST
2578 if (IsDispelSpell(spell))
2579 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_DISPEL_RESIST);
2580 // Chance resist mechanic (select max value from every mechanic spell effect)
2581 int32 resist_mech = 0;
2582 // Get effects mechanic and chance
2583 for(int eff = 0; eff < 3; ++eff)
2585 int32 effect_mech = GetEffectMechanic(spell, eff);
2586 if (effect_mech)
2588 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2589 if (resist_mech < temp)
2590 resist_mech = temp;
2593 // Apply mod
2594 modHitChance-=resist_mech;
2596 // Chance resist debuff
2597 modHitChance-=pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel));
2599 int32 HitChance = modHitChance * 100;
2600 // Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings
2601 HitChance += int32(m_modSpellHitChance*100.0f);
2603 // Decrease hit chance from victim rating bonus
2604 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2605 HitChance -= int32(((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_SPELL)*100.0f);
2607 if (HitChance < 100) HitChance = 100;
2608 if (HitChance > 10000) HitChance = 10000;
2610 int32 tmp = 10000 - HitChance;
2612 uint32 rand = urand(0,10000);
2614 if (rand < tmp)
2615 return SPELL_MISS_RESIST;
2617 // cast by caster in front of victim
2618 if (pVictim->HasInArc(M_PI,this))
2620 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2621 tmp+=deflect_chance;
2622 if (rand < tmp)
2623 return SPELL_MISS_DEFLECT;
2626 return SPELL_MISS_NONE;
2629 // Calculate spell hit result can be:
2630 // Every spell can: Evade/Immune/Reflect/Sucesful hit
2631 // For melee based spells:
2632 // Miss
2633 // Dodge
2634 // Parry
2635 // For spells
2636 // Resist
2637 SpellMissInfo Unit::SpellHitResult(Unit *pVictim, SpellEntry const *spell, bool CanReflect)
2639 // Return evade for units in evade mode
2640 if (pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2641 return SPELL_MISS_EVADE;
2643 // Check for immune
2644 if (pVictim->IsImmunedToSpell(spell))
2645 return SPELL_MISS_IMMUNE;
2647 // All positive spells can`t miss
2648 // TODO: client not show miss log for this spells - so need find info for this in dbc and use it!
2649 if (IsPositiveSpell(spell->Id))
2650 return SPELL_MISS_NONE;
2652 // Check for immune
2653 if (pVictim->IsImmunedToDamage(GetSpellSchoolMask(spell)))
2654 return SPELL_MISS_IMMUNE;
2656 // Try victim reflect spell
2657 if (CanReflect)
2659 int32 reflectchance = pVictim->GetTotalAuraModifier(SPELL_AURA_REFLECT_SPELLS);
2660 Unit::AuraList const& mReflectSpellsSchool = pVictim->GetAurasByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL);
2661 for(Unit::AuraList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i)
2662 if((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spell))
2663 reflectchance += (*i)->GetModifier()->m_amount;
2664 if (reflectchance > 0 && roll_chance_i(reflectchance))
2666 // Start triggers for remove charges if need (trigger only for victim, and mark as active spell)
2667 ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT, PROC_EX_REFLECT, 1, BASE_ATTACK, spell);
2668 return SPELL_MISS_REFLECT;
2672 switch (spell->DmgClass)
2674 case SPELL_DAMAGE_CLASS_RANGED:
2675 case SPELL_DAMAGE_CLASS_MELEE:
2676 return MeleeSpellHitResult(pVictim, spell);
2677 case SPELL_DAMAGE_CLASS_NONE:
2678 case SPELL_DAMAGE_CLASS_MAGIC:
2679 return MagicSpellHitResult(pVictim, spell);
2681 return SPELL_MISS_NONE;
2684 float Unit::MeleeMissChanceCalc(const Unit *pVictim, WeaponAttackType attType) const
2686 if(!pVictim)
2687 return 0.0f;
2689 // Base misschance 5%
2690 float misschance = 5.0f;
2692 // DualWield - Melee spells and physical dmg spells - 5% , white damage 24%
2693 if (haveOffhandWeapon() && attType != RANGED_ATTACK)
2695 bool isNormal = false;
2696 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
2698 if( m_currentSpells[i] && (GetSpellSchoolMask(m_currentSpells[i]->m_spellInfo) & SPELL_SCHOOL_MASK_NORMAL) )
2700 isNormal = true;
2701 break;
2704 if (isNormal || m_currentSpells[CURRENT_MELEE_SPELL])
2706 misschance = 5.0f;
2708 else
2710 misschance = 24.0f;
2714 // PvP : PvE melee misschances per leveldif > 2
2715 int32 chance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2717 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2718 if(leveldif < 0)
2719 leveldif = 0;
2721 // Hit chance from attacker based on ratings and auras
2722 float m_modHitChance;
2723 if (attType == RANGED_ATTACK)
2724 m_modHitChance = m_modRangedHitChance;
2725 else
2726 m_modHitChance = m_modMeleeHitChance;
2728 if(leveldif < 3)
2729 misschance += (leveldif - m_modHitChance);
2730 else
2731 misschance += ((leveldif - 2) * chance - m_modHitChance);
2733 // Hit chance for victim based on ratings
2734 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2736 if (attType == RANGED_ATTACK)
2737 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_RANGED);
2738 else
2739 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_MELEE);
2742 // Modify miss chance by victim auras
2743 if(attType == RANGED_ATTACK)
2744 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2745 else
2746 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2748 // Modify miss chance from skill difference ( bonus from skills is 0.04% )
2749 int32 skillBonus = int32(GetWeaponSkillValue(attType,pVictim)) - int32(pVictim->GetDefenseSkillValue(this));
2750 misschance -= skillBonus * 0.04f;
2752 // Limit miss chance from 0 to 60%
2753 if ( misschance < 0.0f)
2754 return 0.0f;
2755 if ( misschance > 60.0f)
2756 return 60.0f;
2758 return misschance;
2761 uint32 Unit::GetDefenseSkillValue(Unit const* target) const
2763 if(GetTypeId() == TYPEID_PLAYER)
2765 // in PvP use full skill instead current skill value
2766 uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2767 ? ((Player*)this)->GetMaxSkillValue(SKILL_DEFENSE)
2768 : ((Player*)this)->GetSkillValue(SKILL_DEFENSE);
2769 value += uint32(((Player*)this)->GetRatingBonusValue(CR_DEFENSE_SKILL));
2770 return value;
2772 else
2773 return GetUnitMeleeSkill(target);
2776 float Unit::GetUnitDodgeChance() const
2778 if(hasUnitState(UNIT_STAT_STUNNED))
2779 return 0.0f;
2780 if( GetTypeId() == TYPEID_PLAYER )
2781 return GetFloatValue(PLAYER_DODGE_PERCENTAGE);
2782 else
2784 if(((Creature const*)this)->isTotem())
2785 return 0.0f;
2786 else
2788 float dodge = 5.0f;
2789 dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT);
2790 return dodge > 0.0f ? dodge : 0.0f;
2795 float Unit::GetUnitParryChance() const
2797 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2798 return 0.0f;
2800 float chance = 0.0f;
2802 if(GetTypeId() == TYPEID_PLAYER)
2804 Player const* player = (Player const*)this;
2805 if(player->CanParry() )
2807 Item *tmpitem = player->GetWeaponForAttack(BASE_ATTACK,true);
2808 if(!tmpitem)
2809 tmpitem = player->GetWeaponForAttack(OFF_ATTACK,true);
2811 if(tmpitem)
2812 chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE);
2815 else if(GetTypeId() == TYPEID_UNIT)
2817 if(GetCreatureType() == CREATURE_TYPE_HUMANOID)
2819 chance = 5.0f;
2820 chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT);
2824 return chance > 0.0f ? chance : 0.0f;
2827 float Unit::GetUnitBlockChance() const
2829 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2830 return 0.0f;
2832 if(GetTypeId() == TYPEID_PLAYER)
2834 Player const* player = (Player const*)this;
2835 if(player->CanBlock() )
2837 Item *tmpitem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
2838 if(tmpitem && !tmpitem->IsBroken() && tmpitem->GetProto()->Block)
2839 return GetFloatValue(PLAYER_BLOCK_PERCENTAGE);
2841 // is player but has no block ability or no not broken shield equipped
2842 return 0.0f;
2844 else
2846 if(((Creature const*)this)->isTotem())
2847 return 0.0f;
2848 else
2850 float block = 5.0f;
2851 block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT);
2852 return block > 0.0f ? block : 0.0f;
2857 float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit *pVictim) const
2859 float crit;
2861 if(GetTypeId() == TYPEID_PLAYER)
2863 switch(attackType)
2865 case BASE_ATTACK:
2866 crit = GetFloatValue( PLAYER_CRIT_PERCENTAGE );
2867 break;
2868 case OFF_ATTACK:
2869 crit = GetFloatValue( PLAYER_OFFHAND_CRIT_PERCENTAGE );
2870 break;
2871 case RANGED_ATTACK:
2872 crit = GetFloatValue( PLAYER_RANGED_CRIT_PERCENTAGE );
2873 break;
2874 // Just for good manner
2875 default:
2876 crit = 0.0f;
2877 break;
2880 else
2882 crit = 5.0f;
2883 crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PERCENT);
2886 // flat aura mods
2887 if(attackType == RANGED_ATTACK)
2888 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE);
2889 else
2890 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE);
2892 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
2894 // reduce crit chance from Rating for players
2895 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2897 if (attackType==RANGED_ATTACK)
2898 crit -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_RANGED);
2899 else
2900 crit -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE);
2903 // Apply crit chance from defence skill
2904 crit += (int32(GetMaxSkillValueForLevel(pVictim)) - int32(pVictim->GetDefenseSkillValue(this))) * 0.04f;
2906 if (crit < 0.0f)
2907 crit = 0.0f;
2908 return crit;
2911 uint32 Unit::GetWeaponSkillValue (WeaponAttackType attType, Unit const* target) const
2913 uint32 value = 0;
2914 if(GetTypeId() == TYPEID_PLAYER)
2916 Item* item = ((Player*)this)->GetWeaponForAttack(attType,true);
2918 // feral or unarmed skill only for base attack
2919 if(attType != BASE_ATTACK && !item )
2920 return 0;
2922 if(IsInFeralForm())
2923 return GetMaxSkillValueForLevel(); // always maximized SKILL_FERAL_COMBAT in fact
2925 // weapon skill or (unarmed for base attack)
2926 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
2928 // in PvP use full skill instead current skill value
2929 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2930 ? ((Player*)this)->GetMaxSkillValue(skill)
2931 : ((Player*)this)->GetSkillValue(skill);
2932 // Modify value from ratings
2933 value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL));
2934 switch (attType)
2936 case BASE_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_MAINHAND));break;
2937 case OFF_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_OFFHAND));break;
2938 case RANGED_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_RANGED));break;
2941 else
2942 value = GetUnitMeleeSkill(target);
2943 return value;
2946 void Unit::_UpdateSpells( uint32 time )
2948 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
2949 _UpdateAutoRepeatSpell();
2951 // remove finished spells from current pointers
2952 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
2954 if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED)
2956 m_currentSpells[i]->SetReferencedFromCurrent(false);
2957 m_currentSpells[i] = NULL; // remove pointer
2961 // TODO: Find a better way to prevent crash when multiple auras are removed.
2962 m_removedAuras = 0;
2963 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
2964 if ((*i).second)
2965 (*i).second->SetUpdated(false);
2967 for (AuraMap::iterator i = m_Auras.begin(), next; i != m_Auras.end(); i = next)
2969 next = i;
2970 ++next;
2971 if ((*i).second)
2973 // prevent double update
2974 if ((*i).second->IsUpdated())
2975 continue;
2976 (*i).second->SetUpdated(true);
2977 (*i).second->Update( time );
2978 // several auras can be deleted due to update
2979 if (m_removedAuras)
2981 if (m_Auras.empty()) break;
2982 next = m_Auras.begin();
2983 m_removedAuras = 0;
2988 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end();)
2990 if ((*i).second)
2992 if ( !(*i).second->GetAuraDuration() && !((*i).second->IsPermanent() || ((*i).second->IsPassive())) )
2994 RemoveAura(i);
2996 else
2998 ++i;
3001 else
3003 ++i;
3007 if(!m_gameObj.empty())
3009 GameObjectList::iterator ite1, dnext1;
3010 for (ite1 = m_gameObj.begin(); ite1 != m_gameObj.end(); ite1 = dnext1)
3012 dnext1 = ite1;
3013 //(*i)->Update( difftime );
3014 if( !(*ite1)->isSpawned() )
3016 (*ite1)->SetOwnerGUID(0);
3017 (*ite1)->SetRespawnTime(0);
3018 (*ite1)->Delete();
3019 dnext1 = m_gameObj.erase(ite1);
3021 else
3022 ++dnext1;
3027 void Unit::_UpdateAutoRepeatSpell()
3029 //check "realtime" interrupts
3030 if ( (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->isMoving()) || IsNonMeleeSpellCasted(false,false,true) )
3032 // cancel wand shoot
3033 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3034 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3035 m_AutoRepeatFirstCast = true;
3036 return;
3039 //apply delay
3040 if ( m_AutoRepeatFirstCast && getAttackTimer(RANGED_ATTACK) < 500 )
3041 setAttackTimer(RANGED_ATTACK,500);
3042 m_AutoRepeatFirstCast = false;
3044 //castroutine
3045 if (isAttackReady(RANGED_ATTACK))
3047 // Check if able to cast
3048 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->CheckCast(true) != SPELL_CAST_OK)
3050 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3051 return;
3054 // we want to shoot
3055 Spell* spell = new Spell(this, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, true, 0);
3056 spell->prepare(&(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_targets));
3058 // all went good, reset attack
3059 resetAttackTimer(RANGED_ATTACK);
3063 void Unit::SetCurrentCastedSpell( Spell * pSpell )
3065 assert(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells
3067 CurrentSpellTypes CSpellType = pSpell->GetCurrentContainer();
3069 if (pSpell == m_currentSpells[CSpellType]) return; // avoid breaking self
3071 // break same type spell if it is not delayed
3072 InterruptSpell(CSpellType,false);
3074 // special breakage effects:
3075 switch (CSpellType)
3077 case CURRENT_GENERIC_SPELL:
3079 // generic spells always break channeled not delayed spells
3080 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3082 // autorepeat breaking
3083 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3085 // break autorepeat if not Auto Shot
3086 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3087 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3088 m_AutoRepeatFirstCast = true;
3090 } break;
3092 case CURRENT_CHANNELED_SPELL:
3094 // channel spells always break generic non-delayed and any channeled spells
3095 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3096 InterruptSpell(CURRENT_CHANNELED_SPELL);
3098 // it also does break autorepeat if not Auto Shot
3099 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] &&
3100 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT )
3101 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3102 } break;
3104 case CURRENT_AUTOREPEAT_SPELL:
3106 // only Auto Shoot does not break anything
3107 if (pSpell->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3109 // generic autorepeats break generic non-delayed and channeled non-delayed spells
3110 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3111 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3113 // special action: set first cast flag
3114 m_AutoRepeatFirstCast = true;
3115 } break;
3117 default:
3119 // other spell types don't break anything now
3120 } break;
3123 // current spell (if it is still here) may be safely deleted now
3124 if (m_currentSpells[CSpellType])
3125 m_currentSpells[CSpellType]->SetReferencedFromCurrent(false);
3127 // set new current spell
3128 m_currentSpells[CSpellType] = pSpell;
3129 pSpell->SetReferencedFromCurrent(true);
3132 void Unit::InterruptSpell(uint32 spellType, bool withDelayed)
3134 assert(spellType < CURRENT_MAX_SPELL);
3136 if (m_currentSpells[spellType] && (withDelayed || m_currentSpells[spellType]->getState() != SPELL_STATE_DELAYED) )
3138 // send autorepeat cancel message for autorepeat spells
3139 if (spellType == CURRENT_AUTOREPEAT_SPELL)
3141 if(GetTypeId()==TYPEID_PLAYER)
3142 ((Player*)this)->SendAutoRepeatCancel();
3145 if (m_currentSpells[spellType]->getState() != SPELL_STATE_FINISHED)
3146 m_currentSpells[spellType]->cancel();
3148 // cancel can interrupt spell already (caster cancel ->target aura remove -> caster iterrupt)
3149 if (m_currentSpells[spellType])
3151 m_currentSpells[spellType]->SetReferencedFromCurrent(false);
3152 m_currentSpells[spellType] = NULL;
3157 bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat) const
3159 // We don't do loop here to explicitly show that melee spell is excluded.
3160 // Maybe later some special spells will be excluded too.
3162 // generic spells are casted when they are not finished and not delayed
3163 if ( m_currentSpells[CURRENT_GENERIC_SPELL] &&
3164 (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
3165 (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
3166 return(true);
3168 // channeled spells may be delayed, but they are still considered casted
3169 else if ( !skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] &&
3170 (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED) )
3171 return(true);
3173 // autorepeat spells may be finished or delayed, but they are still considered casted
3174 else if ( !skipAutorepeat && m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3175 return(true);
3177 return(false);
3180 void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id)
3182 // generic spells are interrupted if they are not finished or delayed
3183 if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id==spell_id))
3184 InterruptSpell(CURRENT_GENERIC_SPELL,withDelayed);
3186 // autorepeat spells are interrupted if they are not finished or delayed
3187 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id==spell_id))
3188 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,withDelayed);
3190 // channeled spells are interrupted if they are not finished, even if they are delayed
3191 if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id==spell_id))
3192 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
3195 Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const
3197 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
3198 if(m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id==spell_id)
3199 return m_currentSpells[i];
3200 return NULL;
3203 bool Unit::isInFrontInMap(Unit const* target, float distance, float arc) const
3205 return IsWithinDistInMap(target, distance) && HasInArc( arc, target );
3208 void Unit::SetInFront(Unit const* target)
3210 SetOrientation(GetAngle(target));
3213 bool Unit::isInBackInMap(Unit const* target, float distance, float arc) const
3215 return IsWithinDistInMap(target, distance) && !HasInArc( 2 * M_PI - arc, target );
3218 bool Unit::isInAccessablePlaceFor(Creature const* c) const
3220 if(IsInWater())
3221 return c->canSwim();
3222 else
3223 return c->canWalk() || c->canFly();
3226 bool Unit::IsInWater() const
3228 return MapManager::Instance().GetBaseMap(GetMapId())->IsInWater(GetPositionX(),GetPositionY(), GetPositionZ());
3231 bool Unit::IsUnderWater() const
3233 return MapManager::Instance().GetBaseMap(GetMapId())->IsUnderWater(GetPositionX(),GetPositionY(),GetPositionZ());
3236 void Unit::DeMorph()
3238 SetDisplayId(GetNativeDisplayId());
3241 int32 Unit::GetTotalAuraModifier(AuraType auratype) const
3243 int32 modifier = 0;
3245 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3246 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3247 modifier += (*i)->GetModifier()->m_amount;
3249 return modifier;
3252 float Unit::GetTotalAuraMultiplier(AuraType auratype) const
3254 float multiplier = 1.0f;
3256 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3257 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3258 multiplier *= (100.0f + (*i)->GetModifier()->m_amount)/100.0f;
3260 return multiplier;
3263 int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype) const
3265 int32 modifier = 0;
3267 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3268 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3269 if ((*i)->GetModifier()->m_amount > modifier)
3270 modifier = (*i)->GetModifier()->m_amount;
3272 return modifier;
3275 int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const
3277 int32 modifier = 0;
3279 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3280 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3281 if ((*i)->GetModifier()->m_amount < modifier)
3282 modifier = (*i)->GetModifier()->m_amount;
3284 return modifier;
3287 int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3289 int32 modifier = 0;
3291 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3292 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3294 Modifier* mod = (*i)->GetModifier();
3295 if (mod->m_miscvalue & misc_mask)
3296 modifier += mod->m_amount;
3298 return modifier;
3301 float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const
3303 float multiplier = 1.0f;
3305 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3306 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3308 Modifier* mod = (*i)->GetModifier();
3309 if (mod->m_miscvalue & misc_mask)
3310 multiplier *= (100.0f + mod->m_amount)/100.0f;
3312 return multiplier;
3315 int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3317 int32 modifier = 0;
3319 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3320 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3322 Modifier* mod = (*i)->GetModifier();
3323 if (mod->m_miscvalue & misc_mask && mod->m_amount > modifier)
3324 modifier = mod->m_amount;
3327 return modifier;
3330 int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3332 int32 modifier = 0;
3334 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3335 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3337 Modifier* mod = (*i)->GetModifier();
3338 if (mod->m_miscvalue & misc_mask && mod->m_amount < modifier)
3339 modifier = mod->m_amount;
3342 return modifier;
3345 int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3347 int32 modifier = 0;
3349 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3350 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3352 Modifier* mod = (*i)->GetModifier();
3353 if (mod->m_miscvalue == misc_value)
3354 modifier += mod->m_amount;
3356 return modifier;
3359 float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const
3361 float multiplier = 1.0f;
3363 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3364 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3366 Modifier* mod = (*i)->GetModifier();
3367 if (mod->m_miscvalue == misc_value)
3368 multiplier *= (100.0f + mod->m_amount)/100.0f;
3370 return multiplier;
3373 int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3375 int32 modifier = 0;
3377 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3378 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3380 Modifier* mod = (*i)->GetModifier();
3381 if (mod->m_miscvalue == misc_value && mod->m_amount > modifier)
3382 modifier = mod->m_amount;
3385 return modifier;
3388 int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3390 int32 modifier = 0;
3392 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3393 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3395 Modifier* mod = (*i)->GetModifier();
3396 if (mod->m_miscvalue == misc_value && mod->m_amount < modifier)
3397 modifier = mod->m_amount;
3400 return modifier;
3403 bool Unit::AddAura(Aura *Aur)
3405 // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load)
3406 if( !isAlive() && Aur->GetId() != 20584 && Aur->GetId() != 8326 && Aur->GetId() != 2584 &&
3407 (GetTypeId()!=TYPEID_PLAYER || !((Player*)this)->GetSession()->PlayerLoading()) )
3409 delete Aur;
3410 return false;
3413 if(Aur->GetTarget() != this)
3415 sLog.outError("Aura (spell %u eff %u) add to aura list of %s (lowguid: %u) but Aura target is %s (lowguid: %u)",
3416 Aur->GetId(),Aur->GetEffIndex(),(GetTypeId()==TYPEID_PLAYER?"player":"creature"),GetGUIDLow(),
3417 (Aur->GetTarget()->GetTypeId()==TYPEID_PLAYER?"player":"creature"),Aur->GetTarget()->GetGUIDLow());
3418 delete Aur;
3419 return false;
3422 SpellEntry const* aurSpellInfo = Aur->GetSpellProto();
3423 AuraType aurName = Aur->GetModifier()->m_auraname;
3425 spellEffectPair spair = spellEffectPair(Aur->GetId(), Aur->GetEffIndex());
3426 AuraMap::iterator i = m_Auras.find( spair );
3428 // take out same spell
3429 if (i != m_Auras.end())
3431 // passive and persistent auras can stack with themselves any number of times
3432 if (!Aur->IsPassive() && !Aur->IsPersistent())
3434 for(AuraMap::iterator i2 = m_Auras.lower_bound(spair); i2 != m_Auras.upper_bound(spair); ++i2)
3436 if(i2->second->GetCasterGUID()==Aur->GetCasterGUID())
3438 // Aura can stack on self -> Stack it;
3439 if(aurSpellInfo->StackAmount)
3441 i2->second->modStackAmount(1);
3442 delete Aur;
3443 return false;
3445 // can be only single (this check done at _each_ aura add
3446 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3447 break;
3450 bool stop = false;
3451 switch(aurName)
3453 // DoT/HoT/etc
3454 case SPELL_AURA_PERIODIC_DAMAGE: // allow stack
3455 case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
3456 case SPELL_AURA_PERIODIC_LEECH:
3457 case SPELL_AURA_PERIODIC_HEAL:
3458 case SPELL_AURA_OBS_MOD_HEALTH:
3459 case SPELL_AURA_PERIODIC_MANA_LEECH:
3460 case SPELL_AURA_PERIODIC_ENERGIZE:
3461 case SPELL_AURA_OBS_MOD_MANA:
3462 case SPELL_AURA_POWER_BURN_MANA:
3463 break;
3464 default: // not allow
3465 // can be only single (this check done at _each_ aura add
3466 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3467 stop = true;
3468 break;
3471 if(stop)
3472 break;
3477 // passive auras not stacable with other ranks
3478 if (!IsPassiveSpellStackableWithRanks(aurSpellInfo))
3480 if (!RemoveNoStackAurasDueToAura(Aur))
3482 delete Aur;
3483 return false; // couldn't remove conflicting aura with higher rank
3487 // update single target auras list (before aura add to aura list, to prevent unexpected remove recently added aura)
3488 if (Aur->IsSingleTarget() && Aur->GetTarget())
3490 // caster pointer can be deleted in time aura remove, find it by guid at each iteration
3491 for(;;)
3493 Unit* caster = Aur->GetCaster();
3494 if(!caster) // caster deleted and not required adding scAura
3495 break;
3497 bool restart = false;
3498 AuraList& scAuras = caster->GetSingleCastAuras();
3499 for(AuraList::const_iterator itr = scAuras.begin(); itr != scAuras.end(); ++itr)
3501 if( (*itr)->GetTarget() != Aur->GetTarget() &&
3502 IsSingleTargetSpells((*itr)->GetSpellProto(),aurSpellInfo) )
3504 if ((*itr)->IsInUse())
3506 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());
3507 continue;
3509 (*itr)->GetTarget()->RemoveAura((*itr)->GetId(), (*itr)->GetEffIndex());
3510 restart = true;
3511 break;
3515 if(!restart)
3517 // done
3518 scAuras.push_back(Aur);
3519 break;
3524 // add aura, register in lists and arrays
3525 Aur->_AddAura();
3526 m_Auras.insert(AuraMap::value_type(spellEffectPair(Aur->GetId(), Aur->GetEffIndex()), Aur));
3527 if (aurName < TOTAL_AURAS)
3529 m_modAuras[aurName].push_back(Aur);
3532 Aur->ApplyModifier(true,true);
3533 sLog.outDebug("Aura %u now is in use", aurName);
3534 return true;
3537 void Unit::RemoveRankAurasDueToSpell(uint32 spellId)
3539 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
3540 if(!spellInfo)
3541 return;
3542 AuraMap::const_iterator i,next;
3543 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3545 next = i;
3546 ++next;
3547 uint32 i_spellId = (*i).second->GetId();
3548 if((*i).second && i_spellId && i_spellId != spellId)
3550 if(spellmgr.IsRankSpellDueToSpell(spellInfo,i_spellId))
3552 RemoveAurasDueToSpell(i_spellId);
3554 if( m_Auras.empty() )
3555 break;
3556 else
3557 next = m_Auras.begin();
3563 bool Unit::RemoveNoStackAurasDueToAura(Aura *Aur)
3565 if (!Aur)
3566 return false;
3568 SpellEntry const* spellProto = Aur->GetSpellProto();
3569 if (!spellProto)
3570 return false;
3572 uint32 spellId = Aur->GetId();
3573 uint32 effIndex = Aur->GetEffIndex();
3575 // passive spell special case (only non stackable with ranks)
3576 if(IsPassiveSpell(spellId))
3578 if(IsPassiveSpellStackableWithRanks(spellProto))
3579 return true;
3582 SpellSpecific spellId_spec = GetSpellSpecific(spellId);
3584 AuraMap::iterator i,next;
3585 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3587 next = i;
3588 ++next;
3589 if (!(*i).second) continue;
3591 SpellEntry const* i_spellProto = (*i).second->GetSpellProto();
3593 if (!i_spellProto)
3594 continue;
3596 uint32 i_spellId = i_spellProto->Id;
3598 // early checks that spellId is passive non stackable spell
3599 if(IsPassiveSpell(i_spellId))
3601 // passive non-stackable spells not stackable only for same caster
3602 if(Aur->GetCasterGUID()!=i->second->GetCasterGUID())
3603 continue;
3605 // passive non-stackable spells not stackable only with another rank of same spell
3606 if (!spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3607 continue;
3610 uint32 i_effIndex = (*i).second->GetEffIndex();
3612 if(i_spellId == spellId) continue;
3614 bool is_triggered_by_spell = false;
3615 // prevent triggered aura of removing aura that triggered it
3616 for(int j = 0; j < 3; ++j)
3617 if (i_spellProto->EffectTriggerSpell[j] == spellProto->Id)
3618 is_triggered_by_spell = true;
3620 if (is_triggered_by_spell)
3621 continue;
3623 SpellSpecific i_spellId_spec = GetSpellSpecific(i_spellId);
3625 bool is_sspc = IsSingleFromSpellSpecificPerCaster(spellId_spec,i_spellId_spec);
3626 bool is_sspt = IsSingleFromSpellSpecificRanksPerTarget(spellId_spec,i_spellId_spec);
3628 if( is_sspc && Aur->GetCasterGUID() == (*i).second->GetCasterGUID() )
3630 // cannot remove higher rank
3631 if (spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3632 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3633 return false;
3635 // Its a parent aura (create this aura in ApplyModifier)
3636 if ((*i).second->IsInUse())
3638 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());
3639 continue;
3641 RemoveAurasDueToSpell(i_spellId);
3643 if( m_Auras.empty() )
3644 break;
3645 else
3646 next = m_Auras.begin();
3648 else if( is_sspt && Aur->GetCasterGUID() != (*i).second->GetCasterGUID() && spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId) )
3650 // cannot remove higher rank
3651 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3652 return false;
3654 // Its a parent aura (create this aura in ApplyModifier)
3655 if ((*i).second->IsInUse())
3657 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());
3658 continue;
3660 RemoveAurasDueToSpell(i_spellId);
3662 if( m_Auras.empty() )
3663 break;
3664 else
3665 next = m_Auras.begin();
3667 else if( !is_sspc && spellmgr.IsNoStackSpellDueToSpell(spellId, i_spellId) )
3669 // Its a parent aura (create this aura in ApplyModifier)
3670 if ((*i).second->IsInUse())
3672 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());
3673 continue;
3675 RemoveAurasDueToSpell(i_spellId);
3677 if( m_Auras.empty() )
3678 break;
3679 else
3680 next = m_Auras.begin();
3682 // Potions stack aura by aura (elixirs/flask already checked)
3683 else if( spellProto->SpellFamilyName == SPELLFAMILY_POTION && i_spellProto->SpellFamilyName == SPELLFAMILY_POTION )
3685 if (IsNoStackAuraDueToAura(spellId, effIndex, i_spellId, i_effIndex))
3687 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3688 return false; // cannot remove higher rank
3690 // Its a parent aura (create this aura in ApplyModifier)
3691 if ((*i).second->IsInUse())
3693 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());
3694 continue;
3696 RemoveAura(i);
3697 next = i;
3701 return true;
3704 void Unit::RemoveAura(uint32 spellId, uint32 effindex, Aura* except)
3706 spellEffectPair spair = spellEffectPair(spellId, effindex);
3707 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3709 if(iter->second!=except)
3711 RemoveAura(iter);
3712 iter = m_Auras.lower_bound(spair);
3714 else
3715 ++iter;
3719 void Unit::RemoveAurasByCasterSpell(uint32 spellId, uint64 casterGUID)
3721 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3723 Aura *aur = iter->second;
3724 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3725 RemoveAura(iter);
3726 else
3727 ++iter;
3731 void Unit::RemoveAurasDueToSpellByDispel(uint32 spellId, uint64 casterGUID, Unit *dispeler)
3733 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3735 Aura *aur = iter->second;
3736 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3738 // Custom dispel case
3739 // Unstable Affliction
3740 if (aur->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && (aur->GetSpellProto()->SpellFamilyFlags & 0x010000000000LL))
3742 int32 damage = aur->GetModifier()->m_amount*9;
3743 uint64 caster_guid = aur->GetCasterGUID();
3745 // Remove aura
3746 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3748 // backfire damage and silence
3749 dispeler->CastCustomSpell(dispeler, 31117, &damage, NULL, NULL, true, NULL, NULL,caster_guid);
3751 iter = m_Auras.begin(); // iterator can be invalidate at cast if self-dispel
3753 else
3754 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3756 else
3757 ++iter;
3761 void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit *stealer)
3763 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3765 Aura *aur = iter->second;
3766 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3768 int32 basePoints = aur->GetBasePoints();
3769 // construct the new aura for the attacker - will never return NULL, it's just a wrapper for
3770 // some different constructors
3771 Aura * new_aur = CreateAura(aur->GetSpellProto(), aur->GetEffIndex(), &basePoints, stealer, this);
3773 // set its duration and maximum duration
3774 // max duration 2 minutes (in msecs)
3775 int32 dur = aur->GetAuraDuration();
3776 const int32 max_dur = 2*MINUTE*IN_MILISECONDS;
3777 new_aur->SetAuraMaxDuration( max_dur > dur ? dur : max_dur );
3778 new_aur->SetAuraDuration( max_dur > dur ? dur : max_dur );
3780 // Unregister _before_ adding to stealer
3781 aur->UnregisterSingleCastAura();
3783 // strange but intended behaviour: Stolen single target auras won't be treated as single targeted
3784 new_aur->SetIsSingleTarget(false);
3786 // add the new aura to stealer
3787 stealer->AddAura(new_aur);
3789 // Remove aura as dispel
3790 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3792 else
3793 ++iter;
3797 void Unit::RemoveAurasDueToSpellByCancel(uint32 spellId)
3799 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3801 if (iter->second->GetId() == spellId)
3802 RemoveAura(iter, AURA_REMOVE_BY_CANCEL);
3803 else
3804 ++iter;
3808 void Unit::RemoveAurasWithDispelType( DispelType type )
3810 // Create dispel mask by dispel type
3811 uint32 dispelMask = GetDispellMask(type);
3812 // Dispel all existing auras vs current dispel type
3813 AuraMap& auras = GetAuras();
3814 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
3816 SpellEntry const* spell = itr->second->GetSpellProto();
3817 if( (1<<spell->Dispel) & dispelMask )
3819 // Dispel aura
3820 RemoveAurasDueToSpell(spell->Id);
3821 itr = auras.begin();
3823 else
3824 ++itr;
3828 void Unit::RemoveSingleAuraFromStack(uint32 spellId, uint32 effindex)
3830 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3831 if(iter != m_Auras.end())
3833 if (iter->second->modStackAmount(-1))
3834 RemoveAura(iter);
3838 void Unit::RemoveSingleSpellAurasFromStack(uint32 spellId)
3840 for (int i=0; i<3; ++i)
3841 RemoveSingleAuraFromStack(spellId, i);
3844 void Unit::RemoveAurasDueToSpell(uint32 spellId, Aura* except)
3846 for (int i = 0; i < 3; ++i)
3847 RemoveAura(spellId,i,except);
3850 void Unit::RemoveAurasDueToItemSpell(Item* castItem,uint32 spellId)
3852 for (int k=0; k < 3; ++k)
3854 spellEffectPair spair = spellEffectPair(spellId, k);
3855 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3857 if (iter->second->GetCastItemGUID() == castItem->GetGUID())
3859 RemoveAura(iter);
3860 iter = m_Auras.upper_bound(spair); // overwrite by more appropriate
3862 else
3863 ++iter;
3868 void Unit::RemoveAurasWithInterruptFlags(uint32 flags)
3870 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3872 if (iter->second->GetSpellProto()->AuraInterruptFlags & flags)
3873 RemoveAura(iter);
3874 else
3875 ++iter;
3879 void Unit::RemoveNotOwnSingleTargetAuras()
3881 // single target auras from other casters
3882 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3884 if (iter->second->GetCasterGUID()!=GetGUID() && IsSingleTargetSpell(iter->second->GetSpellProto()))
3885 RemoveAura(iter);
3886 else
3887 ++iter;
3890 // single target auras at other targets
3891 AuraList& scAuras = GetSingleCastAuras();
3892 for (AuraList::iterator iter = scAuras.begin(); iter != scAuras.end(); )
3894 Aura* aura = *iter;
3895 if (aura->GetTarget()!=this)
3897 scAuras.erase(iter); // explicitly remove, instead waiting remove in RemoveAura
3898 aura->GetTarget()->RemoveAura(aura->GetId(),aura->GetEffIndex());
3899 iter = scAuras.begin();
3901 else
3902 ++iter;
3907 void Unit::RemoveAura(AuraMap::iterator &i, AuraRemoveMode mode)
3909 Aura* Aur = i->second;
3910 SpellEntry const* AurSpellInfo = Aur->GetSpellProto();
3912 Aur->UnregisterSingleCastAura();
3914 // remove from list before mods removing (prevent cyclic calls, mods added before including to aura list - use reverse order)
3915 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
3917 m_modAuras[Aur->GetModifier()->m_auraname].remove(Aur);
3920 // Set remove mode
3921 Aur->SetRemoveMode(mode);
3922 // some ShapeshiftBoosts at remove trigger removing other auras including parent Shapeshift aura
3923 // remove aura from list before to prevent deleting it before
3924 m_Auras.erase(i);
3925 ++m_removedAuras; // internal count used by unit update
3927 // Statue unsummoned at aura remove
3928 Totem* statue = NULL;
3929 bool caster_channeled = false;
3930 if(IsChanneledSpell(AurSpellInfo))
3932 Unit* caster = Aur->GetCaster();
3934 if(caster)
3936 if(caster->GetTypeId()==TYPEID_UNIT && ((Creature*)caster)->isTotem() && ((Totem*)caster)->GetTotemType()==TOTEM_STATUE)
3937 statue = ((Totem*)caster);
3938 else
3939 caster_channeled = caster==this;
3943 sLog.outDebug("Aura %u now is remove mode %d",Aur->GetModifier()->m_auraname, mode);
3944 Aur->ApplyModifier(false,true);
3945 Aur->_RemoveAura();
3946 delete Aur;
3948 if(caster_channeled)
3949 RemoveAurasAtChanneledTarget (AurSpellInfo);
3951 if(statue)
3952 statue->UnSummon();
3954 // only way correctly remove all auras from list
3955 if( m_Auras.empty() )
3956 i = m_Auras.end();
3957 else
3958 i = m_Auras.begin();
3961 void Unit::RemoveAllAuras()
3963 while (!m_Auras.empty())
3965 AuraMap::iterator iter = m_Auras.begin();
3966 RemoveAura(iter);
3970 void Unit::RemoveArenaAuras(bool onleave)
3972 // in join, remove positive buffs, on end, remove negative
3973 // used to remove positive visible auras in arenas
3974 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
3976 if ( !(iter->second->GetSpellProto()->AttributesEx4 & (1<<21)) // don't remove stances, shadowform, pally/hunter auras
3977 && !iter->second->IsPassive() // don't remove passive auras
3978 && (!(iter->second->GetSpellProto()->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY) || !(iter->second->GetSpellProto()->Attributes & SPELL_ATTR_UNK8)) // not unaffected by invulnerability auras or not having that unknown flag (that seemed the most probable)
3979 && (iter->second->IsPositive() ^ onleave)) // remove positive buffs on enter, negative buffs on leave
3980 RemoveAura(iter);
3981 else
3982 ++iter;
3986 void Unit::RemoveAllAurasOnDeath()
3988 // used just after dieing to remove all visible auras
3989 // and disable the mods for the passive ones
3990 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
3992 if (!iter->second->IsPassive() && !iter->second->IsDeathPersistent())
3993 RemoveAura(iter, AURA_REMOVE_BY_DEATH);
3994 else
3995 ++iter;
3999 void Unit::DelayAura(uint32 spellId, uint32 effindex, int32 delaytime)
4001 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
4002 if (iter != m_Auras.end())
4004 if (iter->second->GetAuraDuration() < delaytime)
4005 iter->second->SetAuraDuration(0);
4006 else
4007 iter->second->SetAuraDuration(iter->second->GetAuraDuration() - delaytime);
4008 iter->second->SendAuraUpdate(false);
4009 sLog.outDebug("Aura %u partially interrupted on unit %u, new duration: %u ms",iter->second->GetModifier()->m_auraname, GetGUIDLow(), iter->second->GetAuraDuration());
4013 void Unit::_RemoveAllAuraMods()
4015 for (AuraMap::const_iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
4017 (*i).second->ApplyModifier(false);
4021 void Unit::_ApplyAllAuraMods()
4023 for (AuraMap::const_iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
4025 (*i).second->ApplyModifier(true);
4029 Aura* Unit::GetAura(uint32 spellId, uint32 effindex)
4031 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
4032 if (iter != m_Auras.end())
4033 return iter->second;
4034 return NULL;
4037 Aura* Unit::GetAura(AuraType type, uint32 family, uint64 familyFlag, uint32 familyFlag2, uint64 casterGUID)
4039 AuraList const& auras = GetAurasByType(type);
4040 for(AuraList::const_iterator i = auras.begin();i != auras.end(); ++i)
4042 SpellEntry const *spell = (*i)->GetSpellProto();
4043 if (spell->SpellFamilyName == family && (spell->SpellFamilyFlags & familyFlag || spell->SpellFamilyFlags2 & familyFlag2))
4045 if (casterGUID && (*i)->GetCasterGUID()!=casterGUID)
4046 continue;
4047 return (*i);
4050 return NULL;
4053 bool Unit::HasAura(uint32 spellId) const
4055 for (int i = 0; i < 3 ; ++i)
4057 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, i));
4058 if (iter != m_Auras.end())
4059 return true;
4061 return false;
4064 void Unit::AddDynObject(DynamicObject* dynObj)
4066 m_dynObjGUIDs.push_back(dynObj->GetGUID());
4069 void Unit::RemoveDynObject(uint32 spellid)
4071 if(m_dynObjGUIDs.empty())
4072 return;
4073 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4075 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4076 if(!dynObj)
4078 i = m_dynObjGUIDs.erase(i);
4080 else if(spellid == 0 || dynObj->GetSpellId() == spellid)
4082 dynObj->Delete();
4083 i = m_dynObjGUIDs.erase(i);
4085 else
4086 ++i;
4090 void Unit::RemoveAllDynObjects()
4092 while(!m_dynObjGUIDs.empty())
4094 DynamicObject* dynObj = GetMap()->GetDynamicObject(*m_dynObjGUIDs.begin());
4095 if(dynObj)
4096 dynObj->Delete();
4097 m_dynObjGUIDs.erase(m_dynObjGUIDs.begin());
4101 DynamicObject * Unit::GetDynObject(uint32 spellId, uint32 effIndex)
4103 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4105 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4106 if(!dynObj)
4108 i = m_dynObjGUIDs.erase(i);
4109 continue;
4112 if (dynObj->GetSpellId() == spellId && dynObj->GetEffIndex() == effIndex)
4113 return dynObj;
4114 ++i;
4116 return NULL;
4119 DynamicObject * Unit::GetDynObject(uint32 spellId)
4121 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4123 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4124 if(!dynObj)
4126 i = m_dynObjGUIDs.erase(i);
4127 continue;
4130 if (dynObj->GetSpellId() == spellId)
4131 return dynObj;
4132 ++i;
4134 return NULL;
4137 GameObject* Unit::GetGameObject(uint32 spellId) const
4139 for (GameObjectList::const_iterator i = m_gameObj.begin(); i != m_gameObj.end(); ++i)
4140 if ((*i)->GetSpellId() == spellId)
4141 return *i;
4143 return NULL;
4146 void Unit::AddGameObject(GameObject* gameObj)
4148 assert(gameObj && gameObj->GetOwnerGUID()==0);
4149 m_gameObj.push_back(gameObj);
4150 gameObj->SetOwnerGUID(GetGUID());
4152 if ( GetTypeId()==TYPEID_PLAYER && gameObj->GetSpellId() )
4154 SpellEntry const* createBySpell = sSpellStore.LookupEntry(gameObj->GetSpellId());
4155 // Need disable spell use for owner
4156 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4157 // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
4158 ((Player*)this)->AddSpellAndCategoryCooldowns(createBySpell,0,NULL,true);
4162 void Unit::RemoveGameObject(GameObject* gameObj, bool del)
4164 assert(gameObj && gameObj->GetOwnerGUID()==GetGUID());
4166 gameObj->SetOwnerGUID(0);
4168 // GO created by some spell
4169 if (uint32 spellid = gameObj->GetSpellId())
4171 RemoveAurasDueToSpell(spellid);
4173 if (GetTypeId()==TYPEID_PLAYER)
4175 SpellEntry const* createBySpell = sSpellStore.LookupEntry(spellid );
4176 // Need activate spell use for owner
4177 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4178 // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
4179 ((Player*)this)->SendCooldownEvent(createBySpell);
4183 m_gameObj.remove(gameObj);
4185 if(del)
4187 gameObj->SetRespawnTime(0);
4188 gameObj->Delete();
4192 void Unit::RemoveGameObject(uint32 spellid, bool del)
4194 if(m_gameObj.empty())
4195 return;
4196 GameObjectList::iterator i, next;
4197 for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next)
4199 next = i;
4200 if(spellid == 0 || (*i)->GetSpellId() == spellid)
4202 (*i)->SetOwnerGUID(0);
4203 if(del)
4205 (*i)->SetRespawnTime(0);
4206 (*i)->Delete();
4209 next = m_gameObj.erase(i);
4211 else
4212 ++next;
4216 void Unit::RemoveAllGameObjects()
4218 // remove references to unit
4219 for(GameObjectList::iterator i = m_gameObj.begin(); i != m_gameObj.end();)
4221 (*i)->SetOwnerGUID(0);
4222 (*i)->SetRespawnTime(0);
4223 (*i)->Delete();
4224 i = m_gameObj.erase(i);
4228 void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage *log)
4230 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+4+1+4+4+1+1+4+4+1)); // we guess size
4231 data.append(log->target->GetPackGUID());
4232 data.append(log->attacker->GetPackGUID());
4233 data << uint32(log->SpellID);
4234 data << uint32(log->damage); // damage amount
4235 data << uint32(log->overkill); // overkill
4236 data << uint8 (log->schoolMask); // damage school
4237 data << uint32(log->absorb); // AbsorbedDamage
4238 data << uint32(log->resist); // resist
4239 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
4240 data << uint8 (log->unused); // unused
4241 data << uint32(log->blocked); // blocked
4242 data << uint32(log->HitInfo);
4243 data << uint8 (0); // flag to use extend data
4244 SendMessageToSet( &data, true );
4247 void Unit::SendSpellNonMeleeDamageLog(Unit *target, uint32 SpellID, uint32 Damage, SpellSchoolMask damageSchoolMask, uint32 AbsorbedDamage, uint32 Resist, bool PhysicalDamage, uint32 Blocked, bool CriticalHit)
4249 SpellNonMeleeDamage log(this, target, SpellID, damageSchoolMask);
4250 log.damage = Damage - AbsorbedDamage - Resist - Blocked;
4251 log.absorb = AbsorbedDamage;
4252 log.resist = Resist;
4253 log.physicalLog = PhysicalDamage;
4254 log.blocked = Blocked;
4255 log.HitInfo = SPELL_HIT_TYPE_UNK1 | SPELL_HIT_TYPE_UNK3 | SPELL_HIT_TYPE_UNK6;
4256 if(CriticalHit)
4257 log.HitInfo |= SPELL_HIT_TYPE_CRIT;
4258 SendSpellNonMeleeDamageLog(&log);
4261 void Unit::SendPeriodicAuraLog(SpellPeriodicAuraLogInfo *pInfo)
4263 Aura *aura = pInfo->aura;
4264 Modifier *mod = aura->GetModifier();
4266 WorldPacket data(SMSG_PERIODICAURALOG, 30);
4267 data.append(aura->GetTarget()->GetPackGUID());
4268 data.appendPackGUID(aura->GetCasterGUID());
4269 data << uint32(aura->GetId()); // spellId
4270 data << uint32(1); // count
4271 data << uint32(mod->m_auraname); // auraId
4272 switch(mod->m_auraname)
4274 case SPELL_AURA_PERIODIC_DAMAGE:
4275 case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
4276 data << uint32(pInfo->damage); // damage
4277 data << uint32(pInfo->overDamage); // overkill?
4278 data << uint32(GetSpellSchoolMask(aura->GetSpellProto()));
4279 data << uint32(pInfo->absorb); // absorb
4280 data << uint32(pInfo->resist); // resist
4281 data << uint8(0); // new 3.1.2
4282 break;
4283 case SPELL_AURA_PERIODIC_HEAL:
4284 case SPELL_AURA_OBS_MOD_HEALTH:
4285 data << uint32(pInfo->damage); // damage
4286 data << uint32(pInfo->overDamage); // overheal?
4287 data << uint8(0); // new 3.1.2
4288 break;
4289 case SPELL_AURA_OBS_MOD_MANA:
4290 case SPELL_AURA_PERIODIC_ENERGIZE:
4291 data << uint32(mod->m_miscvalue); // power type
4292 data << uint32(pInfo->damage); // damage
4293 break;
4294 case SPELL_AURA_PERIODIC_MANA_LEECH:
4295 data << uint32(mod->m_miscvalue); // power type
4296 data << uint32(pInfo->damage); // amount
4297 data << float(pInfo->multiplier); // gain multiplier
4298 break;
4299 default:
4300 sLog.outError("Unit::SendPeriodicAuraLog: unknown aura %u", uint32(mod->m_auraname));
4301 return;
4304 aura->GetTarget()->SendMessageToSet(&data, true);
4307 void Unit::ProcDamageAndSpell(Unit *pVictim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellEntry const *procSpell)
4309 // Not much to do if no flags are set.
4310 if (procAttacker)
4311 ProcDamageAndSpellFor(false,pVictim,procAttacker, procExtra,attType, procSpell, amount);
4312 // Now go on with a victim's events'n'auras
4313 // Not much to do if no flags are set or there is no victim
4314 if(pVictim && pVictim->isAlive() && procVictim)
4315 pVictim->ProcDamageAndSpellFor(true,this,procVictim, procExtra, attType, procSpell, amount);
4318 void Unit::SendSpellMiss(Unit *target, uint32 spellID, SpellMissInfo missInfo)
4320 WorldPacket data(SMSG_SPELLLOGMISS, (4+8+1+4+8+1));
4321 data << uint32(spellID);
4322 data << uint64(GetGUID());
4323 data << uint8(0); // can be 0 or 1
4324 data << uint32(1); // target count
4325 // for(i = 0; i < target count; ++i)
4326 data << uint64(target->GetGUID()); // target GUID
4327 data << uint8(missInfo);
4328 // end loop
4329 SendMessageToSet(&data, true);
4332 void Unit::SendAttackStateUpdate(CalcDamageInfo *damageInfo)
4334 sLog.outDebug("WORLD: Sending SMSG_ATTACKERSTATEUPDATE");
4336 uint32 count = 1;
4337 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, 16 + 45); // we guess size
4338 data << uint32(damageInfo->HitInfo);
4339 data.append(damageInfo->attacker->GetPackGUID());
4340 data.append(damageInfo->target->GetPackGUID());
4341 data << uint32(damageInfo->damage); // Full damage
4342 data << uint32(0); // overkill value
4343 data << uint8(count); // Sub damage count
4345 for(int i = 0; i < count; ++i)
4347 data << uint32(damageInfo->damageSchoolMask); // School of sub damage
4348 data << float(damageInfo->damage); // sub damage
4349 data << uint32(damageInfo->damage); // Sub Damage
4352 if(damageInfo->HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4354 for(int i = 0; i < count; ++i)
4355 data << uint32(damageInfo->absorb); // Absorb
4358 if(damageInfo->HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4360 for(int i = 0; i < count; ++i)
4361 data << uint32(damageInfo->resist); // Resist
4364 data << uint8(damageInfo->TargetState);
4365 data << uint32(0);
4366 data << uint32(0);
4368 if(damageInfo->HitInfo & HITINFO_BLOCK)
4369 data << uint32(damageInfo->blocked_amount);
4371 if(damageInfo->HitInfo & HITINFO_UNK3)
4372 data << uint32(0);
4374 if(damageInfo->HitInfo & HITINFO_UNK1)
4376 data << uint32(0);
4377 data << float(0);
4378 data << float(0);
4379 data << float(0);
4380 data << float(0);
4381 data << float(0);
4382 data << float(0);
4383 data << float(0);
4384 data << float(0);
4385 for(uint8 i = 0; i < 5; ++i)
4387 data << float(0);
4388 data << float(0);
4390 data << uint32(0);
4393 SendMessageToSet( &data, true );
4396 void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit *target, uint8 SwingType, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount)
4398 CalcDamageInfo dmgInfo;
4399 dmgInfo.HitInfo = HitInfo;
4400 dmgInfo.attacker = this;
4401 dmgInfo.target = target;
4402 dmgInfo.damage = Damage - AbsorbDamage - Resist - BlockedAmount;
4403 dmgInfo.damageSchoolMask = damageSchoolMask;
4404 dmgInfo.absorb = AbsorbDamage;
4405 dmgInfo.resist = Resist;
4406 dmgInfo.TargetState = TargetState;
4407 dmgInfo.blocked_amount = BlockedAmount;
4408 SendAttackStateUpdate(&dmgInfo);
4411 bool Unit::HandleHasteAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
4413 SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto();
4415 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4416 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4418 uint32 triggered_spell_id = 0;
4419 Unit* target = pVictim;
4420 int32 basepoints0 = 0;
4422 switch(hasteSpell->SpellFamilyName)
4424 case SPELLFAMILY_ROGUE:
4426 switch(hasteSpell->Id)
4428 // Blade Flurry
4429 case 13877:
4430 case 33735:
4432 target = SelectNearbyTarget();
4433 if(!target)
4434 return false;
4435 basepoints0 = damage;
4436 triggered_spell_id = 22482;
4437 break;
4440 break;
4444 // processed charge only counting case
4445 if(!triggered_spell_id)
4446 return true;
4448 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
4450 if(!triggerEntry)
4452 sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",hasteSpell->Id,triggered_spell_id);
4453 return false;
4456 // default case
4457 if(!target || target!=this && !target->isAlive())
4458 return false;
4460 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
4461 return false;
4463 if(basepoints0)
4464 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
4465 else
4466 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
4468 if( cooldown && GetTypeId()==TYPEID_PLAYER )
4469 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
4471 return true;
4474 bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
4476 SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
4477 uint32 effIndex = triggeredByAura->GetEffIndex();
4478 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
4480 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4481 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4483 uint32 triggered_spell_id = 0;
4484 Unit* target = pVictim;
4485 int32 basepoints0 = 0;
4487 switch(dummySpell->SpellFamilyName)
4489 case SPELLFAMILY_GENERIC:
4491 switch (dummySpell->Id)
4493 // Eye for an Eye
4494 case 9799:
4495 case 25988:
4497 // return damage % to attacker but < 50% own total health
4498 basepoints0 = triggerAmount*int32(damage)/100;
4499 if(basepoints0 > GetMaxHealth()/2)
4500 basepoints0 = GetMaxHealth()/2;
4502 triggered_spell_id = 25997;
4503 break;
4505 // Sweeping Strikes
4506 case 12328:
4507 case 18765:
4508 case 35429:
4510 // prevent chain of triggered spell from same triggered spell
4511 if(procSpell && procSpell->Id==26654)
4512 return false;
4514 target = SelectNearbyTarget();
4515 if(!target)
4516 return false;
4518 triggered_spell_id = 26654;
4519 break;
4521 // Unstable Power
4522 case 24658:
4524 if (!procSpell || procSpell->Id == 24659)
4525 return false;
4526 // Need remove one 24659 aura
4527 RemoveSingleSpellAurasFromStack(24659);
4528 return true;
4530 // Restless Strength
4531 case 24661:
4533 // Need remove one 24662 aura
4534 RemoveSingleSpellAurasFromStack(24662);
4535 return true;
4537 // Adaptive Warding (Frostfire Regalia set)
4538 case 28764:
4540 if(!procSpell)
4541 return false;
4543 // find Mage Armor
4544 bool found = false;
4545 AuraList const& mRegenInterupt = GetAurasByType(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT);
4546 for(AuraList::const_iterator iter = mRegenInterupt.begin(); iter != mRegenInterupt.end(); ++iter)
4548 if(SpellEntry const* iterSpellProto = (*iter)->GetSpellProto())
4550 if(iterSpellProto->SpellFamilyName==SPELLFAMILY_MAGE && (iterSpellProto->SpellFamilyFlags & 0x10000000))
4552 found=true;
4553 break;
4557 if(!found)
4558 return false;
4560 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4562 case SPELL_SCHOOL_NORMAL:
4563 case SPELL_SCHOOL_HOLY:
4564 return false; // ignored
4565 case SPELL_SCHOOL_FIRE: triggered_spell_id = 28765; break;
4566 case SPELL_SCHOOL_NATURE: triggered_spell_id = 28768; break;
4567 case SPELL_SCHOOL_FROST: triggered_spell_id = 28766; break;
4568 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 28769; break;
4569 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 28770; break;
4570 default:
4571 return false;
4574 target = this;
4575 break;
4577 // Obsidian Armor (Justice Bearer`s Pauldrons shoulder)
4578 case 27539:
4580 if(!procSpell)
4581 return false;
4583 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4585 case SPELL_SCHOOL_NORMAL:
4586 return false; // ignore
4587 case SPELL_SCHOOL_HOLY: triggered_spell_id = 27536; break;
4588 case SPELL_SCHOOL_FIRE: triggered_spell_id = 27533; break;
4589 case SPELL_SCHOOL_NATURE: triggered_spell_id = 27538; break;
4590 case SPELL_SCHOOL_FROST: triggered_spell_id = 27534; break;
4591 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 27535; break;
4592 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 27540; break;
4593 default:
4594 return false;
4597 target = this;
4598 break;
4600 // Mana Leech (Passive) (Priest Pet Aura)
4601 case 28305:
4603 // Cast on owner
4604 target = GetOwner();
4605 if(!target)
4606 return false;
4608 triggered_spell_id = 34650;
4609 break;
4611 // Mark of Malice
4612 case 33493:
4614 // Cast finish spell at last charge
4615 if (triggeredByAura->GetAuraCharges() > 1)
4616 return false;
4618 target = this;
4619 triggered_spell_id = 33494;
4620 break;
4622 // Twisted Reflection (boss spell)
4623 case 21063:
4624 triggered_spell_id = 21064;
4625 break;
4626 // Vampiric Aura (boss spell)
4627 case 38196:
4629 basepoints0 = 3 * damage; // 300%
4630 if (basepoints0 < 0)
4631 return false;
4633 triggered_spell_id = 31285;
4634 target = this;
4635 break;
4637 // Aura of Madness (Darkmoon Card: Madness trinket)
4638 //=====================================================
4639 // 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior)
4640 // 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid)
4641 // 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid)
4642 // 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4643 // 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes)
4644 // 41005 Manic: +35 haste (spell, melee and ranged) (All classes)
4645 // 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter)
4646 // 41011 Martyr Complex: +35 stamina (All classes)
4647 // 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4648 // 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4649 case 39446:
4651 if(GetTypeId() != TYPEID_PLAYER)
4652 return false;
4654 // Select class defined buff
4655 switch (getClass())
4657 case CLASS_PALADIN: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4658 case CLASS_DRUID: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4660 uint32 RandomSpell[]={39511,40997,40998,40999,41002,41005,41009,41011,41409};
4661 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4662 break;
4664 case CLASS_ROGUE: // 39511,40997,40998,41002,41005,41011
4665 case CLASS_WARRIOR: // 39511,40997,40998,41002,41005,41011
4667 uint32 RandomSpell[]={39511,40997,40998,41002,41005,41011};
4668 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4669 break;
4671 case CLASS_PRIEST: // 40999,41002,41005,41009,41011,41406,41409
4672 case CLASS_SHAMAN: // 40999,41002,41005,41009,41011,41406,41409
4673 case CLASS_MAGE: // 40999,41002,41005,41009,41011,41406,41409
4674 case CLASS_WARLOCK: // 40999,41002,41005,41009,41011,41406,41409
4676 uint32 RandomSpell[]={40999,41002,41005,41009,41011,41406,41409};
4677 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4678 break;
4680 case CLASS_HUNTER: // 40997,40999,41002,41005,41009,41011,41406,41409
4682 uint32 RandomSpell[]={40997,40999,41002,41005,41009,41011,41406,41409};
4683 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4684 break;
4686 default:
4687 return false;
4690 target = this;
4691 if (roll_chance_i(10))
4692 ((Player*)this)->Say("This is Madness!", LANG_UNIVERSAL);
4693 break;
4696 // TODO: need find item for aura and triggered spells
4697 // Sunwell Exalted Caster Neck (??? neck)
4698 // cast ??? Light's Wrath if Exalted by Aldor
4699 // cast ??? Arcane Bolt if Exalted by Scryers*/
4700 case 46569:
4701 return false; // disable for while
4704 if(GetTypeId() != TYPEID_PLAYER)
4705 return false;
4707 // Get Aldor reputation rank
4708 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4710 target = this;
4711 triggered_spell_id = ???
4712 break;
4714 // Get Scryers reputation rank
4715 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4717 triggered_spell_id = ???
4718 break;
4720 return false;
4722 // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck)
4723 // cast 45479 Light's Wrath if Exalted by Aldor
4724 // cast 45429 Arcane Bolt if Exalted by Scryers
4725 case 45481:
4727 if(GetTypeId() != TYPEID_PLAYER)
4728 return false;
4730 // Get Aldor reputation rank
4731 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4733 target = this;
4734 triggered_spell_id = 45479;
4735 break;
4737 // Get Scryers reputation rank
4738 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4740 triggered_spell_id = 45429;
4741 break;
4743 return false;
4745 // Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck)
4746 // cast 45480 Light's Strength if Exalted by Aldor
4747 // cast 45428 Arcane Strike if Exalted by Scryers
4748 case 45482:
4750 if(GetTypeId() != TYPEID_PLAYER)
4751 return false;
4753 // Get Aldor reputation rank
4754 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4756 target = this;
4757 triggered_spell_id = 45480;
4758 break;
4760 // Get Scryers reputation rank
4761 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4763 triggered_spell_id = 45428;
4764 break;
4766 return false;
4768 // Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck)
4769 // cast 45431 Arcane Insight if Exalted by Aldor
4770 // cast 45432 Light's Ward if Exalted by Scryers
4771 case 45483:
4773 if(GetTypeId() != TYPEID_PLAYER)
4774 return false;
4776 // Get Aldor reputation rank
4777 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4779 target = this;
4780 triggered_spell_id = 45432;
4781 break;
4783 // Get Scryers reputation rank
4784 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4786 target = this;
4787 triggered_spell_id = 45431;
4788 break;
4790 return false;
4792 // Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck)
4793 // cast 45478 Light's Salvation if Exalted by Aldor
4794 // cast 45430 Arcane Surge if Exalted by Scryers
4795 case 45484:
4797 if(GetTypeId() != TYPEID_PLAYER)
4798 return false;
4800 // Get Aldor reputation rank
4801 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4803 target = this;
4804 triggered_spell_id = 45478;
4805 break;
4807 // Get Scryers reputation rank
4808 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4810 triggered_spell_id = 45430;
4811 break;
4813 return false;
4815 // Living Seed
4816 case 48504:
4818 triggered_spell_id = 48503;
4819 basepoints0 = triggerAmount;
4820 target = this;
4821 break;
4823 // Vampiric Touch (generic, used by some boss)
4824 case 52723:
4825 case 60501:
4827 triggered_spell_id = 52724;
4828 basepoints0 = damage / 2;
4829 target = this;
4830 break;
4832 // Divine purpose
4833 case 31871:
4834 case 31872:
4836 // Roll chane
4837 if (!roll_chance_i(triggerAmount))
4838 return false;
4840 // Remove any stun effect on target
4841 AuraMap& Auras = pVictim->GetAuras();
4842 for(AuraMap::const_iterator iter = Auras.begin(); iter != Auras.end();)
4844 SpellEntry const *spell = iter->second->GetSpellProto();
4845 if( spell->Mechanic == MECHANIC_STUN ||
4846 spell->EffectMechanic[iter->second->GetEffIndex()] == MECHANIC_STUN)
4848 pVictim->RemoveAurasDueToSpell(spell->Id);
4849 iter = Auras.begin();
4851 else
4852 ++iter;
4854 return true;
4857 break;
4859 case SPELLFAMILY_MAGE:
4861 // Magic Absorption
4862 if (dummySpell->SpellIconID == 459) // only this spell have SpellIconID == 459 and dummy aura
4864 if (getPowerType() != POWER_MANA)
4865 return false;
4867 // mana reward
4868 basepoints0 = (triggerAmount * GetMaxPower(POWER_MANA) / 100);
4869 target = this;
4870 triggered_spell_id = 29442;
4871 break;
4873 // Master of Elements
4874 if (dummySpell->SpellIconID == 1920)
4876 if(!procSpell)
4877 return false;
4879 // mana cost save
4880 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
4881 basepoints0 = cost * triggerAmount/100;
4882 if( basepoints0 <=0 )
4883 return false;
4885 target = this;
4886 triggered_spell_id = 29077;
4887 break;
4890 //Arcane Potency
4891 if (dummySpell->SpellIconID == 2120)
4893 if(!procSpell)
4894 return false;
4896 target = this;
4897 switch (dummySpell->Id)
4899 case 31571: triggered_spell_id = 57529; break;
4900 case 31572: triggered_spell_id = 57531; break;
4901 default:
4902 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u",dummySpell->Id);
4903 return false;
4905 break;
4908 // Hot Streak
4909 if (dummySpell->SpellIconID == 2999)
4911 if (effIndex!=0)
4912 return true;
4913 Aura *counter = GetAura(triggeredByAura->GetId(), 1);
4914 if (!counter)
4915 return true;
4917 // Count spell criticals in a row in second aura
4918 Modifier *mod = counter->GetModifier();
4919 if (procEx & PROC_EX_CRITICAL_HIT)
4921 mod->m_amount *=2;
4922 if (mod->m_amount < 100) // not enough
4923 return true;
4924 // Crititcal counted -> roll chance
4925 if (roll_chance_i(triggerAmount))
4926 CastSpell(this, 48108, true, castItem, triggeredByAura);
4928 mod->m_amount = 25;
4929 return true;
4931 // Burnout
4932 if (dummySpell->SpellIconID == 2998)
4934 if(!procSpell)
4935 return false;
4937 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
4938 basepoints0 = cost * triggerAmount/100;
4939 if( basepoints0 <=0 )
4940 return false;
4941 triggered_spell_id = 44450;
4942 target = this;
4943 break;
4945 // Incanter's Regalia set (add trigger chance to Mana Shield)
4946 if (dummySpell->SpellFamilyFlags & 0x0000000000008000LL)
4948 if(GetTypeId() != TYPEID_PLAYER)
4949 return false;
4951 target = this;
4952 triggered_spell_id = 37436;
4953 break;
4955 switch(dummySpell->Id)
4957 // Ignite
4958 case 11119:
4959 case 11120:
4960 case 12846:
4961 case 12847:
4962 case 12848:
4964 switch (dummySpell->Id)
4966 case 11119: basepoints0 = int32(0.04f*damage); break;
4967 case 11120: basepoints0 = int32(0.08f*damage); break;
4968 case 12846: basepoints0 = int32(0.12f*damage); break;
4969 case 12847: basepoints0 = int32(0.16f*damage); break;
4970 case 12848: basepoints0 = int32(0.20f*damage); break;
4971 default:
4972 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (IG)",dummySpell->Id);
4973 return false;
4976 triggered_spell_id = 12654;
4977 break;
4979 // Combustion
4980 case 11129:
4982 //last charge and crit
4983 if (triggeredByAura->GetAuraCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT) )
4985 RemoveAurasDueToSpell(28682); //-> remove Combustion auras
4986 return true; // charge counting (will removed)
4989 CastSpell(this, 28682, true, castItem, triggeredByAura);
4990 return (procEx & PROC_EX_CRITICAL_HIT);// charge update only at crit hits, no hidden cooldowns
4993 break;
4995 case SPELLFAMILY_WARRIOR:
4997 // Retaliation
4998 if(dummySpell->SpellFamilyFlags==0x0000000800000000LL)
5000 // check attack comes not from behind
5001 if (!HasInArc(M_PI, pVictim))
5002 return false;
5004 triggered_spell_id = 22858;
5005 break;
5007 // Second Wind
5008 if (dummySpell->SpellIconID == 1697)
5010 // only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example)
5011 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
5012 return false;
5013 // Need stun or root mechanic
5014 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_STUN))))
5015 return false;
5017 switch (dummySpell->Id)
5019 case 29838: triggered_spell_id=29842; break;
5020 case 29834: triggered_spell_id=29841; break;
5021 case 42770: triggered_spell_id=42771; break;
5022 default:
5023 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)",dummySpell->Id);
5024 return false;
5027 target = this;
5028 break;
5030 // Damage Shield
5031 if (dummySpell->SpellIconID == 3214)
5033 triggered_spell_id = 59653;
5034 basepoints0 = GetShieldBlockValue() * triggerAmount / 100;
5035 break;
5037 break;
5039 case SPELLFAMILY_WARLOCK:
5041 // Seed of Corruption
5042 if (dummySpell->SpellFamilyFlags & 0x0000001000000000LL)
5044 Modifier* mod = triggeredByAura->GetModifier();
5045 // if damage is more than need or target die from damage deal finish spell
5046 if( mod->m_amount <= damage || GetHealth() <= damage )
5048 // remember guid before aura delete
5049 uint64 casterGuid = triggeredByAura->GetCasterGUID();
5051 // Remove aura (before cast for prevent infinite loop handlers)
5052 RemoveAurasDueToSpell(triggeredByAura->GetId());
5054 // Cast finish spell (triggeredByAura already not exist!)
5055 CastSpell(this, 27285, true, castItem, NULL, casterGuid);
5056 return true; // no hidden cooldown
5059 // Damage counting
5060 mod->m_amount-=damage;
5061 return true;
5063 // Seed of Corruption (Mobs cast) - no die req
5064 if (dummySpell->SpellFamilyFlags == 0x00LL && dummySpell->SpellIconID == 1932)
5066 Modifier* mod = triggeredByAura->GetModifier();
5067 // if damage is more than need deal finish spell
5068 if( mod->m_amount <= damage )
5070 // remember guid before aura delete
5071 uint64 casterGuid = triggeredByAura->GetCasterGUID();
5073 // Remove aura (before cast for prevent infinite loop handlers)
5074 RemoveAurasDueToSpell(triggeredByAura->GetId());
5076 // Cast finish spell (triggeredByAura already not exist!)
5077 CastSpell(this, 32865, true, castItem, NULL, casterGuid);
5078 return true; // no hidden cooldown
5080 // Damage counting
5081 mod->m_amount-=damage;
5082 return true;
5084 // Fel Synergy
5085 if (dummySpell->SpellIconID == 3222)
5087 target = GetPet();
5088 if (!target)
5089 return false;
5090 triggered_spell_id = 54181;
5091 basepoints0 = damage * triggerAmount / 100;
5092 break;
5094 switch(dummySpell->Id)
5096 // Nightfall
5097 case 18094:
5098 case 18095:
5100 target = this;
5101 triggered_spell_id = 17941;
5102 break;
5104 //Soul Leech
5105 case 30293:
5106 case 30295:
5107 case 30296:
5109 // health
5110 basepoints0 = int32(damage*triggerAmount/100);
5111 target = this;
5112 triggered_spell_id = 30294;
5113 break;
5115 // Shadowflame (Voidheart Raiment set bonus)
5116 case 37377:
5118 triggered_spell_id = 37379;
5119 break;
5121 // Pet Healing (Corruptor Raiment or Rift Stalker Armor)
5122 case 37381:
5124 target = GetPet();
5125 if(!target)
5126 return false;
5128 // heal amount
5129 basepoints0 = damage * triggerAmount/100;
5130 triggered_spell_id = 37382;
5131 break;
5133 // Shadowflame Hellfire (Voidheart Raiment set bonus)
5134 case 39437:
5136 triggered_spell_id = 37378;
5137 break;
5140 break;
5142 case SPELLFAMILY_PRIEST:
5144 // Vampiric Touch
5145 if( dummySpell->SpellFamilyFlags & 0x0000040000000000LL )
5147 if(!pVictim || !pVictim->isAlive())
5148 return false;
5150 // pVictim is caster of aura
5151 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5152 return false;
5154 // Energize 0.25% of max. mana
5155 pVictim->CastSpell(pVictim,57669,true,castItem,triggeredByAura);
5156 return true; // no hidden cooldown
5158 // Divine Aegis
5159 if (dummySpell->SpellIconID == 2820)
5161 basepoints0 = damage * triggerAmount/100;
5162 triggered_spell_id = 47753;
5163 break;
5165 switch(dummySpell->Id)
5167 // Vampiric Embrace
5168 case 15286:
5170 if(!pVictim || !pVictim->isAlive())
5171 return false;
5173 // pVictim is caster of aura
5174 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5175 return false;
5177 // heal amount
5178 int32 team = triggerAmount*damage/500;
5179 int32 self = triggerAmount*damage/100 - team;
5180 pVictim->CastCustomSpell(pVictim,15290,&team,&self,NULL,true,castItem,triggeredByAura);
5181 return true; // no hidden cooldown
5183 // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen)
5184 case 40438:
5186 // Shadow Word: Pain
5187 if( procSpell->SpellFamilyFlags & 0x0000000000008000LL )
5188 triggered_spell_id = 40441;
5189 // Renew
5190 else if( procSpell->SpellFamilyFlags & 0x0000000000000010LL )
5191 triggered_spell_id = 40440;
5192 else
5193 return false;
5195 target = this;
5196 break;
5198 // Oracle Healing Bonus ("Garments of the Oracle" set)
5199 case 26169:
5201 // heal amount
5202 basepoints0 = int32(damage * 10/100);
5203 target = this;
5204 triggered_spell_id = 26170;
5205 break;
5207 // Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set
5208 case 39372:
5210 if(!procSpell || (GetSpellSchoolMask(procSpell) & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW))==0 )
5211 return false;
5213 // heal amount
5214 basepoints0 = damage * triggerAmount/100;
5215 target = this;
5216 triggered_spell_id = 39373;
5217 break;
5219 // Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus)
5220 case 28809:
5222 triggered_spell_id = 28810;
5223 break;
5225 // Glyph of Dispel Magic
5226 case 55677:
5228 if(!target->IsFriendlyTo(this))
5229 return false;
5231 basepoints0 = int32(target->GetMaxHealth() * triggerAmount / 100);
5232 triggered_spell_id = 56131;
5233 break;
5236 break;
5238 case SPELLFAMILY_DRUID:
5240 switch(dummySpell->Id)
5242 // Healing Touch (Dreamwalker Raiment set)
5243 case 28719:
5245 // mana back
5246 basepoints0 = int32(procSpell->manaCost * 30 / 100);
5247 target = this;
5248 triggered_spell_id = 28742;
5249 break;
5251 // Healing Touch Refund (Idol of Longevity trinket)
5252 case 28847:
5254 target = this;
5255 triggered_spell_id = 28848;
5256 break;
5258 // Mana Restore (Malorne Raiment set / Malorne Regalia set)
5259 case 37288:
5260 case 37295:
5262 target = this;
5263 triggered_spell_id = 37238;
5264 break;
5266 // Druid Tier 6 Trinket
5267 case 40442:
5269 float chance;
5271 // Starfire
5272 if( procSpell->SpellFamilyFlags & 0x0000000000000004LL )
5274 triggered_spell_id = 40445;
5275 chance = 25.0f;
5277 // Rejuvenation
5278 else if( procSpell->SpellFamilyFlags & 0x0000000000000010LL )
5280 triggered_spell_id = 40446;
5281 chance = 25.0f;
5283 // Mangle (cat/bear)
5284 else if( procSpell->SpellFamilyFlags & 0x0000044000000000LL )
5286 triggered_spell_id = 40452;
5287 chance = 40.0f;
5289 else
5290 return false;
5292 if (!roll_chance_f(chance))
5293 return false;
5295 target = this;
5296 break;
5298 // Maim Interrupt
5299 case 44835:
5301 // Deadly Interrupt Effect
5302 triggered_spell_id = 32747;
5303 break;
5306 // Eclipse
5307 if (dummySpell->SpellIconID == 2856)
5309 if (!procSpell)
5310 return false;
5311 // Only 0 aura can proc
5312 if (effIndex!=0)
5313 return true;
5314 // Wrath crit
5315 if (procSpell->SpellFamilyFlags & 0x0000000000000001LL)
5317 if (!roll_chance_i(60))
5318 return false;
5319 triggered_spell_id = 48518;
5320 target = this;
5321 break;
5323 // Starfire crit
5324 if (procSpell->SpellFamilyFlags & 0x0000000000000004LL)
5326 triggered_spell_id = 48517;
5327 target = this;
5328 break;
5330 return false;
5332 // Living Seed
5333 else if (dummySpell->SpellIconID == 2860)
5335 triggered_spell_id = 48504;
5336 basepoints0 = triggerAmount * damage / 100;
5337 break;
5339 break;
5341 case SPELLFAMILY_ROGUE:
5343 switch(dummySpell->Id)
5345 // Deadly Throw Interrupt
5346 case 32748:
5348 // Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw
5349 if(this == pVictim)
5350 return false;
5352 triggered_spell_id = 32747;
5353 break;
5356 // Cut to the Chase
5357 if( dummySpell->SpellIconID == 2909 )
5359 // "refresh your Slice and Dice duration to its 5 combo point maximum"
5360 // lookup Slice and Dice
5361 AuraList const& sd = GetAurasByType(SPELL_AURA_MOD_HASTE);
5362 for(AuraList::const_iterator itr = sd.begin(); itr != sd.end(); ++itr)
5364 SpellEntry const *spellProto = (*itr)->GetSpellProto();
5365 if( spellProto->SpellFamilyName == SPELLFAMILY_ROGUE &&
5366 spellProto->SpellFamilyFlags & 0x0000000000040000LL)
5368 (*itr)->SetAuraMaxDuration(GetSpellMaxDuration(spellProto));
5369 (*itr)->RefreshAura();
5370 return true;
5373 return false;
5375 // Deadly Brew
5376 if( dummySpell->SpellIconID == 2963 )
5378 triggered_spell_id = 25809;
5379 break;
5381 // Quick Recovery
5382 if( dummySpell->SpellIconID == 2116 )
5384 if(!procSpell)
5385 return false;
5387 // energy cost save
5388 basepoints0 = procSpell->manaCost * triggerAmount/100;
5389 if(basepoints0 <= 0)
5390 return false;
5392 target = this;
5393 triggered_spell_id = 31663;
5394 break;
5396 break;
5398 case SPELLFAMILY_HUNTER:
5400 // Aspect of the Viper
5401 if ( dummySpell->SpellFamilyFlags & 0x4000000000000LL )
5403 uint32 maxmana = GetMaxPower(POWER_MANA);
5404 basepoints0 = maxmana* GetAttackTime(RANGED_ATTACK)/1000.0f/100.0f;
5406 target = this;
5407 triggered_spell_id = 34075;
5408 break;
5410 // Thrill of the Hunt
5411 if ( dummySpell->SpellIconID == 2236 )
5413 if(!procSpell)
5414 return false;
5416 // mana cost save
5417 int32 mana = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
5418 basepoints0 = mana * 40/100;
5419 if(basepoints0 <= 0)
5420 return false;
5422 target = this;
5423 triggered_spell_id = 34720;
5424 break;
5426 // Hunting Party
5427 if ( dummySpell->SpellIconID == 3406 )
5429 triggered_spell_id = 57669;
5430 target = this;
5431 break;
5433 // Lock and Load
5434 if ( dummySpell->SpellIconID == 3579 )
5436 // Proc only from periodic (from trap activation proc another aura of this spell)
5437 if (!(procFlag & PROC_FLAG_ON_DO_PERIODIC) || !roll_chance_i(triggerAmount))
5438 return false;
5439 triggered_spell_id = 56453;
5440 target = this;
5441 break;
5443 // Rapid Recuperation
5444 if ( dummySpell->SpellIconID == 3560 )
5446 // This effect only from Rapid Killing (mana regen)
5447 if (!(procSpell->SpellFamilyFlags & 0x0100000000000000LL))
5448 return false;
5449 triggered_spell_id = 56654;
5450 target = this;
5451 break;
5453 break;
5455 case SPELLFAMILY_PALADIN:
5457 // Seal of Righteousness - melee proc dummy (addition ${$MWS*(0.022*$AP+0.044*$SPH)} damage)
5458 if (dummySpell->SpellFamilyFlags&0x000000008000000LL && effIndex==0)
5460 triggered_spell_id = 25742;
5461 float ap = GetTotalAttackPowerValue(BASE_ATTACK);
5462 int32 holy = SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
5463 SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, pVictim);
5464 basepoints0 = GetAttackTime(BASE_ATTACK) * int32(ap*0.022f + 0.044f * holy) / 1000;
5465 break;
5467 // Sacred Shield
5468 if (dummySpell->SpellFamilyFlags&0x0008000000000000LL)
5470 triggered_spell_id = 58597;
5471 target = this;
5472 break;
5474 // Righteous Vengeance
5475 if (dummySpell->SpellIconID == 3025)
5477 // 4 damage tick
5478 basepoints0 = triggerAmount*damage/400;
5479 triggered_spell_id = 61840;
5480 break;
5482 // Sheath of Light
5483 if (dummySpell->SpellIconID == 3030)
5485 // 4 healing tick
5486 basepoints0 = triggerAmount*damage/400;
5487 triggered_spell_id = 54203;
5488 break;
5490 switch(dummySpell->Id)
5492 // Judgement of Light
5493 case 20185:
5495 // Get judgement caster
5496 Unit *caster = triggeredByAura->GetCaster();
5497 if (!caster)
5498 return false;
5499 float ap = caster->GetTotalAttackPowerValue(BASE_ATTACK);
5500 int32 holy = caster->SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
5501 caster->SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, this);
5502 basepoints0 = int32(ap*0.10f + 0.10f*holy);
5503 pVictim->CastCustomSpell(pVictim, 20267, &basepoints0, 0, 0, true, 0, triggeredByAura);
5504 return true;
5506 // Judgement of Wisdom
5507 case 20186:
5509 if (pVictim->getPowerType() == POWER_MANA)
5510 pVictim->CastSpell(pVictim, 20268, true, 0, triggeredByAura);
5511 return true;
5513 // Holy Power (Redemption Armor set)
5514 case 28789:
5516 if(!pVictim)
5517 return false;
5519 // Set class defined buff
5520 switch (pVictim->getClass())
5522 case CLASS_PALADIN:
5523 case CLASS_PRIEST:
5524 case CLASS_SHAMAN:
5525 case CLASS_DRUID:
5526 triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5527 break;
5528 case CLASS_MAGE:
5529 case CLASS_WARLOCK:
5530 triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5531 break;
5532 case CLASS_HUNTER:
5533 case CLASS_ROGUE:
5534 triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d.
5535 break;
5536 case CLASS_WARRIOR:
5537 triggered_spell_id = 28790; // Increases the friendly target's armor
5538 break;
5539 default:
5540 return false;
5542 break;
5544 // Seal of Vengeance (damage calc on apply aura)
5545 case 31801:
5547 if(effIndex != 0) // effect 1,2 used by seal unleashing code
5548 return false;
5550 triggered_spell_id = 31803;
5551 break;
5553 // Spiritual Attunement
5554 case 31785:
5555 case 33776:
5557 // if healed by another unit (pVictim)
5558 if(this == pVictim)
5559 return false;
5561 // heal amount
5562 basepoints0 = triggerAmount*damage/100;
5563 target = this;
5564 triggered_spell_id = 31786;
5565 break;
5567 // Seal of Blood do damage trigger
5568 case 31892:
5570 if (effIndex == 0) // 0 effect - is proc on enemy
5571 triggered_spell_id = 31893;
5572 else if (effIndex == 1) // 1 effect - is proc on self
5574 // add spell damage from prev effect (27%)
5575 damage += CalculateDamage(BASE_ATTACK, false) * 27 / 100;
5576 basepoints0 = triggerAmount * damage / 100;
5577 target = this;
5578 triggered_spell_id = 32221;
5580 else
5581 return true;
5582 break;
5584 // Seal of the Martyr do damage trigger
5585 case 53720:
5587 if (effIndex == 0) // 0 effect - is proc on enemy
5588 triggered_spell_id = 53719;
5589 else if (effIndex == 1) // 1 effect - is proc on self
5591 // add spell damage from prev effect (27%)
5592 damage += CalculateDamage(BASE_ATTACK, false) * 27 / 100;
5593 basepoints0 = triggerAmount * damage / 100;
5594 target = this;
5595 triggered_spell_id = 53718;
5597 else
5598 return true;
5599 break;
5601 // Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal)
5602 case 40470:
5604 if( !procSpell )
5605 return false;
5607 float chance;
5609 // Flash of light/Holy light
5610 if( procSpell->SpellFamilyFlags & 0x00000000C0000000LL)
5612 triggered_spell_id = 40471;
5613 chance = 15.0f;
5615 // Judgement
5616 else if( procSpell->SpellFamilyFlags & 0x0000000000800000LL )
5618 triggered_spell_id = 40472;
5619 chance = 50.0f;
5621 else
5622 return false;
5624 if (!roll_chance_f(chance))
5625 return false;
5627 break;
5629 // Glyph of Divinity
5630 case 54939:
5632 // Lookup base amount mana restore
5633 for (int i=0; i<3;++i)
5634 if (procSpell->Effect[i] == SPELL_EFFECT_ENERGIZE)
5636 int32 mana = procSpell->EffectBasePoints[i];
5637 CastCustomSpell(this, 54986, 0, &mana, 0, true, castItem, triggeredByAura);
5638 break;
5640 return true;
5642 // Glyph of Flash of Light
5643 case 54936:
5645 triggered_spell_id = 54957;
5646 basepoints0 = triggerAmount*damage/100;
5647 break;
5649 // Glyph of Holy Light
5650 case 54937:
5652 triggered_spell_id = 54968;
5653 basepoints0 = triggerAmount*damage/100;
5654 break;
5657 break;
5659 case SPELLFAMILY_SHAMAN:
5661 switch(dummySpell->Id)
5663 // Totemic Power (The Earthshatterer set)
5664 case 28823:
5666 if( !pVictim )
5667 return false;
5669 // Set class defined buff
5670 switch (pVictim->getClass())
5672 case CLASS_PALADIN:
5673 case CLASS_PRIEST:
5674 case CLASS_SHAMAN:
5675 case CLASS_DRUID:
5676 triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5677 break;
5678 case CLASS_MAGE:
5679 case CLASS_WARLOCK:
5680 triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5681 break;
5682 case CLASS_HUNTER:
5683 case CLASS_ROGUE:
5684 triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d.
5685 break;
5686 case CLASS_WARRIOR:
5687 triggered_spell_id = 28827; // Increases the friendly target's armor
5688 break;
5689 default:
5690 return false;
5692 break;
5694 // Lesser Healing Wave (Totem of Flowing Water Relic)
5695 case 28849:
5697 target = this;
5698 triggered_spell_id = 28850;
5699 break;
5701 // Windfury Weapon (Passive) 1-5 Ranks
5702 case 33757:
5704 if(GetTypeId()!=TYPEID_PLAYER)
5705 return false;
5707 if(!castItem || !castItem->IsEquipped())
5708 return false;
5710 // custom cooldown processing case
5711 if( cooldown && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
5712 return false;
5714 // Now amount of extra power stored in 1 effect of Enchant spell
5715 // Get it by item enchant id
5716 uint32 spellId;
5717 switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)))
5719 case 283: spellId = 8232; break; // 1 Rank
5720 case 284: spellId = 8235; break; // 2 Rank
5721 case 525: spellId = 10486; break; // 3 Rank
5722 case 1669:spellId = 16362; break; // 4 Rank
5723 case 2636:spellId = 25505; break; // 5 Rank
5724 case 3785:spellId = 58801; break; // 6 Rank
5725 case 3786:spellId = 58803; break; // 7 Rank
5726 case 3787:spellId = 58804; break; // 8 Rank
5727 default:
5729 sLog.outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)",
5730 castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)),dummySpell->Id);
5731 return false;
5735 SpellEntry const* windfurySpellEntry = sSpellStore.LookupEntry(spellId);
5736 if(!windfurySpellEntry)
5738 sLog.outError("Unit::HandleDummyAuraProc: non existed spell id: %u (Windfury)",spellId);
5739 return false;
5742 int32 extra_attack_power = CalculateSpellDamage(windfurySpellEntry, 1, windfurySpellEntry->EffectBasePoints[1], pVictim);
5744 // Off-Hand case
5745 if ( castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
5747 // Value gained from additional AP
5748 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(OFF_ATTACK)/1000/2);
5749 triggered_spell_id = 33750;
5751 // Main-Hand case
5752 else
5754 // Value gained from additional AP
5755 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(BASE_ATTACK)/1000);
5756 triggered_spell_id = 25504;
5759 // apply cooldown before cast to prevent processing itself
5760 if( cooldown )
5761 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
5763 // Attack Twice
5764 for ( uint32 i = 0; i<2; ++i )
5765 CastCustomSpell(pVictim,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5767 return true;
5769 // Shaman Tier 6 Trinket
5770 case 40463:
5772 if( !procSpell )
5773 return false;
5775 float chance;
5776 if (procSpell->SpellFamilyFlags & 0x0000000000000001LL)
5778 triggered_spell_id = 40465; // Lightning Bolt
5779 chance = 15.0f;
5781 else if (procSpell->SpellFamilyFlags & 0x0000000000000080LL)
5783 triggered_spell_id = 40465; // Lesser Healing Wave
5784 chance = 10.0f;
5786 else if (procSpell->SpellFamilyFlags & 0x0000001000000000LL)
5788 triggered_spell_id = 40466; // Stormstrike
5789 chance = 50.0f;
5791 else
5792 return false;
5794 if (!roll_chance_f(chance))
5795 return false;
5797 target = this;
5798 break;
5800 // Glyph of Healing Wave
5801 case 55440:
5803 // Not proc from self heals
5804 if (this==pVictim)
5805 return false;
5806 basepoints0 = triggerAmount * damage / 100;
5807 target = this;
5808 triggered_spell_id = 55533;
5809 break;
5811 // Spirit Hunt
5812 case 58877:
5814 // Cast on owner
5815 target = GetOwner();
5816 if(!target)
5817 return false;
5818 basepoints0 = triggerAmount * damage / 100;
5819 triggered_spell_id = 58879;
5820 break;
5823 // Ancestral Awakening
5824 if (dummySpell->SpellIconID == 3065)
5826 triggered_spell_id = 52759;
5827 basepoints0 = triggerAmount * damage / 100;
5828 target = this;
5829 break;
5831 // Earth Shield
5832 if(dummySpell->SpellFamilyFlags & 0x0000040000000000LL)
5834 basepoints0 = triggerAmount;
5835 target = this;
5836 triggered_spell_id = 379;
5837 break;
5839 // Improved Water Shield
5840 if (dummySpell->SpellIconID == 2287)
5842 // Lesser Healing Wave need aditional 60% roll
5843 if (procSpell->SpellFamilyFlags & 0x0000000000000080LL && !roll_chance_i(60))
5844 return false;
5845 // lookup water shield
5846 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
5847 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
5849 if( (*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
5850 (*itr)->GetSpellProto()->SpellFamilyFlags & 0x0000002000000000LL)
5852 uint32 spell = (*itr)->GetSpellProto()->EffectTriggerSpell[(*itr)->GetEffIndex()];
5853 CastSpell(this, spell, true, castItem, triggeredByAura);
5854 if ((*itr)->DropAuraCharge())
5855 RemoveAurasDueToSpell((*itr)->GetId());
5856 return true;
5859 return false;
5860 break;
5862 // Lightning Overload
5863 if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura
5865 if(!procSpell || GetTypeId() != TYPEID_PLAYER || !pVictim )
5866 return false;
5868 // custom cooldown processing case
5869 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
5870 return false;
5872 uint32 spellId = 0;
5873 // Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost
5874 switch (procSpell->Id)
5876 // Lightning Bolt
5877 case 403: spellId = 45284; break; // Rank 1
5878 case 529: spellId = 45286; break; // Rank 2
5879 case 548: spellId = 45287; break; // Rank 3
5880 case 915: spellId = 45288; break; // Rank 4
5881 case 943: spellId = 45289; break; // Rank 5
5882 case 6041: spellId = 45290; break; // Rank 6
5883 case 10391: spellId = 45291; break; // Rank 7
5884 case 10392: spellId = 45292; break; // Rank 8
5885 case 15207: spellId = 45293; break; // Rank 9
5886 case 15208: spellId = 45294; break; // Rank 10
5887 case 25448: spellId = 45295; break; // Rank 11
5888 case 25449: spellId = 45296; break; // Rank 12
5889 case 49237: spellId = 49239; break; // Rank 13
5890 case 49238: spellId = 49240; break; // Rank 14
5891 // Chain Lightning
5892 case 421: spellId = 45297; break; // Rank 1
5893 case 930: spellId = 45298; break; // Rank 2
5894 case 2860: spellId = 45299; break; // Rank 3
5895 case 10605: spellId = 45300; break; // Rank 4
5896 case 25439: spellId = 45301; break; // Rank 5
5897 case 25442: spellId = 45302; break; // Rank 6
5898 case 49268: spellId = 49270; break; // Rank 7
5899 case 49269: spellId = 49271; break; // Rank 8
5900 default:
5901 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (LO)", procSpell->Id);
5902 return false;
5904 // No thread generated mod
5905 // TODO: exist special flag in spell attributes for this, need found and use!
5906 SpellModifier *mod = new SpellModifier;
5907 mod->op = SPELLMOD_THREAT;
5908 mod->value = -100;
5909 mod->type = SPELLMOD_PCT;
5910 mod->spellId = dummySpell->Id;
5911 mod->mask = 0x0000000000000003LL;
5912 mod->mask2= 0LL;
5913 ((Player*)this)->AddSpellMod(mod, true);
5915 // Remove cooldown (Chain Lightning - have Category Recovery time)
5916 if (procSpell->SpellFamilyFlags & 0x0000000000000002LL)
5917 ((Player*)this)->RemoveSpellCooldown(spellId);
5919 CastSpell(pVictim, spellId, true, castItem, triggeredByAura);
5921 ((Player*)this)->AddSpellMod(mod, false);
5923 if( cooldown && GetTypeId()==TYPEID_PLAYER )
5924 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
5926 return true;
5928 // Static Shock
5929 if(dummySpell->SpellIconID == 3059)
5931 // lookup Lightning Shield
5932 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
5933 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
5935 if( (*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
5936 (*itr)->GetSpellProto()->SpellFamilyFlags & 0x0000000000000400LL)
5938 uint32 spell = 0;
5939 switch ((*itr)->GetId())
5941 case 324: spell = 26364; break;
5942 case 325: spell = 26365; break;
5943 case 905: spell = 26366; break;
5944 case 945: spell = 26367; break;
5945 case 8134: spell = 26369; break;
5946 case 10431: spell = 26370; break;
5947 case 10432: spell = 26363; break;
5948 case 25469: spell = 26371; break;
5949 case 25472: spell = 26372; break;
5950 case 49280: spell = 49278; break;
5951 case 49281: spell = 49279; break;
5952 default:
5953 return false;
5955 CastSpell(target, spell, true, castItem, triggeredByAura);
5956 if ((*itr)->DropAuraCharge())
5957 RemoveAurasDueToSpell((*itr)->GetId());
5958 return true;
5961 return false;
5962 break;
5964 break;
5966 case SPELLFAMILY_DEATHKNIGHT:
5968 // Blood Aura
5969 if (dummySpell->SpellIconID == 2636)
5971 if (GetTypeId() != TYPEID_PLAYER || !((Player*)this)->isHonorOrXPTarget(pVictim))
5972 return false;
5973 basepoints0 = triggerAmount * damage / 100;
5974 triggered_spell_id = 53168;
5975 break;
5977 // Butchery
5978 if (dummySpell->SpellIconID == 2664)
5980 basepoints0 = triggerAmount;
5981 triggered_spell_id = 50163;
5982 target = this;
5983 break;
5985 // Dancing Rune Weapon
5986 if (dummySpell->Id == 49028)
5988 // 1 dummy aura for dismiss rune blade
5989 if (effIndex!=2)
5990 return false;
5991 // TODO: wite script for this "fights on its own, doing the same attacks"
5992 // NOTE: Trigger here on every attack and spell cast
5993 return false;
5995 // Mark of Blood
5996 if (dummySpell->Id == 49005)
5998 // TODO: need more info (cooldowns/PPM)
5999 triggered_spell_id = 61607;
6000 break;
6002 // Vendetta
6003 if (dummySpell->SpellFamilyFlags & 0x0000000000010000LL)
6005 basepoints0 = triggerAmount * GetMaxHealth() / 100;
6006 triggered_spell_id = 50181;
6007 target = this;
6008 break;
6010 // Necrosis
6011 if (dummySpell->SpellIconID == 2709)
6013 basepoints0 = triggerAmount * damage / 100;
6014 triggered_spell_id = 51460;
6015 break;
6017 // Runic Power Back on Snare/Root
6018 if (dummySpell->Id == 61257)
6020 // only for spells and hit/crit (trigger start always) and not start from self casted spells
6021 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
6022 return false;
6023 // Need snare or root mechanic
6024 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_SNARE))))
6025 return false;
6026 triggered_spell_id = 61258;
6027 target = this;
6028 break;
6030 // Wandering Plague
6031 if (dummySpell->SpellIconID == 1614)
6033 if (!roll_chance_f(GetUnitCriticalChance(BASE_ATTACK, pVictim)))
6034 return false;
6035 basepoints0 = triggerAmount * damage / 100;
6036 triggered_spell_id = 50526;
6037 break;
6039 break;
6041 default:
6042 break;
6045 // processed charge only counting case
6046 if(!triggered_spell_id)
6047 return true;
6049 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
6051 if(!triggerEntry)
6053 sLog.outError("Unit::HandleDummyAuraProc: Spell %u have not existed triggered spell %u",dummySpell->Id,triggered_spell_id);
6054 return false;
6057 // default case
6058 if(!target || target!=this && !target->isAlive())
6059 return false;
6061 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
6062 return false;
6064 if(basepoints0)
6065 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
6066 else
6067 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
6069 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6070 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
6072 return true;
6075 bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown)
6077 // Get triggered aura spell info
6078 SpellEntry const* auraSpellInfo = triggeredByAura->GetSpellProto();
6080 // Basepoints of trigger aura
6081 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
6083 // Set trigger spell id, target, custom basepoints
6084 uint32 trigger_spell_id = auraSpellInfo->EffectTriggerSpell[triggeredByAura->GetEffIndex()];
6085 Unit* target = NULL;
6086 int32 basepoints0 = 0;
6088 if(triggeredByAura->GetModifier()->m_auraname == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE)
6089 basepoints0 = triggerAmount;
6091 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
6092 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
6094 // Try handle uncnown trigger spells
6095 if (sSpellStore.LookupEntry(trigger_spell_id)==NULL)
6097 switch (auraSpellInfo->SpellFamilyName)
6099 case SPELLFAMILY_GENERIC:
6100 //if (auraSpellInfo->Id==59532) // Abandon Passengers on Poly
6101 //if (auraSpellInfo->Id==54775) // Abandon Vehicle on Poly
6102 //if (auraSpellInfo->Id==34082) // Advantaged State (DND)
6103 if (auraSpellInfo->Id == 23780) // Aegis of Preservation (Aegis of Preservation trinket)
6104 trigger_spell_id = 23781;
6105 //else if (auraSpellInfo->Id==43504) // Alterac Valley OnKill Proc Aura
6106 //else if (auraSpellInfo->Id == 48876) // Beast's Mark
6108 // trigger_spell_id = 48877;
6110 //else if (auraSpellInfo->Id == 59237) // Beast's Mark
6112 // trigger_spell_id = 59233;
6114 //else if (auraSpellInfo->Id==46939) // Black Bow of the Betrayer
6116 // trigger_spell_id = 29471; // gain mana
6117 // 27526; // drain mana if possible
6119 //else if (auraSpellInfo->Id==50844) // Blood Mirror
6120 //else if (auraSpellInfo->Id==54476) // Blood Presence
6121 //else if (auraSpellInfo->Id==50689) // Blood Presence (Rank 1)
6122 //else if (auraSpellInfo->Id==37030) // Chaotic Temperament
6123 //else if (auraSpellInfo->Id==52856) // Charge
6124 else if (auraSpellInfo->Id==43820) // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket)
6126 // Pct value stored in dummy
6127 basepoints0 = pVictim->GetCreateHealth() * auraSpellInfo->EffectBasePoints[1] / 100;
6128 target = pVictim;
6129 break;
6131 //else if (auraSpellInfo->Id==41248) // Consuming Strikes
6132 // trigger_spell_id = 41249;
6133 //else if (auraSpellInfo->Id==45205) // Copy Offhand Weapon
6134 //else if (auraSpellInfo->Id==57594) // Copy Ranged Weapon
6135 //else if (auraSpellInfo->Id==41054) // Copy Weapon
6136 // trigger_spell_id = 41055;
6137 //else if (auraSpellInfo->Id==45343) // Dark Flame Aura
6138 //else if (auraSpellInfo->Id==47300) // Dark Flame Aura
6139 else if (auraSpellInfo->Id==57345) // Darkmoon Card: Greatness
6141 float stat = 0.0f;
6142 // strength
6143 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); }
6144 // agility
6145 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); }
6146 // intellect
6147 if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);}
6148 // spirit
6149 if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235;stat = GetStat(STAT_SPIRIT); }
6151 //else if (auraSpellInfo->Id==31255) // Deadly Swiftness (Rank 1)
6152 //else if (auraSpellInfo->Id==5301) // Defensive State (DND)
6153 //else if (auraSpellInfo->Id==13358) // Defensive State (DND)
6154 //else if (auraSpellInfo->Id==16092) // Defensive State (DND)
6155 //else if (auraSpellInfo->Id==24949) // Defensive State 2 (DND)
6156 //else if (auraSpellInfo->Id==40329) // Demo Shout Sensor
6157 else if (auraSpellInfo->Id == 33896) // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher)
6158 trigger_spell_id = 33898;
6159 //else if (auraSpellInfo->Id==18943) // Double Attack
6160 //else if (auraSpellInfo->Id==19194) // Double Attack
6161 //else if (auraSpellInfo->Id==19817) // Double Attack
6162 //else if (auraSpellInfo->Id==19818) // Double Attack
6163 //else if (auraSpellInfo->Id==22835) // Drunken Rage
6164 // trigger_spell_id = 14822;
6166 else if (auraSpellInfo->SpellIconID==191) // Elemental Response
6168 switch (auraSpellInfo->Id && auraSpellInfo->AttributesEx==0)
6170 case 34191:
6171 case 34329:
6172 case 34524:
6173 case 34582:
6174 case 36733:
6175 break;
6176 default:
6177 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Elemental Response",auraSpellInfo->Id);
6178 return false;
6180 //This generic aura self-triggers a different spell for each school of magic that lands on the wearer:
6181 switch (procSpell->School)
6183 case SPELL_SCHOOL_FIRE: trigger_spell_id = 34192; break;
6184 case SPELL_SCHOOL_FROST: trigger_spell_id = 34193; break;
6185 case SPELL_SCHOOL_ARCANE:trigger_spell_id = 34194; break;
6186 case SPELL_SCHOOL_NATURE:trigger_spell_id = 34195; break;
6187 case SPELL_SCHOOL_SHADOW:trigger_spell_id = 34196; break;
6188 case SPELL_SCHOOL_HOLY: trigger_spell_id = 34197; break;
6189 case SPELL_SCHOOL_NORMAL:trigger_spell_id = 34198; break;
6190 default:
6191 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u Elemental Response wrong school",auraSpellInfo->Id);
6192 return false;
6196 //else if (auraSpellInfo->Id==40364) // Entangling Roots Sensor
6197 //else if (auraSpellInfo->Id==33207) // Gossip NPC Periodic - Fidget
6198 //else if (auraSpellInfo->Id==50051) // Ethereal Pet Aura
6199 //else if (auraSpellInfo->Id==35321) // Gushing Wound
6200 //else if (auraSpellInfo->Id==38363) // Gushing Wound
6201 //else if (auraSpellInfo->Id==39215) // Gushing Wound
6202 //else if (auraSpellInfo->Id==44527) // Hate Monster (Spar Buddy) (30 sec)
6203 //else if (auraSpellInfo->Id==44819) // Hate Monster (Spar Buddy) (>30% Health)
6204 //else if (auraSpellInfo->Id==44526) // Hate Monster (Spar) (30 sec)
6205 //else if (auraSpellInfo->Id==44820) // Hate Monster (Spar) (<30%)
6206 //else if (auraSpellInfo->Id==49059) // Horde, Hate Monster (Spar Buddy) (>30% Health)
6207 //else if (auraSpellInfo->Id==40250) // Improved Duration
6208 //else if (auraSpellInfo->Id==59288) // Infra-Green Shield
6209 //else if (auraSpellInfo->Id==54072) // Knockback Ball Passive
6210 else if (auraSpellInfo->Id==27522 || auraSpellInfo->Id==40336)
6211 // Mana Drain Trigger
6213 // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target.
6214 if (this && this->isAlive())
6215 CastSpell(this, 29471, true, castItem, triggeredByAura);
6216 if (pVictim && pVictim->isAlive())
6217 CastSpell(pVictim, 27526, true, castItem, triggeredByAura);
6218 return true;
6220 //else if (auraSpellInfo->Id==55580) // Mana Link
6221 //else if (auraSpellInfo->Id==45903) // Offensive State
6222 //else if (auraSpellInfo->Id==44326) // Pure Energy Passive
6223 //else if (auraSpellInfo->Id==43453) // Rune Ward
6224 //else if (auraSpellInfo->Id== 7137) // Shadow Charge (Rank 1)
6225 //else if (auraSpellInfo->Id==36576) // Shaleskin (Shaleskin Flayer, Shaleskin Ripper) 30023 trigger
6226 //else if (auraSpellInfo->Id==34783) // Spell Reflection
6227 //else if (auraSpellInfo->Id==36096) // Spell Reflection
6228 //else if (auraSpellInfo->Id==57587) // Steal Ranged ()
6229 //else if (auraSpellInfo->Id==36207) // Steal Weapon
6230 //else if (auraSpellInfo->Id== 7377) // Take Immune Periodic Damage <Not Working>
6231 //else if (auraSpellInfo->Id==35205) // Vanish
6232 //else if (auraSpellInfo->Id==42730) // Woe Strike
6233 //else if (auraSpellInfo->Id==59735) // Woe Strike
6234 //else if (auraSpellInfo->Id==46146) // [PH] Ahune Spanky Hands
6235 break;
6236 case SPELLFAMILY_MAGE:
6237 if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed
6239 switch (auraSpellInfo->Id)
6241 case 31641: // Rank 1
6242 case 31642: // Rank 2
6243 trigger_spell_id = 31643;
6244 break;
6245 default:
6246 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blazing Speed",auraSpellInfo->Id);
6247 return false;
6250 break;
6251 case SPELLFAMILY_WARRIOR:
6252 if (auraSpellInfo->Id == 50421) // Scent of Blood
6253 trigger_spell_id = 50422;
6254 break;
6255 case SPELLFAMILY_WARLOCK:
6257 // Pyroclasm
6258 if (auraSpellInfo->SpellIconID == 1137)
6260 if(!pVictim || !pVictim->isAlive() || pVictim == this || procSpell == NULL)
6261 return false;
6262 // Calculate spell tick count for spells
6263 uint32 tick = 1; // Default tick = 1
6265 // Hellfire have 15 tick
6266 if (procSpell->SpellFamilyFlags&0x0000000000000040LL)
6267 tick = 15;
6268 // Rain of Fire have 4 tick
6269 else if (procSpell->SpellFamilyFlags&0x0000000000000020LL)
6270 tick = 4;
6271 else
6272 return false;
6274 // Calculate chance = baseChance / tick
6275 float chance = 0;
6276 switch (auraSpellInfo->Id)
6278 case 18096: chance = 13.0f / tick; break;
6279 case 18073: chance = 26.0f / tick; break;
6281 // Roll chance
6282 if (!roll_chance_f(chance))
6283 return false;
6285 trigger_spell_id = 18093;
6287 // Drain Soul
6288 else if (auraSpellInfo->SpellFamilyFlags & 0x0000000000004000LL)
6290 Unit::AuraList const& mAddFlatModifier = GetAurasByType(SPELL_AURA_ADD_FLAT_MODIFIER);
6291 for(Unit::AuraList::const_iterator i = mAddFlatModifier.begin(); i != mAddFlatModifier.end(); ++i)
6293 if ((*i)->GetModifier()->m_miscvalue == SPELLMOD_CHANCE_OF_SUCCESS && (*i)->GetSpellProto()->SpellIconID == 113)
6295 int32 value2 = CalculateSpellDamage((*i)->GetSpellProto(),2,(*i)->GetSpellProto()->EffectBasePoints[2],this);
6296 // Drain Soul
6297 CastCustomSpell(this, 18371, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
6298 break;
6301 // Not remove charge (aura removed on death in any cases)
6302 // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura
6303 return false;
6305 // Nether Protection
6306 else if (auraSpellInfo->SpellIconID == 1985)
6308 if (!procSpell)
6309 return false;
6310 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
6312 case SPELL_SCHOOL_NORMAL:
6313 return false; // ignore
6314 case SPELL_SCHOOL_HOLY: trigger_spell_id = 54370; break;
6315 case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break;
6316 case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break;
6317 case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break;
6318 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break;
6319 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
6320 default:
6321 return false;
6324 break;
6326 case SPELLFAMILY_PRIEST:
6328 // Greater Heal Refund
6329 if (auraSpellInfo->Id==37594)
6330 trigger_spell_id = 37595;
6331 // Blessed Recovery
6332 else if (auraSpellInfo->SpellIconID == 1875)
6334 switch (auraSpellInfo->Id)
6336 case 27811: trigger_spell_id = 27813; break;
6337 case 27815: trigger_spell_id = 27817; break;
6338 case 27816: trigger_spell_id = 27818; break;
6339 default:
6340 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id);
6341 return false;
6343 basepoints0 = damage * triggerAmount / 100 / 3;
6344 target = this;
6346 break;
6348 case SPELLFAMILY_DRUID:
6350 // Druid Forms Trinket
6351 if (auraSpellInfo->Id==37336)
6353 switch(m_form)
6355 case FORM_NONE: trigger_spell_id = 37344;break;
6356 case FORM_CAT: trigger_spell_id = 37341;break;
6357 case FORM_BEAR:
6358 case FORM_DIREBEAR: trigger_spell_id = 37340;break;
6359 case FORM_TREE: trigger_spell_id = 37342;break;
6360 case FORM_MOONKIN: trigger_spell_id = 37343;break;
6361 default:
6362 return false;
6365 //else if (auraSpellInfo->Id==40363)// Entangling Roots ()
6366 // trigger_spell_id = ????;
6367 // Leader of the Pack
6368 else if (auraSpellInfo->Id == 24932)
6370 if (triggerAmount == 0)
6371 return false;
6372 basepoints0 = triggerAmount * GetMaxHealth() / 100;
6373 trigger_spell_id = 34299;
6375 break;
6377 case SPELLFAMILY_HUNTER:
6378 break;
6379 case SPELLFAMILY_PALADIN:
6382 // Blessed Life
6383 if (auraSpellInfo->SpellIconID == 2137)
6385 switch (auraSpellInfo->Id)
6387 case 31828: // Rank 1
6388 case 31829: // Rank 2
6389 case 31830: // Rank 3
6390 break;
6391 default:
6392 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blessed Life", auraSpellInfo->Id);
6393 return false;
6397 // Healing Discount
6398 if (auraSpellInfo->Id==37705)
6400 trigger_spell_id = 37706;
6401 target = this;
6403 // Soul Preserver
6404 if (auraSpellInfo->Id==60510)
6406 trigger_spell_id = 60515;
6407 target = this;
6409 // Illumination
6410 else if (auraSpellInfo->SpellIconID==241)
6412 if(!procSpell)
6413 return false;
6414 // procspell is triggered spell but we need mana cost of original casted spell
6415 uint32 originalSpellId = procSpell->Id;
6416 // Holy Shock heal
6417 if(procSpell->SpellFamilyFlags & 0x0001000000000000LL)
6419 switch(procSpell->Id)
6421 case 25914: originalSpellId = 20473; break;
6422 case 25913: originalSpellId = 20929; break;
6423 case 25903: originalSpellId = 20930; break;
6424 case 27175: originalSpellId = 27174; break;
6425 case 33074: originalSpellId = 33072; break;
6426 case 48820: originalSpellId = 48824; break;
6427 case 48821: originalSpellId = 48825; break;
6428 default:
6429 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in HShock",procSpell->Id);
6430 return false;
6433 SpellEntry const *originalSpell = sSpellStore.LookupEntry(originalSpellId);
6434 if(!originalSpell)
6436 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu",originalSpellId);
6437 return false;
6439 // percent stored in effect 1 (class scripts) base points
6440 int32 cost = originalSpell->manaCost + originalSpell->ManaCostPercentage * GetCreateMana() / 100;
6441 basepoints0 = cost*auraSpellInfo->CalculateSimpleValue(1)/100;
6442 trigger_spell_id = 20272;
6443 target = this;
6445 // Lightning Capacitor
6446 else if (auraSpellInfo->Id==37657)
6448 if(!pVictim || !pVictim->isAlive())
6449 return false;
6450 // stacking
6451 CastSpell(this, 37658, true, NULL, triggeredByAura);
6453 Aura * dummy = GetDummyAura(37658);
6454 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
6455 if(!dummy || dummy->GetStackAmount() < triggerAmount)
6456 return false;
6458 RemoveAurasDueToSpell(37658);
6459 trigger_spell_id = 37661;
6460 target = pVictim;
6462 // Thunder Capacitor
6463 else if (auraSpellInfo->Id == 54841)
6465 if(!pVictim || !pVictim->isAlive())
6466 return false;
6467 // stacking
6468 CastSpell(this, 54842, true, NULL, triggeredByAura);
6470 // counting
6471 Aura * dummy = GetDummyAura(54842);
6472 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
6473 if(!dummy || dummy->GetStackAmount() < triggerAmount)
6474 return false;
6476 RemoveAurasDueToSpell(54842);
6477 trigger_spell_id = 54843;
6478 target = pVictim;
6480 break;
6482 case SPELLFAMILY_SHAMAN:
6484 // Lightning Shield (overwrite non existing triggered spell call in spell.dbc
6485 if(auraSpellInfo->SpellFamilyFlags & 0x0000000000000400)
6487 switch(auraSpellInfo->Id)
6489 case 324: // Rank 1
6490 trigger_spell_id = 26364; break;
6491 case 325: // Rank 2
6492 trigger_spell_id = 26365; break;
6493 case 905: // Rank 3
6494 trigger_spell_id = 26366; break;
6495 case 945: // Rank 4
6496 trigger_spell_id = 26367; break;
6497 case 8134: // Rank 5
6498 trigger_spell_id = 26369; break;
6499 case 10431: // Rank 6
6500 trigger_spell_id = 26370; break;
6501 case 10432: // Rank 7
6502 trigger_spell_id = 26363; break;
6503 case 25469: // Rank 8
6504 trigger_spell_id = 26371; break;
6505 case 25472: // Rank 9
6506 trigger_spell_id = 26372; break;
6507 case 49280: // Rank 10
6508 trigger_spell_id = 49278; break;
6509 case 49281: // Rank 11
6510 trigger_spell_id = 49279; break;
6511 default:
6512 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in LShield", auraSpellInfo->Id);
6513 return false;
6516 // Lightning Shield (The Ten Storms set)
6517 else if (auraSpellInfo->Id == 23551)
6519 trigger_spell_id = 23552;
6520 target = pVictim;
6522 // Damage from Lightning Shield (The Ten Storms set)
6523 else if (auraSpellInfo->Id == 23552)
6524 trigger_spell_id = 27635;
6525 // Mana Surge (The Earthfury set)
6526 else if (auraSpellInfo->Id == 23572)
6528 if(!procSpell)
6529 return false;
6530 basepoints0 = procSpell->manaCost * 35 / 100;
6531 trigger_spell_id = 23571;
6532 target = this;
6534 // Nature's Guardian
6535 else if (auraSpellInfo->SpellIconID == 2013)
6537 // Check health condition - should drop to less 30% (damage deal after this!)
6538 if (!(10*(int32(GetHealth() - damage)) < 3 * GetMaxHealth()))
6539 return false;
6541 if(pVictim && pVictim->isAlive())
6542 pVictim->getThreatManager().modifyThreatPercent(this,-10);
6544 basepoints0 = triggerAmount * GetMaxHealth() / 100;
6545 trigger_spell_id = 31616;
6546 target = this;
6548 break;
6550 case SPELLFAMILY_DEATHKNIGHT:
6552 // Acclimation
6553 if (auraSpellInfo->SpellIconID == 1930)
6555 if (!procSpell)
6556 return false;
6557 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
6559 case SPELL_SCHOOL_NORMAL:
6560 return false; // ignore
6561 case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break;
6562 case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break;
6563 case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break;
6564 case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break;
6565 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break;
6566 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
6567 default:
6568 return false;
6571 // Blood Presence
6572 else if (auraSpellInfo->Id == 48266)
6574 if (GetTypeId() != TYPEID_PLAYER)
6575 return false;
6576 if (!((Player*)this)->isHonorOrXPTarget(pVictim))
6577 return false;
6578 trigger_spell_id = 50475;
6579 basepoints0 = damage * triggerAmount / 100;
6581 break;
6583 default:
6584 break;
6588 // All ok. Check current trigger spell
6589 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(trigger_spell_id);
6590 if ( triggerEntry == NULL )
6592 // Not cast unknown spell
6593 // sLog.outError("Unit::HandleProcTriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?",auraSpellInfo->Id,triggeredByAura->GetEffIndex());
6594 return false;
6597 // not allow proc extra attack spell at extra attack
6598 if( m_extraAttacks && IsSpellHaveEffect(triggerEntry, SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6599 return false;
6601 // Custom requirements (not listed in procEx) Warning! damage dealing after this
6602 // Custom triggered spells
6603 switch (auraSpellInfo->Id)
6605 // Persistent Shield (Scarab Brooch trinket)
6606 // This spell originally trigger 13567 - Dummy Trigger (vs dummy efect)
6607 case 26467:
6609 basepoints0 = damage * 15 / 100;
6610 target = pVictim;
6611 trigger_spell_id = 26470;
6612 break;
6614 // Cheat Death
6615 case 28845:
6617 // When your health drops below 20% ....
6618 if (GetHealth() - damage > GetMaxHealth() / 5 || GetHealth() < GetMaxHealth() / 5)
6619 return false;
6620 break;
6622 // Deadly Swiftness (Rank 1)
6623 case 31255:
6625 // whenever you deal damage to a target who is below 20% health.
6626 if (pVictim->GetHealth() > pVictim->GetMaxHealth() / 5)
6627 return false;
6629 target = this;
6630 trigger_spell_id = 22588;
6632 // Greater Heal Refund (Avatar Raiment set)
6633 case 37594:
6635 // Not give if target already have full health
6636 if (pVictim->GetHealth() == pVictim->GetMaxHealth())
6637 return false;
6638 // If your Greater Heal brings the target to full health, you gain $37595s1 mana.
6639 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
6640 return false;
6641 break;
6643 // Bonus Healing (Crystal Spire of Karabor mace)
6644 case 40971:
6646 // If your target is below $s1% health
6647 if (pVictim->GetHealth() > pVictim->GetMaxHealth() * triggerAmount / 100)
6648 return false;
6649 break;
6651 // Evasive Maneuvers (Commendation of Kael`thas trinket)
6652 case 45057:
6654 // reduce you below $s1% health
6655 if (GetHealth() - damage > GetMaxHealth() * triggerAmount / 100)
6656 return false;
6657 break;
6659 // Rapid Recuperation
6660 case 53228:
6661 case 53232:
6663 // This effect only from Rapid Fire (ability cast)
6664 if (!(procSpell->SpellFamilyFlags & 0x0000000000000020LL))
6665 return false;
6666 break;
6670 // Custom basepoints/target for exist spell
6671 // dummy basepoints or other customs
6672 switch(trigger_spell_id)
6674 // Cast positive spell on enemy target
6675 case 7099: // Curse of Mending
6676 case 39647: // Curse of Mending
6677 case 29494: // Temptation
6678 case 20233: // Improved Lay on Hands (cast on target)
6680 target = pVictim;
6681 break;
6683 // Combo points add triggers (need add combopoint only for main target, and after possible combopoints reset)
6684 case 15250: // Rogue Setup
6686 if(!pVictim || pVictim != getVictim()) // applied only for main target
6687 return false;
6688 break; // continue normal case
6690 // Finish movies that add combo
6691 case 14189: // Seal Fate (Netherblade set)
6692 case 14157: // Ruthlessness
6694 // Need add combopoint AFTER finish movie (or they dropped in finish phase)
6695 break;
6697 // Bloodthirst (($m/100)% of max health)
6698 case 23880:
6700 basepoints0 = int32(GetMaxHealth() * triggerAmount / 100);
6701 break;
6703 // Shamanistic Rage triggered spell
6704 case 30824:
6706 basepoints0 = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
6707 break;
6709 // Enlightenment (trigger only from mana cost spells)
6710 case 35095:
6712 if(!procSpell || procSpell->powerType!=POWER_MANA || procSpell->manaCost==0 && procSpell->ManaCostPercentage==0 && procSpell->manaCostPerlevel==0)
6713 return false;
6714 break;
6716 // Brain Freeze
6717 case 57761:
6719 if(!procSpell)
6720 return false;
6721 // For trigger from Blizzard need exist Improved Blizzard
6722 if (procSpell->SpellFamilyName==SPELLFAMILY_MAGE && procSpell->SpellFamilyFlags & 0x0000000000000080LL)
6724 bool found = false;
6725 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
6726 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
6728 int32 script = (*i)->GetModifier()->m_miscvalue;
6729 if(script==836 || script==988 || script==989)
6731 found=true;
6732 break;
6735 if(!found)
6736 return false;
6738 break;
6740 // Astral Shift
6741 case 52179:
6743 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
6744 return false;
6746 // Need stun, fear or silence mechanic
6747 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_SILENCE)|(1<<MECHANIC_STUN)|(1<<MECHANIC_FEAR))))
6748 return false;
6749 break;
6751 // Burning Determination
6752 case 54748:
6754 if(!procSpell)
6755 return false;
6756 // Need Interrupt or Silenced mechanic
6757 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_INTERRUPT)|(1<<MECHANIC_SILENCE))))
6758 return false;
6759 break;
6761 // Lock and Load
6762 case 56453:
6764 // Proc only from trap activation (from periodic proc another aura of this spell)
6765 if (!(procFlags & PROC_FLAG_ON_TRAP_ACTIVATION) || !roll_chance_i(triggerAmount))
6766 return false;
6767 break;
6771 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(trigger_spell_id))
6772 return false;
6774 // try detect target manually if not set
6775 if ( target == NULL )
6776 target = !(procFlags & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) && IsPositiveSpell(trigger_spell_id) ? this : pVictim;
6778 // default case
6779 if(!target || target!=this && !target->isAlive())
6780 return false;
6782 if(basepoints0)
6783 CastCustomSpell(target,trigger_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
6784 else
6785 CastSpell(target,trigger_spell_id,true,castItem,triggeredByAura);
6787 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6788 ((Player*)this)->AddSpellCooldown(trigger_spell_id,0,time(NULL) + cooldown);
6790 return true;
6793 bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, uint32 damage, Aura *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown)
6795 int32 scriptId = triggeredByAura->GetModifier()->m_miscvalue;
6797 if(!pVictim || !pVictim->isAlive())
6798 return false;
6800 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
6801 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
6803 uint32 triggered_spell_id = 0;
6805 switch(scriptId)
6807 case 836: // Improved Blizzard (Rank 1)
6809 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6810 return false;
6811 triggered_spell_id = 12484;
6812 break;
6814 case 988: // Improved Blizzard (Rank 2)
6816 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6817 return false;
6818 triggered_spell_id = 12485;
6819 break;
6821 case 989: // Improved Blizzard (Rank 3)
6823 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6824 return false;
6825 triggered_spell_id = 12486;
6826 break;
6828 case 4086: // Improved Mend Pet (Rank 1)
6829 case 4087: // Improved Mend Pet (Rank 2)
6831 int32 chance = triggeredByAura->GetSpellProto()->EffectBasePoints[triggeredByAura->GetEffIndex()];
6832 if(!roll_chance_i(chance))
6833 return false;
6835 triggered_spell_id = 24406;
6836 break;
6838 case 4533: // Dreamwalker Raiment 2 pieces bonus
6840 // Chance 50%
6841 if (!roll_chance_i(50))
6842 return false;
6844 switch (pVictim->getPowerType())
6846 case POWER_MANA: triggered_spell_id = 28722; break;
6847 case POWER_RAGE: triggered_spell_id = 28723; break;
6848 case POWER_ENERGY: triggered_spell_id = 28724; break;
6849 default:
6850 return false;
6852 break;
6854 case 4537: // Dreamwalker Raiment 6 pieces bonus
6855 triggered_spell_id = 28750; // Blessing of the Claw
6856 break;
6857 case 5497: // Improved Mana Gems (Serpent-Coil Braid)
6858 triggered_spell_id = 37445; // Mana Surge
6859 break;
6860 case 8152: // Serendipity
6862 // if heal your target over maximum health
6863 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
6864 return false;
6865 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
6866 int32 basepoints0 = cost * triggeredByAura->GetModifier()->m_amount/100;
6867 CastCustomSpell(this, 47762, &basepoints0, 0, 0, true, 0, triggeredByAura);
6868 return true;
6872 // not processed
6873 if(!triggered_spell_id)
6874 return false;
6876 // standard non-dummy case
6877 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
6879 if(!triggerEntry)
6881 sLog.outError("Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u",triggered_spell_id,scriptId);
6882 return false;
6885 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
6886 return false;
6888 CastSpell(pVictim, triggered_spell_id, true, castItem, triggeredByAura);
6890 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6891 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
6893 return true;
6896 void Unit::setPowerType(Powers new_powertype)
6898 SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype);
6900 if(GetTypeId() == TYPEID_PLAYER)
6902 if(((Player*)this)->GetGroup())
6903 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE);
6905 else if(((Creature*)this)->isPet())
6907 Pet *pet = ((Pet*)this);
6908 if(pet->isControlled())
6910 Unit *owner = GetOwner();
6911 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
6912 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE);
6916 switch(new_powertype)
6918 default:
6919 case POWER_MANA:
6920 break;
6921 case POWER_RAGE:
6922 SetMaxPower(POWER_RAGE,GetCreatePowers(POWER_RAGE));
6923 SetPower( POWER_RAGE,0);
6924 break;
6925 case POWER_FOCUS:
6926 SetMaxPower(POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
6927 SetPower( POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
6928 break;
6929 case POWER_ENERGY:
6930 SetMaxPower(POWER_ENERGY,GetCreatePowers(POWER_ENERGY));
6931 SetPower( POWER_ENERGY,0);
6932 break;
6933 case POWER_HAPPINESS:
6934 SetMaxPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
6935 SetPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
6936 break;
6940 FactionTemplateEntry const* Unit::getFactionTemplateEntry() const
6942 FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry(getFaction());
6943 if(!entry)
6945 static uint64 guid = 0; // prevent repeating spam same faction problem
6947 if(GetGUID() != guid)
6949 if(GetTypeId() == TYPEID_PLAYER)
6950 sLog.outError("Player %s have invalid faction (faction template id) #%u", ((Player*)this)->GetName(), getFaction());
6951 else
6952 sLog.outError("Creature (template id: %u) have invalid faction (faction template id) #%u", ((Creature*)this)->GetCreatureInfo()->Entry, getFaction());
6953 guid = GetGUID();
6956 return entry;
6959 bool Unit::IsHostileTo(Unit const* unit) const
6961 // always non-hostile to self
6962 if(unit==this)
6963 return false;
6965 // always non-hostile to GM in GM mode
6966 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
6967 return false;
6969 // always hostile to enemy
6970 if(getVictim()==unit || unit->getVictim()==this)
6971 return true;
6973 // test pet/charm masters instead pers/charmeds
6974 Unit const* testerOwner = GetCharmerOrOwner();
6975 Unit const* targetOwner = unit->GetCharmerOrOwner();
6977 // always hostile to owner's enemy
6978 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
6979 return true;
6981 // always hostile to enemy owner
6982 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
6983 return true;
6985 // always hostile to owner of owner's enemy
6986 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
6987 return true;
6989 Unit const* tester = testerOwner ? testerOwner : this;
6990 Unit const* target = targetOwner ? targetOwner : unit;
6992 // always non-hostile to target with common owner, or to owner/pet
6993 if(tester==target)
6994 return false;
6996 // special cases (Duel, etc)
6997 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
6999 Player const* pTester = (Player const*)tester;
7000 Player const* pTarget = (Player const*)target;
7002 // Duel
7003 if(pTester->duel && pTester->duel->opponent == pTarget && pTester->duel->startTime != 0)
7004 return true;
7006 // Group
7007 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
7008 return false;
7010 // Sanctuary
7011 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
7012 return false;
7014 // PvP FFA state
7015 if(pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
7016 return true;
7018 //= PvP states
7019 // Green/Blue (can't attack)
7020 if(pTester->GetTeam()==pTarget->GetTeam())
7021 return false;
7023 // Red (can attack) if true, Blue/Yellow (can't attack) in another case
7024 return pTester->IsPvP() && pTarget->IsPvP();
7027 // faction base cases
7028 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
7029 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
7030 if(!tester_faction || !target_faction)
7031 return false;
7033 if(target->isAttackingPlayer() && tester->IsContestedGuard())
7034 return true;
7036 // PvC forced reaction and reputation case
7037 if(tester->GetTypeId()==TYPEID_PLAYER)
7039 // forced reaction
7040 if(target_faction->faction)
7042 if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
7043 return *force <= REP_HOSTILE;
7045 // if faction have reputation then hostile state for tester at 100% dependent from at_war state
7046 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
7047 if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
7048 return (factionState->Flags & FACTION_FLAG_AT_WAR);
7051 // CvP forced reaction and reputation case
7052 else if(target->GetTypeId()==TYPEID_PLAYER)
7054 // forced reaction
7055 if(tester_faction->faction)
7057 if(ReputationRank const* force = ((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
7058 return *force <= REP_HOSTILE;
7060 // apply reputation state
7061 FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction);
7062 if(raw_tester_faction && raw_tester_faction->reputationListID >=0 )
7063 return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) <= REP_HOSTILE;
7067 // common faction based case (CvC,PvC,CvP)
7068 return tester_faction->IsHostileTo(*target_faction);
7071 bool Unit::IsFriendlyTo(Unit const* unit) const
7073 // always friendly to self
7074 if(unit==this)
7075 return true;
7077 // always friendly to GM in GM mode
7078 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
7079 return true;
7081 // always non-friendly to enemy
7082 if(getVictim()==unit || unit->getVictim()==this)
7083 return false;
7085 // test pet/charm masters instead pers/charmeds
7086 Unit const* testerOwner = GetCharmerOrOwner();
7087 Unit const* targetOwner = unit->GetCharmerOrOwner();
7089 // always non-friendly to owner's enemy
7090 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
7091 return false;
7093 // always non-friendly to enemy owner
7094 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
7095 return false;
7097 // always non-friendly to owner of owner's enemy
7098 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
7099 return false;
7101 Unit const* tester = testerOwner ? testerOwner : this;
7102 Unit const* target = targetOwner ? targetOwner : unit;
7104 // always friendly to target with common owner, or to owner/pet
7105 if(tester==target)
7106 return true;
7108 // special cases (Duel)
7109 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
7111 Player const* pTester = (Player const*)tester;
7112 Player const* pTarget = (Player const*)target;
7114 // Duel
7115 if(pTester->duel && pTester->duel->opponent == target && pTester->duel->startTime != 0)
7116 return false;
7118 // Group
7119 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
7120 return true;
7122 // Sanctuary
7123 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
7124 return true;
7126 // PvP FFA state
7127 if(pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
7128 return false;
7130 //= PvP states
7131 // Green/Blue (non-attackable)
7132 if(pTester->GetTeam()==pTarget->GetTeam())
7133 return true;
7135 // Blue (friendly/non-attackable) if not PVP, or Yellow/Red in another case (attackable)
7136 return !pTarget->IsPvP();
7139 // faction base cases
7140 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
7141 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
7142 if(!tester_faction || !target_faction)
7143 return false;
7145 if(target->isAttackingPlayer() && tester->IsContestedGuard())
7146 return false;
7148 // PvC forced reaction and reputation case
7149 if(tester->GetTypeId()==TYPEID_PLAYER)
7151 // forced reaction
7152 if(target_faction->faction)
7154 if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
7155 return *force >= REP_FRIENDLY;
7157 // if faction have reputation then friendly state for tester at 100% dependent from at_war state
7158 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
7159 if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
7160 return !(factionState->Flags & FACTION_FLAG_AT_WAR);
7163 // CvP forced reaction and reputation case
7164 else if(target->GetTypeId()==TYPEID_PLAYER)
7166 // forced reaction
7167 if(tester_faction->faction)
7169 if(ReputationRank const* force =((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
7170 return *force >= REP_FRIENDLY;
7172 // apply reputation state
7173 if(FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction))
7174 if(raw_tester_faction->reputationListID >=0 )
7175 return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) >= REP_FRIENDLY;
7179 // common faction based case (CvC,PvC,CvP)
7180 return tester_faction->IsFriendlyTo(*target_faction);
7183 bool Unit::IsHostileToPlayers() const
7185 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
7186 if(!my_faction || !my_faction->faction)
7187 return false;
7189 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
7190 if(raw_faction && raw_faction->reputationListID >=0 )
7191 return false;
7193 return my_faction->IsHostileToPlayers();
7196 bool Unit::IsNeutralToAll() const
7198 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
7199 if(!my_faction || !my_faction->faction)
7200 return true;
7202 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
7203 if(raw_faction && raw_faction->reputationListID >=0 )
7204 return false;
7206 return my_faction->IsNeutralToAll();
7209 bool Unit::Attack(Unit *victim, bool meleeAttack)
7211 if(!victim || victim == this)
7212 return false;
7214 // dead units can neither attack nor be attacked
7215 if(!isAlive() || !victim->isAlive())
7216 return false;
7218 // player cannot attack in mount state
7219 if(GetTypeId()==TYPEID_PLAYER && IsMounted())
7220 return false;
7222 // nobody can attack GM in GM-mode
7223 if(victim->GetTypeId()==TYPEID_PLAYER)
7225 if(((Player*)victim)->isGameMaster())
7226 return false;
7228 else
7230 if(((Creature*)victim)->IsInEvadeMode())
7231 return false;
7234 // remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack)
7235 if(HasAuraType(SPELL_AURA_MOD_UNATTACKABLE))
7236 RemoveSpellsCausingAura(SPELL_AURA_MOD_UNATTACKABLE);
7238 // in fighting already
7239 if (m_attacking)
7241 if (m_attacking == victim)
7243 // switch to melee attack from ranged/magic
7244 if( meleeAttack && !hasUnitState(UNIT_STAT_MELEE_ATTACKING) )
7246 addUnitState(UNIT_STAT_MELEE_ATTACKING);
7247 SendAttackStart(victim);
7248 return true;
7250 return false;
7253 // remove old target data
7254 AttackStop(true);
7256 // new battle
7257 else
7259 // set position before any AI calls/assistance
7260 if(GetTypeId()==TYPEID_UNIT)
7261 ((Creature*)this)->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ());
7264 //Set our target
7265 SetUInt64Value(UNIT_FIELD_TARGET, victim->GetGUID());
7267 if(meleeAttack)
7268 addUnitState(UNIT_STAT_MELEE_ATTACKING);
7270 m_attacking = victim;
7271 m_attacking->_addAttacker(this);
7273 if(GetTypeId()==TYPEID_UNIT)
7275 WorldPacket data(SMSG_AI_REACTION, 12);
7276 data << uint64(GetGUID());
7277 data << uint32(AI_REACTION_AGGRO); // Aggro sound
7278 ((WorldObject*)this)->SendMessageToSet(&data, true);
7280 ((Creature*)this)->CallAssistance();
7283 // delay offhand weapon attack to next attack time
7284 if(haveOffhandWeapon())
7285 resetAttackTimer(OFF_ATTACK);
7287 if(meleeAttack)
7288 SendAttackStart(victim);
7290 return true;
7293 bool Unit::AttackStop(bool targetSwitch /*=false*/)
7295 if (!m_attacking)
7296 return false;
7298 Unit* victim = m_attacking;
7300 m_attacking->_removeAttacker(this);
7301 m_attacking = NULL;
7303 //Clear our target
7304 SetUInt64Value(UNIT_FIELD_TARGET, 0);
7306 clearUnitState(UNIT_STAT_MELEE_ATTACKING);
7308 InterruptSpell(CURRENT_MELEE_SPELL);
7310 // reset only at real combat stop
7311 if(!targetSwitch && GetTypeId()==TYPEID_UNIT )
7313 ((Creature*)this)->SetNoCallAssistance(false);
7314 ((Creature*)this)->SetNoSearchAssistance(false);
7317 SendAttackStop(victim);
7319 return true;
7322 void Unit::CombatStop(bool includingCast)
7324 if (includingCast && IsNonMeleeSpellCasted(false))
7325 InterruptNonMeleeSpells(false);
7327 AttackStop();
7328 RemoveAllAttackers();
7329 if( GetTypeId()==TYPEID_PLAYER )
7330 ((Player*)this)->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel
7331 ClearInCombat();
7334 void Unit::CombatStopWithPets(bool includingCast)
7336 CombatStop(includingCast);
7337 if(Pet* pet = GetPet())
7338 pet->CombatStop(includingCast);
7339 if(Unit* charm = GetCharm())
7340 charm->CombatStop(includingCast);
7341 if(GetTypeId()==TYPEID_PLAYER)
7343 GuardianPetList const& guardians = ((Player*)this)->GetGuardians();
7344 for(GuardianPetList::const_iterator itr = guardians.begin(); itr != guardians.end(); ++itr)
7345 if(Unit* guardian = Unit::GetUnit(*this,*itr))
7346 guardian->CombatStop(includingCast);
7350 bool Unit::isAttackingPlayer() const
7352 if(hasUnitState(UNIT_STAT_ATTACK_PLAYER))
7353 return true;
7355 Pet* pet = GetPet();
7356 if(pet && pet->isAttackingPlayer())
7357 return true;
7359 Unit* charmed = GetCharm();
7360 if(charmed && charmed->isAttackingPlayer())
7361 return true;
7363 for (int8 i = 0; i < MAX_TOTEM; ++i)
7365 if(m_TotemSlot[i])
7367 Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]);
7368 if(totem && totem->isAttackingPlayer())
7369 return true;
7373 return false;
7376 void Unit::RemoveAllAttackers()
7378 while (!m_attackers.empty())
7380 AttackerSet::iterator iter = m_attackers.begin();
7381 if(!(*iter)->AttackStop())
7383 sLog.outError("WORLD: Unit has an attacker that isn't attacking it!");
7384 m_attackers.erase(iter);
7389 void Unit::ModifyAuraState(AuraState flag, bool apply)
7391 if (apply)
7393 if (!HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)))
7395 SetFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
7396 if(GetTypeId() == TYPEID_PLAYER)
7398 const PlayerSpellMap& sp_list = ((Player*)this)->GetSpellMap();
7399 for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
7401 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
7402 SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first);
7403 if (!spellInfo || !IsPassiveSpell(itr->first)) continue;
7404 if (spellInfo->CasterAuraState == flag)
7405 CastSpell(this, itr->first, true, NULL);
7410 else
7412 if (HasFlag(UNIT_FIELD_AURASTATE,1<<(flag-1)))
7414 RemoveFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
7416 if (flag != AURA_STATE_ENRAGE) // enrage aura state triggering continues auras
7418 Unit::AuraMap& tAuras = GetAuras();
7419 for (Unit::AuraMap::iterator itr = tAuras.begin(); itr != tAuras.end();)
7421 SpellEntry const* spellProto = (*itr).second->GetSpellProto();
7422 if (spellProto->CasterAuraState == flag)
7424 // exceptions (applied at state but not removed at state change)
7425 // Rampage
7426 if(spellProto->SpellIconID==2006 && spellProto->SpellFamilyName==SPELLFAMILY_WARRIOR && spellProto->SpellFamilyFlags==0x100000)
7428 ++itr;
7429 continue;
7432 RemoveAura(itr);
7434 else
7435 ++itr;
7442 Unit *Unit::GetOwner() const
7444 if(uint64 ownerid = GetOwnerGUID())
7445 return ObjectAccessor::GetUnit(*this, ownerid);
7446 return NULL;
7449 Unit *Unit::GetCharmer() const
7451 if(uint64 charmerid = GetCharmerGUID())
7452 return ObjectAccessor::GetUnit(*this, charmerid);
7453 return NULL;
7456 Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself()
7458 uint64 guid = GetCharmerOrOwnerGUID();
7459 if(IS_PLAYER_GUID(guid))
7460 return ObjectAccessor::GetPlayer(*this, guid);
7462 return GetTypeId()==TYPEID_PLAYER ? (Player*)this : NULL;
7465 Pet* Unit::GetPet() const
7467 if(uint64 pet_guid = GetPetGUID())
7469 if(Pet* pet = ObjectAccessor::GetPet(pet_guid))
7470 return pet;
7472 sLog.outError("Unit::GetPet: Pet %u not exist.",GUID_LOPART(pet_guid));
7473 const_cast<Unit*>(this)->SetPet(0);
7476 return NULL;
7479 Unit* Unit::GetCharm() const
7481 if(uint64 charm_guid = GetCharmGUID())
7483 if(Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid))
7484 return pet;
7486 sLog.outError("Unit::GetCharm: Charmed creature %u not exist.",GUID_LOPART(charm_guid));
7487 const_cast<Unit*>(this)->SetCharm(NULL);
7490 return NULL;
7493 float Unit::GetCombatDistance( const Unit* target ) const
7495 float radius = target->GetFloatValue(UNIT_FIELD_COMBATREACH) + GetFloatValue(UNIT_FIELD_COMBATREACH);
7496 float dx = GetPositionX() - target->GetPositionX();
7497 float dy = GetPositionY() - target->GetPositionY();
7498 float dz = GetPositionZ() - target->GetPositionZ();
7499 float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - radius;
7500 return ( dist > 0 ? dist : 0);
7503 void Unit::SetPet(Pet* pet)
7505 SetUInt64Value(UNIT_FIELD_SUMMON, pet ? pet->GetGUID() : 0);
7507 // FIXME: hack, speed must be set only at follow
7508 if(pet)
7509 for(int i = 0; i < MAX_MOVE_TYPE; ++i)
7510 pet->SetSpeed(UnitMoveType(i), m_speed_rate[i], true);
7513 void Unit::SetCharm(Unit* pet)
7515 SetUInt64Value(UNIT_FIELD_CHARM, pet ? pet->GetGUID() : 0);
7517 if(GetTypeId() == TYPEID_PLAYER)
7518 ((Player*)this)->m_mover = pet ? pet : this;
7521 void Unit::UnsummonAllTotems()
7523 for (int8 i = 0; i < MAX_TOTEM; ++i)
7525 if(!m_TotemSlot[i])
7526 continue;
7528 Creature *OldTotem = GetMap()->GetCreature(m_TotemSlot[i]);
7529 if (OldTotem && OldTotem->isTotem())
7530 ((Totem*)OldTotem)->UnSummon();
7534 int32 Unit::DealHeal(Unit *pVictim, uint32 addhealth, SpellEntry const *spellProto, bool critical)
7536 int32 gain = pVictim->ModifyHealth(int32(addhealth));
7538 if (GetTypeId()==TYPEID_PLAYER)
7540 SendHealSpellLog(pVictim, spellProto->Id, addhealth, critical);
7542 if (BattleGround *bg = ((Player*)this)->GetBattleGround())
7543 bg->UpdatePlayerScore((Player*)this, SCORE_HEALING_DONE, gain);
7545 // use the actual gain, as the overheal shall not be counted, skip gain 0 (it ignored anyway in to criteria)
7546 if (gain)
7547 ((Player*)this)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE, gain, 0, pVictim);
7549 ((Player*)this)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED, addhealth);
7552 if (pVictim->GetTypeId()==TYPEID_PLAYER)
7554 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED, gain);
7555 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED, addhealth);
7558 return gain;
7561 Unit* Unit::SelectMagnetTarget(Unit *victim, SpellEntry const *spellInfo)
7563 if(!victim)
7564 return NULL;
7566 // Magic case
7567 if(spellInfo && (spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC))
7569 Unit::AuraList const& magnetAuras = victim->GetAurasByType(SPELL_AURA_SPELL_MAGNET);
7570 for(Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
7571 if(Unit* magnet = (*itr)->GetCaster())
7572 if(magnet->IsWithinLOSInMap(this) && magnet->isAlive())
7573 return magnet;
7575 // Melee && ranged case
7576 else
7578 AuraList const& hitTriggerAuras = victim->GetAurasByType(SPELL_AURA_ADD_CASTER_HIT_TRIGGER);
7579 for(AuraList::const_iterator i = hitTriggerAuras.begin(); i != hitTriggerAuras.end(); ++i)
7580 if(Unit* magnet = (*i)->GetCaster())
7581 if(magnet->isAlive() && magnet->IsWithinLOSInMap(this))
7582 if(roll_chance_i((*i)->GetModifier()->m_amount))
7583 return magnet;
7586 return victim;
7589 void Unit::SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, bool critical)
7591 // we guess size
7592 WorldPacket data(SMSG_SPELLHEALLOG, (8+8+4+4+1));
7593 data.append(pVictim->GetPackGUID());
7594 data.append(GetPackGUID());
7595 data << uint32(SpellID);
7596 data << uint32(Damage);
7597 data << uint32(0); // over healing?
7598 data << uint8(critical ? 1 : 0);
7599 data << uint8(0); // unused in client?
7600 SendMessageToSet(&data, true);
7603 void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
7605 WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1));
7606 data.append(pVictim->GetPackGUID());
7607 data.append(GetPackGUID());
7608 data << uint32(SpellID);
7609 data << uint32(powertype);
7610 data << uint32(Damage);
7611 SendMessageToSet(&data, true);
7614 uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack)
7616 if(!spellProto || !pVictim || damagetype==DIRECT_DAMAGE )
7617 return pdamage;
7619 // For totems get damage bonus from owner (statue isn't totem in fact)
7620 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
7622 if(Unit* owner = GetOwner())
7623 return owner->SpellDamageBonus(pVictim, spellProto, pdamage, damagetype);
7626 // Taken/Done total percent damage auras
7627 float DoneTotalMod = 1.0f;
7628 float TakenTotalMod = 1.0f;
7629 int32 DoneTotal = 0;
7630 int32 TakenTotal = 0;
7632 // ..done
7633 // Pet damage
7634 if( GetTypeId() == TYPEID_UNIT && !((Creature*)this)->isPet() )
7635 DoneTotalMod *= ((Creature*)this)->GetSpellDamageMod(((Creature*)this)->GetCreatureInfo()->rank);
7637 AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
7638 for(AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
7640 if( ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto)) &&
7641 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
7642 // -1 == any item class (not wand then)
7643 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
7644 // 0 == any inventory type (not wand then)
7646 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7650 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7651 // Add flat bonus from spell damage versus
7652 DoneTotal += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask);
7653 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
7654 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
7655 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7656 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7658 // done scripted mod (take it from owner)
7659 Unit *owner = GetOwner();
7660 if (!owner) owner = this;
7661 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7662 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7664 if (!(*i)->isAffectedOnSpell(spellProto))
7665 continue;
7666 switch((*i)->GetModifier()->m_miscvalue)
7668 case 4920: // Molten Fury
7669 case 4919:
7670 case 6917: // Death's Embrace
7671 case 6926:
7672 case 6928:
7674 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7675 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7676 break;
7678 // Soul Siphon
7679 case 4992:
7680 case 4993:
7682 // effect 1 m_amount
7683 int32 maxPercent = (*i)->GetModifier()->m_amount;
7684 // effect 0 m_amount
7685 int32 stepPercent = CalculateSpellDamage((*i)->GetSpellProto(), 0, (*i)->GetSpellProto()->EffectBasePoints[0], this);
7686 // count affliction effects and calc additional damage in percentage
7687 int32 modPercent = 0;
7688 AuraMap const& victimAuras = pVictim->GetAuras();
7689 for (AuraMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
7691 SpellEntry const* m_spell = itr->second->GetSpellProto();
7692 if (m_spell->SpellFamilyName != SPELLFAMILY_WARLOCK || !(m_spell->SpellFamilyFlags & 0x0004071B8044C402LL))
7693 continue;
7694 modPercent += stepPercent * itr->second->GetStackAmount();
7695 if (modPercent >= maxPercent)
7697 modPercent = maxPercent;
7698 break;
7701 DoneTotalMod *= (modPercent+100.0f)/100.0f;
7702 break;
7704 case 6916: // Death's Embrace
7705 case 6925:
7706 case 6927:
7707 if (HasAuraState(AURA_STATE_HEALTHLESS_20_PERCENT))
7708 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7709 break;
7710 case 5481: // Starfire Bonus
7712 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x0000000000200002LL))
7713 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7714 break;
7716 case 4418: // Increased Shock Damage
7717 case 4554: // Increased Lightning Damage
7718 case 4555: // Improved Moonfire
7719 case 5142: // Increased Lightning Damage
7720 case 5147: // Improved Consecration / Libram of Resurgence
7721 case 5148: // Idol of the Shooting Star
7722 case 6008: // Increased Lightning Damage / Totem of Hex
7724 DoneTotal+=(*i)->GetModifier()->m_amount;
7725 break;
7727 // Tundra Stalker
7728 // Merciless Combat
7729 case 7277:
7731 // Merciless Combat
7732 if ((*i)->GetSpellProto()->SpellIconID == 2656)
7734 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7735 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7737 else // Tundra Stalker
7739 if (pVictim->GetAura(SPELL_AURA_DUMMY, SPELLFAMILY_DEATHKNIGHT, 0x0400000000000000LL))
7740 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7741 break;
7743 break;
7745 case 7293: // Rage of Rivendare
7747 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0x0200000000000000LL))
7748 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7749 break;
7751 // Twisted Faith
7752 case 7377:
7754 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x0000000000008000LL, 0, GetGUID()))
7755 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7756 break;
7758 // Marked for Death
7759 case 7598:
7760 case 7599:
7761 case 7600:
7762 case 7601:
7763 case 7602:
7765 if (pVictim->GetAura(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, 0x0000000000000400LL))
7766 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7767 break;
7772 // Custom scripted damage
7773 // Ice Lance
7774 if (spellProto->SpellFamilyName == SPELLFAMILY_MAGE && spellProto->SpellIconID == 186)
7776 if (pVictim->isFrozen())
7777 DoneTotalMod *= 3.0f;
7780 // ..taken
7781 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
7782 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
7783 if( (*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto) )
7784 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7786 // .. taken pct: dummy auras
7787 if (pVictim->GetTypeId() == TYPEID_PLAYER)
7789 //Cheat Death
7790 if (Aura *dummy = pVictim->GetDummyAura(45182))
7792 float mod = -((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2*4;
7793 if (mod < dummy->GetModifier()->m_amount)
7794 mod = dummy->GetModifier()->m_amount;
7795 TakenTotalMod *= (mod+100.0f)/100.0f;
7799 // From caster spells
7800 AuraList const& mOwnerTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_FROM_CASTER);
7801 for(AuraList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i)
7802 if( (*i)->GetCasterGUID() == GetGUID() && (*i)->isAffectedOnSpell(spellProto))
7803 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7805 // Mod damage from spell mechanic
7806 uint32 mechanicMask = GetAllSpellMechanicMask(spellProto);
7807 if (mechanicMask)
7809 AuraList const& mDamageDoneMechanic = pVictim->GetAurasByType(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT);
7810 for(AuraList::const_iterator i = mDamageDoneMechanic.begin();i != mDamageDoneMechanic.end(); ++i)
7811 if(mechanicMask & uint32(1<<((*i)->GetModifier()->m_miscvalue)))
7812 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7815 // Taken/Done fixed damage bonus auras
7816 int32 DoneAdvertisedBenefit = SpellBaseDamageBonus(GetSpellSchoolMask(spellProto));
7817 int32 TakenAdvertisedBenefit = SpellBaseDamageBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
7819 // Pets just add their bonus damage to their spell damage
7820 // note that their spell damage is just gain of their own auras
7821 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
7822 DoneAdvertisedBenefit += ((Pet*)this)->GetBonusDamage();
7824 float LvlPenalty = CalculateLevelPenalty(spellProto);
7825 // Spellmod SpellDamage
7826 float SpellModSpellDamage = 100.0f;
7827 if(Player* modOwner = GetSpellModOwner())
7828 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_SPELL_BONUS_DAMAGE,SpellModSpellDamage);
7829 SpellModSpellDamage /= 100.0f;
7831 // Check for table values
7832 SpellBonusEntry const* bonus = spellmgr.GetSpellBonusData(spellProto->Id);
7833 if (bonus)
7835 float coeff;
7836 if (damagetype == DOT)
7837 coeff = bonus->dot_damage * LvlPenalty * stack;
7838 else
7839 coeff = bonus->direct_damage * LvlPenalty * stack;
7841 if (bonus->ap_bonus)
7842 DoneTotal += int32(bonus->ap_bonus * GetTotalAttackPowerValue(BASE_ATTACK) * stack);
7844 DoneTotal += int32(DoneAdvertisedBenefit * coeff * SpellModSpellDamage);
7845 TakenTotal += int32(TakenAdvertisedBenefit * coeff);
7847 // Default calculation
7848 else if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
7850 // Damage Done from spell damage bonus
7851 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
7852 // Damage over Time spells bonus calculation
7853 float DotFactor = 1.0f;
7854 if(damagetype == DOT)
7856 int32 DotDuration = GetSpellDuration(spellProto);
7857 // 200% limit
7858 if(DotDuration > 0)
7860 if(DotDuration > 30000) DotDuration = 30000;
7861 if(!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
7862 int x = 0;
7863 for(int j = 0; j < 3; j++)
7865 if( spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
7866 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
7867 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
7869 x = j;
7870 break;
7873 int32 DotTicks = 6;
7874 if(spellProto->EffectAmplitude[x] != 0)
7875 DotTicks = DotDuration / spellProto->EffectAmplitude[x];
7876 if(DotTicks)
7878 DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
7879 TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
7883 // Distribute Damage over multiple effects, reduce by AoE
7884 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
7885 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
7886 for(int j = 0; j < 3; ++j)
7888 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
7889 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
7891 CastingTime /= 2;
7892 break;
7895 DoneTotal += int32(DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * SpellModSpellDamage);
7896 TakenTotal+= int32(TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty);
7899 float tmpDamage = (pdamage + DoneTotal) * DoneTotalMod;
7900 // apply spellmod to Done damage (flat and pct)
7901 if(Player* modOwner = GetSpellModOwner())
7902 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
7904 tmpDamage = (tmpDamage + TakenTotal) * TakenTotalMod;
7906 return tmpDamage > 0 ? uint32(tmpDamage) : 0;
7909 int32 Unit::SpellBaseDamageBonus(SpellSchoolMask schoolMask)
7911 int32 DoneAdvertisedBenefit = 0;
7913 // ..done
7914 AuraList const& mDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
7915 for(AuraList::const_iterator i = mDamageDone.begin();i != mDamageDone.end(); ++i)
7916 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0 &&
7917 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
7918 // -1 == any item class (not wand then)
7919 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
7920 // 0 == any inventory type (not wand then)
7921 DoneAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7923 if (GetTypeId() == TYPEID_PLAYER)
7925 // Base value
7926 DoneAdvertisedBenefit +=((Player*)this)->GetBaseSpellDamageBonus();
7928 // Damage bonus from stats
7929 AuraList const& mDamageDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT);
7930 for(AuraList::const_iterator i = mDamageDoneOfStatPercent.begin();i != mDamageDoneOfStatPercent.end(); ++i)
7932 if((*i)->GetModifier()->m_miscvalue & schoolMask)
7934 // stat used stored in miscValueB for this aura
7935 Stats usedStat = Stats((*i)->GetMiscBValue());
7936 DoneAdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
7939 // ... and attack power
7940 AuraList const& mDamageDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER);
7941 for(AuraList::const_iterator i =mDamageDonebyAP.begin();i != mDamageDonebyAP.end(); ++i)
7942 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
7943 DoneAdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
7946 return DoneAdvertisedBenefit;
7949 int32 Unit::SpellBaseDamageBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
7951 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7953 int32 TakenAdvertisedBenefit = 0;
7954 // ..done (for creature type by mask) in taken
7955 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
7956 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
7957 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7958 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7960 // ..taken
7961 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
7962 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
7963 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
7964 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7966 return TakenAdvertisedBenefit;
7969 bool Unit::isSpellCrit(Unit *pVictim, SpellEntry const *spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType)
7971 // not critting spell
7972 if((spellProto->AttributesEx2 & SPELL_ATTR_EX2_CANT_CRIT))
7973 return false;
7975 float crit_chance = 0.0f;
7976 switch(spellProto->DmgClass)
7978 case SPELL_DAMAGE_CLASS_NONE:
7979 return false;
7980 case SPELL_DAMAGE_CLASS_MAGIC:
7982 if (schoolMask & SPELL_SCHOOL_MASK_NORMAL)
7983 crit_chance = 0.0f;
7984 // For other schools
7985 else if (GetTypeId() == TYPEID_PLAYER)
7986 crit_chance = GetFloatValue( PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask));
7987 else
7989 crit_chance = m_baseSpellCritChance;
7990 crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
7992 // taken
7993 if (pVictim)
7995 if (!IsPositiveSpell(spellProto->Id))
7997 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE
7998 crit_chance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask);
7999 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE
8000 crit_chance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
8001 // Modify by player victim resilience
8002 if (pVictim->GetTypeId() == TYPEID_PLAYER)
8003 crit_chance -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
8006 // scripted (increase crit chance ... against ... target by x%
8007 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8008 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
8010 if (!((*i)->isAffectedOnSpell(spellProto)))
8011 continue;
8012 switch((*i)->GetModifier()->m_miscvalue)
8014 case 849: if (pVictim->isFrozen()) crit_chance+= 17.0f; break; //Shatter Rank 1
8015 case 910: if (pVictim->isFrozen()) crit_chance+= 34.0f; break; //Shatter Rank 2
8016 case 911: if (pVictim->isFrozen()) crit_chance+= 50.0f; break; //Shatter Rank 3
8017 case 7917: // Glyph of Shadowburn
8018 if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
8019 crit_chance+=(*i)->GetModifier()->m_amount;
8020 break;
8021 case 7997: // Renewed Hope
8022 case 7998:
8023 if (pVictim->HasAura(6788))
8024 crit_chance+=(*i)->GetModifier()->m_amount;
8025 break;
8026 case 21: // Test of Faith
8027 case 6935:
8028 case 6918:
8029 if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
8030 crit_chance+=(*i)->GetModifier()->m_amount;
8031 break;
8032 default:
8033 break;
8036 // Custom crit by class
8037 switch(spellProto->SpellFamilyName)
8039 case SPELLFAMILY_PALADIN:
8040 // Sacred Shield
8041 if (spellProto->SpellFamilyFlags & 0x0000000040000000LL)
8043 Aura *aura = pVictim->GetDummyAura(58597);
8044 if (aura && aura->GetCasterGUID() == GetGUID())
8045 crit_chance+=aura->GetModifier()->m_amount;
8046 break;
8048 break;
8049 case SPELLFAMILY_SHAMAN:
8050 // Lava Burst
8051 if (spellProto->SpellFamilyFlags & 0x0000100000000000LL)
8053 if (Aura *flameShock = pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, 0x0000000010000000LL, 0, GetGUID()))
8055 // Consume shock aura if not have Glyph of Flame Shock
8056 if (!GetAura(55447, 0))
8057 pVictim->RemoveAurasByCasterSpell(flameShock->GetId(), GetGUID());
8058 return true;
8060 break;
8062 break;
8066 break;
8068 case SPELL_DAMAGE_CLASS_MELEE:
8069 case SPELL_DAMAGE_CLASS_RANGED:
8071 if (pVictim)
8073 crit_chance = GetUnitCriticalChance(attackType, pVictim);
8074 crit_chance+= GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
8076 break;
8078 default:
8079 return false;
8081 // percent done
8082 // only players use intelligence for critical chance computations
8083 if(Player* modOwner = GetSpellModOwner())
8084 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance);
8086 crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f;
8087 if (roll_chance_f(crit_chance))
8088 return true;
8089 return false;
8092 uint32 Unit::SpellCriticalDamageBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
8094 // Calculate critical bonus
8095 int32 crit_bonus;
8096 switch(spellProto->DmgClass)
8098 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
8099 case SPELL_DAMAGE_CLASS_RANGED:
8100 // TODO: write here full calculation for melee/ranged spells
8101 crit_bonus = damage;
8102 break;
8103 default:
8104 crit_bonus = damage / 2; // for spells is 50%
8105 break;
8108 // adds additional damage to crit_bonus (from talents)
8109 if(Player* modOwner = GetSpellModOwner())
8110 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
8112 if(pVictim)
8114 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8115 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
8118 if(crit_bonus > 0)
8119 damage += crit_bonus;
8121 return damage;
8124 uint32 Unit::SpellCriticalHealingBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
8126 // Calculate critical bonus
8127 int32 crit_bonus;
8128 switch(spellProto->DmgClass)
8130 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
8131 case SPELL_DAMAGE_CLASS_RANGED:
8132 // TODO: write here full calculation for melee/ranged spells
8133 crit_bonus = damage;
8134 break;
8135 default:
8136 crit_bonus = damage / 2; // for spells is 50%
8137 break;
8140 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplier(SPELL_AURA_MOD_CRITICAL_HEALING_BONUS));
8142 if(pVictim)
8144 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8145 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
8148 if(crit_bonus > 0)
8149 damage += crit_bonus;
8151 return damage;
8154 uint32 Unit::SpellHealingBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 healamount, DamageEffectType damagetype, uint32 stack)
8156 // No heal amount for this class spells
8157 if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE)
8158 return healamount;
8160 // For totems get healing bonus from owner (statue isn't totem in fact)
8161 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
8162 if(Unit* owner = GetOwner())
8163 return owner->SpellHealingBonus(pVictim, spellProto, healamount, damagetype, stack);
8165 // Healing Done
8166 // Taken/Done total percent damage auras
8167 float DoneTotalMod = 1.0f;
8168 float TakenTotalMod = 1.0f;
8169 int32 DoneTotal = 0;
8170 int32 TakenTotal = 0;
8172 // Healing done percent
8173 AuraList const& mHealingDonePct = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT);
8174 for(AuraList::const_iterator i = mHealingDonePct.begin();i != mHealingDonePct.end(); ++i)
8175 DoneTotalMod *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
8177 // done scripted mod (take it from owner)
8178 Unit *owner = GetOwner();
8179 if (!owner) owner = this;
8180 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8181 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
8183 if (!(*i)->isAffectedOnSpell(spellProto))
8184 continue;
8185 switch((*i)->GetModifier()->m_miscvalue)
8187 case 4415: // Increased Rejuvenation Healing
8188 case 4953:
8189 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
8190 DoneTotal+=(*i)->GetModifier()->m_amount;
8191 break;
8192 case 7997: // Renewed Hope
8193 case 7998:
8194 if (pVictim->HasAura(6788))
8195 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
8196 break;
8197 case 21: // Test of Faith
8198 case 6935:
8199 case 6918:
8200 if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
8201 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
8202 break;
8203 case 7798: // Glyph of Regrowth
8205 if (pVictim->GetAura(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, 0x0000000000000040LL))
8206 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8207 break;
8209 case 8477: // Nourish Heal Boost
8211 int32 stepPercent = (*i)->GetModifier()->m_amount;
8212 int32 modPercent = 0;
8213 AuraMap const& victimAuras = pVictim->GetAuras();
8214 for (AuraMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
8216 if (itr->second->GetCasterGUID()!=GetGUID())
8217 continue;
8218 SpellEntry const* m_spell = itr->second->GetSpellProto();
8219 if ( m_spell->SpellFamilyName != SPELLFAMILY_DRUID ||
8220 !(m_spell->SpellFamilyFlags & 0x0000001000000050LL))
8221 continue;
8222 modPercent += stepPercent * itr->second->GetStackAmount();
8224 DoneTotalMod *= (modPercent+100.0f)/100.0f;
8225 break;
8227 case 7871: // Glyph of Lesser Healing Wave
8229 if (pVictim->GetAura(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, 0x0000040000000000LL, 0, GetGUID()))
8230 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8231 break;
8233 default:
8234 break;
8238 // Taken/Done fixed damage bonus auras
8239 int32 DoneAdvertisedBenefit = SpellBaseHealingBonus(GetSpellSchoolMask(spellProto));
8240 int32 TakenAdvertisedBenefit = SpellBaseHealingBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
8242 float LvlPenalty = CalculateLevelPenalty(spellProto);
8243 // Spellmod SpellDamage
8244 float SpellModSpellDamage = 100.0f;
8245 if(Player* modOwner = GetSpellModOwner())
8246 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_SPELL_BONUS_DAMAGE, SpellModSpellDamage);
8247 SpellModSpellDamage /= 100.0f;
8249 // Check for table values
8250 SpellBonusEntry const* bonus = spellmgr.GetSpellBonusData(spellProto->Id);
8251 if (bonus)
8253 float coeff;
8254 if (damagetype == DOT)
8255 coeff = bonus->dot_damage * LvlPenalty * stack;
8256 else
8257 coeff = bonus->direct_damage * LvlPenalty * stack;
8259 if (bonus->ap_bonus)
8260 DoneTotal += int32(bonus->ap_bonus * GetTotalAttackPowerValue(BASE_ATTACK) * stack);
8262 DoneTotal += int32(DoneAdvertisedBenefit * coeff * SpellModSpellDamage);
8263 TakenTotal += int32(TakenAdvertisedBenefit * coeff);
8265 // Default calculation
8266 else if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
8268 // Damage Done from spell damage bonus
8269 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
8270 // Damage over Time spells bonus calculation
8271 float DotFactor = 1.0f;
8272 if(damagetype == DOT)
8274 int32 DotDuration = GetSpellDuration(spellProto);
8275 // 200% limit
8276 if(DotDuration > 0)
8278 if(DotDuration > 30000) DotDuration = 30000;
8279 if(!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
8280 int x = 0;
8281 for(int j = 0; j < 3; j++)
8283 if( spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
8284 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
8285 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
8287 x = j;
8288 break;
8291 int32 DotTicks = 6;
8292 if(spellProto->EffectAmplitude[x] != 0)
8293 DotTicks = DotDuration / spellProto->EffectAmplitude[x];
8294 if(DotTicks)
8296 DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
8297 TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
8301 // Distribute Damage over multiple effects, reduce by AoE
8302 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
8303 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
8304 for(int j = 0; j < 3; ++j)
8306 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
8307 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
8309 CastingTime /= 2;
8310 break;
8313 DoneTotal += int32(DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * SpellModSpellDamage * 1.88f);
8314 TakenTotal += int32(TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * 1.88f);
8317 // use float as more appropriate for negative values and percent applying
8318 float heal = (healamount + DoneTotal)*DoneTotalMod;
8319 // apply spellmod to Done amount
8320 if(Player* modOwner = GetSpellModOwner())
8321 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal);
8323 // Taken mods
8324 // Healing Wave cast
8325 if (spellProto->SpellFamilyName == SPELLFAMILY_SHAMAN && spellProto->SpellFamilyFlags & 0x0000000000000040LL)
8327 // Search for Healing Way on Victim
8328 Unit::AuraList const& auraDummy = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
8329 for(Unit::AuraList::const_iterator itr = auraDummy.begin(); itr!=auraDummy.end(); ++itr)
8330 if((*itr)->GetId() == 29203)
8331 TakenTotalMod *= ((*itr)->GetModifier()->m_amount+100.0f) / 100.0f;
8334 // Healing taken percent
8335 float minval = pVictim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
8336 if(minval)
8337 TakenTotalMod *= (100.0f + minval) / 100.0f;
8339 float maxval = pVictim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
8340 if(maxval)
8341 TakenTotalMod *= (100.0f + maxval) / 100.0f;
8343 AuraList const& mHealingGet= pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING_RECEIVED);
8344 for(AuraList::const_iterator i = mHealingGet.begin(); i != mHealingGet.end(); ++i)
8345 if ((*i)->isAffectedOnSpell(spellProto))
8346 TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
8348 heal = (heal + TakenTotal) * TakenTotalMod;
8350 return heal < 0 ? 0 : uint32(heal);
8353 int32 Unit::SpellBaseHealingBonus(SpellSchoolMask schoolMask)
8355 int32 AdvertisedBenefit = 0;
8357 AuraList const& mHealingDone = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE);
8358 for(AuraList::const_iterator i = mHealingDone.begin();i != mHealingDone.end(); ++i)
8359 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
8360 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
8362 // Healing bonus of spirit, intellect and strength
8363 if (GetTypeId() == TYPEID_PLAYER)
8365 // Base value
8366 AdvertisedBenefit +=((Player*)this)->GetBaseSpellHealingBonus();
8368 // Healing bonus from stats
8369 AuraList const& mHealingDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT);
8370 for(AuraList::const_iterator i = mHealingDoneOfStatPercent.begin();i != mHealingDoneOfStatPercent.end(); ++i)
8372 // stat used dependent from misc value (stat index)
8373 Stats usedStat = Stats((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()]);
8374 AdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
8377 // ... and attack power
8378 AuraList const& mHealingDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER);
8379 for(AuraList::const_iterator i = mHealingDonebyAP.begin();i != mHealingDonebyAP.end(); ++i)
8380 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
8381 AdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
8383 return AdvertisedBenefit;
8386 int32 Unit::SpellBaseHealingBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
8388 int32 AdvertisedBenefit = 0;
8389 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING);
8390 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
8391 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
8392 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
8393 return AdvertisedBenefit;
8396 bool Unit::IsImmunedToDamage(SpellSchoolMask shoolMask)
8398 //If m_immuneToSchool type contain this school type, IMMUNE damage.
8399 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
8400 for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
8401 if(itr->type & shoolMask)
8402 return true;
8404 //If m_immuneToDamage type contain magic, IMMUNE damage.
8405 SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
8406 for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
8407 if(itr->type & shoolMask)
8408 return true;
8410 return false;
8413 bool Unit::IsImmunedToSpell(SpellEntry const* spellInfo)
8415 if (!spellInfo)
8416 return false;
8418 //FIX ME this hack: don't get feared if stunned
8419 if (spellInfo->Mechanic == MECHANIC_FEAR )
8421 if ( hasUnitState(UNIT_STAT_STUNNED) )
8422 return true;
8425 //TODO add spellEffect immunity checks!, player with flag in bg is imune to imunity buffs from other friendly players!
8426 //SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_EFFECT];
8428 SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_DISPEL];
8429 for(SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr)
8430 if(itr->type == spellInfo->Dispel)
8431 return true;
8433 if( !(spellInfo->AttributesEx & SPELL_ATTR_EX_UNAFFECTED_BY_SCHOOL_IMMUNE) && // unaffected by school immunity
8434 !(spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)) // can remove immune (by dispell or immune it)
8436 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
8437 for(SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
8438 if( !(IsPositiveSpell(itr->spellId) && IsPositiveSpell(spellInfo->Id)) &&
8439 (itr->type & GetSpellSchoolMask(spellInfo)) )
8440 return true;
8443 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
8444 for(SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
8446 if(itr->type == spellInfo->Mechanic)
8448 return true;
8452 return false;
8455 bool Unit::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
8457 //If m_immuneToEffect type contain this effect type, IMMUNE effect.
8458 uint32 effect = spellInfo->Effect[index];
8459 SpellImmuneList const& effectList = m_spellImmune[IMMUNITY_EFFECT];
8460 for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr)
8461 if(itr->type == effect)
8462 return true;
8464 if(uint32 mechanic = spellInfo->EffectMechanic[index])
8466 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
8467 for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
8468 if(itr->type == mechanic)
8469 return true;
8472 if(uint32 aura = spellInfo->EffectApplyAuraName[index])
8474 SpellImmuneList const& list = m_spellImmune[IMMUNITY_STATE];
8475 for(SpellImmuneList::const_iterator itr = list.begin(); itr != list.end(); ++itr)
8476 if(itr->type == aura)
8477 return true;
8478 // Check for immune to application of harmful magical effects
8479 AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MOD_IMMUNE_AURA_APPLY_SCHOOL);
8480 for(AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
8481 if (spellInfo->Dispel == DISPEL_MAGIC && // Magic debuff
8482 ((*iter)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellInfo)) && // Check school
8483 !IsPositiveEffect(spellInfo->Id, index)) // Harmful
8484 return true;
8487 return false;
8490 bool Unit::IsDamageToThreatSpell(SpellEntry const * spellInfo) const
8492 if(!spellInfo)
8493 return false;
8495 uint32 family = spellInfo->SpellFamilyName;
8496 uint64 flags = spellInfo->SpellFamilyFlags;
8498 if((family == 5 && flags == 256) || //Searing Pain
8499 (family == 6 && flags == 8192) || //Mind Blast
8500 (family == 11 && flags == 1048576)) //Earth Shock
8501 return true;
8503 return false;
8506 void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage,WeaponAttackType attType, SpellEntry const *spellProto)
8508 if(!pVictim)
8509 return;
8511 if(*pdamage == 0)
8512 return;
8514 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8516 // Taken/Done fixed damage bonus auras
8517 int32 DoneFlatBenefit = 0;
8518 int32 TakenFlatBenefit = 0;
8520 // ..done (for creature type by mask) in taken
8521 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
8522 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
8523 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8524 DoneFlatBenefit += (*i)->GetModifier()->m_amount;
8526 // ..done
8527 // SPELL_AURA_MOD_DAMAGE_DONE included in weapon damage
8529 // ..done (base at attack power for marked target and base at attack power for creature type)
8530 int32 APbonus = 0;
8531 if(attType == RANGED_ATTACK)
8533 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS);
8535 // ..done (base at attack power and creature type)
8536 AuraList const& mCreatureAttackPower = GetAurasByType(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS);
8537 for(AuraList::const_iterator i = mCreatureAttackPower.begin();i != mCreatureAttackPower.end(); ++i)
8538 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8539 APbonus += (*i)->GetModifier()->m_amount;
8541 else
8543 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS);
8545 // ..done (base at attack power and creature type)
8546 AuraList const& mCreatureAttackPower = GetAurasByType(SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS);
8547 for(AuraList::const_iterator i = mCreatureAttackPower.begin();i != mCreatureAttackPower.end(); ++i)
8548 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8549 APbonus += (*i)->GetModifier()->m_amount;
8552 if (APbonus!=0) // Can be negative
8554 bool normalized = false;
8555 if(spellProto)
8557 for (uint8 i = 0; i<3;++i)
8559 if (spellProto->Effect[i] == SPELL_EFFECT_NORMALIZED_WEAPON_DMG)
8561 normalized = true;
8562 break;
8567 DoneFlatBenefit += int32(APbonus/14.0f * GetAPMultiplier(attType,normalized));
8570 // ..taken
8571 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
8572 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
8573 if((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask())
8574 TakenFlatBenefit += (*i)->GetModifier()->m_amount;
8576 if(attType!=RANGED_ATTACK)
8577 TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN);
8578 else
8579 TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN);
8581 // Done/Taken total percent damage auras
8582 float DoneTotalMod = 1.0f;
8583 float TakenTotalMod = 1.0f;
8585 // ..done
8586 // SPELL_AURA_MOD_DAMAGE_PERCENT_DONE included in weapon damage
8587 // SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT included in weapon damage
8589 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
8590 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
8591 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8592 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8594 // ..taken
8595 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
8596 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
8597 if((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask())
8598 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8600 // .. taken pct: dummy auras
8601 AuraList const& mDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
8602 for(AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
8604 switch((*i)->GetSpellProto()->SpellIconID)
8606 //Cheat Death
8607 case 2109:
8608 if((*i)->GetModifier()->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)
8610 if(pVictim->GetTypeId() != TYPEID_PLAYER)
8611 continue;
8612 float mod = ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f);
8613 if (mod < (*i)->GetModifier()->m_amount)
8614 mod = (*i)->GetModifier()->m_amount;
8615 TakenTotalMod *= (mod+100.0f)/100.0f;
8617 break;
8618 //Mangle
8619 case 2312:
8620 if(spellProto==NULL)
8621 break;
8622 // Should increase Shred (initial Damage of Lacerate and Rake handled in Spell::EffectSchoolDMG)
8623 if(spellProto->SpellFamilyName==SPELLFAMILY_DRUID && (spellProto->SpellFamilyFlags==0x00008000LL))
8624 TakenTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
8625 break;
8629 // .. taken pct: class scripts
8630 AuraList const& mclassScritAuras = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8631 for(AuraList::const_iterator i = mclassScritAuras.begin(); i != mclassScritAuras.end(); ++i)
8633 switch((*i)->GetMiscValue())
8635 case 6427: case 6428: // Dirty Deeds
8636 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
8638 Aura* eff0 = GetAura((*i)->GetId(),0);
8639 if(!eff0 || (*i)->GetEffIndex()!=1)
8641 sLog.outError("Spell structure of DD (%u) changed.",(*i)->GetId());
8642 continue;
8645 // effect 0 have expected value but in negative state
8646 TakenTotalMod *= (-eff0->GetModifier()->m_amount+100.0f)/100.0f;
8648 break;
8652 if(attType != RANGED_ATTACK)
8654 AuraList const& mModMeleeDamageTakenPercent = pVictim->GetAurasByType(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT);
8655 for(AuraList::const_iterator i = mModMeleeDamageTakenPercent.begin(); i != mModMeleeDamageTakenPercent.end(); ++i)
8656 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8658 else
8660 AuraList const& mModRangedDamageTakenPercent = pVictim->GetAurasByType(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT);
8661 for(AuraList::const_iterator i = mModRangedDamageTakenPercent.begin(); i != mModRangedDamageTakenPercent.end(); ++i)
8662 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8665 float tmpDamage = float(int32(*pdamage) + DoneFlatBenefit) * DoneTotalMod;
8667 // apply spellmod to Done damage
8668 if(spellProto)
8670 if(Player* modOwner = GetSpellModOwner())
8671 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, tmpDamage);
8674 tmpDamage = (tmpDamage + TakenFlatBenefit)*TakenTotalMod;
8676 // bonus result can be negative
8677 *pdamage = tmpDamage > 0 ? uint32(tmpDamage) : 0;
8680 void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply)
8682 if (apply)
8684 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(), next; itr != m_spellImmune[op].end(); itr = next)
8686 next = itr; ++next;
8687 if(itr->type == type)
8689 m_spellImmune[op].erase(itr);
8690 next = m_spellImmune[op].begin();
8693 SpellImmune Immune;
8694 Immune.spellId = spellId;
8695 Immune.type = type;
8696 m_spellImmune[op].push_back(Immune);
8698 else
8700 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(); itr != m_spellImmune[op].end(); ++itr)
8702 if(itr->spellId == spellId)
8704 m_spellImmune[op].erase(itr);
8705 break;
8712 void Unit::ApplySpellDispelImmunity(const SpellEntry * spellProto, DispelType type, bool apply)
8714 ApplySpellImmune(spellProto->Id,IMMUNITY_DISPEL, type, apply);
8716 if (apply && spellProto->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)
8717 RemoveAurasWithDispelType(type);
8720 float Unit::GetWeaponProcChance() const
8722 // normalized proc chance for weapon attack speed
8723 // (odd formula...)
8724 if(isAttackReady(BASE_ATTACK))
8725 return (GetAttackTime(BASE_ATTACK) * 1.8f / 1000.0f);
8726 else if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
8727 return (GetAttackTime(OFF_ATTACK) * 1.6f / 1000.0f);
8728 return 0;
8731 float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM) const
8733 // proc per minute chance calculation
8734 if (PPM <= 0) return 0.0f;
8735 uint32 result = uint32((WeaponSpeed * PPM) / 600.0f); // result is chance in percents (probability = Speed_in_sec * (PPM / 60))
8736 return result;
8739 void Unit::Mount(uint32 mount)
8741 if(!mount)
8742 return;
8744 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNTING);
8746 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount);
8748 SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
8750 // unsummon pet
8751 if(GetTypeId() == TYPEID_PLAYER)
8752 ((Player*)this)->UnsummonPetTemporaryIfAny();
8755 void Unit::Unmount()
8757 if(!IsMounted())
8758 return;
8760 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED);
8762 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
8763 RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
8765 // only resummon old pet if the player is already added to a map
8766 // this prevents adding a pet to a not created map which would otherwise cause a crash
8767 // (it could probably happen when logging in after a previous crash)
8768 if(GetTypeId() == TYPEID_PLAYER)
8769 ((Player*)this)->ResummonPetTemporaryUnSummonedIfAny();
8772 void Unit::SetInCombatWith(Unit* enemy)
8774 Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf();
8775 if(eOwner->IsPvP())
8777 SetInCombatState(true,enemy);
8778 return;
8781 //check for duel
8782 if(eOwner->GetTypeId() == TYPEID_PLAYER && ((Player*)eOwner)->duel)
8784 Unit const* myOwner = GetCharmerOrOwnerOrSelf();
8785 if(((Player const*)eOwner)->duel->opponent == myOwner)
8787 SetInCombatState(true,enemy);
8788 return;
8791 SetInCombatState(false,enemy);
8794 void Unit::SetInCombatState(bool PvP, Unit* enemy)
8796 // only alive units can be in combat
8797 if(!isAlive())
8798 return;
8800 if(PvP)
8801 m_CombatTimer = 5000;
8803 bool creatureNotInCombat = GetTypeId()==TYPEID_UNIT && !HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
8805 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
8807 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
8808 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
8810 if(creatureNotInCombat && ((Creature*)this)->AI())
8811 ((Creature*)this)->AI()->EnterCombat(enemy);
8814 void Unit::ClearInCombat()
8816 m_CombatTimer = 0;
8817 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
8819 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
8820 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
8822 // Player's state will be cleared in Player::UpdateContestedPvP
8823 if(GetTypeId()!=TYPEID_PLAYER)
8824 clearUnitState(UNIT_STAT_ATTACK_PLAYER);
8825 else
8826 ((Player*)this)->UpdatePotionCooldown();
8829 bool Unit::isTargetableForAttack() const
8831 if (GetTypeId()==TYPEID_PLAYER && ((Player *)this)->isGameMaster())
8832 return false;
8834 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE))
8835 return false;
8837 return isAlive() && !hasUnitState(UNIT_STAT_DIED)&& !isInFlight() /*&& !isStealth()*/;
8840 int32 Unit::ModifyHealth(int32 dVal)
8842 int32 gain = 0;
8844 if(dVal==0)
8845 return 0;
8847 int32 curHealth = (int32)GetHealth();
8849 int32 val = dVal + curHealth;
8850 if(val <= 0)
8852 SetHealth(0);
8853 return -curHealth;
8856 int32 maxHealth = (int32)GetMaxHealth();
8858 if(val < maxHealth)
8860 SetHealth(val);
8861 gain = val - curHealth;
8863 else if(curHealth != maxHealth)
8865 SetHealth(maxHealth);
8866 gain = maxHealth - curHealth;
8869 return gain;
8872 int32 Unit::ModifyPower(Powers power, int32 dVal)
8874 int32 gain = 0;
8876 if(dVal==0)
8877 return 0;
8879 int32 curPower = (int32)GetPower(power);
8881 int32 val = dVal + curPower;
8882 if(val <= 0)
8884 SetPower(power,0);
8885 return -curPower;
8888 int32 maxPower = (int32)GetMaxPower(power);
8890 if(val < maxPower)
8892 SetPower(power,val);
8893 gain = val - curPower;
8895 else if(curPower != maxPower)
8897 SetPower(power,maxPower);
8898 gain = maxPower - curPower;
8901 return gain;
8904 bool Unit::isVisibleForOrDetect(Unit const* u, bool detect, bool inVisibleList, bool is3dDistance) const
8906 if(!u)
8907 return false;
8909 // Always can see self
8910 if (u==this)
8911 return true;
8913 // player visible for other player if not logout and at same transport
8914 // including case when player is out of world
8915 bool at_same_transport =
8916 GetTypeId() == TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER &&
8917 !((Player*)this)->GetSession()->PlayerLogout() && !((Player*)u)->GetSession()->PlayerLogout() &&
8918 !((Player*)this)->GetSession()->PlayerLoading() && !((Player*)u)->GetSession()->PlayerLoading() &&
8919 ((Player*)this)->GetTransport() && ((Player*)this)->GetTransport() == ((Player*)u)->GetTransport();
8921 // not in world
8922 if(!at_same_transport && (!IsInWorld() || !u->IsInWorld()))
8923 return false;
8925 // forbidden to seen (at GM respawn command)
8926 if(m_Visibility==VISIBILITY_RESPAWN)
8927 return false;
8929 // Grid dead/alive checks
8930 if( u->GetTypeId()==TYPEID_PLAYER)
8932 // non visible at grid for any stealth state
8933 if(!IsVisibleInGridForPlayer((Player *)u))
8934 return false;
8936 // if player is dead then he can't detect anyone in any cases
8937 if(!u->isAlive())
8938 detect = false;
8940 else
8942 // all dead creatures/players not visible for any creatures
8943 if(!u->isAlive() || !isAlive())
8944 return false;
8947 // always seen by owner
8948 if(GetCharmerOrOwnerGUID()==u->GetGUID())
8949 return true;
8951 // different visible distance checks
8952 if(u->isInFlight()) // what see player in flight
8954 // use object grey distance for all (only see objects any way)
8955 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceInFlight()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
8956 return false;
8958 else if(!isAlive()) // distance for show body
8960 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForObject()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
8961 return false;
8963 else if(GetTypeId()==TYPEID_PLAYER) // distance for show player
8965 if(u->GetTypeId()==TYPEID_PLAYER)
8967 // Players far than max visible distance for player or not in our map are not visible too
8968 if (!at_same_transport && !IsWithinDistInMap(u,World::GetMaxVisibleDistanceForPlayer()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8969 return false;
8971 else
8973 // Units far than max visible distance for creature or not in our map are not visible too
8974 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForCreature()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8975 return false;
8978 else if(GetCharmerOrOwnerGUID()) // distance for show pet/charmed
8980 // Pet/charmed far than max visible distance for player or not in our map are not visible too
8981 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForPlayer()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8982 return false;
8984 else // distance for show creature
8986 // Units far than max visible distance for creature or not in our map are not visible too
8987 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForCreature()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8988 return false;
8991 // Visible units, always are visible for all units, except for units under invisibility and phases
8992 if (m_Visibility == VISIBILITY_ON && u->m_invisibilityMask==0 && InSamePhase(u))
8993 return true;
8995 // GMs see any players, not higher GMs and all units in any phase
8996 if (u->GetTypeId() == TYPEID_PLAYER && ((Player *)u)->isGameMaster())
8998 if(GetTypeId() == TYPEID_PLAYER)
8999 return ((Player *)this)->GetSession()->GetSecurity() <= ((Player *)u)->GetSession()->GetSecurity();
9000 else
9001 return true;
9004 // non faction visibility non-breakable for non-GMs
9005 if (m_Visibility == VISIBILITY_OFF)
9006 return false;
9008 // phased visibility (both must phased in same way)
9009 if(!InSamePhase(u))
9010 return false;
9012 // raw invisibility
9013 bool invisible = (m_invisibilityMask != 0 || u->m_invisibilityMask !=0);
9015 // detectable invisibility case
9016 if( invisible && (
9017 // Invisible units, always are visible for units under same invisibility type
9018 (m_invisibilityMask & u->m_invisibilityMask)!=0 ||
9019 // Invisible units, always are visible for unit that can detect this invisibility (have appropriate level for detect)
9020 u->canDetectInvisibilityOf(this) ||
9021 // Units that can detect invisibility always are visible for units that can be detected
9022 canDetectInvisibilityOf(u) ))
9024 invisible = false;
9027 // special cases for always overwrite invisibility/stealth
9028 if(invisible || m_Visibility == VISIBILITY_GROUP_STEALTH)
9030 // non-hostile case
9031 if (!u->IsHostileTo(this))
9033 // 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)
9034 if(GetTypeId()==TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER)
9036 if(((Player*)this)->IsGroupVisibleFor(((Player*)u)))
9037 return true;
9039 // else apply same rules as for hostile case (detecting check for stealth)
9042 // hostile case
9043 else
9045 // Hunter mark functionality
9046 AuraList const& auras = GetAurasByType(SPELL_AURA_MOD_STALKED);
9047 for(AuraList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
9048 if((*iter)->GetCasterGUID()==u->GetGUID())
9049 return true;
9051 // else apply detecting check for stealth
9054 // none other cases for detect invisibility, so invisible
9055 if(invisible)
9056 return false;
9058 // else apply stealth detecting check
9061 // unit got in stealth in this moment and must ignore old detected state
9062 if (m_Visibility == VISIBILITY_GROUP_NO_DETECT)
9063 return false;
9065 // GM invisibility checks early, invisibility if any detectable, so if not stealth then visible
9066 if (m_Visibility != VISIBILITY_GROUP_STEALTH)
9067 return true;
9069 // NOW ONLY STEALTH CASE
9071 // stealth and detected and visible for some seconds
9072 if (u->GetTypeId() == TYPEID_PLAYER && ((Player*)u)->m_DetectInvTimer > 300 && ((Player*)u)->HaveAtClient(this))
9073 return true;
9075 //if in non-detect mode then invisible for unit
9076 if (!detect)
9077 return false;
9079 // Special cases
9081 // If is attacked then stealth is lost, some creature can use stealth too
9082 if( !getAttackers().empty() )
9083 return true;
9085 // If there is collision rogue is seen regardless of level difference
9086 if (IsWithinDist(u,0.24f))
9087 return true;
9089 //If a mob or player is stunned he will not be able to detect stealth
9090 if (u->hasUnitState(UNIT_STAT_STUNNED) && (u != this))
9091 return false;
9093 // Creature can detect target only in aggro radius
9094 if(u->GetTypeId() != TYPEID_PLAYER)
9096 //Always invisible from back and out of aggro range
9097 bool isInFront = u->isInFrontInMap(this,((Creature const*)u)->GetAttackDistance(this));
9098 if(!isInFront)
9099 return false;
9101 else
9103 //Always invisible from back
9104 bool isInFront = u->isInFrontInMap(this,(GetTypeId()==TYPEID_PLAYER || GetCharmerOrOwnerGUID()) ? World::GetMaxVisibleDistanceForPlayer() : World::GetMaxVisibleDistanceForCreature());
9105 if(!isInFront)
9106 return false;
9109 // if doesn't have stealth detection (Shadow Sight), then check how stealthy the unit is, otherwise just check los
9110 if(!u->HasAuraType(SPELL_AURA_DETECT_STEALTH))
9112 //Calculation if target is in front
9114 //Visible distance based on stealth value (stealth rank 4 300MOD, 10.5 - 3 = 7.5)
9115 float visibleDistance = 10.5f - (GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH)/100.0f);
9117 //Visible distance is modified by
9118 //-Level Diff (every level diff = 1.0f in visible distance)
9119 visibleDistance += int32(u->getLevelForTarget(this)) - int32(getLevelForTarget(u));
9121 //This allows to check talent tree and will add addition stealth dependent on used points)
9122 int32 stealthMod = GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_LEVEL);
9123 if(stealthMod < 0)
9124 stealthMod = 0;
9126 //-Stealth Mod(positive like Master of Deception) and Stealth Detection(negative like paranoia)
9127 //based on wowwiki every 5 mod we have 1 more level diff in calculation
9128 visibleDistance += (int32(u->GetTotalAuraModifier(SPELL_AURA_MOD_DETECT)) - stealthMod)/5.0f;
9130 if(!IsWithinDist(u,visibleDistance))
9131 return false;
9134 // Now check is target visible with LoS
9135 float ox,oy,oz;
9136 u->GetPosition(ox,oy,oz);
9137 return IsWithinLOS(ox,oy,oz);
9140 void Unit::SetVisibility(UnitVisibility x)
9142 m_Visibility = x;
9144 if(IsInWorld())
9146 Map *m = GetMap();
9148 if(GetTypeId()==TYPEID_PLAYER)
9149 m->PlayerRelocation((Player*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
9150 else
9151 m->CreatureRelocation((Creature*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
9155 bool Unit::canDetectInvisibilityOf(Unit const* u) const
9157 if(uint32 mask = (m_detectInvisibilityMask & u->m_invisibilityMask))
9159 for(uint32 i = 0; i < 10; ++i)
9161 if(((1 << i) & mask)==0)
9162 continue;
9164 // find invisibility level
9165 uint32 invLevel = 0;
9166 Unit::AuraList const& iAuras = u->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY);
9167 for(Unit::AuraList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr)
9168 if(((*itr)->GetModifier()->m_miscvalue)==i && invLevel < (*itr)->GetModifier()->m_amount)
9169 invLevel = (*itr)->GetModifier()->m_amount;
9171 // find invisibility detect level
9172 uint32 detectLevel = 0;
9173 Unit::AuraList const& dAuras = GetAurasByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION);
9174 for(Unit::AuraList::const_iterator itr = dAuras.begin(); itr != dAuras.end(); ++itr)
9175 if(((*itr)->GetModifier()->m_miscvalue)==i && detectLevel < (*itr)->GetModifier()->m_amount)
9176 detectLevel = (*itr)->GetModifier()->m_amount;
9178 if(i==6 && GetTypeId()==TYPEID_PLAYER) // special drunk detection case
9180 detectLevel = ((Player*)this)->GetDrunkValue();
9183 if(invLevel <= detectLevel)
9184 return true;
9188 return false;
9191 void Unit::UpdateSpeed(UnitMoveType mtype, bool forced)
9193 int32 main_speed_mod = 0;
9194 float stack_bonus = 1.0f;
9195 float non_stack_bonus = 1.0f;
9197 switch(mtype)
9199 case MOVE_WALK:
9200 return;
9201 case MOVE_RUN:
9203 if (IsMounted()) // Use on mount auras
9205 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED);
9206 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS);
9207 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK))/100.0f;
9209 else
9211 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED);
9212 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS);
9213 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK))/100.0f;
9215 break;
9217 case MOVE_RUN_BACK:
9218 return;
9219 case MOVE_SWIM:
9221 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SWIM_SPEED);
9222 break;
9224 case MOVE_SWIM_BACK:
9225 return;
9226 case MOVE_FLIGHT:
9228 if (IsMounted()) // Use on mount auras
9229 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
9230 else // Use not mount (shapeshift for example) auras (should stack)
9231 main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_SPEED_FLIGHT);
9232 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_FLIGHT_SPEED_ALWAYS);
9233 non_stack_bonus = (100.0 + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK))/100.0f;
9234 break;
9236 case MOVE_FLIGHT_BACK:
9237 return;
9238 default:
9239 sLog.outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype);
9240 return;
9243 float bonus = non_stack_bonus > stack_bonus ? non_stack_bonus : stack_bonus;
9244 // now we ready for speed calculation
9245 float speed = main_speed_mod ? bonus*(100.0f + main_speed_mod)/100.0f : bonus;
9247 switch(mtype)
9249 case MOVE_RUN:
9250 case MOVE_SWIM:
9251 case MOVE_FLIGHT:
9253 // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need
9254 // TODO: possible affect only on MOVE_RUN
9255 if(int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED))
9257 // Use speed from aura
9258 float max_speed = normalization / baseMoveSpeed[mtype];
9259 if (speed > max_speed)
9260 speed = max_speed;
9262 break;
9264 default:
9265 break;
9268 // Apply strongest slow aura mod to speed
9269 int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED);
9270 if (slow)
9271 speed *=(100.0f + slow)/100.0f;
9272 SetSpeed(mtype, speed, forced);
9275 float Unit::GetSpeed( UnitMoveType mtype ) const
9277 return m_speed_rate[mtype]*baseMoveSpeed[mtype];
9280 void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced)
9282 if (rate < 0)
9283 rate = 0.0f;
9285 // Update speed only on change
9286 if (m_speed_rate[mtype] == rate)
9287 return;
9289 m_speed_rate[mtype] = rate;
9291 propagateSpeedChange();
9293 WorldPacket data;
9294 if(!forced)
9296 switch(mtype)
9298 case MOVE_WALK:
9299 data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9300 break;
9301 case MOVE_RUN:
9302 data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8+4+2+4+4+4+4+4+4+4);
9303 break;
9304 case MOVE_RUN_BACK:
9305 data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9306 break;
9307 case MOVE_SWIM:
9308 data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8+4+2+4+4+4+4+4+4+4);
9309 break;
9310 case MOVE_SWIM_BACK:
9311 data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9312 break;
9313 case MOVE_TURN_RATE:
9314 data.Initialize(MSG_MOVE_SET_TURN_RATE, 8+4+2+4+4+4+4+4+4+4);
9315 break;
9316 case MOVE_FLIGHT:
9317 data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8+4+2+4+4+4+4+4+4+4);
9318 break;
9319 case MOVE_FLIGHT_BACK:
9320 data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9321 break;
9322 case MOVE_PITCH_RATE:
9323 data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8+4+2+4+4+4+4+4+4+4);
9324 break;
9325 default:
9326 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
9327 return;
9330 data.append(GetPackGUID());
9331 data << uint32(0); // movement flags
9332 data << uint16(0); // unk flags
9333 data << uint32(getMSTime());
9334 data << float(GetPositionX());
9335 data << float(GetPositionY());
9336 data << float(GetPositionZ());
9337 data << float(GetOrientation());
9338 data << uint32(0); // fall time
9339 data << float(GetSpeed(mtype));
9340 SendMessageToSet( &data, true );
9342 else
9344 if(GetTypeId() == TYPEID_PLAYER)
9346 // register forced speed changes for WorldSession::HandleForceSpeedChangeAck
9347 // and do it only for real sent packets and use run for run/mounted as client expected
9348 ++((Player*)this)->m_forced_speed_changes[mtype];
9351 switch(mtype)
9353 case MOVE_WALK:
9354 data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE, 16);
9355 break;
9356 case MOVE_RUN:
9357 data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE, 17);
9358 break;
9359 case MOVE_RUN_BACK:
9360 data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE, 16);
9361 break;
9362 case MOVE_SWIM:
9363 data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE, 16);
9364 break;
9365 case MOVE_SWIM_BACK:
9366 data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, 16);
9367 break;
9368 case MOVE_TURN_RATE:
9369 data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE, 16);
9370 break;
9371 case MOVE_FLIGHT:
9372 data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE, 16);
9373 break;
9374 case MOVE_FLIGHT_BACK:
9375 data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, 16);
9376 break;
9377 case MOVE_PITCH_RATE:
9378 data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE, 16);
9379 break;
9380 default:
9381 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
9382 return;
9384 data.append(GetPackGUID());
9385 data << (uint32)0; // moveEvent, NUM_PMOVE_EVTS = 0x39
9386 if (mtype == MOVE_RUN)
9387 data << uint8(0); // new 2.1.0
9388 data << float(GetSpeed(mtype));
9389 SendMessageToSet( &data, true );
9391 if(Pet* pet = GetPet())
9392 pet->SetSpeed(MOVE_RUN, m_speed_rate[mtype],forced);
9395 void Unit::SetHover(bool on)
9397 if(on)
9398 CastSpell(this, 11010, true);
9399 else
9400 RemoveAurasDueToSpell(11010);
9403 void Unit::setDeathState(DeathState s)
9405 if (s != ALIVE && s!= JUST_ALIVED)
9407 CombatStop();
9408 DeleteThreatList();
9409 ClearComboPointHolders(); // any combo points pointed to unit lost at it death
9411 if(IsNonMeleeSpellCasted(false))
9412 InterruptNonMeleeSpells(false);
9415 if (s == JUST_DIED)
9417 RemoveAllAurasOnDeath();
9418 UnsummonAllTotems();
9420 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false);
9421 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, false);
9422 // remove aurastates allowing special moves
9423 ClearAllReactives();
9424 ClearDiminishings();
9426 else if(s == JUST_ALIVED)
9428 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground)
9431 if (m_deathState != ALIVE && s == ALIVE)
9433 //_ApplyAllAuraMods();
9435 m_deathState = s;
9438 /*########################################
9439 ######## ########
9440 ######## AGGRO SYSTEM ########
9441 ######## ########
9442 ########################################*/
9443 bool Unit::CanHaveThreatList() const
9445 // only creatures can have threat list
9446 if( GetTypeId() != TYPEID_UNIT )
9447 return false;
9449 // only alive units can have threat list
9450 if( !isAlive() )
9451 return false;
9453 // totems can not have threat list
9454 if( ((Creature*)this)->isTotem() )
9455 return false;
9457 // vehicles can not have threat list
9458 if( ((Creature*)this)->isVehicle() )
9459 return false;
9461 // pets can not have a threat list, unless they are controlled by a creature
9462 if( ((Creature*)this)->isPet() && IS_PLAYER_GUID(((Pet*)this)->GetOwnerGUID()) )
9463 return false;
9465 return true;
9468 //======================================================================
9470 float Unit::ApplyTotalThreatModifier(float threat, SpellSchoolMask schoolMask)
9472 if(!HasAuraType(SPELL_AURA_MOD_THREAT))
9473 return threat;
9475 SpellSchools school = GetFirstSchoolInMask(schoolMask);
9477 return threat * m_threatModifier[school];
9480 //======================================================================
9482 void Unit::AddThreat(Unit* pVictim, float threat, SpellSchoolMask schoolMask, SpellEntry const *threatSpell)
9484 // Only mobs can manage threat lists
9485 if(CanHaveThreatList())
9486 m_ThreatManager.addThreat(pVictim, threat, schoolMask, threatSpell);
9489 //======================================================================
9491 void Unit::DeleteThreatList()
9493 m_ThreatManager.clearReferences();
9496 //======================================================================
9498 void Unit::TauntApply(Unit* taunter)
9500 assert(GetTypeId()== TYPEID_UNIT);
9502 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
9503 return;
9505 if(!CanHaveThreatList())
9506 return;
9508 Unit *target = getVictim();
9509 if(target && target == taunter)
9510 return;
9512 SetInFront(taunter);
9513 if (((Creature*)this)->AI())
9514 ((Creature*)this)->AI()->AttackStart(taunter);
9516 m_ThreatManager.tauntApply(taunter);
9519 //======================================================================
9521 void Unit::TauntFadeOut(Unit *taunter)
9523 assert(GetTypeId()== TYPEID_UNIT);
9525 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
9526 return;
9528 if(!CanHaveThreatList())
9529 return;
9531 Unit *target = getVictim();
9532 if(!target || target != taunter)
9533 return;
9535 if(m_ThreatManager.isThreatListEmpty())
9537 if(((Creature*)this)->AI())
9538 ((Creature*)this)->AI()->EnterEvadeMode();
9539 return;
9542 m_ThreatManager.tauntFadeOut(taunter);
9543 target = m_ThreatManager.getHostilTarget();
9545 if (target && target != taunter)
9547 SetInFront(target);
9548 if (((Creature*)this)->AI())
9549 ((Creature*)this)->AI()->AttackStart(target);
9553 //======================================================================
9555 bool Unit::SelectHostilTarget()
9557 //function provides main threat functionality
9558 //next-victim-selection algorithm and evade mode are called
9559 //threat list sorting etc.
9561 assert(GetTypeId()== TYPEID_UNIT);
9563 if (!this->isAlive())
9564 return false;
9565 //This function only useful once AI has been initialized
9566 if (!((Creature*)this)->AI())
9567 return false;
9569 Unit* target = NULL;
9571 // First checking if we have some taunt on us
9572 const AuraList& tauntAuras = GetAurasByType(SPELL_AURA_MOD_TAUNT);
9573 if ( !tauntAuras.empty() )
9575 Unit* caster;
9577 // The last taunt aura caster is alive an we are happy to attack him
9578 if ( (caster = tauntAuras.back()->GetCaster()) && caster->isAlive() )
9579 return true;
9580 else if (tauntAuras.size() > 1)
9582 // We do not have last taunt aura caster but we have more taunt auras,
9583 // so find first available target
9585 // Auras are pushed_back, last caster will be on the end
9586 AuraList::const_iterator aura = --tauntAuras.end();
9589 --aura;
9590 if ( (caster = (*aura)->GetCaster()) &&
9591 caster->IsInMap(this) && caster->isTargetableForAttack() && caster->isInAccessablePlaceFor((Creature*)this) )
9593 target = caster;
9594 break;
9596 }while (aura != tauntAuras.begin());
9600 if ( !target && !m_ThreatManager.isThreatListEmpty() )
9601 // No taunt aura or taunt aura caster is dead standart target selection
9602 target = m_ThreatManager.getHostilTarget();
9604 if(target)
9606 if(!hasUnitState(UNIT_STAT_STUNNED))
9607 SetInFront(target);
9608 ((Creature*)this)->AI()->AttackStart(target);
9609 return true;
9612 // no target but something prevent go to evade mode
9613 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_TAUNT) )
9614 return false;
9616 // last case when creature don't must go to evade mode:
9617 // it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list
9618 // for example at owner command to pet attack some far away creature
9619 // Note: creature not have targeted movement generator but have attacker in this case
9620 if( GetMotionMaster()->GetCurrentMovementGeneratorType() != TARGETED_MOTION_TYPE )
9622 for(AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr)
9624 if( (*itr)->IsInMap(this) && (*itr)->isTargetableForAttack() && (*itr)->isInAccessablePlaceFor((Creature*)this) )
9625 return false;
9629 // enter in evade mode in other case
9630 ((Creature*)this)->AI()->EnterEvadeMode();
9632 return false;
9635 //======================================================================
9636 //======================================================================
9637 //======================================================================
9639 int32 Unit::CalculateSpellDamage(SpellEntry const* spellProto, uint8 effect_index, int32 effBasePoints, Unit const* target)
9641 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
9643 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
9645 int32 level = int32(getLevel());
9646 if (level > (int32)spellProto->maxLevel && spellProto->maxLevel > 0)
9647 level = (int32)spellProto->maxLevel;
9648 else if (level < (int32)spellProto->baseLevel)
9649 level = (int32)spellProto->baseLevel;
9650 level-= (int32)spellProto->spellLevel;
9652 float basePointsPerLevel = spellProto->EffectRealPointsPerLevel[effect_index];
9653 float randomPointsPerLevel = spellProto->EffectDicePerLevel[effect_index];
9654 int32 basePoints = int32(effBasePoints + level * basePointsPerLevel);
9655 int32 randomPoints = int32(spellProto->EffectDieSides[effect_index] + level * randomPointsPerLevel);
9656 float comboDamage = spellProto->EffectPointsPerComboPoint[effect_index];
9658 // range can have possitive and negative values, so order its for irand
9659 int32 randvalue = int32(spellProto->EffectBaseDice[effect_index]) >= randomPoints
9660 ? irand(randomPoints, int32(spellProto->EffectBaseDice[effect_index]))
9661 : irand(int32(spellProto->EffectBaseDice[effect_index]), randomPoints);
9663 int32 value = basePoints + randvalue;
9664 //random damage
9665 if(comboDamage != 0 && unitPlayer && target && (target->GetGUID() == unitPlayer->GetComboTarget()))
9666 value += (int32)(comboDamage * comboPoints);
9668 if(Player* modOwner = GetSpellModOwner())
9670 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_ALL_EFFECTS, value);
9671 switch(effect_index)
9673 case 0:
9674 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT1, value);
9675 break;
9676 case 1:
9677 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT2, value);
9678 break;
9679 case 2:
9680 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT3, value);
9681 break;
9685 if(spellProto->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION && spellProto->spellLevel &&
9686 spellProto->Effect[effect_index] != SPELL_EFFECT_WEAPON_PERCENT_DAMAGE &&
9687 spellProto->Effect[effect_index] != SPELL_EFFECT_KNOCK_BACK)
9688 value = int32(value*0.25f*exp(getLevel()*(70-spellProto->spellLevel)/1000.0f));
9690 return value;
9693 int32 Unit::CalculateSpellDuration(SpellEntry const* spellProto, uint8 effect_index, Unit const* target)
9695 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
9697 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
9699 int32 minduration = GetSpellDuration(spellProto);
9700 int32 maxduration = GetSpellMaxDuration(spellProto);
9702 int32 duration;
9704 if( minduration != -1 && minduration != maxduration )
9705 duration = minduration + int32((maxduration - minduration) * comboPoints / 5);
9706 else
9707 duration = minduration;
9709 if (duration > 0)
9711 int32 mechanic = GetEffectMechanic(spellProto, effect_index);
9712 // Find total mod value (negative bonus)
9713 int32 durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD, mechanic);
9714 // Modify from SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL aura (stack always ?)
9715 durationMod_always+=target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL, spellProto->Dispel);
9716 // Find max mod (negative bonus)
9717 int32 durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK, mechanic);
9719 int32 durationMod = 0;
9720 // Select strongest negative mod
9721 if (durationMod_always > durationMod_not_stack)
9722 durationMod = durationMod_not_stack;
9723 else
9724 durationMod = durationMod_always;
9726 if (durationMod != 0)
9727 duration = int32(int64(duration) * (100+durationMod) /100);
9729 if (duration < 0) duration = 0;
9732 return duration;
9735 DiminishingLevels Unit::GetDiminishing(DiminishingGroup group)
9737 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9739 if(i->DRGroup != group)
9740 continue;
9742 if(!i->hitCount)
9743 return DIMINISHING_LEVEL_1;
9745 if(!i->hitTime)
9746 return DIMINISHING_LEVEL_1;
9748 // If last spell was casted more than 15 seconds ago - reset the count.
9749 if(i->stack==0 && getMSTimeDiff(i->hitTime,getMSTime()) > 15000)
9751 i->hitCount = DIMINISHING_LEVEL_1;
9752 return DIMINISHING_LEVEL_1;
9754 // or else increase the count.
9755 else
9757 return DiminishingLevels(i->hitCount);
9760 return DIMINISHING_LEVEL_1;
9763 void Unit::IncrDiminishing(DiminishingGroup group)
9765 // Checking for existing in the table
9766 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9768 if(i->DRGroup != group)
9769 continue;
9770 if(i->hitCount < DIMINISHING_LEVEL_IMMUNE)
9771 i->hitCount += 1;
9772 return;
9774 m_Diminishing.push_back(DiminishingReturn(group,getMSTime(),DIMINISHING_LEVEL_2));
9777 void Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration,Unit* caster,DiminishingLevels Level)
9779 if(duration == -1 || group == DIMINISHING_NONE || caster->IsFriendlyTo(this) )
9780 return;
9782 // Duration of crowd control abilities on pvp target is limited by 10 sec. (2.2.0)
9783 if(duration > 10000 && IsDiminishingReturnsGroupDurationLimited(group))
9785 // test pet/charm masters instead pets/charmeds
9786 Unit const* targetOwner = GetCharmerOrOwner();
9787 Unit const* casterOwner = caster->GetCharmerOrOwner();
9789 Unit const* target = targetOwner ? targetOwner : this;
9790 Unit const* source = casterOwner ? casterOwner : caster;
9792 if(target->GetTypeId() == TYPEID_PLAYER && source->GetTypeId() == TYPEID_PLAYER)
9793 duration = 10000;
9796 float mod = 1.0f;
9798 // Some diminishings applies to mobs too (for example, Stun)
9799 if((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER && GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL)
9801 DiminishingLevels diminish = Level;
9802 switch(diminish)
9804 case DIMINISHING_LEVEL_1: break;
9805 case DIMINISHING_LEVEL_2: mod = 0.5f; break;
9806 case DIMINISHING_LEVEL_3: mod = 0.25f; break;
9807 case DIMINISHING_LEVEL_IMMUNE: mod = 0.0f;break;
9808 default: break;
9812 duration = int32(duration * mod);
9815 void Unit::ApplyDiminishingAura( DiminishingGroup group, bool apply )
9817 // Checking for existing in the table
9818 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9820 if(i->DRGroup != group)
9821 continue;
9823 if(apply)
9824 i->stack += 1;
9825 else if(i->stack)
9827 i->stack -= 1;
9828 // Remember time after last aura from group removed
9829 if (i->stack == 0)
9830 i->hitTime = getMSTime();
9832 break;
9836 Unit* Unit::GetUnit(WorldObject& object, uint64 guid)
9838 return ObjectAccessor::GetUnit(object,guid);
9841 bool Unit::isVisibleForInState( Player const* u, bool inVisibleList ) const
9843 return isVisibleForOrDetect(u, false, inVisibleList, false);
9846 uint32 Unit::GetCreatureType() const
9848 if(GetTypeId() == TYPEID_PLAYER)
9850 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
9851 if(ssEntry && ssEntry->creatureType > 0)
9852 return ssEntry->creatureType;
9853 else
9854 return CREATURE_TYPE_HUMANOID;
9856 else
9857 return ((Creature*)this)->GetCreatureInfo()->type;
9860 /*#######################################
9861 ######## ########
9862 ######## STAT SYSTEM ########
9863 ######## ########
9864 #######################################*/
9866 bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply)
9868 if(unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
9870 sLog.outError("ERROR in HandleStatModifier(): non existed UnitMods or wrong UnitModifierType!");
9871 return false;
9874 float val = 1.0f;
9876 switch(modifierType)
9878 case BASE_VALUE:
9879 case TOTAL_VALUE:
9880 m_auraModifiersGroup[unitMod][modifierType] += apply ? amount : -amount;
9881 break;
9882 case BASE_PCT:
9883 case TOTAL_PCT:
9884 if(amount <= -100.0f) //small hack-fix for -100% modifiers
9885 amount = -200.0f;
9887 val = (100.0f + amount) / 100.0f;
9888 m_auraModifiersGroup[unitMod][modifierType] *= apply ? val : (1.0f/val);
9889 break;
9891 default:
9892 break;
9895 if(!CanModifyStats())
9896 return false;
9898 switch(unitMod)
9900 case UNIT_MOD_STAT_STRENGTH:
9901 case UNIT_MOD_STAT_AGILITY:
9902 case UNIT_MOD_STAT_STAMINA:
9903 case UNIT_MOD_STAT_INTELLECT:
9904 case UNIT_MOD_STAT_SPIRIT: UpdateStats(GetStatByAuraGroup(unitMod)); break;
9906 case UNIT_MOD_ARMOR: UpdateArmor(); break;
9907 case UNIT_MOD_HEALTH: UpdateMaxHealth(); break;
9909 case UNIT_MOD_MANA:
9910 case UNIT_MOD_RAGE:
9911 case UNIT_MOD_FOCUS:
9912 case UNIT_MOD_ENERGY:
9913 case UNIT_MOD_HAPPINESS:
9914 case UNIT_MOD_RUNE:
9915 case UNIT_MOD_RUNIC_POWER: UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); break;
9917 case UNIT_MOD_RESISTANCE_HOLY:
9918 case UNIT_MOD_RESISTANCE_FIRE:
9919 case UNIT_MOD_RESISTANCE_NATURE:
9920 case UNIT_MOD_RESISTANCE_FROST:
9921 case UNIT_MOD_RESISTANCE_SHADOW:
9922 case UNIT_MOD_RESISTANCE_ARCANE: UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); break;
9924 case UNIT_MOD_ATTACK_POWER: UpdateAttackPowerAndDamage(); break;
9925 case UNIT_MOD_ATTACK_POWER_RANGED: UpdateAttackPowerAndDamage(true); break;
9927 case UNIT_MOD_DAMAGE_MAINHAND: UpdateDamagePhysical(BASE_ATTACK); break;
9928 case UNIT_MOD_DAMAGE_OFFHAND: UpdateDamagePhysical(OFF_ATTACK); break;
9929 case UNIT_MOD_DAMAGE_RANGED: UpdateDamagePhysical(RANGED_ATTACK); break;
9931 default:
9932 break;
9935 return true;
9938 float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const
9940 if( unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
9942 sLog.outError("trial to access non existed modifier value from UnitMods!");
9943 return 0.0f;
9946 if(modifierType == TOTAL_PCT && m_auraModifiersGroup[unitMod][modifierType] <= 0.0f)
9947 return 0.0f;
9949 return m_auraModifiersGroup[unitMod][modifierType];
9952 float Unit::GetTotalStatValue(Stats stat) const
9954 UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat);
9956 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
9957 return 0.0f;
9959 // value = ((base_value * base_pct) + total_value) * total_pct
9960 float value = m_auraModifiersGroup[unitMod][BASE_VALUE] + GetCreateStat(stat);
9961 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
9962 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
9963 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
9965 return value;
9968 float Unit::GetTotalAuraModValue(UnitMods unitMod) const
9970 if(unitMod >= UNIT_MOD_END)
9972 sLog.outError("trial to access non existed UnitMods in GetTotalAuraModValue()!");
9973 return 0.0f;
9976 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
9977 return 0.0f;
9979 float value = m_auraModifiersGroup[unitMod][BASE_VALUE];
9980 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
9981 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
9982 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
9984 return value;
9987 SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const
9989 SpellSchools school = SPELL_SCHOOL_NORMAL;
9991 switch(unitMod)
9993 case UNIT_MOD_RESISTANCE_HOLY: school = SPELL_SCHOOL_HOLY; break;
9994 case UNIT_MOD_RESISTANCE_FIRE: school = SPELL_SCHOOL_FIRE; break;
9995 case UNIT_MOD_RESISTANCE_NATURE: school = SPELL_SCHOOL_NATURE; break;
9996 case UNIT_MOD_RESISTANCE_FROST: school = SPELL_SCHOOL_FROST; break;
9997 case UNIT_MOD_RESISTANCE_SHADOW: school = SPELL_SCHOOL_SHADOW; break;
9998 case UNIT_MOD_RESISTANCE_ARCANE: school = SPELL_SCHOOL_ARCANE; break;
10000 default:
10001 break;
10004 return school;
10007 Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const
10009 Stats stat = STAT_STRENGTH;
10011 switch(unitMod)
10013 case UNIT_MOD_STAT_STRENGTH: stat = STAT_STRENGTH; break;
10014 case UNIT_MOD_STAT_AGILITY: stat = STAT_AGILITY; break;
10015 case UNIT_MOD_STAT_STAMINA: stat = STAT_STAMINA; break;
10016 case UNIT_MOD_STAT_INTELLECT: stat = STAT_INTELLECT; break;
10017 case UNIT_MOD_STAT_SPIRIT: stat = STAT_SPIRIT; break;
10019 default:
10020 break;
10023 return stat;
10026 Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const
10028 switch(unitMod)
10030 case UNIT_MOD_MANA: return POWER_MANA;
10031 case UNIT_MOD_RAGE: return POWER_RAGE;
10032 case UNIT_MOD_FOCUS: return POWER_FOCUS;
10033 case UNIT_MOD_ENERGY: return POWER_ENERGY;
10034 case UNIT_MOD_HAPPINESS: return POWER_HAPPINESS;
10035 case UNIT_MOD_RUNE: return POWER_RUNE;
10036 case UNIT_MOD_RUNIC_POWER:return POWER_RUNIC_POWER;
10037 default: return POWER_MANA;
10040 return POWER_MANA;
10043 float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const
10045 if (attType == RANGED_ATTACK)
10047 int32 ap = GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS);
10048 if (ap < 0)
10049 return 0.0f;
10050 return ap * (1.0f + GetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER));
10052 else
10054 int32 ap = GetInt32Value(UNIT_FIELD_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS);
10055 if (ap < 0)
10056 return 0.0f;
10057 return ap * (1.0f + GetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER));
10061 float Unit::GetWeaponDamageRange(WeaponAttackType attType ,WeaponDamageRange type) const
10063 if (attType == OFF_ATTACK && !haveOffhandWeapon())
10064 return 0.0f;
10066 return m_weaponDamage[attType][type];
10069 void Unit::SetLevel(uint32 lvl)
10071 SetUInt32Value(UNIT_FIELD_LEVEL, lvl);
10073 // group update
10074 if ((GetTypeId() == TYPEID_PLAYER) && ((Player*)this)->GetGroup())
10075 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL);
10078 void Unit::SetHealth(uint32 val)
10080 uint32 maxHealth = GetMaxHealth();
10081 if(maxHealth < val)
10082 val = maxHealth;
10084 SetUInt32Value(UNIT_FIELD_HEALTH, val);
10086 // group update
10087 if(GetTypeId() == TYPEID_PLAYER)
10089 if(((Player*)this)->GetGroup())
10090 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP);
10092 else if(((Creature*)this)->isPet())
10094 Pet *pet = ((Pet*)this);
10095 if(pet->isControlled())
10097 Unit *owner = GetOwner();
10098 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10099 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP);
10104 void Unit::SetMaxHealth(uint32 val)
10106 uint32 health = GetHealth();
10107 SetUInt32Value(UNIT_FIELD_MAXHEALTH, val);
10109 // group update
10110 if(GetTypeId() == TYPEID_PLAYER)
10112 if(((Player*)this)->GetGroup())
10113 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP);
10115 else if(((Creature*)this)->isPet())
10117 Pet *pet = ((Pet*)this);
10118 if(pet->isControlled())
10120 Unit *owner = GetOwner();
10121 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10122 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP);
10126 if(val < health)
10127 SetHealth(val);
10130 void Unit::SetPower(Powers power, uint32 val)
10132 if(GetPower(power) == val)
10133 return;
10135 uint32 maxPower = GetMaxPower(power);
10136 if(maxPower < val)
10137 val = maxPower;
10139 SetStatInt32Value(UNIT_FIELD_POWER1 + power, val);
10141 WorldPacket data(SMSG_POWER_UPDATE);
10142 data.append(GetPackGUID());
10143 data << uint8(power);
10144 data << uint32(val);
10145 SendMessageToSet(&data, GetTypeId() == TYPEID_PLAYER ? true : false);
10147 // group update
10148 if(GetTypeId() == TYPEID_PLAYER)
10150 if(((Player*)this)->GetGroup())
10151 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
10153 else if(((Creature*)this)->isPet())
10155 Pet *pet = ((Pet*)this);
10156 if(pet->isControlled())
10158 Unit *owner = GetOwner();
10159 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10160 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
10163 // Update the pet's character sheet with happiness damage bonus
10164 if(pet->getPetType() == HUNTER_PET && power == POWER_HAPPINESS)
10166 pet->UpdateDamagePhysical(BASE_ATTACK);
10171 void Unit::SetMaxPower(Powers power, uint32 val)
10173 uint32 cur_power = GetPower(power);
10174 SetStatInt32Value(UNIT_FIELD_MAXPOWER1 + power, val);
10176 // group update
10177 if(GetTypeId() == TYPEID_PLAYER)
10179 if(((Player*)this)->GetGroup())
10180 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
10182 else if(((Creature*)this)->isPet())
10184 Pet *pet = ((Pet*)this);
10185 if(pet->isControlled())
10187 Unit *owner = GetOwner();
10188 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10189 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
10193 if(val < cur_power)
10194 SetPower(power, val);
10197 void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply)
10199 ApplyModUInt32Value(UNIT_FIELD_POWER1+power, val, apply);
10201 // group update
10202 if(GetTypeId() == TYPEID_PLAYER)
10204 if(((Player*)this)->GetGroup())
10205 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
10207 else if(((Creature*)this)->isPet())
10209 Pet *pet = ((Pet*)this);
10210 if(pet->isControlled())
10212 Unit *owner = GetOwner();
10213 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10214 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
10219 void Unit::ApplyMaxPowerMod(Powers power, uint32 val, bool apply)
10221 ApplyModUInt32Value(UNIT_FIELD_MAXPOWER1+power, val, apply);
10223 // group update
10224 if(GetTypeId() == TYPEID_PLAYER)
10226 if(((Player*)this)->GetGroup())
10227 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
10229 else if(((Creature*)this)->isPet())
10231 Pet *pet = ((Pet*)this);
10232 if(pet->isControlled())
10234 Unit *owner = GetOwner();
10235 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10236 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
10241 void Unit::ApplyAuraProcTriggerDamage( Aura* aura, bool apply )
10243 AuraList& tAuraProcTriggerDamage = m_modAuras[SPELL_AURA_PROC_TRIGGER_DAMAGE];
10244 if(apply)
10245 tAuraProcTriggerDamage.push_back(aura);
10246 else
10247 tAuraProcTriggerDamage.remove(aura);
10250 uint32 Unit::GetCreatePowers( Powers power ) const
10252 // POWER_FOCUS and POWER_HAPPINESS only have hunter pet
10253 switch(power)
10255 case POWER_MANA: return GetCreateMana();
10256 case POWER_RAGE: return 1000;
10257 case POWER_FOCUS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 100);
10258 case POWER_ENERGY: return 100;
10259 case POWER_HAPPINESS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 1050000);
10260 case POWER_RUNIC_POWER: return 1000;
10261 case POWER_RUNE: return 0;
10262 case POWER_HEALTH: return 0;
10265 return 0;
10268 void Unit::AddToWorld()
10270 Object::AddToWorld();
10273 void Unit::RemoveFromWorld()
10275 // cleanup
10276 if(IsInWorld())
10278 RemoveNotOwnSingleTargetAuras();
10281 Object::RemoveFromWorld();
10284 void Unit::CleanupsBeforeDelete()
10286 if(m_uint32Values) // only for fully created object
10288 InterruptNonMeleeSpells(true);
10289 m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList
10290 CombatStop();
10291 ClearComboPointHolders();
10292 DeleteThreatList();
10293 getHostilRefManager().setOnlineOfflineState(false);
10294 RemoveAllAuras();
10295 RemoveAllGameObjects();
10296 RemoveAllDynObjects();
10297 GetMotionMaster()->Clear(false); // remove different non-standard movement generators.
10299 RemoveFromWorld();
10302 CharmInfo* Unit::InitCharmInfo(Unit *charm)
10304 if(!m_charmInfo)
10305 m_charmInfo = new CharmInfo(charm);
10306 return m_charmInfo;
10309 CharmInfo::CharmInfo(Unit* unit)
10310 : m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_reactState(REACT_PASSIVE), m_petnumber(0)
10312 for(int i =0; i<4; ++i)
10314 m_charmspells[i].spellId = 0;
10315 m_charmspells[i].active = ACT_DISABLED;
10319 void CharmInfo::InitPetActionBar()
10321 // the first 3 SpellOrActions are attack, follow and stay
10322 // last 3 SpellOrActions are reactions
10323 for(uint32 i = 0; i < 3; ++i)
10325 SetActionBar(i,COMMAND_ATTACK - i,ACT_COMMAND);
10326 SetActionBar(i + 7,COMMAND_ATTACK - i,ACT_REACTION);
10328 // middle 4 SpellOrActions are spells/special attacks/abilities
10329 for(uint32 i = 0; i < 4; ++i)
10330 SetActionBar(i + 3,0,ACT_DISABLED);
10333 void CharmInfo::InitEmptyActionBar()
10335 SetActionBar(0,COMMAND_ATTACK,ACT_COMMAND);
10336 for(uint32 x = 1; x < MAX_UNIT_ACTION_BAR_INDEX; ++x)
10337 SetActionBar(x,0,ACT_PASSIVE);
10340 void CharmInfo::InitPossessCreateSpells()
10342 InitEmptyActionBar(); //charm action bar
10344 if(m_unit->GetTypeId() == TYPEID_PLAYER) //possessed players don't have spells, keep the action bar empty
10345 return;
10347 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10349 if (IsPassiveSpell(((Creature*)m_unit)->m_spells[x]))
10350 m_unit->CastSpell(m_unit, ((Creature*)m_unit)->m_spells[x], true);
10351 else
10352 AddSpellToActionBar(((Creature*)m_unit)->m_spells[x], ACT_PASSIVE);
10356 void CharmInfo::InitCharmCreateSpells()
10358 if(m_unit->GetTypeId() == TYPEID_PLAYER) //charmed players don't have spells
10360 InitEmptyActionBar();
10361 return;
10364 InitPetActionBar();
10366 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10368 uint32 spellId = ((Creature*)m_unit)->m_spells[x];
10369 m_charmspells[x].spellId = spellId;
10371 if(!spellId)
10372 continue;
10374 if (IsPassiveSpell(spellId))
10376 m_unit->CastSpell(m_unit, spellId, true);
10377 m_charmspells[x].active = ACT_PASSIVE;
10379 else
10381 ActiveStates newstate;
10382 bool onlyselfcast = true;
10383 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
10385 if(!spellInfo) onlyselfcast = false;
10386 for(uint32 i = 0;i<3 && onlyselfcast;++i) //non existent spell will not make any problems as onlyselfcast would be false -> break right away
10388 if(spellInfo->EffectImplicitTargetA[i] != TARGET_SELF && spellInfo->EffectImplicitTargetA[i] != 0)
10389 onlyselfcast = false;
10392 if(onlyselfcast || !IsPositiveSpell(spellId)) //only self cast and spells versus enemies are autocastable
10393 newstate = ACT_DISABLED;
10394 else
10395 newstate = ACT_PASSIVE;
10397 AddSpellToActionBar(spellId, newstate);
10402 bool CharmInfo::AddSpellToActionBar(uint32 spell_id, ActiveStates newstate)
10404 uint32 first_id = spellmgr.GetFirstSpellInChain(spell_id);
10406 // new spell rank can be already listed
10407 for(uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
10409 if (PetActionBar[i].SpellOrAction && PetActionBar[i].IsActionBarForSpell())
10411 if (spellmgr.GetFirstSpellInChain(PetActionBar[i].SpellOrAction) == first_id)
10413 PetActionBar[i].SpellOrAction = spell_id;
10414 return true;
10419 // or use empty slot in other case
10420 for(uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
10422 if (!PetActionBar[i].SpellOrAction && PetActionBar[i].IsActionBarForSpell())
10424 SetActionBar(i,spell_id,newstate == ACT_DECIDE ? ACT_DISABLED : newstate);
10425 return true;
10428 return false;
10431 bool CharmInfo::RemoveSpellFromActionBar(uint32 spell_id)
10433 uint32 first_id = spellmgr.GetFirstSpellInChain(spell_id);
10435 for(uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
10437 if (PetActionBar[i].SpellOrAction && PetActionBar[i].IsActionBarForSpell())
10439 if (spellmgr.GetFirstSpellInChain(PetActionBar[i].SpellOrAction) == first_id)
10441 SetActionBar(i,0,ACT_DISABLED);
10442 return true;
10447 return false;
10450 void CharmInfo::ToggleCreatureAutocast(uint32 spellid, bool apply)
10452 if(IsPassiveSpell(spellid))
10453 return;
10455 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10457 if(spellid == m_charmspells[x].spellId)
10459 m_charmspells[x].active = apply ? ACT_ENABLED : ACT_DISABLED;
10464 void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow)
10466 m_petnumber = petnumber;
10467 if(statwindow)
10468 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber);
10469 else
10470 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0);
10473 bool CharmInfo::LoadActionBar( std::string data )
10475 Tokens tokens = StrSplit(data, " ");
10477 if (tokens.size() != MAX_UNIT_ACTION_BAR_INDEX*2)
10478 return false;
10480 int index;
10481 Tokens::iterator iter;
10482 for(iter = tokens.begin(), index = 0; index < MAX_UNIT_ACTION_BAR_INDEX; ++iter, ++index )
10484 // use unsigned cast to avoid sign negative format use at long-> ActiveStates (int) conversion
10485 PetActionBar[index].Type = atol((*iter).c_str());
10486 ++iter;
10487 PetActionBar[index].SpellOrAction = atol((*iter).c_str());
10489 // check correctness
10490 if(PetActionBar[index].IsActionBarForSpell() && !sSpellStore.LookupEntry(PetActionBar[index].SpellOrAction))
10491 SetActionBar(index,0,ACT_DISABLED);
10493 return true;
10496 void CharmInfo::BuildActionBar( WorldPacket* data )
10498 for(uint32 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
10500 *data << uint16(PetActionBar[i].SpellOrAction);
10501 *data << uint16(PetActionBar[i].Type);
10505 void CharmInfo::SetSpellAutocast( uint32 spell_id, bool state )
10507 for(int i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
10509 if(spell_id == PetActionBar[i].SpellOrAction && PetActionBar[i].IsActionBarForSpell())
10511 PetActionBar[i].Type = state ? ACT_ENABLED : ACT_DISABLED;
10512 break;
10517 bool Unit::isFrozen() const
10519 return HasAuraState(AURA_STATE_FROZEN);
10522 struct ProcTriggeredData
10524 ProcTriggeredData(SpellProcEventEntry const * _spellProcEvent, Aura* _triggeredByAura)
10525 : spellProcEvent(_spellProcEvent), triggeredByAura(_triggeredByAura),
10526 triggeredByAura_SpellPair(Unit::spellEffectPair(triggeredByAura->GetId(),triggeredByAura->GetEffIndex()))
10528 SpellProcEventEntry const *spellProcEvent;
10529 Aura* triggeredByAura;
10530 Unit::spellEffectPair triggeredByAura_SpellPair;
10533 typedef std::list< ProcTriggeredData > ProcTriggeredList;
10534 typedef std::list< uint32> RemoveSpellList;
10536 // List of auras that CAN be trigger but may not exist in spell_proc_event
10537 // in most case need for drop charges
10538 // in some types of aura need do additional check
10539 // for example SPELL_AURA_MECHANIC_IMMUNITY - need check for mechanic
10540 bool InitTriggerAuraData()
10542 for (int i=0;i<TOTAL_AURAS;++i)
10544 isTriggerAura[i]=false;
10545 isNonTriggerAura[i] = false;
10547 isTriggerAura[SPELL_AURA_DUMMY] = true;
10548 isTriggerAura[SPELL_AURA_MOD_CONFUSE] = true;
10549 isTriggerAura[SPELL_AURA_MOD_THREAT] = true;
10550 isTriggerAura[SPELL_AURA_MOD_STUN] = true; // Aura not have charges but need remove him on trigger
10551 isTriggerAura[SPELL_AURA_MOD_DAMAGE_DONE] = true;
10552 isTriggerAura[SPELL_AURA_MOD_DAMAGE_TAKEN] = true;
10553 isTriggerAura[SPELL_AURA_MOD_RESISTANCE] = true;
10554 isTriggerAura[SPELL_AURA_MOD_ROOT] = true;
10555 isTriggerAura[SPELL_AURA_REFLECT_SPELLS] = true;
10556 isTriggerAura[SPELL_AURA_DAMAGE_IMMUNITY] = true;
10557 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL] = true;
10558 isTriggerAura[SPELL_AURA_PROC_TRIGGER_DAMAGE] = true;
10559 isTriggerAura[SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK] = true;
10560 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT] = true;
10561 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL] = true;
10562 isTriggerAura[SPELL_AURA_REFLECT_SPELLS_SCHOOL] = true;
10563 isTriggerAura[SPELL_AURA_MECHANIC_IMMUNITY] = true;
10564 isTriggerAura[SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN] = true;
10565 isTriggerAura[SPELL_AURA_SPELL_MAGNET] = true;
10566 isTriggerAura[SPELL_AURA_MOD_ATTACK_POWER] = true;
10567 isTriggerAura[SPELL_AURA_ADD_CASTER_HIT_TRIGGER] = true;
10568 isTriggerAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true;
10569 isTriggerAura[SPELL_AURA_MOD_MECHANIC_RESISTANCE] = true;
10570 isTriggerAura[SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS] = true;
10571 isTriggerAura[SPELL_AURA_MOD_HASTE] = true;
10572 isTriggerAura[SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE]=true;
10573 isTriggerAura[SPELL_AURA_PRAYER_OF_MENDING] = true;
10574 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE] = true;
10575 isTriggerAura[SPELL_AURA_MOD_DAMAGE_FROM_CASTER] = true;
10576 isTriggerAura[SPELL_AURA_MOD_SPELL_CRIT_CHANCE] = true;
10578 isNonTriggerAura[SPELL_AURA_MOD_POWER_REGEN]=true;
10579 isNonTriggerAura[SPELL_AURA_REDUCE_PUSHBACK]=true;
10581 return true;
10584 uint32 createProcExtendMask(SpellNonMeleeDamage *damageInfo, SpellMissInfo missCondition)
10586 uint32 procEx = PROC_EX_NONE;
10587 // Check victim state
10588 if (missCondition!=SPELL_MISS_NONE)
10589 switch (missCondition)
10591 case SPELL_MISS_MISS: procEx|=PROC_EX_MISS; break;
10592 case SPELL_MISS_RESIST: procEx|=PROC_EX_RESIST; break;
10593 case SPELL_MISS_DODGE: procEx|=PROC_EX_DODGE; break;
10594 case SPELL_MISS_PARRY: procEx|=PROC_EX_PARRY; break;
10595 case SPELL_MISS_BLOCK: procEx|=PROC_EX_BLOCK; break;
10596 case SPELL_MISS_EVADE: procEx|=PROC_EX_EVADE; break;
10597 case SPELL_MISS_IMMUNE: procEx|=PROC_EX_IMMUNE; break;
10598 case SPELL_MISS_IMMUNE2: procEx|=PROC_EX_IMMUNE; break;
10599 case SPELL_MISS_DEFLECT: procEx|=PROC_EX_DEFLECT;break;
10600 case SPELL_MISS_ABSORB: procEx|=PROC_EX_ABSORB; break;
10601 case SPELL_MISS_REFLECT: procEx|=PROC_EX_REFLECT;break;
10602 default:
10603 break;
10605 else
10607 // On block
10608 if (damageInfo->blocked)
10609 procEx|=PROC_EX_BLOCK;
10610 // On absorb
10611 if (damageInfo->absorb)
10612 procEx|=PROC_EX_ABSORB;
10613 // On crit
10614 if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT)
10615 procEx|=PROC_EX_CRITICAL_HIT;
10616 else
10617 procEx|=PROC_EX_NORMAL_HIT;
10619 return procEx;
10622 void Unit::ProcDamageAndSpellFor( bool isVictim, Unit * pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const * procSpell, uint32 damage )
10624 // For melee/ranged based attack need update skills and set some Aura states
10625 if (procFlag & MELEE_BASED_TRIGGER_MASK)
10627 // Update skills here for players
10628 if (GetTypeId() == TYPEID_PLAYER)
10630 // On melee based hit/miss/resist need update skill (for victim and attacker)
10631 if (procExtra&(PROC_EX_NORMAL_HIT|PROC_EX_MISS|PROC_EX_RESIST))
10633 if (pTarget->GetTypeId() != TYPEID_PLAYER && pTarget->GetCreatureType() != CREATURE_TYPE_CRITTER)
10634 ((Player*)this)->UpdateCombatSkills(pTarget, attType, isVictim);
10636 // Update defence if player is victim and parry/dodge/block
10637 if (isVictim && procExtra&(PROC_EX_DODGE|PROC_EX_PARRY|PROC_EX_BLOCK))
10638 ((Player*)this)->UpdateDefense();
10640 // If exist crit/parry/dodge/block need update aura state (for victim and attacker)
10641 if (procExtra & (PROC_EX_CRITICAL_HIT|PROC_EX_PARRY|PROC_EX_DODGE|PROC_EX_BLOCK))
10643 // for victim
10644 if (isVictim)
10646 // if victim and dodge attack
10647 if (procExtra&PROC_EX_DODGE)
10649 //Update AURA_STATE on dodge
10650 if (getClass() != CLASS_ROGUE) // skip Rogue Riposte
10652 ModifyAuraState(AURA_STATE_DEFENSE, true);
10653 StartReactiveTimer( REACTIVE_DEFENSE );
10656 // if victim and parry attack
10657 if (procExtra & PROC_EX_PARRY)
10659 // For Hunters only Counterattack (skip Mongoose bite)
10660 if (getClass() == CLASS_HUNTER)
10662 ModifyAuraState(AURA_STATE_HUNTER_PARRY, true);
10663 StartReactiveTimer( REACTIVE_HUNTER_PARRY );
10665 else
10667 ModifyAuraState(AURA_STATE_DEFENSE, true);
10668 StartReactiveTimer( REACTIVE_DEFENSE );
10671 // if and victim block attack
10672 if (procExtra & PROC_EX_BLOCK)
10674 ModifyAuraState(AURA_STATE_DEFENSE,true);
10675 StartReactiveTimer( REACTIVE_DEFENSE );
10678 else //For attacker
10680 // Overpower on victim dodge
10681 if (procExtra&PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR)
10683 ((Player*)this)->AddComboPoints(pTarget, 1);
10684 StartReactiveTimer( REACTIVE_OVERPOWER );
10690 RemoveSpellList removedSpells;
10691 ProcTriggeredList procTriggered;
10692 // Fill procTriggered list
10693 for(AuraMap::const_iterator itr = GetAuras().begin(); itr!= GetAuras().end(); ++itr)
10695 SpellProcEventEntry const* spellProcEvent = NULL;
10696 if(!IsTriggeredAtSpellProcEvent(pTarget, itr->second, procSpell, procFlag, procExtra, attType, isVictim, (damage > 0), spellProcEvent))
10697 continue;
10699 procTriggered.push_back( ProcTriggeredData(spellProcEvent, itr->second) );
10702 // Nothing found
10703 if (procTriggered.empty())
10704 return;
10706 // Handle effects proceed this time
10707 for(ProcTriggeredList::const_iterator i = procTriggered.begin(); i != procTriggered.end(); ++i)
10709 // Some auras can be deleted in function called in this loop (except first, ofc)
10710 // Until storing auars in std::multimap to hard check deleting by another way
10711 if(i != procTriggered.begin())
10713 bool found = false;
10714 AuraMap::const_iterator lower = GetAuras().lower_bound(i->triggeredByAura_SpellPair);
10715 AuraMap::const_iterator upper = GetAuras().upper_bound(i->triggeredByAura_SpellPair);
10716 for(AuraMap::const_iterator itr = lower; itr!= upper; ++itr)
10718 if(itr->second==i->triggeredByAura)
10720 found = true;
10721 break;
10724 if(!found)
10726 // sLog.outDebug("Spell aura %u (id:%u effect:%u) has been deleted before call spell proc event handler", i->triggeredByAura->GetModifier()->m_auraname, i->triggeredByAura_SpellPair.first, i->triggeredByAura_SpellPair.second);
10727 // sLog.outDebug("It can be deleted one from early proccesed auras:");
10728 // for(ProcTriggeredList::const_iterator i2 = procTriggered.begin(); i != i2; ++i2)
10729 // sLog.outDebug(" Spell aura %u (id:%u effect:%u)", i->triggeredByAura->GetModifier()->m_auraname,i2->triggeredByAura_SpellPair.first,i2->triggeredByAura_SpellPair.second);
10730 // sLog.outDebug(" <end of list>");
10731 continue;
10735 SpellProcEventEntry const *spellProcEvent = i->spellProcEvent;
10736 Aura *triggeredByAura = i->triggeredByAura;
10737 Modifier *auraModifier = triggeredByAura->GetModifier();
10738 SpellEntry const *spellInfo = triggeredByAura->GetSpellProto();
10739 bool useCharges = triggeredByAura->GetAuraCharges() > 0;
10740 // For players set spell cooldown if need
10741 uint32 cooldown = 0;
10742 if (GetTypeId() == TYPEID_PLAYER && spellProcEvent && spellProcEvent->cooldown)
10743 cooldown = spellProcEvent->cooldown;
10745 switch(auraModifier->m_auraname)
10747 case SPELL_AURA_PROC_TRIGGER_SPELL:
10749 sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
10750 // Don`t drop charge or add cooldown for not started trigger
10751 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10752 continue;
10753 break;
10755 case SPELL_AURA_PROC_TRIGGER_DAMAGE:
10757 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());
10758 SpellNonMeleeDamage damageInfo(this, pTarget, spellInfo->Id, spellInfo->SchoolMask);
10759 CalculateSpellDamage(&damageInfo, auraModifier->m_amount, spellInfo);
10760 DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb);
10761 SendSpellNonMeleeDamageLog(&damageInfo);
10762 DealSpellDamage(&damageInfo, true);
10763 break;
10765 case SPELL_AURA_MANA_SHIELD:
10766 case SPELL_AURA_OBS_MOD_MANA:
10767 case SPELL_AURA_DUMMY:
10769 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());
10770 if (!HandleDummyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10771 continue;
10772 break;
10774 case SPELL_AURA_MOD_HASTE:
10776 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());
10777 if (!HandleHasteAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10778 continue;
10779 break;
10781 case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
10783 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());
10784 if (!HandleOverrideClassScriptAuraProc(pTarget, damage, triggeredByAura, procSpell, cooldown))
10785 continue;
10786 break;
10788 case SPELL_AURA_PRAYER_OF_MENDING:
10790 sLog.outDebug("ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
10791 (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
10793 HandleMeandingAuraProc(triggeredByAura);
10794 break;
10796 case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE:
10798 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());
10800 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10801 continue;
10802 break;
10804 case SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK:
10805 // Skip melee hits or instant cast spells
10806 if (procSpell == NULL || GetSpellCastTime(procSpell) == 0)
10807 continue;
10808 break;
10809 case SPELL_AURA_REFLECT_SPELLS_SCHOOL:
10810 // Skip Melee hits and spells ws wrong school
10811 if (procSpell == NULL || (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0)
10812 continue;
10813 break;
10814 case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT:
10815 case SPELL_AURA_MOD_POWER_COST_SCHOOL:
10816 // Skip melee hits and spells ws wrong school or zero cost
10817 if (procSpell == NULL ||
10818 (procSpell->manaCost == 0 && procSpell->ManaCostPercentage == 0) || // Cost check
10819 (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0) // School check
10820 continue;
10821 break;
10822 case SPELL_AURA_MECHANIC_IMMUNITY:
10823 // Compare mechanic
10824 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
10825 continue;
10826 break;
10827 case SPELL_AURA_MOD_MECHANIC_RESISTANCE:
10828 // Compare mechanic
10829 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
10830 continue;
10831 break;
10832 case SPELL_AURA_MOD_DAMAGE_FROM_CASTER:
10833 // Compare casters
10834 if (triggeredByAura->GetCasterGUID() != pTarget->GetGUID())
10835 continue;
10836 break;
10837 default:
10838 // nothing do, just charges counter
10839 break;
10841 // Remove charge (aura can be removed by triggers)
10842 if(useCharges)
10844 // need found aura on drop (can be dropped by triggers)
10845 AuraMap::const_iterator lower = GetAuras().lower_bound(i->triggeredByAura_SpellPair);
10846 AuraMap::const_iterator upper = GetAuras().upper_bound(i->triggeredByAura_SpellPair);
10847 for(AuraMap::const_iterator itr = lower; itr!= upper; ++itr)
10849 // If last charge dropped add spell to remove list
10850 if(itr->second == i->triggeredByAura && triggeredByAura->DropAuraCharge())
10852 removedSpells.push_back(triggeredByAura->GetId());
10853 break;
10858 if (!removedSpells.empty())
10860 // Sort spells and remove dublicates
10861 removedSpells.sort();
10862 removedSpells.unique();
10863 // Remove auras from removedAuras
10864 for(RemoveSpellList::const_iterator i = removedSpells.begin(); i != removedSpells.end();++i)
10865 RemoveAurasDueToSpell(*i);
10869 SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const
10871 return SPELL_SCHOOL_MASK_NORMAL;
10874 Player* Unit::GetSpellModOwner()
10876 if(GetTypeId()==TYPEID_PLAYER)
10877 return (Player*)this;
10878 if(((Creature*)this)->isPet() || ((Creature*)this)->isTotem())
10880 Unit* owner = GetOwner();
10881 if(owner && owner->GetTypeId()==TYPEID_PLAYER)
10882 return (Player*)owner;
10884 return NULL;
10887 ///----------Pet responses methods-----------------
10888 void Unit::SendPetCastFail(uint32 spellid, SpellCastResult msg)
10890 if(msg == SPELL_CAST_OK)
10891 return;
10893 Unit *owner = GetCharmerOrOwner();
10894 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10895 return;
10897 WorldPacket data(SMSG_PET_CAST_FAILED, 1 + 4 + 1);
10898 data << uint8(0); // cast count?
10899 data << uint32(spellid);
10900 data << uint8(msg);
10901 // uint32 for some reason
10902 // uint32 for some reason
10903 ((Player*)owner)->GetSession()->SendPacket(&data);
10906 void Unit::SendPetActionFeedback (uint8 msg)
10908 Unit* owner = GetOwner();
10909 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10910 return;
10912 WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1);
10913 data << uint8(msg);
10914 ((Player*)owner)->GetSession()->SendPacket(&data);
10917 void Unit::SendPetTalk (uint32 pettalk)
10919 Unit* owner = GetOwner();
10920 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10921 return;
10923 WorldPacket data(SMSG_PET_ACTION_SOUND, 8 + 4);
10924 data << uint64(GetGUID());
10925 data << uint32(pettalk);
10926 ((Player*)owner)->GetSession()->SendPacket(&data);
10929 void Unit::SendPetSpellCooldown (uint32 spellid, time_t cooltime)
10931 Unit* owner = GetOwner();
10932 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10933 return;
10935 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4+4);
10936 data << uint64(GetGUID());
10937 data << uint8(0x0); // flags (0x1, 0x2)
10938 data << uint32(spellid);
10939 data << uint32(cooltime);
10941 ((Player*)owner)->GetSession()->SendPacket(&data);
10944 void Unit::SendPetClearCooldown (uint32 spellid)
10946 Unit* owner = GetOwner();
10947 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10948 return;
10950 WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
10951 data << uint32(spellid);
10952 data << uint64(GetGUID());
10953 ((Player*)owner)->GetSession()->SendPacket(&data);
10956 void Unit::SendPetAIReaction(uint64 guid)
10958 Unit* owner = GetOwner();
10959 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10960 return;
10962 WorldPacket data(SMSG_AI_REACTION, 8 + 4);
10963 data << uint64(guid);
10964 data << uint32(AI_REACTION_AGGRO);
10965 ((Player*)owner)->GetSession()->SendPacket(&data);
10968 ///----------End of Pet responses methods----------
10970 void Unit::StopMoving()
10972 clearUnitState(UNIT_STAT_MOVING);
10974 // send explicit stop packet
10975 // rely on vmaps here because for example stormwind is in air
10976 //float z = MapManager::Instance().GetBaseMap(GetMapId())->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), true);
10977 //if (fabs(GetPositionZ() - z) < 2.0f)
10978 // Relocate(GetPositionX(), GetPositionY(), z);
10979 Relocate(GetPositionX(), GetPositionY(),GetPositionZ());
10981 SendMonsterMove(GetPositionX(), GetPositionY(), GetPositionZ(), 0, 0, 0);
10983 // update position and orientation;
10984 WorldPacket data;
10985 BuildHeartBeatMsg(&data);
10986 SendMessageToSet(&data,false);
10989 void Unit::SetFeared(bool apply, uint64 casterGUID, uint32 spellID, uint32 time)
10991 if( apply )
10993 if(HasAuraType(SPELL_AURA_PREVENTS_FLEEING))
10994 return;
10996 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
10998 GetMotionMaster()->MovementExpired(false);
10999 CastStop(GetGUID()==casterGUID ? spellID : 0);
11001 Unit* caster = ObjectAccessor::GetUnit(*this,casterGUID);
11003 GetMotionMaster()->MoveFleeing(caster, time); // caster==NULL processed in MoveFleeing
11005 else
11007 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
11009 GetMotionMaster()->MovementExpired(false);
11011 if( GetTypeId() != TYPEID_PLAYER && isAlive() )
11013 // restore appropriate movement generator
11014 if(getVictim())
11015 GetMotionMaster()->MoveChase(getVictim());
11016 else
11017 GetMotionMaster()->Initialize();
11019 // attack caster if can
11020 Unit* caster = ObjectAccessor::GetObjectInWorld(casterGUID, (Unit*)NULL);
11021 if(caster && ((Creature*)this)->AI())
11022 ((Creature*)this)->AI()->AttackedBy(caster);
11026 if (GetTypeId() == TYPEID_PLAYER)
11027 ((Player*)this)->SetClientControl(this, !apply);
11030 void Unit::SetConfused(bool apply, uint64 casterGUID, uint32 spellID)
11032 if( apply )
11034 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
11036 CastStop(GetGUID()==casterGUID ? spellID : 0);
11038 GetMotionMaster()->MoveConfused();
11040 else
11042 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
11044 GetMotionMaster()->MovementExpired(false);
11046 if (GetTypeId() == TYPEID_UNIT)
11048 // if in combat restore movement generator
11049 if(getVictim())
11050 GetMotionMaster()->MoveChase(getVictim());
11054 if(GetTypeId() == TYPEID_PLAYER)
11055 ((Player*)this)->SetClientControl(this, !apply);
11058 bool Unit::IsSitState() const
11060 uint8 s = getStandState();
11061 return
11062 s == UNIT_STAND_STATE_SIT_CHAIR || s == UNIT_STAND_STATE_SIT_LOW_CHAIR ||
11063 s == UNIT_STAND_STATE_SIT_MEDIUM_CHAIR || s == UNIT_STAND_STATE_SIT_HIGH_CHAIR ||
11064 s == UNIT_STAND_STATE_SIT;
11067 bool Unit::IsStandState() const
11069 uint8 s = getStandState();
11070 return !IsSitState() && s != UNIT_STAND_STATE_SLEEP && s != UNIT_STAND_STATE_KNEEL;
11073 void Unit::SetStandState(uint8 state)
11075 SetByteValue(UNIT_FIELD_BYTES_1, 0, state);
11077 if (IsStandState())
11078 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED);
11080 if(GetTypeId()==TYPEID_PLAYER)
11082 WorldPacket data(SMSG_STANDSTATE_UPDATE, 1);
11083 data << (uint8)state;
11084 ((Player*)this)->GetSession()->SendPacket(&data);
11088 bool Unit::IsPolymorphed() const
11090 return GetSpellSpecific(getTransForm())==SPELL_MAGE_POLYMORPH;
11093 void Unit::SetDisplayId(uint32 modelId)
11095 SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId);
11097 if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
11099 Pet *pet = ((Pet*)this);
11100 if(!pet->isControlled())
11101 return;
11102 Unit *owner = GetOwner();
11103 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11104 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID);
11108 void Unit::ClearComboPointHolders()
11110 while(!m_ComboPointHolders.empty())
11112 uint32 lowguid = *m_ComboPointHolders.begin();
11114 Player* plr = objmgr.GetPlayer(MAKE_NEW_GUID(lowguid, 0, HIGHGUID_PLAYER));
11115 if(plr && plr->GetComboTarget()==GetGUID()) // recheck for safe
11116 plr->ClearComboPoints(); // remove also guid from m_ComboPointHolders;
11117 else
11118 m_ComboPointHolders.erase(lowguid); // or remove manually
11122 void Unit::ClearAllReactives()
11124 for(int i=0; i < MAX_REACTIVE; ++i)
11125 m_reactiveTimer[i] = 0;
11127 if (HasAuraState( AURA_STATE_DEFENSE))
11128 ModifyAuraState(AURA_STATE_DEFENSE, false);
11129 if (getClass() == CLASS_HUNTER && HasAuraState( AURA_STATE_HUNTER_PARRY))
11130 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
11131 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
11132 ((Player*)this)->ClearComboPoints();
11135 void Unit::UpdateReactives( uint32 p_time )
11137 for(int i = 0; i < MAX_REACTIVE; ++i)
11139 ReactiveType reactive = ReactiveType(i);
11141 if(!m_reactiveTimer[reactive])
11142 continue;
11144 if ( m_reactiveTimer[reactive] <= p_time)
11146 m_reactiveTimer[reactive] = 0;
11148 switch ( reactive )
11150 case REACTIVE_DEFENSE:
11151 if (HasAuraState(AURA_STATE_DEFENSE))
11152 ModifyAuraState(AURA_STATE_DEFENSE, false);
11153 break;
11154 case REACTIVE_HUNTER_PARRY:
11155 if ( getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
11156 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
11157 break;
11158 case REACTIVE_OVERPOWER:
11159 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
11160 ((Player*)this)->ClearComboPoints();
11161 break;
11162 default:
11163 break;
11166 else
11168 m_reactiveTimer[reactive] -= p_time;
11173 Unit* Unit::SelectNearbyTarget() const
11175 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
11176 Cell cell(p);
11177 cell.data.Part.reserved = ALL_DISTRICT;
11178 cell.SetNoCreate();
11180 std::list<Unit *> targets;
11183 MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, ATTACK_DISTANCE);
11184 MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> searcher(this, targets, u_check);
11186 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
11187 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
11189 CellLock<GridReadGuard> cell_lock(cell, p);
11190 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
11191 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
11194 // remove current target
11195 if(getVictim())
11196 targets.remove(getVictim());
11198 // remove not LoS targets
11199 for(std::list<Unit *>::iterator tIter = targets.begin(); tIter != targets.end();)
11201 if(!IsWithinLOSInMap(*tIter))
11203 std::list<Unit *>::iterator tIter2 = tIter;
11204 ++tIter;
11205 targets.erase(tIter2);
11207 else
11208 ++tIter;
11211 // no appropriate targets
11212 if(targets.empty())
11213 return NULL;
11215 // select random
11216 uint32 rIdx = urand(0,targets.size()-1);
11217 std::list<Unit *>::const_iterator tcIter = targets.begin();
11218 for(uint32 i = 0; i < rIdx; ++i)
11219 ++tcIter;
11221 return *tcIter;
11224 bool Unit::hasNegativeAuraWithInterruptFlag(uint32 flag)
11226 for (AuraMap::const_iterator iter = m_Auras.begin(); iter != m_Auras.end(); ++iter)
11228 if (!iter->second->IsPositive() && iter->second->GetSpellProto()->AuraInterruptFlags & flag)
11229 return true;
11231 return false;
11234 void Unit::ApplyAttackTimePercentMod( WeaponAttackType att,float val, bool apply )
11236 if(val > 0)
11238 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply);
11239 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,val,!apply);
11241 else
11243 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply);
11244 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,-val,apply);
11248 void Unit::ApplyCastTimePercentMod(float val, bool apply )
11250 if(val > 0)
11251 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,val,!apply);
11252 else
11253 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,-val,apply);
11256 uint32 Unit::GetCastingTimeForBonus( SpellEntry const *spellProto, DamageEffectType damagetype, uint32 CastingTime )
11258 // Not apply this to creature casted spells with casttime==0
11259 if(CastingTime==0 && GetTypeId()==TYPEID_UNIT && !((Creature*)this)->isPet())
11260 return 3500;
11262 if (CastingTime > 7000) CastingTime = 7000;
11263 if (CastingTime < 1500) CastingTime = 1500;
11265 if(damagetype == DOT && !IsChanneledSpell(spellProto))
11266 CastingTime = 3500;
11268 int32 overTime = 0;
11269 uint8 effects = 0;
11270 bool DirectDamage = false;
11271 bool AreaEffect = false;
11273 for ( uint32 i=0; i<3;++i)
11275 switch ( spellProto->Effect[i] )
11277 case SPELL_EFFECT_SCHOOL_DAMAGE:
11278 case SPELL_EFFECT_POWER_DRAIN:
11279 case SPELL_EFFECT_HEALTH_LEECH:
11280 case SPELL_EFFECT_ENVIRONMENTAL_DAMAGE:
11281 case SPELL_EFFECT_POWER_BURN:
11282 case SPELL_EFFECT_HEAL:
11283 DirectDamage = true;
11284 break;
11285 case SPELL_EFFECT_APPLY_AURA:
11286 switch ( spellProto->EffectApplyAuraName[i] )
11288 case SPELL_AURA_PERIODIC_DAMAGE:
11289 case SPELL_AURA_PERIODIC_HEAL:
11290 case SPELL_AURA_PERIODIC_LEECH:
11291 if ( GetSpellDuration(spellProto) )
11292 overTime = GetSpellDuration(spellProto);
11293 break;
11294 default:
11295 // -5% per additional effect
11296 ++effects;
11297 break;
11299 default:
11300 break;
11303 if(IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetA[i])) || IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetB[i])))
11304 AreaEffect = true;
11307 // Combined Spells with Both Over Time and Direct Damage
11308 if ( overTime > 0 && CastingTime > 0 && DirectDamage )
11310 // mainly for DoTs which are 3500 here otherwise
11311 uint32 OriginalCastTime = GetSpellCastTime(spellProto);
11312 if (OriginalCastTime > 7000) OriginalCastTime = 7000;
11313 if (OriginalCastTime < 1500) OriginalCastTime = 1500;
11314 // Portion to Over Time
11315 float PtOT = (overTime / 15000.0f) / ((overTime / 15000.0f) + (OriginalCastTime / 3500.0f));
11317 if ( damagetype == DOT )
11318 CastingTime = uint32(CastingTime * PtOT);
11319 else if ( PtOT < 1.0f )
11320 CastingTime = uint32(CastingTime * (1 - PtOT));
11321 else
11322 CastingTime = 0;
11325 // Area Effect Spells receive only half of bonus
11326 if ( AreaEffect )
11327 CastingTime /= 2;
11329 // -5% of total per any additional effect
11330 for ( uint8 i=0; i<effects; ++i)
11332 if ( CastingTime > 175 )
11334 CastingTime -= 175;
11336 else
11338 CastingTime = 0;
11339 break;
11343 return CastingTime;
11346 void Unit::UpdateAuraForGroup(uint8 slot)
11348 if(GetTypeId() == TYPEID_PLAYER)
11350 Player* player = (Player*)this;
11351 if(player->GetGroup())
11353 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_AURAS);
11354 player->SetAuraUpdateMask(slot);
11357 else if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
11359 Pet *pet = ((Pet*)this);
11360 if(pet->isControlled())
11362 Unit *owner = GetOwner();
11363 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11365 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_AURAS);
11366 pet->SetAuraUpdateMask(slot);
11372 float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized)
11374 if (!normalized || GetTypeId() != TYPEID_PLAYER)
11375 return float(GetAttackTime(attType))/1000.0f;
11377 Item *Weapon = ((Player*)this)->GetWeaponForAttack(attType);
11378 if (!Weapon)
11379 return 2.4; // fist attack
11381 switch (Weapon->GetProto()->InventoryType)
11383 case INVTYPE_2HWEAPON:
11384 return 3.3;
11385 case INVTYPE_RANGED:
11386 case INVTYPE_RANGEDRIGHT:
11387 case INVTYPE_THROWN:
11388 return 2.8;
11389 case INVTYPE_WEAPON:
11390 case INVTYPE_WEAPONMAINHAND:
11391 case INVTYPE_WEAPONOFFHAND:
11392 default:
11393 return Weapon->GetProto()->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7 : 2.4;
11397 Aura* Unit::GetDummyAura( uint32 spell_id ) const
11399 Unit::AuraList const& mDummy = GetAurasByType(SPELL_AURA_DUMMY);
11400 for(Unit::AuraList::const_iterator itr = mDummy.begin(); itr != mDummy.end(); ++itr)
11401 if ((*itr)->GetId() == spell_id)
11402 return *itr;
11404 return NULL;
11407 bool Unit::IsUnderLastManaUseEffect() const
11409 return getMSTimeDiff(m_lastManaUse,getMSTime()) < 5000;
11412 void Unit::SetContestedPvP(Player *attackedPlayer)
11414 Player* player = GetCharmerOrOwnerPlayerOrPlayerItself();
11416 if(!player || attackedPlayer && (attackedPlayer == player || player->duel && player->duel->opponent == attackedPlayer))
11417 return;
11419 player->SetContestedPvPTimer(30000);
11420 if(!player->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
11422 player->addUnitState(UNIT_STAT_ATTACK_PLAYER);
11423 player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
11424 // call MoveInLineOfSight for nearby contested guards
11425 SetVisibility(GetVisibility());
11427 if(!hasUnitState(UNIT_STAT_ATTACK_PLAYER))
11429 addUnitState(UNIT_STAT_ATTACK_PLAYER);
11430 // call MoveInLineOfSight for nearby contested guards
11431 SetVisibility(GetVisibility());
11435 void Unit::AddPetAura(PetAura const* petSpell)
11437 m_petAuras.insert(petSpell);
11438 if(Pet* pet = GetPet())
11439 pet->CastPetAura(petSpell);
11442 void Unit::RemovePetAura(PetAura const* petSpell)
11444 m_petAuras.erase(petSpell);
11445 if(Pet* pet = GetPet())
11446 pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry()));
11449 Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget,uint32 spell_id)
11451 Pet* pet = new Pet(HUNTER_PET);
11453 if(!pet->CreateBaseAtCreature(creatureTarget))
11455 delete pet;
11456 return NULL;
11459 pet->SetOwnerGUID(GetGUID());
11460 pet->SetCreatorGUID(GetGUID());
11461 pet->SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, getFaction());
11462 pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id);
11464 if(GetTypeId()==TYPEID_PLAYER)
11465 pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
11467 if(IsPvP())
11468 pet->SetPvP(true);
11470 uint32 level = (creatureTarget->getLevel() < (getLevel() - 5)) ? (getLevel() - 5) : creatureTarget->getLevel();
11472 if(!pet->InitStatsForLevel(level))
11474 sLog.outError("Pet::InitStatsForLevel() failed for creature (Entry: %u)!",creatureTarget->GetEntry());
11475 delete pet;
11476 return NULL;
11479 pet->GetCharmInfo()->SetPetNumber(objmgr.GeneratePetNumber(), true);
11480 // this enables pet details window (Shift+P)
11481 pet->AIM_Initialize();
11482 pet->InitPetCreateSpells();
11483 pet->InitLevelupSpellsForLevel();
11484 pet->InitTalentForLevel();
11485 pet->SetHealth(pet->GetMaxHealth());
11487 return pet;
11490 bool Unit::IsTriggeredAtSpellProcEvent(Unit *pVictim, Aura* aura, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const*& spellProcEvent )
11492 SpellEntry const* spellProto = aura->GetSpellProto ();
11494 // Get proc Event Entry
11495 spellProcEvent = spellmgr.GetSpellProcEvent(spellProto->Id);
11497 // Aura info stored here
11498 Modifier *mod = aura->GetModifier();
11499 // Skip this auras
11500 if (isNonTriggerAura[mod->m_auraname])
11501 return false;
11502 // If not trigger by default and spellProcEvent==NULL - skip
11503 if (!isTriggerAura[mod->m_auraname] && spellProcEvent==NULL)
11504 return false;
11506 // Get EventProcFlag
11507 uint32 EventProcFlag;
11508 if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags
11509 EventProcFlag = spellProcEvent->procFlags;
11510 else
11511 EventProcFlag = spellProto->procFlags; // else get from spell proto
11512 // Continue if no trigger exist
11513 if (!EventProcFlag)
11514 return false;
11516 // Check spellProcEvent data requirements
11517 if(!SpellMgr::IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active))
11518 return false;
11520 // In most cases req get honor or XP from kill
11521 if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER)
11523 bool allow = ((Player*)this)->isHonorOrXPTarget(pVictim);
11524 // Shadow Word: Death - can trigger from every kill
11525 if (aura->GetId() == 32409)
11526 allow = true;
11527 if (!allow)
11528 return false;
11530 // Aura added by spell can`t trogger from self (prevent drop charges/do triggers)
11531 // But except periodic triggers (can triggered from self)
11532 if(procSpell && procSpell->Id == spellProto->Id && !(spellProto->procFlags&PROC_FLAG_ON_TAKE_PERIODIC))
11533 return false;
11535 // Check if current equipment allows aura to proc
11536 if(!isVictim && GetTypeId() == TYPEID_PLAYER)
11538 if(spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
11540 Item *item = NULL;
11541 if(attType == BASE_ATTACK)
11542 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
11543 else if (attType == OFF_ATTACK)
11544 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
11545 else
11546 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
11548 if (!((Player*)this)->IsUseEquipedWeapon(attType==BASE_ATTACK))
11549 return false;
11551 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
11552 return false;
11554 else if(spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
11556 // Check if player is wearing shield
11557 Item *item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
11558 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
11559 return false;
11562 // Get chance from spell
11563 float chance = (float)spellProto->procChance;
11564 // If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance;
11565 if(spellProcEvent && spellProcEvent->customChance)
11566 chance = spellProcEvent->customChance;
11567 // If PPM exist calculate chance from PPM
11568 if(!isVictim && spellProcEvent && spellProcEvent->ppmRate != 0)
11570 uint32 WeaponSpeed = GetAttackTime(attType);
11571 chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate);
11573 // Apply chance modifer aura
11574 if(Player* modOwner = GetSpellModOwner())
11575 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
11577 return roll_chance_f(chance);
11580 bool Unit::HandleMeandingAuraProc( Aura* triggeredByAura )
11582 // aura can be deleted at casts
11583 SpellEntry const* spellProto = triggeredByAura->GetSpellProto();
11584 uint32 effIdx = triggeredByAura->GetEffIndex();
11585 int32 heal = triggeredByAura->GetModifier()->m_amount;
11586 uint64 caster_guid = triggeredByAura->GetCasterGUID();
11588 // jumps
11589 int32 jumps = triggeredByAura->GetAuraCharges()-1;
11591 // current aura expire
11592 triggeredByAura->SetAuraCharges(1); // will removed at next charges decrease
11594 // next target selection
11595 if(jumps > 0 && GetTypeId()==TYPEID_PLAYER && IS_PLAYER_GUID(caster_guid))
11597 float radius;
11598 if (spellProto->EffectRadiusIndex[effIdx])
11599 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
11600 else
11601 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
11603 if(Player* caster = ((Player*)triggeredByAura->GetCaster()))
11605 caster->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius,NULL);
11607 if(Player* target = ((Player*)this)->GetNextRandomRaidMember(radius))
11609 // aura will applied from caster, but spell casted from current aura holder
11610 SpellModifier *mod = new SpellModifier;
11611 mod->op = SPELLMOD_CHARGES;
11612 mod->value = jumps-5; // negative
11613 mod->type = SPELLMOD_FLAT;
11614 mod->spellId = spellProto->Id;
11615 mod->mask = spellProto->SpellFamilyFlags;
11616 mod->mask2 = spellProto->SpellFamilyFlags2;
11618 caster->AddSpellMod(mod, true);
11619 CastCustomSpell(target,spellProto->Id,&heal,NULL,NULL,true,NULL,triggeredByAura,caster->GetGUID());
11620 caster->AddSpellMod(mod, false);
11625 // heal
11626 CastCustomSpell(this,33110,&heal,NULL,NULL,true,NULL,NULL,caster_guid);
11627 return true;
11630 void Unit::RemoveAurasAtChanneledTarget(SpellEntry const* spellInfo)
11632 uint64 target_guid = GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT);
11634 if(!IS_UNIT_GUID(target_guid))
11635 return;
11637 Unit* target = ObjectAccessor::GetUnit(*this, target_guid);
11638 if(!target)
11639 return;
11641 for (AuraMap::iterator iter = target->GetAuras().begin(); iter != target->GetAuras().end(); )
11643 if (iter->second->GetId() == spellInfo->Id && iter->second->GetCasterGUID()==GetGUID())
11644 target->RemoveAura(iter);
11645 else
11646 ++iter;
11650 void Unit::SetPhaseMask(uint32 newPhaseMask, bool update)
11652 WorldObject::SetPhaseMask(newPhaseMask,update);
11654 if(IsInWorld())
11655 if(Pet* pet = GetPet())
11656 pet->SetPhaseMask(newPhaseMask,true);
11659 void Unit::NearTeleportTo( float x, float y, float z, float orientation, bool casting /*= false*/ )
11661 if(GetTypeId() == TYPEID_PLAYER)
11662 ((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));
11663 else
11665 GetMap()->CreatureRelocation((Creature*)this, x, y, z, orientation);
11667 WorldPacket data;
11668 // Work strange for many spells: triggered active mover set for targeted player to creature
11669 //BuildTeleportAckMsg(&data, x, y, z, orientation);
11670 BuildHeartBeatMsg(&data);
11671 SendMessageToSet(&data, false);
11675 void Unit::SetPvP( bool state )
11677 if(state)
11678 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP);
11679 else
11680 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP);
11682 if(Pet* pet = GetPet())
11683 pet->SetPvP(state);
11684 if(Unit* charmed = GetCharm())
11685 charmed->SetPvP(state);
11687 for (int8 i = 0; i < MAX_TOTEM; ++i)
11688 if(m_TotemSlot[i])
11689 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
11690 totem->SetPvP(state);