[7709] Cleanups in AI()->AttackedBy use.
[AHbot.git] / src / game / Unit.cpp
blob62a3f875cb448bef401e827faa0f1747c508b038
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);
288 data << uint32(Time); // Time in between points
289 data << uint32(1); // 1 single waypoint
290 data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B
292 if(player)
293 player->GetSession()->SendPacket(&data);
294 else
295 SendMessageToSet( &data, true );
298 void Unit::SendMonsterMoveByPath(Path const& path, uint32 start, uint32 end, uint32 MovementFlags)
300 uint32 traveltime = uint32(path.GetTotalLength(start, end) * 32);
302 uint32 pathSize = end-start;
304 WorldPacket data( SMSG_MONSTER_MOVE, (GetPackGUID().size()+4+4+4+4+1+4+4+4+pathSize*4*3) );
305 data.append(GetPackGUID());
306 data << GetPositionX();
307 data << GetPositionY();
308 data << GetPositionZ();
309 data << getMSTime();
310 data << uint8( 0 );
311 data << uint32( MovementFlags );
312 data << uint32( traveltime );
313 data << uint32( pathSize );
314 data.append( (char*)path.GetNodes(start), pathSize * 4 * 3 );
315 SendMessageToSet(&data, true);
318 void Unit::resetAttackTimer(WeaponAttackType type)
320 m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]);
323 bool Unit::canReachWithAttack(Unit *pVictim) const
325 assert(pVictim);
326 float reach = GetFloatValue(UNIT_FIELD_COMBATREACH);
327 if( reach <= 0.0f )
328 reach = 1.0f;
329 return IsWithinDistInMap(pVictim, reach);
332 void Unit::RemoveSpellsCausingAura(AuraType auraType)
334 if (auraType >= TOTAL_AURAS) return;
335 AuraList::iterator iter, next;
336 for (iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end(); iter = next)
338 next = iter;
339 ++next;
341 if (*iter)
343 RemoveAurasDueToSpell((*iter)->GetId());
344 if (!m_modAuras[auraType].empty())
345 next = m_modAuras[auraType].begin();
346 else
347 return;
352 bool Unit::HasAuraType(AuraType auraType) const
354 return (!m_modAuras[auraType].empty());
357 /* Called by DealDamage for auras that have a chance to be dispelled on damage taken. */
358 void Unit::RemoveSpellbyDamageTaken(AuraType auraType, uint32 damage)
360 if(!HasAuraType(auraType))
361 return;
363 // The chance to dispel an aura depends on the damage taken with respect to the casters level.
364 uint32 max_dmg = getLevel() > 8 ? 25 * getLevel() - 150 : 50;
365 float chance = float(damage) / max_dmg * 100.0f;
366 if (roll_chance_f(chance))
367 RemoveSpellsCausingAura(auraType);
370 uint32 Unit::DealDamage(Unit *pVictim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellEntry const *spellProto, bool durabilityLoss)
372 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
373 return 0;
375 //You don't lose health from damage taken from another player while in a sanctuary
376 //You still see it in the combat log though
377 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
379 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
380 if(area && area->flags & AREA_FLAG_SANCTUARY) //sanctuary
381 return 0;
384 // remove affects from victim (including from 0 damage and DoTs)
385 if(pVictim != this)
386 pVictim->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
388 // remove affects from attacker at any non-DoT damage (including 0 damage)
389 if( damagetype != DOT)
391 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
392 RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
394 if(pVictim != this)
395 RemoveSpellsCausingAura(SPELL_AURA_MOD_INVISIBILITY);
397 if(pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->IsStandState() && !pVictim->hasUnitState(UNIT_STAT_STUNNED))
398 pVictim->SetStandState(UNIT_STAND_STATE_STAND);
401 //Script Event damage Deal
402 if( GetTypeId()== TYPEID_UNIT && ((Creature *)this)->AI())
403 ((Creature *)this)->AI()->DamageDeal(pVictim, damage);
404 //Script Event damage taken
405 if( pVictim->GetTypeId()== TYPEID_UNIT && ((Creature *)pVictim)->AI() )
406 ((Creature *)pVictim)->AI()->DamageTaken(this, damage);
408 if(!damage)
410 // Rage from physical damage received .
411 if(cleanDamage && cleanDamage->damage && (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL) && pVictim->GetTypeId() == TYPEID_PLAYER && (pVictim->getPowerType() == POWER_RAGE))
412 ((Player*)pVictim)->RewardRage(cleanDamage->damage, 0, false);
414 return 0;
416 if (!spellProto || !IsAuraAddedBySpell(SPELL_AURA_MOD_FEAR, spellProto->Id))
417 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_FEAR, damage);
418 // root type spells do not dispel the root effect
419 if (!spellProto || !(spellProto->Mechanic == MECHANIC_ROOT || IsAuraAddedBySpell(SPELL_AURA_MOD_ROOT, spellProto->Id)))
420 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_ROOT, damage);
422 // no xp,health if type 8 /critters/
423 if(pVictim->GetTypeId() != TYPEID_PLAYER && pVictim->GetCreatureType() == CREATURE_TYPE_CRITTER)
425 pVictim->setDeathState(JUST_DIED);
426 pVictim->SetHealth(0);
428 // allow loot only if has loot_id in creature_template
429 CreatureInfo const* cInfo = ((Creature*)pVictim)->GetCreatureInfo();
430 if(cInfo && cInfo->lootid)
431 pVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
433 // some critters required for quests
434 if(GetTypeId() == TYPEID_PLAYER)
435 ((Player*)this)->KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
437 return damage;
440 DEBUG_LOG("DealDamageStart");
442 uint32 health = pVictim->GetHealth();
443 sLog.outDetail("deal dmg:%d to health:%d ",damage,health);
445 // duel ends when player has 1 or less hp
446 bool duel_hasEnded = false;
447 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->duel && damage >= (health-1))
449 // prevent kill only if killed in duel and killed by opponent or opponent controlled creature
450 if(((Player*)pVictim)->duel->opponent==this || ((Player*)pVictim)->duel->opponent->GetGUID() == GetOwnerGUID())
451 damage = health-1;
453 duel_hasEnded = true;
455 //Get in CombatState
456 if(pVictim != this && damagetype != DOT)
458 SetInCombatWith(pVictim);
459 pVictim->SetInCombatWith(this);
461 if(Player* attackedPlayer = pVictim->GetCharmerOrOwnerPlayerOrPlayerItself())
462 SetContestedPvP(attackedPlayer);
465 // Rage from Damage made (only from direct weapon damage)
466 if( cleanDamage && damagetype==DIRECT_DAMAGE && this != pVictim && GetTypeId() == TYPEID_PLAYER && (getPowerType() == POWER_RAGE))
468 uint32 weaponSpeedHitFactor;
470 switch(cleanDamage->attackType)
472 case BASE_ATTACK:
474 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
475 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 7);
476 else
477 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
479 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
481 break;
483 case OFF_ATTACK:
485 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
486 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
487 else
488 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 1.75f);
490 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
492 break;
494 case RANGED_ATTACK:
495 break;
499 if (GetTypeId() == TYPEID_PLAYER && this != pVictim)
501 Player *killer = ((Player*)this);
503 // in bg, count dmg if victim is also a player
504 if (pVictim->GetTypeId()==TYPEID_PLAYER)
506 if (BattleGround *bg = killer->GetBattleGround())
508 // FIXME: kept by compatibility. don't know in BG if the restriction apply.
509 bg->UpdatePlayerScore(killer, SCORE_DAMAGE_DONE, damage);
513 killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE, damage, 0, pVictim);
514 killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT, damage);
517 if (pVictim->GetTypeId() == TYPEID_PLAYER)
518 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED, damage);
520 if (pVictim->GetTypeId() == TYPEID_UNIT && !((Creature*)pVictim)->isPet() && !((Creature*)pVictim)->hasLootRecipient())
521 ((Creature*)pVictim)->SetLootRecipient(this);
523 if (health <= damage)
525 DEBUG_LOG("DealDamage: victim just died");
527 if (pVictim->GetTypeId() == TYPEID_PLAYER)
528 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, health);
531 // find player: owner of controlled `this` or `this` itself maybe
532 Player *player = GetCharmerOrOwnerPlayerOrPlayerItself();
534 if(pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->GetLootRecipient())
535 player = ((Creature*)pVictim)->GetLootRecipient();
536 // Reward player, his pets, and group/raid members
537 // call kill spell proc event (before real die and combat stop to triggering auras removed at death/combat stop)
538 if(player && player!=pVictim)
540 player->RewardPlayerAndGroupAtKill(pVictim);
541 player->ProcDamageAndSpell(pVictim, PROC_FLAG_KILL, PROC_FLAG_KILLED, PROC_EX_NONE, 0);
544 DEBUG_LOG("DealDamageAttackStop");
546 // stop combat
547 pVictim->CombatStop();
548 pVictim->getHostilRefManager().deleteReferences();
550 bool damageFromSpiritOfRedemtionTalent = spellProto && spellProto->Id == 27795;
552 // if talent known but not triggered (check priest class for speedup check)
553 Aura* spiritOfRedemtionTalentReady = NULL;
554 if( !damageFromSpiritOfRedemtionTalent && // not called from SPELL_AURA_SPIRIT_OF_REDEMPTION
555 pVictim->GetTypeId()==TYPEID_PLAYER && pVictim->getClass()==CLASS_PRIEST )
557 AuraList const& vDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
558 for(AuraList::const_iterator itr = vDummyAuras.begin(); itr != vDummyAuras.end(); ++itr)
560 if((*itr)->GetSpellProto()->SpellIconID==1654)
562 spiritOfRedemtionTalentReady = *itr;
563 break;
568 DEBUG_LOG("SET JUST_DIED");
569 if(!spiritOfRedemtionTalentReady)
570 pVictim->setDeathState(JUST_DIED);
572 DEBUG_LOG("DealDamageHealth1");
574 if(spiritOfRedemtionTalentReady)
576 // save value before aura remove
577 uint32 ressSpellId = pVictim->GetUInt32Value(PLAYER_SELF_RES_SPELL);
578 if(!ressSpellId)
579 ressSpellId = ((Player*)pVictim)->GetResurrectionSpellId();
581 //Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers)
582 pVictim->RemoveAllAurasOnDeath();
584 // restore for use at real death
585 pVictim->SetUInt32Value(PLAYER_SELF_RES_SPELL,ressSpellId);
587 // FORM_SPIRITOFREDEMPTION and related auras
588 pVictim->CastSpell(pVictim,27827,true,NULL,spiritOfRedemtionTalentReady);
590 else
591 pVictim->SetHealth(0);
593 // remember victim PvP death for corpse type and corpse reclaim delay
594 // at original death (not at SpiritOfRedemtionTalent timeout)
595 if( pVictim->GetTypeId()==TYPEID_PLAYER && !damageFromSpiritOfRedemtionTalent )
596 ((Player*)pVictim)->SetPvPDeath(player!=NULL);
598 // Call KilledUnit for creatures
599 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->AI())
600 ((Creature*)this)->AI()->KilledUnit(pVictim);
602 // achievement stuff
603 if (pVictim->GetTypeId() == TYPEID_PLAYER)
605 if (GetTypeId() == TYPEID_UNIT)
606 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE, GetEntry());
607 else if(GetTypeId() == TYPEID_PLAYER && pVictim != this)
608 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER, 1, ((Player*)this)->GetTeam());
611 // 10% durability loss on death
612 // clean InHateListOf
613 if (pVictim->GetTypeId() == TYPEID_PLAYER)
615 // only if not player and not controlled by player pet. And not at BG
616 if (durabilityLoss && !player && !((Player*)pVictim)->InBattleGround())
618 DEBUG_LOG("We are dead, loosing 10 percents durability");
619 ((Player*)pVictim)->DurabilityLossAll(0.10f,false);
620 // durability lost message
621 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
622 ((Player*)pVictim)->GetSession()->SendPacket(&data);
625 else // creature died
627 DEBUG_LOG("DealDamageNotPlayer");
628 Creature *cVictim = (Creature*)pVictim;
630 if(!cVictim->isPet())
632 cVictim->DeleteThreatList();
633 cVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
635 // Call creature just died function
636 if (cVictim->AI())
637 cVictim->AI()->JustDied(this);
639 // Dungeon specific stuff, only applies to players killing creatures
640 if(cVictim->GetInstanceId())
642 Map *m = cVictim->GetMap();
643 Player *creditedPlayer = GetCharmerOrOwnerPlayerOrPlayerItself();
644 // TODO: do instance binding anyway if the charmer/owner is offline
646 if(m->IsDungeon() && creditedPlayer)
648 if(m->IsRaid() || m->IsHeroic())
650 if(cVictim->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
651 ((InstanceMap *)m)->PermBindAllPlayers(creditedPlayer);
653 else
655 // the reset time is set but not added to the scheduler
656 // until the players leave the instance
657 time_t resettime = cVictim->GetRespawnTimeEx() + 2 * HOUR;
658 if(InstanceSave *save = sInstanceSaveManager.GetInstanceSave(cVictim->GetInstanceId()))
659 if(save->GetResetTime() < resettime) save->SetResetTime(resettime);
665 // last damage from non duel opponent or opponent controlled creature
666 if(duel_hasEnded)
668 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
669 Player *he = (Player*)pVictim;
671 assert(he->duel);
673 he->duel->opponent->CombatStopWithPets(true);
674 he->CombatStopWithPets(true);
676 he->DuelComplete(DUEL_INTERUPTED);
679 // battleground things (do this at the end, so the death state flag will be properly set to handle in the bg->handlekill)
680 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->InBattleGround())
682 Player *killed = ((Player*)pVictim);
683 if(BattleGround *bg = killed->GetBattleGround())
684 if(player)
685 bg->HandleKillPlayer(killed, player);
686 //later we can add support for creature->player kills here i'm
687 //not sure, but i guess those kills also get counted in av
688 //else if(GetTypeId() == TYPEID_UNIT)
689 // bg->HandleKillPlayer(killed,(Creature*)this);
692 else // if (health <= damage)
694 DEBUG_LOG("DealDamageAlive");
696 if (pVictim->GetTypeId() == TYPEID_PLAYER)
697 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, damage);
699 pVictim->ModifyHealth(- (int32)damage);
701 if(damagetype != DOT)
703 if(!getVictim())
705 // if not have main target then attack state with target (including AI call)
706 //start melee attacks only after melee hit
707 Attack(pVictim,(damagetype == DIRECT_DAMAGE));
710 // if damage pVictim call AI reaction
711 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
712 ((Creature*)pVictim)->AI()->AttackedBy(this);
715 // polymorphed and other negative transformed cases
716 if(pVictim->getTransForm() && pVictim->hasUnitState(UNIT_STAT_CONFUSED))
717 pVictim->RemoveAurasDueToSpell(pVictim->getTransForm());
719 if(damagetype == DIRECT_DAMAGE || damagetype == SPELL_DIRECT_DAMAGE)
721 if (!spellProto || !(spellProto->AuraInterruptFlags&AURA_INTERRUPT_FLAG_DIRECT_DAMAGE))
722 pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DIRECT_DAMAGE);
724 if (pVictim->GetTypeId() != TYPEID_PLAYER)
726 if(spellProto && IsDamageToThreatSpell(spellProto))
727 pVictim->AddThreat(this, damage*2, damageSchoolMask, spellProto);
728 else
729 pVictim->AddThreat(this, damage, damageSchoolMask, spellProto);
731 else // victim is a player
733 // Rage from damage received
734 if(this != pVictim && pVictim->getPowerType() == POWER_RAGE)
736 uint32 rage_damage = damage + (cleanDamage ? cleanDamage->damage : 0);
737 ((Player*)pVictim)->RewardRage(rage_damage, 0, false);
740 // random durability for items (HIT TAKEN)
741 if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
743 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
744 ((Player*)pVictim)->DurabilityPointLossForEquipSlot(slot);
748 if(GetTypeId()==TYPEID_PLAYER)
750 // random durability for items (HIT DONE)
751 if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
753 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
754 ((Player*)this)->DurabilityPointLossForEquipSlot(slot);
758 // TODO: Store auras by interrupt flag to speed this up.
759 AuraMap& vAuras = pVictim->GetAuras();
760 for (AuraMap::iterator i = vAuras.begin(), next; i != vAuras.end(); i = next)
762 const SpellEntry *se = i->second->GetSpellProto();
763 next = i; ++next;
764 if (spellProto && spellProto->Id == se->Id) // Not drop auras added by self
765 continue;
766 if( se->AuraInterruptFlags & AURA_INTERRUPT_FLAG_DAMAGE )
768 bool remove = true;
769 if (se->procFlags & (1<<3))
771 if (!roll_chance_i(se->procChance))
772 remove = false;
774 if (remove)
776 pVictim->RemoveAurasDueToSpell(i->second->GetId());
777 // FIXME: this may cause the auras with proc chance to be rerolled several times
778 next = vAuras.begin();
783 if (damagetype != NODAMAGE && damage && pVictim->GetTypeId() == TYPEID_PLAYER)
785 if( damagetype != DOT )
787 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
789 // skip channeled spell (processed differently below)
790 if (i == CURRENT_CHANNELED_SPELL)
791 continue;
793 if(Spell* spell = pVictim->m_currentSpells[i])
794 if(spell->getState() == SPELL_STATE_PREPARING)
796 if(spell->m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_ABORT_ON_DMG)
797 pVictim->InterruptSpell(i);
798 else
799 spell->Delayed();
804 if(Spell* spell = pVictim->m_currentSpells[CURRENT_CHANNELED_SPELL])
806 if (spell->getState() == SPELL_STATE_CASTING)
808 uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags;
809 if( channelInterruptFlags & CHANNEL_FLAG_DELAY )
811 if(pVictim!=this) //don't shorten the duration of channeling if you damage yourself
812 spell->DelayedChannel();
814 else if( (channelInterruptFlags & (CHANNEL_FLAG_DAMAGE | CHANNEL_FLAG_DAMAGE2)) )
816 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
817 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
820 else if (spell->getState() == SPELL_STATE_DELAYED)
821 // break channeled spell in delayed state on damage
823 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
824 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
829 // last damage from duel opponent
830 if(duel_hasEnded)
832 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
833 Player *he = (Player*)pVictim;
835 assert(he->duel);
837 he->SetHealth(1);
839 he->duel->opponent->CombatStopWithPets(true);
840 he->CombatStopWithPets(true);
842 he->CastSpell(he, 7267, true); // beg
843 he->DuelComplete(DUEL_WON);
847 DEBUG_LOG("DealDamageEnd returned %d damage", damage);
849 return damage;
852 void Unit::CastStop(uint32 except_spellid)
854 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
855 if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id!=except_spellid)
856 InterruptSpell(i,false);
859 void Unit::CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
861 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
863 if(!spellInfo)
865 sLog.outError("CastSpell: unknown spell id %i by caster: %s %u)", spellId,(GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
866 return;
869 CastSpell(Victim,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
872 void Unit::CastSpell(Unit* Victim,SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
874 if(!spellInfo)
876 sLog.outError("CastSpell: unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
877 return;
880 if (castItem)
881 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
883 if(!originalCaster && triggeredByAura)
884 originalCaster = triggeredByAura->GetCasterGUID();
886 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
888 SpellCastTargets targets;
889 targets.setUnitTarget( Victim );
890 spell->m_CastItem = castItem;
891 spell->prepare(&targets, triggeredByAura);
894 void Unit::CastCustomSpell(Unit* Victim,uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
896 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
898 if(!spellInfo)
900 sLog.outError("CastCustomSpell: unknown spell id %i", spellId);
901 return;
904 CastCustomSpell(Victim,spellInfo,bp0,bp1,bp2,triggered,castItem,triggeredByAura, originalCaster);
907 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)
909 if(!spellInfo)
911 sLog.outError("CastCustomSpell: unknown spell");
912 return;
915 if (castItem)
916 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
918 if(!originalCaster && triggeredByAura)
919 originalCaster = triggeredByAura->GetCasterGUID();
921 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster);
923 if(bp0)
924 spell->m_currentBasePoints[0] = *bp0-int32(spellInfo->EffectBaseDice[0]);
926 if(bp1)
927 spell->m_currentBasePoints[1] = *bp1-int32(spellInfo->EffectBaseDice[1]);
929 if(bp2)
930 spell->m_currentBasePoints[2] = *bp2-int32(spellInfo->EffectBaseDice[2]);
932 SpellCastTargets targets;
933 targets.setUnitTarget( Victim );
934 spell->m_CastItem = castItem;
935 spell->prepare(&targets, triggeredByAura);
938 // used for scripting
939 void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
941 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
943 if(!spellInfo)
945 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()));
946 return;
949 CastSpell(x, y, z,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
952 // used for scripting
953 void Unit::CastSpell(float x, float y, float z, SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
955 if(!spellInfo)
957 sLog.outError("CastSpell(x,y,z): unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
958 return;
961 if (castItem)
962 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
964 if(!originalCaster && triggeredByAura)
965 originalCaster = triggeredByAura->GetCasterGUID();
967 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
969 SpellCastTargets targets;
970 targets.setDestination(x, y, z);
971 spell->m_CastItem = castItem;
972 spell->prepare(&targets, triggeredByAura);
975 // Obsolete func need remove, here only for comotability vs another patches
976 uint32 Unit::SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage, bool isTriggeredSpell, bool useSpellDamage)
978 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellID);
979 SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, spellInfo->SchoolMask);
980 CalculateSpellDamage(&damageInfo, damage, spellInfo);
981 SendSpellNonMeleeDamageLog(&damageInfo);
982 DealSpellDamage(&damageInfo, true);
983 return damageInfo.damage;
986 void Unit::CalculateSpellDamage(SpellNonMeleeDamage *damageInfo, int32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType)
988 SpellSchoolMask damageSchoolMask = SpellSchoolMask(damageInfo->schoolMask);
989 Unit *pVictim = damageInfo->target;
991 if (damage < 0)
992 return;
994 if(!this || !pVictim)
995 return;
996 if(!this->isAlive() || !pVictim->isAlive())
997 return;
999 uint32 crTypeMask = pVictim->GetCreatureTypeMask();
1000 // Check spell crit chance
1001 bool crit = isSpellCrit(pVictim, spellInfo, damageSchoolMask, attackType);
1002 bool blocked = false;
1003 // Per-school calc
1004 switch (spellInfo->DmgClass)
1006 // Melee and Ranged Spells
1007 case SPELL_DAMAGE_CLASS_RANGED:
1008 case SPELL_DAMAGE_CLASS_MELEE:
1010 // Physical Damage
1011 if ( damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL )
1013 //Calculate armor mitigation
1014 damage = CalcArmorReducedDamage(pVictim, damage);
1015 // Get blocked status
1016 blocked = isSpellBlocked(pVictim, spellInfo, attackType);
1018 // Magical Damage
1019 else
1021 // Calculate damage bonus
1022 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1024 if (crit)
1026 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1028 // Calculate crit bonus
1029 uint32 crit_bonus = damage;
1030 // Apply crit_damage bonus for melee spells
1031 if(Player* modOwner = GetSpellModOwner())
1032 modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
1033 damage += crit_bonus;
1035 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1036 int32 critPctDamageMod=0;
1037 if(attackType == RANGED_ATTACK)
1038 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1039 else
1041 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1042 critPctDamageMod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1044 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1045 critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1047 if (critPctDamageMod!=0)
1048 damage = int32((damage) * float((100.0f + critPctDamageMod)/100.0f));
1050 // Resilience - reduce crit damage
1051 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1052 damage -= ((Player*)pVictim)->GetMeleeCritDamageReduction(damage);
1054 // Spell weapon based damage CAN BE crit & blocked at same time
1055 if (blocked)
1057 damageInfo->blocked = uint32(pVictim->GetShieldBlockValue());
1058 if (damage < damageInfo->blocked)
1059 damageInfo->blocked = damage;
1060 damage-=damageInfo->blocked;
1063 break;
1064 // Magical Attacks
1065 case SPELL_DAMAGE_CLASS_NONE:
1066 case SPELL_DAMAGE_CLASS_MAGIC:
1068 // Calculate damage bonus
1069 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1070 // If crit add critical bonus
1071 if (crit)
1073 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1074 damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim);
1075 // Resilience - reduce crit damage
1076 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1077 damage -= ((Player*)pVictim)->GetSpellCritDamageReduction(damage);
1080 break;
1083 // Calculate absorb resist
1084 if(damage > 0)
1086 // lookup absorb/resist ignore auras on caster for spell
1087 bool ignore = false;
1088 Unit::AuraList const& ignoreAbsorb = GetAurasByType(SPELL_AURA_MOD_IGNORE_ABSORB_FOR_SPELL);
1089 for(Unit::AuraList::const_iterator i = ignoreAbsorb.begin(); i != ignoreAbsorb.end(); ++i)
1090 if ((*i)->isAffectedOnSpell(spellInfo))
1092 ignore = true;
1093 break;
1096 if (!ignore)
1098 CalcAbsorbResist(pVictim, damageSchoolMask, SPELL_DIRECT_DAMAGE, damage, &damageInfo->absorb, &damageInfo->resist);
1099 damage-= damageInfo->absorb + damageInfo->resist;
1102 else
1103 damage = 0;
1104 damageInfo->damage = damage;
1107 void Unit::DealSpellDamage(SpellNonMeleeDamage *damageInfo, bool durabilityLoss)
1109 if (damageInfo==0)
1110 return;
1112 Unit *pVictim = damageInfo->target;
1114 if(!this || !pVictim)
1115 return;
1117 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1118 return;
1120 SpellEntry const *spellProto = sSpellStore.LookupEntry(damageInfo->SpellID);
1121 if (spellProto == NULL)
1123 sLog.outDebug("Unit::DealSpellDamage have wrong damageInfo->SpellID: %u", damageInfo->SpellID);
1124 return;
1127 //You don't lose health from damage taken from another player while in a sanctuary
1128 //You still see it in the combat log though
1129 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1131 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1132 if(area && area->flags & 0x800) //sanctuary
1133 return;
1136 // Call default DealDamage
1137 CleanDamage cleanDamage(damageInfo->cleanDamage, BASE_ATTACK, MELEE_HIT_NORMAL);
1138 DealDamage(pVictim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, SpellSchoolMask(damageInfo->schoolMask), spellProto, durabilityLoss);
1141 //TODO for melee need create structure as in
1142 void Unit::CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType)
1144 damageInfo->attacker = this;
1145 damageInfo->target = pVictim;
1146 damageInfo->damageSchoolMask = GetMeleeDamageSchoolMask();
1147 damageInfo->attackType = attackType;
1148 damageInfo->damage = 0;
1149 damageInfo->cleanDamage = 0;
1150 damageInfo->absorb = 0;
1151 damageInfo->resist = 0;
1152 damageInfo->blocked_amount = 0;
1154 damageInfo->TargetState = 0;
1155 damageInfo->HitInfo = 0;
1156 damageInfo->procAttacker = PROC_FLAG_NONE;
1157 damageInfo->procVictim = PROC_FLAG_NONE;
1158 damageInfo->procEx = PROC_EX_NONE;
1159 damageInfo->hitOutCome = MELEE_HIT_EVADE;
1161 if(!this || !pVictim)
1162 return;
1163 if(!this->isAlive() || !pVictim->isAlive())
1164 return;
1166 // Select HitInfo/procAttacker/procVictim flag based on attack type
1167 switch (attackType)
1169 case BASE_ATTACK:
1170 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MILEE_HIT;
1171 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;
1172 damageInfo->HitInfo = HITINFO_NORMALSWING2;
1173 break;
1174 case OFF_ATTACK:
1175 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MILEE_HIT | PROC_FLAG_SUCCESSFUL_OFFHAND_HIT;
1176 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;//|PROC_FLAG_TAKEN_OFFHAND_HIT // not used
1177 damageInfo->HitInfo = HITINFO_LEFTSWING;
1178 break;
1179 case RANGED_ATTACK:
1180 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
1181 damageInfo->procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
1182 damageInfo->HitInfo = 0x08;// test
1183 break;
1184 default:
1185 break;
1188 // Physical Immune check
1189 if(damageInfo->target->IsImmunedToDamage(SpellSchoolMask(damageInfo->damageSchoolMask)))
1191 damageInfo->HitInfo |= HITINFO_NORMALSWING;
1192 damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE;
1194 damageInfo->procEx |=PROC_EX_IMMUNE;
1195 damageInfo->damage = 0;
1196 damageInfo->cleanDamage = 0;
1197 return;
1199 damage += CalculateDamage (damageInfo->attackType, false);
1200 // Add melee damage bonus
1201 MeleeDamageBonus(damageInfo->target, &damage, damageInfo->attackType);
1202 // Calculate armor reduction
1203 damageInfo->damage = CalcArmorReducedDamage(damageInfo->target, damage);
1204 damageInfo->cleanDamage += damage - damageInfo->damage;
1206 damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType);
1208 // Disable parry or dodge for ranged attack
1209 if(damageInfo->attackType == RANGED_ATTACK)
1211 if (damageInfo->hitOutCome == MELEE_HIT_PARRY) damageInfo->hitOutCome = MELEE_HIT_NORMAL;
1212 if (damageInfo->hitOutCome == MELEE_HIT_DODGE) damageInfo->hitOutCome = MELEE_HIT_MISS;
1215 switch(damageInfo->hitOutCome)
1217 case MELEE_HIT_EVADE:
1219 damageInfo->HitInfo |= HITINFO_MISS|HITINFO_SWINGNOHITSOUND;
1220 damageInfo->TargetState = VICTIMSTATE_EVADES;
1222 damageInfo->procEx|=PROC_EX_EVADE;
1223 damageInfo->damage = 0;
1224 damageInfo->cleanDamage = 0;
1225 return;
1227 case MELEE_HIT_MISS:
1229 damageInfo->HitInfo |= HITINFO_MISS;
1230 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1232 damageInfo->procEx|=PROC_EX_MISS;
1233 damageInfo->damage = 0;
1234 damageInfo->cleanDamage = 0;
1235 break;
1237 case MELEE_HIT_NORMAL:
1238 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1239 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1240 break;
1241 case MELEE_HIT_CRIT:
1243 damageInfo->HitInfo |= HITINFO_CRITICALHIT;
1244 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1246 damageInfo->procEx|=PROC_EX_CRITICAL_HIT;
1247 // Crit bonus calc
1248 damageInfo->damage += damageInfo->damage;
1249 int32 mod=0;
1250 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1251 if(damageInfo->attackType == RANGED_ATTACK)
1252 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1253 else
1255 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1256 mod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1259 uint32 crTypeMask = damageInfo->target->GetCreatureTypeMask();
1261 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1262 mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1263 if (mod!=0)
1264 damageInfo->damage = int32((damageInfo->damage) * float((100.0f + mod)/100.0f));
1266 // Resilience - reduce crit damage
1267 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1269 uint32 resilienceReduction = ((Player*)pVictim)->GetMeleeCritDamageReduction(damageInfo->damage);
1270 damageInfo->damage -= resilienceReduction;
1271 damageInfo->cleanDamage += resilienceReduction;
1273 break;
1275 case MELEE_HIT_PARRY:
1276 damageInfo->TargetState = VICTIMSTATE_PARRY;
1277 damageInfo->procEx|=PROC_EX_PARRY;
1278 damageInfo->cleanDamage += damageInfo->damage;
1279 damageInfo->damage = 0;
1280 break;
1282 case MELEE_HIT_DODGE:
1283 damageInfo->TargetState = VICTIMSTATE_DODGE;
1284 damageInfo->procEx|=PROC_EX_DODGE;
1285 damageInfo->cleanDamage += damageInfo->damage;
1286 damageInfo->damage = 0;
1287 break;
1288 case MELEE_HIT_BLOCK:
1290 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1291 damageInfo->HitInfo |= HITINFO_BLOCK;
1292 damageInfo->procEx|=PROC_EX_BLOCK;
1293 damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue();
1294 if (damageInfo->blocked_amount >= damageInfo->damage)
1296 damageInfo->TargetState = VICTIMSTATE_BLOCKS;
1297 damageInfo->blocked_amount = damageInfo->damage;
1299 damageInfo->damage -= damageInfo->blocked_amount;
1300 damageInfo->cleanDamage += damageInfo->blocked_amount;
1301 break;
1303 case MELEE_HIT_GLANCING:
1305 damageInfo->HitInfo |= HITINFO_GLANCING;
1306 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1307 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1308 float reducePercent = 1.0f; //damage factor
1309 // calculate base values and mods
1310 float baseLowEnd = 1.3f;
1311 float baseHighEnd = 1.2f;
1312 switch(getClass()) // lowering base values for casters
1314 case CLASS_SHAMAN:
1315 case CLASS_PRIEST:
1316 case CLASS_MAGE:
1317 case CLASS_WARLOCK:
1318 case CLASS_DRUID:
1319 baseLowEnd -= 0.7f;
1320 baseHighEnd -= 0.3f;
1321 break;
1324 float maxLowEnd = 0.6f;
1325 switch(getClass()) // upper for melee classes
1327 case CLASS_WARRIOR:
1328 case CLASS_ROGUE:
1329 maxLowEnd = 0.91f; //If the attacker is a melee class then instead the lower value of 0.91
1332 // calculate values
1333 int32 diff = damageInfo->target->GetDefenseSkillValue() - GetWeaponSkillValue(damageInfo->attackType);
1334 float lowEnd = baseLowEnd - ( 0.05f * diff );
1335 float highEnd = baseHighEnd - ( 0.03f * diff );
1337 // apply max/min bounds
1338 if ( lowEnd < 0.01f ) //the low end must not go bellow 0.01f
1339 lowEnd = 0.01f;
1340 else if ( lowEnd > maxLowEnd ) //the smaller value of this and 0.6 is kept as the low end
1341 lowEnd = maxLowEnd;
1343 if ( highEnd < 0.2f ) //high end limits
1344 highEnd = 0.2f;
1345 if ( highEnd > 0.99f )
1346 highEnd = 0.99f;
1348 if(lowEnd > highEnd) // prevent negative range size
1349 lowEnd = highEnd;
1351 reducePercent = lowEnd + rand_norm() * ( highEnd - lowEnd );
1353 damageInfo->cleanDamage += damageInfo->damage-uint32(reducePercent * damageInfo->damage);
1354 damageInfo->damage = uint32(reducePercent * damageInfo->damage);
1355 break;
1357 case MELEE_HIT_CRUSHING:
1359 damageInfo->HitInfo |= HITINFO_CRUSHING;
1360 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1361 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1362 // 150% normal damage
1363 damageInfo->damage += (damageInfo->damage / 2);
1364 break;
1366 default:
1368 break;
1371 // Calculate absorb resist
1372 if(int32(damageInfo->damage) > 0)
1374 damageInfo->procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1375 // Calculate absorb & resists
1376 CalcAbsorbResist(damageInfo->target, SpellSchoolMask(damageInfo->damageSchoolMask), DIRECT_DAMAGE, damageInfo->damage, &damageInfo->absorb, &damageInfo->resist);
1377 damageInfo->damage-=damageInfo->absorb + damageInfo->resist;
1378 if (damageInfo->absorb)
1380 damageInfo->HitInfo|=HITINFO_ABSORB;
1381 damageInfo->procEx|=PROC_EX_ABSORB;
1383 if (damageInfo->resist)
1384 damageInfo->HitInfo|=HITINFO_RESIST;
1387 else // Umpossible get negative result but....
1388 damageInfo->damage = 0;
1391 void Unit::DealMeleeDamage(CalcDamageInfo *damageInfo, bool durabilityLoss)
1393 if (damageInfo==0) return;
1394 Unit *pVictim = damageInfo->target;
1396 if(!this || !pVictim)
1397 return;
1399 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1400 return;
1402 //You don't lose health from damage taken from another player while in a sanctuary
1403 //You still see it in the combat log though
1404 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1406 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1407 if(area && area->flags & 0x800) //sanctuary
1408 return;
1411 // Hmmmm dont like this emotes cloent must by self do all animations
1412 if (damageInfo->HitInfo&HITINFO_CRITICALHIT)
1413 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_WOUNDCRITICAL);
1414 if(damageInfo->blocked_amount && damageInfo->TargetState!=VICTIMSTATE_BLOCKS)
1415 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_PARRYSHIELD);
1417 if(damageInfo->TargetState == VICTIMSTATE_PARRY)
1419 // Get attack timers
1420 float offtime = float(pVictim->getAttackTimer(OFF_ATTACK));
1421 float basetime = float(pVictim->getAttackTimer(BASE_ATTACK));
1422 // Reduce attack time
1423 if (pVictim->haveOffhandWeapon() && offtime < basetime)
1425 float percent20 = pVictim->GetAttackTime(OFF_ATTACK) * 0.20f;
1426 float percent60 = 3.0f * percent20;
1427 if(offtime > percent20 && offtime <= percent60)
1429 pVictim->setAttackTimer(OFF_ATTACK, uint32(percent20));
1431 else if(offtime > percent60)
1433 offtime -= 2.0f * percent20;
1434 pVictim->setAttackTimer(OFF_ATTACK, uint32(offtime));
1437 else
1439 float percent20 = pVictim->GetAttackTime(BASE_ATTACK) * 0.20;
1440 float percent60 = 3.0f * percent20;
1441 if(basetime > percent20 && basetime <= percent60)
1443 pVictim->setAttackTimer(BASE_ATTACK, uint32(percent20));
1445 else if(basetime > percent60)
1447 basetime -= 2.0f * percent20;
1448 pVictim->setAttackTimer(BASE_ATTACK, uint32(basetime));
1453 // Call default DealDamage
1454 CleanDamage cleanDamage(damageInfo->cleanDamage,damageInfo->attackType,damageInfo->hitOutCome);
1455 DealDamage(pVictim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->damageSchoolMask), NULL, durabilityLoss);
1457 // If this is a creature and it attacks from behind it has a probability to daze it's victim
1458 if( (damageInfo->hitOutCome==MELEE_HIT_CRIT || damageInfo->hitOutCome==MELEE_HIT_CRUSHING || damageInfo->hitOutCome==MELEE_HIT_NORMAL || damageInfo->hitOutCome==MELEE_HIT_GLANCING) &&
1459 GetTypeId() != TYPEID_PLAYER && !((Creature*)this)->GetCharmerOrOwnerGUID() && !pVictim->HasInArc(M_PI, this) )
1461 // -probability is between 0% and 40%
1462 // 20% base chance
1463 float Probability = 20.0f;
1465 //there is a newbie protection, at level 10 just 7% base chance; assuming linear function
1466 if( pVictim->getLevel() < 30 )
1467 Probability = 0.65f*pVictim->getLevel()+0.5f;
1469 uint32 VictimDefense=pVictim->GetDefenseSkillValue();
1470 uint32 AttackerMeleeSkill=GetUnitMeleeSkill();
1472 Probability *= AttackerMeleeSkill/(float)VictimDefense;
1474 if(Probability > 40.0f)
1475 Probability = 40.0f;
1477 if(roll_chance_f(Probability))
1478 CastSpell(pVictim, 1604, true);
1481 // If not miss
1482 if (!(damageInfo->HitInfo & HITINFO_MISS))
1484 if(GetTypeId() == TYPEID_PLAYER && pVictim->isAlive())
1486 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
1487 ((Player*)this)->CastItemCombatSpell(((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0,i), pVictim, damageInfo->attackType);
1490 // victim's damage shield
1491 std::set<Aura*> alreadyDone;
1492 uint32 removedAuras = pVictim->m_removedAuras;
1493 AuraList const& vDamageShields = pVictim->GetAurasByType(SPELL_AURA_DAMAGE_SHIELD);
1494 for(AuraList::const_iterator i = vDamageShields.begin(), next = vDamageShields.begin(); i != vDamageShields.end(); i = next)
1496 next++;
1497 if (alreadyDone.find(*i) == alreadyDone.end())
1499 alreadyDone.insert(*i);
1500 uint32 damage=(*i)->GetModifier()->m_amount;
1501 SpellEntry const *spellProto = sSpellStore.LookupEntry((*i)->GetId());
1502 if(!spellProto)
1503 continue;
1504 //Calculate absorb resist ??? no data in opcode for this possibly unable to absorb or resist?
1505 //uint32 absorb;
1506 //uint32 resist;
1507 //CalcAbsorbResist(pVictim, SpellSchools(spellProto->School), SPELL_DIRECT_DAMAGE, damage, &absorb, &resist);
1508 //damage-=absorb + resist;
1510 WorldPacket data(SMSG_SPELLDAMAGESHIELD,(8+8+4+4+4+4));
1511 data << uint64(pVictim->GetGUID());
1512 data << uint64(GetGUID());
1513 data << uint32(spellProto->Id);
1514 data << uint32(damage); // Damage
1515 data << uint32(0); // Overkill
1516 data << uint32(spellProto->SchoolMask);
1517 pVictim->SendMessageToSet(&data, true );
1519 pVictim->DealDamage(this, damage, 0, SPELL_DIRECT_DAMAGE, GetSpellSchoolMask(spellProto), spellProto, true);
1521 if (pVictim->m_removedAuras > removedAuras)
1523 removedAuras = pVictim->m_removedAuras;
1524 next = vDamageShields.begin();
1532 void Unit::HandleEmoteCommand(uint32 anim_id)
1534 WorldPacket data( SMSG_EMOTE, 12 );
1535 data << uint32(anim_id);
1536 data << uint64(GetGUID());
1537 SendMessageToSet(&data, true);
1540 uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage)
1542 uint32 newdamage = 0;
1543 float armor = pVictim->GetArmor();
1544 // Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura
1545 armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL);
1547 // Apply Player CR_ARMOR_PENETRATION rating
1548 if (GetTypeId()==TYPEID_PLAYER)
1549 armor *= 1.0f - ((Player*)this)->GetRatingBonusValue(CR_ARMOR_PENETRATION) / 100.0f;
1551 if (armor < 0.0f) armor=0.0f;
1553 float levelModifier = getLevel();
1554 if ( levelModifier > 59 )
1555 levelModifier = levelModifier + (4.5f * (levelModifier-59));
1557 float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40);
1558 tmpvalue = tmpvalue/(1.0f + tmpvalue);
1560 if(tmpvalue < 0.0f)
1561 tmpvalue = 0.0f;
1562 if(tmpvalue > 0.75f)
1563 tmpvalue = 0.75f;
1564 newdamage = uint32(damage - (damage * tmpvalue));
1566 return (newdamage > 1) ? newdamage : 1;
1569 void Unit::CalcAbsorbResist(Unit *pVictim,SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist)
1571 if(!pVictim || !pVictim->isAlive() || !damage)
1572 return;
1574 // Magic damage, check for resists
1575 if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL)==0)
1577 // Get base victim resistance for school
1578 float tmpvalue2 = (float)pVictim->GetResistance(GetFirstSchoolInMask(schoolMask));
1579 // Ignore resistance by self SPELL_AURA_MOD_TARGET_RESISTANCE aura
1580 tmpvalue2 += (float)GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask);
1582 tmpvalue2 *= (float)(0.15f / getLevel());
1583 if (tmpvalue2 < 0.0f)
1584 tmpvalue2 = 0.0f;
1585 if (tmpvalue2 > 0.75f)
1586 tmpvalue2 = 0.75f;
1587 uint32 ran = urand(0, 100);
1588 uint32 faq[4] = {24,6,4,6};
1589 uint8 m = 0;
1590 float Binom = 0.0f;
1591 for (uint8 i = 0; i < 4; i++)
1593 Binom += 2400 *( powf(tmpvalue2, i) * powf( (1-tmpvalue2), (4-i)))/faq[i];
1594 if (ran > Binom )
1595 ++m;
1596 else
1597 break;
1599 if (damagetype == DOT && m == 4)
1600 *resist += uint32(damage - 1);
1601 else
1602 *resist += uint32(damage * m / 4);
1603 if(*resist > damage)
1604 *resist = damage;
1606 else
1607 *resist = 0;
1609 int32 RemainingDamage = damage - *resist;
1611 // Get unit state (need for some absorb check)
1612 uint32 unitflag = pVictim->GetUInt32Value(UNIT_FIELD_FLAGS);
1613 // Reflect damage spells (not cast any damage spell in aura lookup)
1614 uint32 reflectSpell = 0;
1615 int32 reflectDamage = 0;
1616 // Need remove expired auras after
1617 bool existExpired = false;
1618 // absorb without mana cost
1619 AuraList const& vSchoolAbsorb = pVictim->GetAurasByType(SPELL_AURA_SCHOOL_ABSORB);
1620 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end() && RemainingDamage > 0; ++i)
1622 Modifier* mod = (*i)->GetModifier();
1623 if (!(mod->m_miscvalue & schoolMask))
1624 continue;
1626 SpellEntry const* spellProto = (*i)->GetSpellProto();
1628 // Max Amount can be absorbed by this aura
1629 int32 currentAbsorb = mod->m_amount;
1631 // Found empty aura (umpossible but..)
1632 if (currentAbsorb <=0)
1634 existExpired = true;
1635 continue;
1637 // Handle custom absorb auras
1638 // TODO: try find better way
1639 switch(spellProto->SpellFamilyName)
1641 case SPELLFAMILY_GENERIC:
1643 // Astral Shift
1644 if (spellProto->SpellIconID == 3066)
1646 //reduces all damage taken while stun, fear or silence
1647 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1648 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1649 continue;
1651 // Nerves of Steel
1652 if (spellProto->SpellIconID == 2115)
1654 // while affected by Stun and Fear
1655 if (unitflag&(UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING))
1656 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1657 continue;
1659 // Spell Deflection
1660 if (spellProto->SpellIconID == 3006)
1662 // You have a chance equal to your Parry chance
1663 if (damagetype == DIRECT_DAMAGE && // Only for direct damage
1664 roll_chance_f(pVictim->GetUnitParryChance())) // Roll chance
1665 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1666 continue;
1668 // Reflective Shield (Lady Malande boss)
1669 if (spellProto->Id == 41475)
1671 if(RemainingDamage < currentAbsorb)
1672 reflectDamage = RemainingDamage / 2;
1673 else
1674 reflectDamage = currentAbsorb / 2;
1675 reflectSpell = 33619;
1676 break;
1678 if (spellProto->Id == 39228 || // Argussian Compass
1679 spellProto->Id == 60218) // Essence of Gossamer
1681 // Max absorb stored in 1 dummy effect
1682 if (spellProto->EffectBasePoints[1] < currentAbsorb)
1683 currentAbsorb = spellProto->EffectBasePoints[1];
1684 break;
1686 break;
1688 case SPELLFAMILY_DRUID:
1690 // Primal Tenacity
1691 if (spellProto->SpellIconID == 2253)
1693 //reduces all damage taken while Stunned
1694 if (unitflag & UNIT_FLAG_STUNNED)
1695 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1696 continue;
1698 break;
1700 case SPELLFAMILY_ROGUE:
1702 // Cheat Death
1703 if(spellProto->SpellIconID == 2109)
1705 if (pVictim->GetTypeId()==TYPEID_PLAYER && // Only players
1706 pVictim->GetHealth() <= RemainingDamage && // Only if damage kill
1707 !((Player*)pVictim)->HasSpellCooldown(31231) && // Only if no cooldown
1708 roll_chance_i(currentAbsorb)) // Only if roll
1710 pVictim->CastSpell(pVictim,31231,true);
1711 ((Player*)pVictim)->AddSpellCooldown(31231,0,time(NULL)+60);
1712 // with health > 10% lost health until health==10%, in other case no losses
1713 uint32 health10 = pVictim->GetMaxHealth()/10;
1714 RemainingDamage = pVictim->GetHealth() > health10 ? pVictim->GetHealth() - health10 : 0;
1716 continue;
1718 break;
1720 case SPELLFAMILY_PRIEST:
1722 // Reflective Shield
1723 if (spellProto->SpellFamilyFlags == 0x1)
1725 if (pVictim == this)
1726 break;
1727 Unit* caster = (*i)->GetCaster();
1728 if (!caster)
1729 break;
1730 AuraList const& vOverRideCS = caster->GetAurasByType(SPELL_AURA_DUMMY);
1731 for(AuraList::const_iterator k = vOverRideCS.begin(); k != vOverRideCS.end(); ++k)
1733 switch((*k)->GetModifier()->m_miscvalue)
1735 case 5065: // Rank 1
1736 case 5064: // Rank 2
1737 case 5063: // Rank 3
1739 if(RemainingDamage >= currentAbsorb)
1740 reflectDamage = (*k)->GetModifier()->m_amount * currentAbsorb/100;
1741 else
1742 reflectDamage = (*k)->GetModifier()->m_amount * RemainingDamage/100;
1743 reflectSpell = 33619;
1744 } break;
1745 default: break;
1748 break;
1750 break;
1752 case SPELLFAMILY_SHAMAN:
1754 // Astral Shift
1755 if (spellProto->SpellIconID == 3066)
1757 //reduces all damage taken while stun, fear or silence
1758 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1759 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1760 continue;
1762 break;
1764 case SPELLFAMILY_DEATHKNIGHT:
1766 // Shadow of Death
1767 if (spellProto->SpellIconID == 1958)
1769 // TODO: absorb only while transform
1770 continue;
1772 // Anti-Magic Shell (on self)
1773 if (spellProto->Id == 48707)
1775 // damage absorbed by Anti-Magic Shell energizes the DK with additional runic power.
1776 // This, if I'm not mistaken, shows that we get back ~2% of the absorbed damage as runic power.
1777 int32 absorbed = RemainingDamage * currentAbsorb / 100;
1778 int32 regen = absorbed * 2 / 10;
1779 pVictim->CastCustomSpell(pVictim, 49088, &regen, 0, 0, true, 0, *i);
1780 RemainingDamage -= absorbed;
1781 continue;
1783 // Anti-Magic Shell (on single party/raid member)
1784 if (spellProto->Id == 50462)
1786 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1787 continue;
1789 // Anti-Magic Zone
1790 if (spellProto->Id == 50461)
1792 Unit* caster = (*i)->GetCaster();
1793 if (!caster)
1794 continue;
1795 int32 absorbed = RemainingDamage * currentAbsorb / 100;
1796 int32 canabsorb = caster->GetHealth();
1797 if (canabsorb < absorbed)
1798 absorbed = canabsorb;
1799 DealDamage(caster, absorbed, NULL, damagetype, schoolMask, 0, false);
1800 RemainingDamage -= absorbed;
1801 continue;
1803 break;
1805 default:
1806 break;
1809 // currentAbsorb - damage can be absorbed by shield
1810 // If need absorb less damage
1811 if (RemainingDamage < currentAbsorb)
1812 currentAbsorb = RemainingDamage;
1814 RemainingDamage -= currentAbsorb;
1816 // Reduce shield amount
1817 mod->m_amount-=currentAbsorb;
1818 // Need remove it later
1819 if (mod->m_amount<=0)
1820 existExpired = true;
1823 // Remove all expired absorb auras
1824 if (existExpired)
1826 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end();)
1828 if ((*i)->GetModifier()->m_amount<=0)
1830 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1831 i = vSchoolAbsorb.begin();
1833 else
1834 ++i;
1837 // Cast back reflect damage spell
1838 if (reflectSpell)
1839 pVictim->CastCustomSpell(this, reflectSpell, &reflectDamage, NULL, NULL, true);
1841 // absorb by mana cost
1842 AuraList const& vManaShield = pVictim->GetAurasByType(SPELL_AURA_MANA_SHIELD);
1843 for(AuraList::const_iterator i = vManaShield.begin(), next; i != vManaShield.end() && RemainingDamage > 0; i = next)
1845 next = i; ++next;
1847 // check damage school mask
1848 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1849 continue;
1851 int32 currentAbsorb;
1852 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1853 currentAbsorb = (*i)->GetModifier()->m_amount;
1854 else
1855 currentAbsorb = RemainingDamage;
1857 float manaMultiplier = (*i)->GetSpellProto()->EffectMultipleValue[(*i)->GetEffIndex()];
1858 if(Player *modOwner = pVictim->GetSpellModOwner())
1859 modOwner->ApplySpellMod((*i)->GetId(), SPELLMOD_MULTIPLE_VALUE, manaMultiplier);
1861 int32 maxAbsorb = int32(pVictim->GetPower(POWER_MANA) / manaMultiplier);
1862 if (currentAbsorb > maxAbsorb)
1863 currentAbsorb = maxAbsorb;
1865 (*i)->GetModifier()->m_amount -= currentAbsorb;
1866 if((*i)->GetModifier()->m_amount <= 0)
1868 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1869 next = vManaShield.begin();
1872 int32 manaReduction = int32(currentAbsorb * manaMultiplier);
1873 pVictim->ApplyPowerMod(POWER_MANA, manaReduction, false);
1875 RemainingDamage -= currentAbsorb;
1878 // only split damage if not damaging yourself
1879 if(pVictim != this)
1881 AuraList const& vSplitDamageFlat = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_FLAT);
1882 for(AuraList::const_iterator i = vSplitDamageFlat.begin(), next; i != vSplitDamageFlat.end() && RemainingDamage >= 0; i = next)
1884 next = i; ++next;
1886 // check damage school mask
1887 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1888 continue;
1890 // Damage can be splitted only if aura has an alive caster
1891 Unit *caster = (*i)->GetCaster();
1892 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1893 continue;
1895 int32 currentAbsorb;
1896 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1897 currentAbsorb = (*i)->GetModifier()->m_amount;
1898 else
1899 currentAbsorb = RemainingDamage;
1901 RemainingDamage -= currentAbsorb;
1903 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, currentAbsorb, schoolMask, 0, 0, false, 0, false);
1905 CleanDamage cleanDamage = CleanDamage(currentAbsorb, BASE_ATTACK, MELEE_HIT_NORMAL);
1906 DealDamage(caster, currentAbsorb, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
1909 AuraList const& vSplitDamagePct = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_PCT);
1910 for(AuraList::const_iterator i = vSplitDamagePct.begin(), next; i != vSplitDamagePct.end() && RemainingDamage >= 0; i = next)
1912 next = i; ++next;
1914 // check damage school mask
1915 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1916 continue;
1918 // Damage can be splitted only if aura has an alive caster
1919 Unit *caster = (*i)->GetCaster();
1920 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1921 continue;
1923 int32 splitted = int32(RemainingDamage * (*i)->GetModifier()->m_amount / 100.0f);
1925 RemainingDamage -= splitted;
1927 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, 0, 0, false, 0, false);
1929 CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL);
1930 DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
1934 *absorb = damage - RemainingDamage - *resist;
1937 void Unit::AttackerStateUpdate (Unit *pVictim, WeaponAttackType attType, bool extra )
1939 if(hasUnitState(UNIT_STAT_CONFUSED | UNIT_STAT_STUNNED | UNIT_STAT_FLEEING) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) )
1940 return;
1942 if (!pVictim->isAlive())
1943 return;
1945 if(IsNonMeleeSpellCasted(false))
1946 return;
1948 uint32 hitInfo;
1949 if (attType == BASE_ATTACK)
1950 hitInfo = HITINFO_NORMALSWING2;
1951 else if (attType == OFF_ATTACK)
1952 hitInfo = HITINFO_LEFTSWING;
1953 else
1954 return; // ignore ranged case
1956 uint32 extraAttacks = m_extraAttacks;
1958 // melee attack spell casted at main hand attack only
1959 if (attType == BASE_ATTACK && m_currentSpells[CURRENT_MELEE_SPELL])
1961 m_currentSpells[CURRENT_MELEE_SPELL]->cast();
1963 // not recent extra attack only at any non extra attack (melee spell case)
1964 if(!extra && extraAttacks)
1966 while(m_extraAttacks)
1968 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
1969 if(m_extraAttacks > 0)
1970 --m_extraAttacks;
1973 return;
1976 // attack can be redirected to another target
1977 pVictim = SelectMagnetTarget(pVictim);
1979 CalcDamageInfo damageInfo;
1980 CalculateMeleeDamage(pVictim, 0, &damageInfo, attType);
1981 // Send log damage message to client
1982 SendAttackStateUpdate(&damageInfo);
1983 ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.damage, damageInfo.attackType);
1984 DealMeleeDamage(&damageInfo,true);
1986 if (GetTypeId() == TYPEID_PLAYER)
1987 DEBUG_LOG("AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
1988 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
1989 else
1990 DEBUG_LOG("AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
1991 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
1993 // if damage pVictim call AI reaction
1994 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
1995 ((Creature*)pVictim)->AI()->AttackedBy(this);
1997 // extra attack only at any non extra attack (normal case)
1998 if(!extra && extraAttacks)
2000 while(m_extraAttacks)
2002 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
2003 if(m_extraAttacks > 0)
2004 --m_extraAttacks;
2009 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType) const
2011 // This is only wrapper
2013 // Miss chance based on melee
2014 float miss_chance = MeleeMissChanceCalc(pVictim, attType);
2016 // Critical hit chance
2017 float crit_chance = GetUnitCriticalChance(attType, pVictim);
2019 // stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case)
2020 float dodge_chance = pVictim->GetUnitDodgeChance();
2021 float block_chance = pVictim->GetUnitBlockChance();
2022 float parry_chance = pVictim->GetUnitParryChance();
2024 // Useful if want to specify crit & miss chances for melee, else it could be removed
2025 DEBUG_LOG("MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance,crit_chance,dodge_chance,parry_chance,block_chance);
2027 return RollMeleeOutcomeAgainst(pVictim, attType, int32(crit_chance*100), int32(miss_chance*100), int32(dodge_chance*100),int32(parry_chance*100),int32(block_chance*100));
2030 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst (const Unit *pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const
2032 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2033 return MELEE_HIT_EVADE;
2035 int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(pVictim);
2036 int32 victimMaxSkillValueForLevel = pVictim->GetMaxSkillValueForLevel(this);
2038 int32 attackerWeaponSkill = GetWeaponSkillValue(attType,pVictim);
2039 int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this);
2041 // bonus from skills is 0.04%
2042 int32 skillBonus = 4 * ( attackerWeaponSkill - victimMaxSkillValueForLevel );
2043 int32 sum = 0, tmp = 0;
2044 int32 roll = urand (0, 10000);
2046 DEBUG_LOG ("RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus);
2047 DEBUG_LOG ("RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d",
2048 roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance);
2050 tmp = miss_chance;
2052 if (tmp > 0 && roll < (sum += tmp ))
2054 DEBUG_LOG ("RollMeleeOutcomeAgainst: MISS");
2055 return MELEE_HIT_MISS;
2058 // always crit against a sitting target (except 0 crit chance)
2059 if( pVictim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !pVictim->IsStandState() )
2061 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT (sitting victim)");
2062 return MELEE_HIT_CRIT;
2065 // Dodge chance
2067 // only players can't dodge if attacker is behind
2068 if (pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->HasInArc(M_PI,this))
2070 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind and victim was a player.");
2072 else
2074 // Reduce dodge chance by attacker expertise rating
2075 if (GetTypeId() == TYPEID_PLAYER)
2076 dodge_chance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2078 // Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2079 dodge_chance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE);
2081 tmp = dodge_chance;
2082 if ( (tmp > 0) // check if unit _can_ dodge
2083 && ((tmp -= skillBonus) > 0)
2084 && roll < (sum += tmp))
2086 DEBUG_LOG ("RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum-tmp, sum);
2087 return MELEE_HIT_DODGE;
2091 // parry & block chances
2093 // check if attack comes from behind, nobody can parry or block if attacker is behind
2094 if (!pVictim->HasInArc(M_PI,this))
2096 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind.");
2098 else
2100 // Reduce parry chance by attacker expertise rating
2101 if (GetTypeId() == TYPEID_PLAYER)
2102 parry_chance-= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2104 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY) )
2106 int32 tmp = int32(parry_chance);
2107 if ( (tmp > 0) // check if unit _can_ parry
2108 && ((tmp -= skillBonus) > 0)
2109 && (roll < (sum += tmp)))
2111 DEBUG_LOG ("RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum-tmp, sum);
2112 return MELEE_HIT_PARRY;
2116 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) )
2118 tmp = block_chance;
2119 if ( (tmp > 0) // check if unit _can_ block
2120 && ((tmp -= skillBonus) > 0)
2121 && (roll < (sum += tmp)))
2123 DEBUG_LOG ("RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum-tmp, sum);
2124 return MELEE_HIT_BLOCK;
2129 // Critical chance
2130 tmp = crit_chance;
2132 if (tmp > 0 && roll < (sum += tmp))
2134 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum-tmp, sum);
2135 return MELEE_HIT_CRIT;
2138 // 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)
2139 if( attType != RANGED_ATTACK &&
2140 (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet()) &&
2141 pVictim->GetTypeId() != TYPEID_PLAYER && !((Creature*)pVictim)->isPet() &&
2142 getLevel() < pVictim->getLevelForTarget(this) )
2144 // cap possible value (with bonuses > max skill)
2145 int32 skill = attackerWeaponSkill;
2146 int32 maxskill = attackerMaxSkillValueForLevel;
2147 skill = (skill > maxskill) ? maxskill : skill;
2149 tmp = (10 + (victimDefenseSkill - skill)) * 100;
2150 tmp = tmp > 4000 ? 4000 : tmp;
2151 if (roll < (sum += tmp))
2153 DEBUG_LOG ("RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum-4000, sum);
2154 return MELEE_HIT_GLANCING;
2158 // mobs can score crushing blows if they're 4 or more levels above victim
2159 if (getLevelForTarget(pVictim) >= pVictim->getLevelForTarget(this) + 4 &&
2160 // can be from by creature (if can) or from controlled player that considered as creature
2161 (GetTypeId()!=TYPEID_PLAYER && !((Creature*)this)->isPet() &&
2162 !(((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH) ||
2163 GetTypeId()==TYPEID_PLAYER && GetCharmerOrOwnerGUID()))
2165 // when their weapon skill is 15 or more above victim's defense skill
2166 tmp = victimDefenseSkill;
2167 int32 tmpmax = victimMaxSkillValueForLevel;
2168 // having defense above your maximum (from items, talents etc.) has no effect
2169 tmp = tmp > tmpmax ? tmpmax : tmp;
2170 // tmp = mob's level * 5 - player's current defense skill
2171 tmp = attackerMaxSkillValueForLevel - tmp;
2172 if(tmp >= 15)
2174 // add 2% chance per lacking skill point, min. is 15%
2175 tmp = tmp * 200 - 1500;
2176 if (roll < (sum += tmp))
2178 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum-tmp, sum);
2179 return MELEE_HIT_CRUSHING;
2184 DEBUG_LOG ("RollMeleeOutcomeAgainst: NORMAL");
2185 return MELEE_HIT_NORMAL;
2188 uint32 Unit::CalculateDamage (WeaponAttackType attType, bool normalized)
2190 float min_damage, max_damage;
2192 if (normalized && GetTypeId()==TYPEID_PLAYER)
2193 ((Player*)this)->CalculateMinMaxDamage(attType,normalized,min_damage, max_damage);
2194 else
2196 switch (attType)
2198 case RANGED_ATTACK:
2199 min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE);
2200 max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE);
2201 break;
2202 case BASE_ATTACK:
2203 min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE);
2204 max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE);
2205 break;
2206 case OFF_ATTACK:
2207 min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE);
2208 max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE);
2209 break;
2210 // Just for good manner
2211 default:
2212 min_damage = 0.0f;
2213 max_damage = 0.0f;
2214 break;
2218 if (min_damage > max_damage)
2220 std::swap(min_damage,max_damage);
2223 if(max_damage == 0.0f)
2224 max_damage = 5.0f;
2226 return urand((uint32)min_damage, (uint32)max_damage);
2229 float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const
2231 if(spellProto->spellLevel <= 0)
2232 return 1.0f;
2234 float LvlPenalty = 0.0f;
2236 if(spellProto->spellLevel < 20)
2237 LvlPenalty = 20.0f - spellProto->spellLevel * 3.75f;
2238 float LvlFactor = (float(spellProto->spellLevel) + 6.0f) / float(getLevel());
2239 if(LvlFactor > 1.0f)
2240 LvlFactor = 1.0f;
2242 return (100.0f - LvlPenalty) * LvlFactor / 100.0f;
2245 void Unit::SendAttackStart(Unit* pVictim)
2247 WorldPacket data( SMSG_ATTACKSTART, 16 );
2248 data << uint64(GetGUID());
2249 data << uint64(pVictim->GetGUID());
2251 SendMessageToSet(&data, true);
2252 DEBUG_LOG( "WORLD: Sent SMSG_ATTACKSTART" );
2255 void Unit::SendAttackStop(Unit* victim)
2257 if(!victim)
2258 return;
2260 WorldPacket data( SMSG_ATTACKSTOP, (4+16) ); // we guess size
2261 data.append(GetPackGUID());
2262 data.append(victim->GetPackGUID()); // can be 0x00...
2263 data << uint32(0); // can be 0x1
2264 SendMessageToSet(&data, true);
2265 sLog.outDetail("%s %u stopped attacking %s %u", (GetTypeId()==TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), (victim->GetTypeId()==TYPEID_PLAYER ? "player" : "creature"),victim->GetGUIDLow());
2267 /*if(victim->GetTypeId() == TYPEID_UNIT)
2268 ((Creature*)victim)->AI().EnterEvadeMode(this);*/
2271 bool Unit::isSpellBlocked(Unit *pVictim, SpellEntry const *spellProto, WeaponAttackType attackType)
2273 if (pVictim->HasInArc(M_PI,this))
2275 /* Currently not exist spells with ignore block
2276 // Ignore combat result aura (parry/dodge check on prepare)
2277 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2278 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2280 if (!(*i)->isAffectedOnSpell(spellProto))
2281 continue;
2282 if ((*i)->GetModifier()->m_miscvalue == )
2283 return false;
2287 // Check creatures flags_extra for disable block
2288 if(pVictim->GetTypeId()==TYPEID_UNIT &&
2289 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK )
2290 return false;
2292 float blockChance = pVictim->GetUnitBlockChance();
2293 blockChance += (int32(GetWeaponSkillValue(attackType)) - int32(pVictim->GetMaxSkillValueForLevel()))*0.04f;
2294 if (roll_chance_f(blockChance))
2295 return true;
2297 return false;
2300 // Melee based spells can be miss, parry or dodge on this step
2301 // Crit or block - determined on damage calculation phase! (and can be both in some time)
2302 float Unit::MeleeSpellMissChance(Unit *pVictim, WeaponAttackType attType, int32 skillDiff, SpellEntry const *spell)
2304 // Calculate hit chance (more correct for chance mod)
2305 int32 HitChance;
2307 // PvP - PvE melee chances
2308 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2309 int32 leveldif = pVictim->getLevelForTarget(this) - getLevelForTarget(pVictim);
2310 if(leveldif < 3)
2311 HitChance = 95 - leveldif;
2312 else
2313 HitChance = 93 - (leveldif - 2) * lchance;
2315 // Hit chance depends from victim auras
2316 if(attType == RANGED_ATTACK)
2317 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2318 else
2319 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2321 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2322 if(Player *modOwner = GetSpellModOwner())
2323 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, HitChance);
2325 // Miss = 100 - hit
2326 float miss_chance= 100.0f - HitChance;
2328 // Bonuses from attacker aura and ratings
2329 if (attType == RANGED_ATTACK)
2330 miss_chance -= m_modRangedHitChance;
2331 else
2332 miss_chance -= m_modMeleeHitChance;
2334 // bonus from skills is 0.04%
2335 miss_chance -= skillDiff * 0.04f;
2337 // Limit miss chance from 0 to 60%
2338 if (miss_chance < 0.0f)
2339 return 0.0f;
2340 if (miss_chance > 60.0f)
2341 return 60.0f;
2342 return miss_chance;
2345 // Melee based spells hit result calculations
2346 SpellMissInfo Unit::MeleeSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2348 WeaponAttackType attType = BASE_ATTACK;
2350 if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED)
2351 attType = RANGED_ATTACK;
2353 // bonus from skills is 0.04% per skill Diff
2354 int32 attackerWeaponSkill = int32(GetWeaponSkillValue(attType,pVictim));
2355 int32 skillDiff = attackerWeaponSkill - int32(pVictim->GetMaxSkillValueForLevel(this));
2356 int32 fullSkillDiff = attackerWeaponSkill - int32(pVictim->GetDefenseSkillValue(this));
2358 uint32 roll = urand (0, 10000);
2360 uint32 missChance = uint32(MeleeSpellMissChance(pVictim, attType, fullSkillDiff, spell)*100.0f);
2361 // Roll miss
2362 uint32 tmp = missChance;
2363 if (roll < tmp)
2364 return SPELL_MISS_MISS;
2366 // Chance resist mechanic (select max value from every mechanic spell effect)
2367 int32 resist_mech = 0;
2368 // Get effects mechanic and chance
2369 for(int eff = 0; eff < 3; ++eff)
2371 int32 effect_mech = GetEffectMechanic(spell, eff);
2372 if (effect_mech)
2374 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2375 if (resist_mech < temp*100)
2376 resist_mech = temp*100;
2379 // Roll chance
2380 tmp += resist_mech;
2381 if (roll < tmp)
2382 return SPELL_MISS_RESIST;
2384 bool canDodge = true;
2385 bool canParry = true;
2387 // Same spells cannot be parry/dodge
2388 if (spell->Attributes & SPELL_ATTR_IMPOSSIBLE_DODGE_PARRY_BLOCK)
2389 return SPELL_MISS_NONE;
2391 // Ranged attack cannot be parry/dodge only deflect
2392 if (attType == RANGED_ATTACK)
2394 // only if in front
2395 if (pVictim->HasInArc(M_PI,this))
2397 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2398 tmp+=deflect_chance;
2399 if (roll < tmp)
2400 return SPELL_MISS_DEFLECT;
2402 return SPELL_MISS_NONE;
2405 // Check for attack from behind
2406 if (!pVictim->HasInArc(M_PI,this))
2408 // Can`t dodge from behind in PvP (but its possible in PvE)
2409 if (GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
2410 canDodge = false;
2411 // Can`t parry
2412 canParry = false;
2414 // Check creatures flags_extra for disable parry
2415 if(pVictim->GetTypeId()==TYPEID_UNIT)
2417 uint32 flagEx = ((Creature*)pVictim)->GetCreatureInfo()->flags_extra;
2418 if( flagEx & CREATURE_FLAG_EXTRA_NO_PARRY )
2419 canParry = false;
2421 // Ignore combat result aura
2422 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2423 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2425 if (!(*i)->isAffectedOnSpell(spell))
2426 continue;
2427 switch((*i)->GetModifier()->m_miscvalue)
2429 case MELEE_HIT_DODGE: canDodge = false; break;
2430 case MELEE_HIT_BLOCK: break; // Block check in hit step
2431 case MELEE_HIT_PARRY: canParry = false; break;
2432 default:
2433 DEBUG_LOG("Spell %u SPELL_AURA_IGNORE_COMBAT_RESULT have unhandled state %d", (*i)->GetId(), (*i)->GetModifier()->m_miscvalue);
2434 break;
2438 if (canDodge)
2440 // Roll dodge
2441 int32 dodgeChance = int32(pVictim->GetUnitDodgeChance()*100.0f) - skillDiff * 4;
2442 // Reduce enemy dodge chance by SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2443 dodgeChance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE)*100;
2444 // Reduce dodge chance by attacker expertise rating
2445 if (GetTypeId() == TYPEID_PLAYER)
2446 dodgeChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2447 if (dodgeChance < 0)
2448 dodgeChance = 0;
2450 tmp += dodgeChance;
2451 if (roll < tmp)
2452 return SPELL_MISS_DODGE;
2455 if (canParry)
2457 // Roll parry
2458 int32 parryChance = int32(pVictim->GetUnitParryChance()*100.0f) - skillDiff * 4;
2459 // Reduce parry chance by attacker expertise rating
2460 if (GetTypeId() == TYPEID_PLAYER)
2461 parryChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2462 if (parryChance < 0)
2463 parryChance = 0;
2465 tmp += parryChance;
2466 if (roll < tmp)
2467 return SPELL_MISS_PARRY;
2470 return SPELL_MISS_NONE;
2473 // TODO need use unit spell resistances in calculations
2474 SpellMissInfo Unit::MagicSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2476 // Can`t miss on dead target (on skinning for example)
2477 if (!pVictim->isAlive())
2478 return SPELL_MISS_NONE;
2480 SpellSchoolMask schoolMask = GetSpellSchoolMask(spell);
2481 // PvP - PvE spell misschances per leveldif > 2
2482 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 7 : 11;
2483 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2485 // Base hit chance from attacker and victim levels
2486 int32 modHitChance;
2487 if(leveldif < 3)
2488 modHitChance = 96 - leveldif;
2489 else
2490 modHitChance = 94 - (leveldif - 2) * lchance;
2492 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2493 if(Player *modOwner = GetSpellModOwner())
2494 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance);
2495 // Increase from attacker SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT auras
2496 modHitChance+=GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT, schoolMask);
2497 // Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras
2498 modHitChance+= pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask);
2499 // Reduce spell hit chance for Area of effect spells from victim SPELL_AURA_MOD_AOE_AVOIDANCE aura
2500 if (IsAreaOfEffectSpell(spell))
2501 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE);
2502 // Reduce spell hit chance for dispel mechanic spells from victim SPELL_AURA_MOD_DISPEL_RESIST
2503 if (IsDispelSpell(spell))
2504 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_DISPEL_RESIST);
2505 // Chance resist mechanic (select max value from every mechanic spell effect)
2506 int32 resist_mech = 0;
2507 // Get effects mechanic and chance
2508 for(int eff = 0; eff < 3; ++eff)
2510 int32 effect_mech = GetEffectMechanic(spell, eff);
2511 if (effect_mech)
2513 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2514 if (resist_mech < temp)
2515 resist_mech = temp;
2518 // Apply mod
2519 modHitChance-=resist_mech;
2521 // Chance resist debuff
2522 modHitChance-=pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel));
2524 int32 HitChance = modHitChance * 100;
2525 // Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings
2526 HitChance += int32(m_modSpellHitChance*100.0f);
2528 // Decrease hit chance from victim rating bonus
2529 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2530 HitChance -= int32(((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_SPELL)*100.0f);
2532 if (HitChance < 100) HitChance = 100;
2533 if (HitChance > 10000) HitChance = 10000;
2535 int32 tmp = 10000 - HitChance;
2537 uint32 rand = urand(0,10000);
2539 if (rand < tmp)
2540 return SPELL_MISS_RESIST;
2542 // cast by caster in front of victim
2543 if (pVictim->HasInArc(M_PI,this))
2545 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2546 tmp+=deflect_chance;
2547 if (rand < tmp)
2548 return SPELL_MISS_DEFLECT;
2551 return SPELL_MISS_NONE;
2554 // Calculate spell hit result can be:
2555 // Every spell can: Evade/Immune/Reflect/Sucesful hit
2556 // For melee based spells:
2557 // Miss
2558 // Dodge
2559 // Parry
2560 // For spells
2561 // Resist
2562 SpellMissInfo Unit::SpellHitResult(Unit *pVictim, SpellEntry const *spell, bool CanReflect)
2564 // Return evade for units in evade mode
2565 if (pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2566 return SPELL_MISS_EVADE;
2568 // Check for immune
2569 if (pVictim->IsImmunedToSpell(spell))
2570 return SPELL_MISS_IMMUNE;
2572 // All positive spells can`t miss
2573 // TODO: client not show miss log for this spells - so need find info for this in dbc and use it!
2574 if (IsPositiveSpell(spell->Id))
2575 return SPELL_MISS_NONE;
2577 // Check for immune
2578 if (pVictim->IsImmunedToDamage(GetSpellSchoolMask(spell)))
2579 return SPELL_MISS_IMMUNE;
2581 // Try victim reflect spell
2582 if (CanReflect)
2584 int32 reflectchance = pVictim->GetTotalAuraModifier(SPELL_AURA_REFLECT_SPELLS);
2585 Unit::AuraList const& mReflectSpellsSchool = pVictim->GetAurasByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL);
2586 for(Unit::AuraList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i)
2587 if((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spell))
2588 reflectchance += (*i)->GetModifier()->m_amount;
2589 if (reflectchance > 0 && roll_chance_i(reflectchance))
2591 // Start triggers for remove charges if need (trigger only for victim, and mark as active spell)
2592 ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT, PROC_EX_REFLECT, 1, BASE_ATTACK, spell);
2593 return SPELL_MISS_REFLECT;
2597 switch (spell->DmgClass)
2599 case SPELL_DAMAGE_CLASS_RANGED:
2600 case SPELL_DAMAGE_CLASS_MELEE:
2601 return MeleeSpellHitResult(pVictim, spell);
2602 case SPELL_DAMAGE_CLASS_NONE:
2603 case SPELL_DAMAGE_CLASS_MAGIC:
2604 return MagicSpellHitResult(pVictim, spell);
2606 return SPELL_MISS_NONE;
2609 float Unit::MeleeMissChanceCalc(const Unit *pVictim, WeaponAttackType attType) const
2611 if(!pVictim)
2612 return 0.0f;
2614 // Base misschance 5%
2615 float misschance = 5.0f;
2617 // DualWield - Melee spells and physical dmg spells - 5% , white damage 24%
2618 if (haveOffhandWeapon() && attType != RANGED_ATTACK)
2620 bool isNormal = false;
2621 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
2623 if( m_currentSpells[i] && (GetSpellSchoolMask(m_currentSpells[i]->m_spellInfo) & SPELL_SCHOOL_MASK_NORMAL) )
2625 isNormal = true;
2626 break;
2629 if (isNormal || m_currentSpells[CURRENT_MELEE_SPELL])
2631 misschance = 5.0f;
2633 else
2635 misschance = 24.0f;
2639 // PvP : PvE melee misschances per leveldif > 2
2640 int32 chance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2642 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2643 if(leveldif < 0)
2644 leveldif = 0;
2646 // Hit chance from attacker based on ratings and auras
2647 float m_modHitChance;
2648 if (attType == RANGED_ATTACK)
2649 m_modHitChance = m_modRangedHitChance;
2650 else
2651 m_modHitChance = m_modMeleeHitChance;
2653 if(leveldif < 3)
2654 misschance += (leveldif - m_modHitChance);
2655 else
2656 misschance += ((leveldif - 2) * chance - m_modHitChance);
2658 // Hit chance for victim based on ratings
2659 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2661 if (attType == RANGED_ATTACK)
2662 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_RANGED);
2663 else
2664 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_MELEE);
2667 // Modify miss chance by victim auras
2668 if(attType == RANGED_ATTACK)
2669 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2670 else
2671 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2673 // Modify miss chance from skill difference ( bonus from skills is 0.04% )
2674 int32 skillBonus = int32(GetWeaponSkillValue(attType,pVictim)) - int32(pVictim->GetDefenseSkillValue(this));
2675 misschance -= skillBonus * 0.04f;
2677 // Limit miss chance from 0 to 60%
2678 if ( misschance < 0.0f)
2679 return 0.0f;
2680 if ( misschance > 60.0f)
2681 return 60.0f;
2683 return misschance;
2686 uint32 Unit::GetDefenseSkillValue(Unit const* target) const
2688 if(GetTypeId() == TYPEID_PLAYER)
2690 // in PvP use full skill instead current skill value
2691 uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2692 ? ((Player*)this)->GetMaxSkillValue(SKILL_DEFENSE)
2693 : ((Player*)this)->GetSkillValue(SKILL_DEFENSE);
2694 value += uint32(((Player*)this)->GetRatingBonusValue(CR_DEFENSE_SKILL));
2695 return value;
2697 else
2698 return GetUnitMeleeSkill(target);
2701 float Unit::GetUnitDodgeChance() const
2703 if(hasUnitState(UNIT_STAT_STUNNED))
2704 return 0.0f;
2705 if( GetTypeId() == TYPEID_PLAYER )
2706 return GetFloatValue(PLAYER_DODGE_PERCENTAGE);
2707 else
2709 if(((Creature const*)this)->isTotem())
2710 return 0.0f;
2711 else
2713 float dodge = 5.0f;
2714 dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT);
2715 return dodge > 0.0f ? dodge : 0.0f;
2720 float Unit::GetUnitParryChance() const
2722 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2723 return 0.0f;
2725 float chance = 0.0f;
2727 if(GetTypeId() == TYPEID_PLAYER)
2729 Player const* player = (Player const*)this;
2730 if(player->CanParry() )
2732 Item *tmpitem = player->GetWeaponForAttack(BASE_ATTACK,true);
2733 if(!tmpitem)
2734 tmpitem = player->GetWeaponForAttack(OFF_ATTACK,true);
2736 if(tmpitem)
2737 chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE);
2740 else if(GetTypeId() == TYPEID_UNIT)
2742 if(GetCreatureType() == CREATURE_TYPE_HUMANOID)
2744 chance = 5.0f;
2745 chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT);
2749 return chance > 0.0f ? chance : 0.0f;
2752 float Unit::GetUnitBlockChance() const
2754 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2755 return 0.0f;
2757 if(GetTypeId() == TYPEID_PLAYER)
2759 Player const* player = (Player const*)this;
2760 if(player->CanBlock() )
2762 Item *tmpitem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
2763 if(tmpitem && !tmpitem->IsBroken() && tmpitem->GetProto()->Block)
2764 return GetFloatValue(PLAYER_BLOCK_PERCENTAGE);
2766 // is player but has no block ability or no not broken shield equipped
2767 return 0.0f;
2769 else
2771 if(((Creature const*)this)->isTotem())
2772 return 0.0f;
2773 else
2775 float block = 5.0f;
2776 block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT);
2777 return block > 0.0f ? block : 0.0f;
2782 float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit *pVictim) const
2784 float crit;
2786 if(GetTypeId() == TYPEID_PLAYER)
2788 switch(attackType)
2790 case BASE_ATTACK:
2791 crit = GetFloatValue( PLAYER_CRIT_PERCENTAGE );
2792 break;
2793 case OFF_ATTACK:
2794 crit = GetFloatValue( PLAYER_OFFHAND_CRIT_PERCENTAGE );
2795 break;
2796 case RANGED_ATTACK:
2797 crit = GetFloatValue( PLAYER_RANGED_CRIT_PERCENTAGE );
2798 break;
2799 // Just for good manner
2800 default:
2801 crit = 0.0f;
2802 break;
2805 else
2807 crit = 5.0f;
2808 crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PERCENT);
2811 // flat aura mods
2812 if(attackType == RANGED_ATTACK)
2813 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE);
2814 else
2815 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE);
2817 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
2819 // reduce crit chance from Rating for players
2820 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2822 if (attackType==RANGED_ATTACK)
2823 crit -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_RANGED);
2824 else
2825 crit -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE);
2828 // Apply crit chance from defence skill
2829 crit += (int32(GetMaxSkillValueForLevel(pVictim)) - int32(pVictim->GetDefenseSkillValue(this))) * 0.04f;
2831 if (crit < 0.0f)
2832 crit = 0.0f;
2833 return crit;
2836 uint32 Unit::GetWeaponSkillValue (WeaponAttackType attType, Unit const* target) const
2838 uint32 value = 0;
2839 if(GetTypeId() == TYPEID_PLAYER)
2841 Item* item = ((Player*)this)->GetWeaponForAttack(attType,true);
2843 // feral or unarmed skill only for base attack
2844 if(attType != BASE_ATTACK && !item )
2845 return 0;
2847 if(IsInFeralForm())
2848 return GetMaxSkillValueForLevel(); // always maximized SKILL_FERAL_COMBAT in fact
2850 // weapon skill or (unarmed for base attack)
2851 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
2853 // in PvP use full skill instead current skill value
2854 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2855 ? ((Player*)this)->GetMaxSkillValue(skill)
2856 : ((Player*)this)->GetSkillValue(skill);
2857 // Modify value from ratings
2858 value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL));
2859 switch (attType)
2861 case BASE_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_MAINHAND));break;
2862 case OFF_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_OFFHAND));break;
2863 case RANGED_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_RANGED));break;
2866 else
2867 value = GetUnitMeleeSkill(target);
2868 return value;
2871 void Unit::_UpdateSpells( uint32 time )
2873 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
2874 _UpdateAutoRepeatSpell();
2876 // remove finished spells from current pointers
2877 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
2879 if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED)
2881 m_currentSpells[i]->SetReferencedFromCurrent(false);
2882 m_currentSpells[i] = NULL; // remove pointer
2886 // TODO: Find a better way to prevent crash when multiple auras are removed.
2887 m_removedAuras = 0;
2888 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
2889 if ((*i).second)
2890 (*i).second->SetUpdated(false);
2892 for (AuraMap::iterator i = m_Auras.begin(), next; i != m_Auras.end(); i = next)
2894 next = i;
2895 ++next;
2896 if ((*i).second)
2898 // prevent double update
2899 if ((*i).second->IsUpdated())
2900 continue;
2901 (*i).second->SetUpdated(true);
2902 (*i).second->Update( time );
2903 // several auras can be deleted due to update
2904 if (m_removedAuras)
2906 if (m_Auras.empty()) break;
2907 next = m_Auras.begin();
2908 m_removedAuras = 0;
2913 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end();)
2915 if ((*i).second)
2917 if ( !(*i).second->GetAuraDuration() && !((*i).second->IsPermanent() || ((*i).second->IsPassive())) )
2919 RemoveAura(i);
2921 else
2923 ++i;
2926 else
2928 ++i;
2932 if(!m_gameObj.empty())
2934 GameObjectList::iterator ite1, dnext1;
2935 for (ite1 = m_gameObj.begin(); ite1 != m_gameObj.end(); ite1 = dnext1)
2937 dnext1 = ite1;
2938 //(*i)->Update( difftime );
2939 if( !(*ite1)->isSpawned() )
2941 (*ite1)->SetOwnerGUID(0);
2942 (*ite1)->SetRespawnTime(0);
2943 (*ite1)->Delete();
2944 dnext1 = m_gameObj.erase(ite1);
2946 else
2947 ++dnext1;
2952 void Unit::_UpdateAutoRepeatSpell()
2954 //check "realtime" interrupts
2955 if ( (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->isMoving()) || IsNonMeleeSpellCasted(false,false,true) )
2957 // cancel wand shoot
2958 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
2959 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2960 m_AutoRepeatFirstCast = true;
2961 return;
2964 //apply delay
2965 if ( m_AutoRepeatFirstCast && getAttackTimer(RANGED_ATTACK) < 500 )
2966 setAttackTimer(RANGED_ATTACK,500);
2967 m_AutoRepeatFirstCast = false;
2969 //castroutine
2970 if (isAttackReady(RANGED_ATTACK))
2972 // Check if able to cast
2973 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->CheckCast(true) != SPELL_CAST_OK)
2975 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2976 return;
2979 // we want to shoot
2980 Spell* spell = new Spell(this, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, true, 0);
2981 spell->prepare(&(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_targets));
2983 // all went good, reset attack
2984 resetAttackTimer(RANGED_ATTACK);
2988 void Unit::SetCurrentCastedSpell( Spell * pSpell )
2990 assert(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells
2992 uint32 CSpellType = pSpell->GetCurrentContainer();
2994 if (pSpell == m_currentSpells[CSpellType]) return; // avoid breaking self
2996 // break same type spell if it is not delayed
2997 InterruptSpell(CSpellType,false);
2999 // special breakage effects:
3000 switch (CSpellType)
3002 case CURRENT_GENERIC_SPELL:
3004 // generic spells always break channeled not delayed spells
3005 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3007 // autorepeat breaking
3008 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3010 // break autorepeat if not Auto Shot
3011 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3012 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3013 m_AutoRepeatFirstCast = true;
3015 } break;
3017 case CURRENT_CHANNELED_SPELL:
3019 // channel spells always break generic non-delayed and any channeled spells
3020 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3021 InterruptSpell(CURRENT_CHANNELED_SPELL);
3023 // it also does break autorepeat if not Auto Shot
3024 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] &&
3025 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT )
3026 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3027 } break;
3029 case CURRENT_AUTOREPEAT_SPELL:
3031 // only Auto Shoot does not break anything
3032 if (pSpell->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3034 // generic autorepeats break generic non-delayed and channeled non-delayed spells
3035 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3036 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3038 // special action: set first cast flag
3039 m_AutoRepeatFirstCast = true;
3040 } break;
3042 default:
3044 // other spell types don't break anything now
3045 } break;
3048 // current spell (if it is still here) may be safely deleted now
3049 if (m_currentSpells[CSpellType])
3050 m_currentSpells[CSpellType]->SetReferencedFromCurrent(false);
3052 // set new current spell
3053 m_currentSpells[CSpellType] = pSpell;
3054 pSpell->SetReferencedFromCurrent(true);
3057 void Unit::InterruptSpell(uint32 spellType, bool withDelayed)
3059 assert(spellType < CURRENT_MAX_SPELL);
3061 if (m_currentSpells[spellType] && (withDelayed || m_currentSpells[spellType]->getState() != SPELL_STATE_DELAYED) )
3063 // send autorepeat cancel message for autorepeat spells
3064 if (spellType == CURRENT_AUTOREPEAT_SPELL)
3066 if(GetTypeId()==TYPEID_PLAYER)
3067 ((Player*)this)->SendAutoRepeatCancel();
3070 if (m_currentSpells[spellType]->getState() != SPELL_STATE_FINISHED)
3071 m_currentSpells[spellType]->cancel();
3073 // cancel can interrupt spell already (caster cancel ->target aura remove -> caster iterrupt)
3074 if (m_currentSpells[spellType])
3076 m_currentSpells[spellType]->SetReferencedFromCurrent(false);
3077 m_currentSpells[spellType] = NULL;
3082 bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat) const
3084 // We don't do loop here to explicitly show that melee spell is excluded.
3085 // Maybe later some special spells will be excluded too.
3087 // generic spells are casted when they are not finished and not delayed
3088 if ( m_currentSpells[CURRENT_GENERIC_SPELL] &&
3089 (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
3090 (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
3091 return(true);
3093 // channeled spells may be delayed, but they are still considered casted
3094 else if ( !skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] &&
3095 (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED) )
3096 return(true);
3098 // autorepeat spells may be finished or delayed, but they are still considered casted
3099 else if ( !skipAutorepeat && m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3100 return(true);
3102 return(false);
3105 void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id)
3107 // generic spells are interrupted if they are not finished or delayed
3108 if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id==spell_id))
3109 InterruptSpell(CURRENT_GENERIC_SPELL,withDelayed);
3111 // autorepeat spells are interrupted if they are not finished or delayed
3112 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id==spell_id))
3113 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,withDelayed);
3115 // channeled spells are interrupted if they are not finished, even if they are delayed
3116 if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id==spell_id))
3117 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
3120 Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const
3122 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
3123 if(m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id==spell_id)
3124 return m_currentSpells[i];
3125 return NULL;
3128 bool Unit::isInFront(Unit const* target, float distance, float arc) const
3130 return IsWithinDistInMap(target, distance) && HasInArc( arc, target );
3133 void Unit::SetInFront(Unit const* target)
3135 SetOrientation(GetAngle(target));
3138 bool Unit::isInBack(Unit const* target, float distance, float arc) const
3140 return IsWithinDistInMap(target, distance) && !HasInArc( 2 * M_PI - arc, target );
3143 bool Unit::isInAccessablePlaceFor(Creature const* c) const
3145 if(IsInWater())
3146 return c->canSwim();
3147 else
3148 return c->canWalk() || c->canFly();
3151 bool Unit::IsInWater() const
3153 return MapManager::Instance().GetBaseMap(GetMapId())->IsInWater(GetPositionX(),GetPositionY(), GetPositionZ());
3156 bool Unit::IsUnderWater() const
3158 return MapManager::Instance().GetBaseMap(GetMapId())->IsUnderWater(GetPositionX(),GetPositionY(),GetPositionZ());
3161 void Unit::DeMorph()
3163 SetDisplayId(GetNativeDisplayId());
3166 int32 Unit::GetTotalAuraModifier(AuraType auratype) const
3168 int32 modifier = 0;
3170 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3171 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3172 modifier += (*i)->GetModifier()->m_amount;
3174 return modifier;
3177 float Unit::GetTotalAuraMultiplier(AuraType auratype) const
3179 float multiplier = 1.0f;
3181 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3182 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3183 multiplier *= (100.0f + (*i)->GetModifier()->m_amount)/100.0f;
3185 return multiplier;
3188 int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype) const
3190 int32 modifier = 0;
3192 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3193 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3194 if ((*i)->GetModifier()->m_amount > modifier)
3195 modifier = (*i)->GetModifier()->m_amount;
3197 return modifier;
3200 int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const
3202 int32 modifier = 0;
3204 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3205 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3206 if ((*i)->GetModifier()->m_amount < modifier)
3207 modifier = (*i)->GetModifier()->m_amount;
3209 return modifier;
3212 int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3214 int32 modifier = 0;
3216 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3217 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3219 Modifier* mod = (*i)->GetModifier();
3220 if (mod->m_miscvalue & misc_mask)
3221 modifier += mod->m_amount;
3223 return modifier;
3226 float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const
3228 float multiplier = 1.0f;
3230 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3231 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3233 Modifier* mod = (*i)->GetModifier();
3234 if (mod->m_miscvalue & misc_mask)
3235 multiplier *= (100.0f + mod->m_amount)/100.0f;
3237 return multiplier;
3240 int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3242 int32 modifier = 0;
3244 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3245 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3247 Modifier* mod = (*i)->GetModifier();
3248 if (mod->m_miscvalue & misc_mask && mod->m_amount > modifier)
3249 modifier = mod->m_amount;
3252 return modifier;
3255 int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3257 int32 modifier = 0;
3259 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3260 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3262 Modifier* mod = (*i)->GetModifier();
3263 if (mod->m_miscvalue & misc_mask && mod->m_amount < modifier)
3264 modifier = mod->m_amount;
3267 return modifier;
3270 int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3272 int32 modifier = 0;
3274 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3275 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3277 Modifier* mod = (*i)->GetModifier();
3278 if (mod->m_miscvalue == misc_value)
3279 modifier += mod->m_amount;
3281 return modifier;
3284 float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const
3286 float multiplier = 1.0f;
3288 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3289 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3291 Modifier* mod = (*i)->GetModifier();
3292 if (mod->m_miscvalue == misc_value)
3293 multiplier *= (100.0f + mod->m_amount)/100.0f;
3295 return multiplier;
3298 int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3300 int32 modifier = 0;
3302 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3303 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3305 Modifier* mod = (*i)->GetModifier();
3306 if (mod->m_miscvalue == misc_value && mod->m_amount > modifier)
3307 modifier = mod->m_amount;
3310 return modifier;
3313 int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3315 int32 modifier = 0;
3317 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3318 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3320 Modifier* mod = (*i)->GetModifier();
3321 if (mod->m_miscvalue == misc_value && mod->m_amount < modifier)
3322 modifier = mod->m_amount;
3325 return modifier;
3328 bool Unit::AddAura(Aura *Aur)
3330 // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load)
3331 if( !isAlive() && Aur->GetId() != 20584 && Aur->GetId() != 8326 && Aur->GetId() != 2584 &&
3332 (GetTypeId()!=TYPEID_PLAYER || !((Player*)this)->GetSession()->PlayerLoading()) )
3334 delete Aur;
3335 return false;
3338 if(Aur->GetTarget() != this)
3340 sLog.outError("Aura (spell %u eff %u) add to aura list of %s (lowguid: %u) but Aura target is %s (lowguid: %u)",
3341 Aur->GetId(),Aur->GetEffIndex(),(GetTypeId()==TYPEID_PLAYER?"player":"creature"),GetGUIDLow(),
3342 (Aur->GetTarget()->GetTypeId()==TYPEID_PLAYER?"player":"creature"),Aur->GetTarget()->GetGUIDLow());
3343 delete Aur;
3344 return false;
3347 SpellEntry const* aurSpellInfo = Aur->GetSpellProto();
3349 spellEffectPair spair = spellEffectPair(Aur->GetId(), Aur->GetEffIndex());
3350 AuraMap::iterator i = m_Auras.find( spair );
3352 // take out same spell
3353 if (i != m_Auras.end())
3355 // passive and persistent auras can stack with themselves any number of times
3356 if (!Aur->IsPassive() && !Aur->IsPersistent())
3358 for(AuraMap::iterator i2 = m_Auras.lower_bound(spair); i2 != m_Auras.upper_bound(spair); ++i2)
3360 if(i2->second->GetCasterGUID()==Aur->GetCasterGUID())
3362 // Aura can stack on self -> Stack it;
3363 if(aurSpellInfo->StackAmount)
3365 i2->second->modStackAmount(1);
3366 delete Aur;
3367 return false;
3369 // can be only single (this check done at _each_ aura add
3370 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3371 break;
3374 bool stop = false;
3375 switch(aurSpellInfo->EffectApplyAuraName[Aur->GetEffIndex()])
3377 // DoT/HoT/etc
3378 case SPELL_AURA_PERIODIC_DAMAGE: // allow stack
3379 case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
3380 case SPELL_AURA_PERIODIC_LEECH:
3381 case SPELL_AURA_PERIODIC_HEAL:
3382 case SPELL_AURA_OBS_MOD_HEALTH:
3383 case SPELL_AURA_PERIODIC_MANA_LEECH:
3384 case SPELL_AURA_PERIODIC_ENERGIZE:
3385 case SPELL_AURA_OBS_MOD_MANA:
3386 case SPELL_AURA_POWER_BURN_MANA:
3387 break;
3388 default: // not allow
3389 // can be only single (this check done at _each_ aura add
3390 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3391 stop = true;
3392 break;
3395 if(stop)
3396 break;
3401 // passive auras not stacable with other ranks
3402 if (!IsPassiveSpellStackableWithRanks(aurSpellInfo))
3404 if (!RemoveNoStackAurasDueToAura(Aur))
3406 delete Aur;
3407 return false; // couldn't remove conflicting aura with higher rank
3411 // update single target auras list (before aura add to aura list, to prevent unexpected remove recently added aura)
3412 if (Aur->IsSingleTarget() && Aur->GetTarget())
3414 // caster pointer can be deleted in time aura remove, find it by guid at each iteration
3415 for(;;)
3417 Unit* caster = Aur->GetCaster();
3418 if(!caster) // caster deleted and not required adding scAura
3419 break;
3421 bool restart = false;
3422 AuraList& scAuras = caster->GetSingleCastAuras();
3423 for(AuraList::iterator itr = scAuras.begin(); itr != scAuras.end(); ++itr)
3425 if( (*itr)->GetTarget() != Aur->GetTarget() &&
3426 IsSingleTargetSpells((*itr)->GetSpellProto(),aurSpellInfo) )
3428 if ((*itr)->IsInUse())
3430 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());
3431 continue;
3433 (*itr)->GetTarget()->RemoveAura((*itr)->GetId(), (*itr)->GetEffIndex());
3434 restart = true;
3435 break;
3439 if(!restart)
3441 // done
3442 scAuras.push_back(Aur);
3443 break;
3448 // add aura, register in lists and arrays
3449 Aur->_AddAura();
3450 m_Auras.insert(AuraMap::value_type(spellEffectPair(Aur->GetId(), Aur->GetEffIndex()), Aur));
3451 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
3453 m_modAuras[Aur->GetModifier()->m_auraname].push_back(Aur);
3456 Aur->ApplyModifier(true,true);
3457 sLog.outDebug("Aura %u now is in use", Aur->GetModifier()->m_auraname);
3458 return true;
3461 void Unit::RemoveRankAurasDueToSpell(uint32 spellId)
3463 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
3464 if(!spellInfo)
3465 return;
3466 AuraMap::iterator i,next;
3467 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3469 next = i;
3470 ++next;
3471 uint32 i_spellId = (*i).second->GetId();
3472 if((*i).second && i_spellId && i_spellId != spellId)
3474 if(spellmgr.IsRankSpellDueToSpell(spellInfo,i_spellId))
3476 RemoveAurasDueToSpell(i_spellId);
3478 if( m_Auras.empty() )
3479 break;
3480 else
3481 next = m_Auras.begin();
3487 bool Unit::RemoveNoStackAurasDueToAura(Aura *Aur)
3489 if (!Aur)
3490 return false;
3492 SpellEntry const* spellProto = Aur->GetSpellProto();
3493 if (!spellProto)
3494 return false;
3496 uint32 spellId = Aur->GetId();
3497 uint32 effIndex = Aur->GetEffIndex();
3499 // passive spell special case (only non stackable with ranks)
3500 if(IsPassiveSpell(spellId))
3502 if(IsPassiveSpellStackableWithRanks(spellProto))
3503 return true;
3506 SpellSpecific spellId_spec = GetSpellSpecific(spellId);
3508 AuraMap::iterator i,next;
3509 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3511 next = i;
3512 ++next;
3513 if (!(*i).second) continue;
3515 SpellEntry const* i_spellProto = (*i).second->GetSpellProto();
3517 if (!i_spellProto)
3518 continue;
3520 uint32 i_spellId = i_spellProto->Id;
3522 // early checks that spellId is passive non stackable spell
3523 if(IsPassiveSpell(i_spellId))
3525 // passive non-stackable spells not stackable only for same caster
3526 if(Aur->GetCasterGUID()!=i->second->GetCasterGUID())
3527 continue;
3529 // passive non-stackable spells not stackable only with another rank of same spell
3530 if (!spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3531 continue;
3534 uint32 i_effIndex = (*i).second->GetEffIndex();
3536 if(i_spellId == spellId) continue;
3538 bool is_triggered_by_spell = false;
3539 // prevent triggered aura of removing aura that triggered it
3540 for(int j = 0; j < 3; ++j)
3541 if (i_spellProto->EffectTriggerSpell[j] == spellProto->Id)
3542 is_triggered_by_spell = true;
3544 if (is_triggered_by_spell)
3545 continue;
3547 SpellSpecific i_spellId_spec = GetSpellSpecific(i_spellId);
3549 bool is_sspc = IsSingleFromSpellSpecificPerCaster(spellId_spec,i_spellId_spec);
3550 bool is_sspt = IsSingleFromSpellSpecificRanksPerTarget(spellId_spec,i_spellId_spec);
3552 if( is_sspc && Aur->GetCasterGUID() == (*i).second->GetCasterGUID() )
3554 // cannot remove higher rank
3555 if (spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3556 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3557 return false;
3559 // Its a parent aura (create this aura in ApplyModifier)
3560 if ((*i).second->IsInUse())
3562 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());
3563 continue;
3565 RemoveAurasDueToSpell(i_spellId);
3567 if( m_Auras.empty() )
3568 break;
3569 else
3570 next = m_Auras.begin();
3572 else if( is_sspt && Aur->GetCasterGUID() != (*i).second->GetCasterGUID() && spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId) )
3574 // cannot remove higher rank
3575 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3576 return false;
3578 // Its a parent aura (create this aura in ApplyModifier)
3579 if ((*i).second->IsInUse())
3581 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());
3582 continue;
3584 RemoveAurasDueToSpell(i_spellId);
3586 if( m_Auras.empty() )
3587 break;
3588 else
3589 next = m_Auras.begin();
3591 else if( !is_sspc && spellmgr.IsNoStackSpellDueToSpell(spellId, i_spellId) )
3593 // Its a parent aura (create this aura in ApplyModifier)
3594 if ((*i).second->IsInUse())
3596 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());
3597 continue;
3599 RemoveAurasDueToSpell(i_spellId);
3601 if( m_Auras.empty() )
3602 break;
3603 else
3604 next = m_Auras.begin();
3606 // Potions stack aura by aura (elixirs/flask already checked)
3607 else if( spellProto->SpellFamilyName == SPELLFAMILY_POTION && i_spellProto->SpellFamilyName == SPELLFAMILY_POTION )
3609 if (IsNoStackAuraDueToAura(spellId, effIndex, i_spellId, i_effIndex))
3611 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3612 return false; // cannot remove higher rank
3614 // Its a parent aura (create this aura in ApplyModifier)
3615 if ((*i).second->IsInUse())
3617 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());
3618 continue;
3620 RemoveAura(i);
3621 next = i;
3625 return true;
3628 void Unit::RemoveAura(uint32 spellId, uint32 effindex, Aura* except)
3630 spellEffectPair spair = spellEffectPair(spellId, effindex);
3631 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3633 if(iter->second!=except)
3635 RemoveAura(iter);
3636 iter = m_Auras.lower_bound(spair);
3638 else
3639 ++iter;
3643 void Unit::RemoveAurasByCasterSpell(uint32 spellId, uint64 casterGUID)
3645 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3647 Aura *aur = iter->second;
3648 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3649 RemoveAura(iter);
3650 else
3651 ++iter;
3655 void Unit::RemoveAurasDueToSpellByDispel(uint32 spellId, uint64 casterGUID, Unit *dispeler)
3657 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3659 Aura *aur = iter->second;
3660 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3662 // Custom dispel case
3663 // Unstable Affliction
3664 if (aur->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && (aur->GetSpellProto()->SpellFamilyFlags & 0x010000000000LL))
3666 int32 damage = aur->GetModifier()->m_amount*9;
3667 uint64 caster_guid = aur->GetCasterGUID();
3669 // Remove aura
3670 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3672 // backfire damage and silence
3673 dispeler->CastCustomSpell(dispeler, 31117, &damage, NULL, NULL, true, NULL, NULL,caster_guid);
3675 iter = m_Auras.begin(); // iterator can be invalidate at cast if self-dispel
3677 else
3678 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3680 else
3681 ++iter;
3685 void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit *stealer)
3687 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3689 Aura *aur = iter->second;
3690 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3692 int32 basePoints = aur->GetBasePoints();
3693 // construct the new aura for the attacker - will never return NULL, it's just a wrapper for
3694 // some different constructors
3695 Aura * new_aur = CreateAura(aur->GetSpellProto(), aur->GetEffIndex(), &basePoints, stealer, this);
3697 // set its duration and maximum duration
3698 // max duration 2 minutes (in msecs)
3699 int32 dur = aur->GetAuraDuration();
3700 const int32 max_dur = 2*MINUTE*IN_MILISECONDS;
3701 new_aur->SetAuraMaxDuration( max_dur > dur ? dur : max_dur );
3702 new_aur->SetAuraDuration( max_dur > dur ? dur : max_dur );
3704 // Unregister _before_ adding to stealer
3705 aur->UnregisterSingleCastAura();
3707 // strange but intended behaviour: Stolen single target auras won't be treated as single targeted
3708 new_aur->SetIsSingleTarget(false);
3710 // add the new aura to stealer
3711 stealer->AddAura(new_aur);
3713 // Remove aura as dispel
3714 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3716 else
3717 ++iter;
3721 void Unit::RemoveAurasDueToSpellByCancel(uint32 spellId)
3723 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3725 if (iter->second->GetId() == spellId)
3726 RemoveAura(iter, AURA_REMOVE_BY_CANCEL);
3727 else
3728 ++iter;
3732 void Unit::RemoveAurasWithDispelType( DispelType type )
3734 // Create dispel mask by dispel type
3735 uint32 dispelMask = GetDispellMask(type);
3736 // Dispel all existing auras vs current dispel type
3737 AuraMap& auras = GetAuras();
3738 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
3740 SpellEntry const* spell = itr->second->GetSpellProto();
3741 if( (1<<spell->Dispel) & dispelMask )
3743 // Dispel aura
3744 RemoveAurasDueToSpell(spell->Id);
3745 itr = auras.begin();
3747 else
3748 ++itr;
3752 void Unit::RemoveSingleAuraFromStack(uint32 spellId, uint32 effindex)
3754 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3755 if(iter != m_Auras.end())
3757 if (iter->second->modStackAmount(-1))
3758 RemoveAura(iter);
3762 void Unit::RemoveSingleSpellAurasFromStack(uint32 spellId)
3764 for (int i=0; i<3; ++i)
3765 RemoveSingleAuraFromStack(spellId, i);
3768 void Unit::RemoveAurasDueToSpell(uint32 spellId, Aura* except)
3770 for (int i = 0; i < 3; ++i)
3771 RemoveAura(spellId,i,except);
3774 void Unit::RemoveAurasDueToItemSpell(Item* castItem,uint32 spellId)
3776 for (int k=0; k < 3; ++k)
3778 spellEffectPair spair = spellEffectPair(spellId, k);
3779 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3781 if (iter->second->GetCastItemGUID() == castItem->GetGUID())
3783 RemoveAura(iter);
3784 iter = m_Auras.upper_bound(spair); // overwrite by more appropriate
3786 else
3787 ++iter;
3792 void Unit::RemoveAurasWithInterruptFlags(uint32 flags)
3794 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3796 if (iter->second->GetSpellProto()->AuraInterruptFlags & flags)
3797 RemoveAura(iter);
3798 else
3799 ++iter;
3803 void Unit::RemoveNotOwnSingleTargetAuras()
3805 // single target auras from other casters
3806 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3808 if (iter->second->GetCasterGUID()!=GetGUID() && IsSingleTargetSpell(iter->second->GetSpellProto()))
3809 RemoveAura(iter);
3810 else
3811 ++iter;
3814 // single target auras at other targets
3815 AuraList& scAuras = GetSingleCastAuras();
3816 for (AuraList::iterator iter = scAuras.begin(); iter != scAuras.end(); )
3818 Aura* aura = *iter;
3819 if (aura->GetTarget()!=this)
3821 scAuras.erase(iter); // explicitly remove, instead waiting remove in RemoveAura
3822 aura->GetTarget()->RemoveAura(aura->GetId(),aura->GetEffIndex());
3823 iter = scAuras.begin();
3825 else
3826 ++iter;
3831 void Unit::RemoveAura(AuraMap::iterator &i, AuraRemoveMode mode)
3833 Aura* Aur = i->second;
3834 SpellEntry const* AurSpellInfo = Aur->GetSpellProto();
3836 Aur->UnregisterSingleCastAura();
3838 // remove from list before mods removing (prevent cyclic calls, mods added before including to aura list - use reverse order)
3839 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
3841 m_modAuras[Aur->GetModifier()->m_auraname].remove(Aur);
3844 // Set remove mode
3845 Aur->SetRemoveMode(mode);
3846 // some ShapeshiftBoosts at remove trigger removing other auras including parent Shapeshift aura
3847 // remove aura from list before to prevent deleting it before
3848 m_Auras.erase(i);
3849 ++m_removedAuras; // internal count used by unit update
3851 // Statue unsummoned at aura remove
3852 Totem* statue = NULL;
3853 bool caster_channeled = false;
3854 if(IsChanneledSpell(AurSpellInfo))
3856 Unit* caster = Aur->GetCaster();
3858 if(caster)
3860 if(caster->GetTypeId()==TYPEID_UNIT && ((Creature*)caster)->isTotem() && ((Totem*)caster)->GetTotemType()==TOTEM_STATUE)
3861 statue = ((Totem*)caster);
3862 else
3863 caster_channeled = caster==this;
3867 sLog.outDebug("Aura %u now is remove mode %d",Aur->GetModifier()->m_auraname, mode);
3868 Aur->ApplyModifier(false,true);
3869 Aur->_RemoveAura();
3870 delete Aur;
3872 if(caster_channeled)
3873 RemoveAurasAtChanneledTarget (AurSpellInfo);
3875 if(statue)
3876 statue->UnSummon();
3878 // only way correctly remove all auras from list
3879 if( m_Auras.empty() )
3880 i = m_Auras.end();
3881 else
3882 i = m_Auras.begin();
3885 void Unit::RemoveAllAuras()
3887 while (!m_Auras.empty())
3889 AuraMap::iterator iter = m_Auras.begin();
3890 RemoveAura(iter);
3894 void Unit::RemoveArenaAuras(bool onleave)
3896 // in join, remove positive buffs, on end, remove negative
3897 // used to remove positive visible auras in arenas
3898 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
3900 if ( !(iter->second->GetSpellProto()->AttributesEx4 & (1<<21)) // don't remove stances, shadowform, pally/hunter auras
3901 && !iter->second->IsPassive() // don't remove passive auras
3902 && (!(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)
3903 && (iter->second->IsPositive() ^ onleave)) // remove positive buffs on enter, negative buffs on leave
3904 RemoveAura(iter);
3905 else
3906 ++iter;
3910 void Unit::RemoveAllAurasOnDeath()
3912 // used just after dieing to remove all visible auras
3913 // and disable the mods for the passive ones
3914 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
3916 if (!iter->second->IsPassive() && !iter->second->IsDeathPersistent())
3917 RemoveAura(iter, AURA_REMOVE_BY_DEATH);
3918 else
3919 ++iter;
3923 void Unit::DelayAura(uint32 spellId, uint32 effindex, int32 delaytime)
3925 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3926 if (iter != m_Auras.end())
3928 if (iter->second->GetAuraDuration() < delaytime)
3929 iter->second->SetAuraDuration(0);
3930 else
3931 iter->second->SetAuraDuration(iter->second->GetAuraDuration() - delaytime);
3932 iter->second->SendAuraUpdate(false);
3933 sLog.outDebug("Aura %u partially interrupted on unit %u, new duration: %u ms",iter->second->GetModifier()->m_auraname, GetGUIDLow(), iter->second->GetAuraDuration());
3937 void Unit::_RemoveAllAuraMods()
3939 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
3941 (*i).second->ApplyModifier(false);
3945 void Unit::_ApplyAllAuraMods()
3947 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
3949 (*i).second->ApplyModifier(true);
3953 Aura* Unit::GetAura(uint32 spellId, uint32 effindex)
3955 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3956 if (iter != m_Auras.end())
3957 return iter->second;
3958 return NULL;
3961 Aura* Unit::GetAura(AuraType type, uint32 family, uint64 familyFlag, uint32 familyFlag2, uint64 casterGUID)
3963 AuraList const& auras = GetAurasByType(type);
3964 for(AuraList::const_iterator i = auras.begin();i != auras.end(); ++i)
3966 SpellEntry const *spell = (*i)->GetSpellProto();
3967 if (spell->SpellFamilyName == family && (spell->SpellFamilyFlags & familyFlag || spell->SpellFamilyFlags2 & familyFlag2))
3969 if (casterGUID && (*i)->GetCasterGUID()!=casterGUID)
3970 continue;
3971 return (*i);
3974 return NULL;
3977 bool Unit::HasAura(uint32 spellId) const
3979 for (int i = 0; i < 3 ; ++i)
3981 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, i));
3982 if (iter != m_Auras.end())
3983 return true;
3985 return false;
3988 void Unit::AddDynObject(DynamicObject* dynObj)
3990 m_dynObjGUIDs.push_back(dynObj->GetGUID());
3993 void Unit::RemoveDynObject(uint32 spellid)
3995 if(m_dynObjGUIDs.empty())
3996 return;
3997 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
3999 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4000 if(!dynObj)
4002 i = m_dynObjGUIDs.erase(i);
4004 else if(spellid == 0 || dynObj->GetSpellId() == spellid)
4006 dynObj->Delete();
4007 i = m_dynObjGUIDs.erase(i);
4009 else
4010 ++i;
4014 void Unit::RemoveAllDynObjects()
4016 while(!m_dynObjGUIDs.empty())
4018 DynamicObject* dynObj = GetMap()->GetDynamicObject(*m_dynObjGUIDs.begin());
4019 if(dynObj)
4020 dynObj->Delete();
4021 m_dynObjGUIDs.erase(m_dynObjGUIDs.begin());
4025 DynamicObject * Unit::GetDynObject(uint32 spellId, uint32 effIndex)
4027 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4029 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4030 if(!dynObj)
4032 i = m_dynObjGUIDs.erase(i);
4033 continue;
4036 if (dynObj->GetSpellId() == spellId && dynObj->GetEffIndex() == effIndex)
4037 return dynObj;
4038 ++i;
4040 return NULL;
4043 DynamicObject * Unit::GetDynObject(uint32 spellId)
4045 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4047 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4048 if(!dynObj)
4050 i = m_dynObjGUIDs.erase(i);
4051 continue;
4054 if (dynObj->GetSpellId() == spellId)
4055 return dynObj;
4056 ++i;
4058 return NULL;
4061 GameObject* Unit::GetGameObject(uint32 spellId) const
4063 for (GameObjectList::const_iterator i = m_gameObj.begin(); i != m_gameObj.end();)
4064 if ((*i)->GetSpellId() == spellId)
4065 return *i;
4067 return NULL;
4070 void Unit::AddGameObject(GameObject* gameObj)
4072 assert(gameObj && gameObj->GetOwnerGUID()==0);
4073 m_gameObj.push_back(gameObj);
4074 gameObj->SetOwnerGUID(GetGUID());
4076 if ( GetTypeId()==TYPEID_PLAYER && gameObj->GetSpellId() )
4078 SpellEntry const* createBySpell = sSpellStore.LookupEntry(gameObj->GetSpellId());
4079 // Need disable spell use for owner
4080 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4081 // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
4082 ((Player*)this)->AddSpellAndCategoryCooldowns(createBySpell,0,NULL,true);
4086 void Unit::RemoveGameObject(GameObject* gameObj, bool del)
4088 assert(gameObj && gameObj->GetOwnerGUID()==GetGUID());
4090 gameObj->SetOwnerGUID(0);
4092 // GO created by some spell
4093 if (uint32 spellid = gameObj->GetSpellId())
4095 RemoveAurasDueToSpell(spellid);
4097 if (GetTypeId()==TYPEID_PLAYER)
4099 SpellEntry const* createBySpell = sSpellStore.LookupEntry(spellid );
4100 // Need activate spell use for owner
4101 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4102 // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
4103 ((Player*)this)->SendCooldownEvent(createBySpell);
4107 m_gameObj.remove(gameObj);
4109 if(del)
4111 gameObj->SetRespawnTime(0);
4112 gameObj->Delete();
4116 void Unit::RemoveGameObject(uint32 spellid, bool del)
4118 if(m_gameObj.empty())
4119 return;
4120 GameObjectList::iterator i, next;
4121 for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next)
4123 next = i;
4124 if(spellid == 0 || (*i)->GetSpellId() == spellid)
4126 (*i)->SetOwnerGUID(0);
4127 if(del)
4129 (*i)->SetRespawnTime(0);
4130 (*i)->Delete();
4133 next = m_gameObj.erase(i);
4135 else
4136 ++next;
4140 void Unit::RemoveAllGameObjects()
4142 // remove references to unit
4143 for(GameObjectList::iterator i = m_gameObj.begin(); i != m_gameObj.end();)
4145 (*i)->SetOwnerGUID(0);
4146 (*i)->SetRespawnTime(0);
4147 (*i)->Delete();
4148 i = m_gameObj.erase(i);
4152 void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage *log)
4154 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+1+4+4+1+1+4+4+1)); // we guess size
4155 data.append(log->target->GetPackGUID());
4156 data.append(log->attacker->GetPackGUID());
4157 data << uint32(log->SpellID);
4158 data << uint32(log->damage); //damage amount
4159 data << uint32(0);
4160 data << uint8 (log->schoolMask); //damage school
4161 data << uint32(log->absorb); //AbsorbedDamage
4162 data << uint32(log->resist); //resist
4163 data << uint8 (log->phusicalLog); // damsge type? flag
4164 data << uint8 (log->unused); //unused
4165 data << uint32(log->blocked); //blocked
4166 data << uint32(log->HitInfo);
4167 data << uint8 (0); // flag to use extend data
4168 SendMessageToSet( &data, true );
4171 void Unit::SendSpellNonMeleeDamageLog(Unit *target,uint32 SpellID,uint32 Damage, SpellSchoolMask damageSchoolMask,uint32 AbsorbedDamage, uint32 Resist,bool PhysicalDamage, uint32 Blocked, bool CriticalHit)
4173 sLog.outDebug("Sending: SMSG_SPELLNONMELEEDAMAGELOG");
4174 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+1+4+4+1+1+4+4+1)); // we guess size
4175 data.append(target->GetPackGUID());
4176 data.append(GetPackGUID());
4177 data << uint32(SpellID);
4178 data << uint32(Damage-AbsorbedDamage-Resist-Blocked);
4179 data << uint32(0); // wotlk
4180 data << uint8(damageSchoolMask); // spell school
4181 data << uint32(AbsorbedDamage); // AbsorbedDamage
4182 data << uint32(Resist); // resist
4183 data << uint8(PhysicalDamage); // 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
4184 data << uint8(0); // unk isFromAura
4185 data << uint32(Blocked); // blocked
4186 data << uint32(CriticalHit ? 0x27 : 0x25); // hitType, flags: 0x2 - SPELL_HIT_TYPE_CRIT, 0x10 - replace caster?
4187 data << uint8(0); // isDebug?
4188 SendMessageToSet( &data, true );
4191 void Unit::ProcDamageAndSpell(Unit *pVictim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellEntry const *procSpell)
4193 // Not much to do if no flags are set.
4194 if (procAttacker)
4195 ProcDamageAndSpellFor(false,pVictim,procAttacker, procExtra,attType, procSpell, amount);
4196 // Now go on with a victim's events'n'auras
4197 // Not much to do if no flags are set or there is no victim
4198 if(pVictim && pVictim->isAlive() && procVictim)
4199 pVictim->ProcDamageAndSpellFor(true,this,procVictim, procExtra, attType, procSpell, amount);
4202 void Unit::SendSpellMiss(Unit *target, uint32 spellID, SpellMissInfo missInfo)
4204 WorldPacket data(SMSG_SPELLLOGMISS, (4+8+1+4+8+1));
4205 data << uint32(spellID);
4206 data << uint64(GetGUID());
4207 data << uint8(0); // can be 0 or 1
4208 data << uint32(1); // target count
4209 // for(i = 0; i < target count; ++i)
4210 data << uint64(target->GetGUID()); // target GUID
4211 data << uint8(missInfo);
4212 // end loop
4213 SendMessageToSet(&data, true);
4216 void Unit::SendAttackStateUpdate(CalcDamageInfo *damageInfo)
4218 uint32 count = 1;
4219 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, (16+45)); // we guess size
4220 data << (uint32)damageInfo->HitInfo;
4221 data.append(GetPackGUID());
4222 data.append(damageInfo->target->GetPackGUID());
4223 data << (uint32)(damageInfo->damage); // Full damage
4224 data << uint32(0); // overkill value
4226 data << (uint8)count; // Sub damage count
4228 for(int i = 0; i < count; ++i)
4230 data << (uint32)(damageInfo->damageSchoolMask); // School of sub damage
4231 data << (float)damageInfo->damage; // sub damage
4232 data << (uint32)damageInfo->damage; // Sub Damage
4235 if(damageInfo->HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4237 for(int i = 0; i < count; ++i)
4238 data << (uint32)damageInfo->absorb; // Absorb
4241 if(damageInfo->HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4243 for(int i = 0; i < count; ++i)
4244 data << (uint32)damageInfo->resist; // Resist
4247 data << (uint8)damageInfo->TargetState;
4248 data << (uint32)0;
4249 data << (uint32)0;
4251 if(damageInfo->HitInfo & HITINFO_BLOCK)
4252 data << (uint32)damageInfo->blocked_amount;
4254 if(damageInfo->HitInfo & HITINFO_UNK3)
4255 data << uint32(0);
4257 if(damageInfo->HitInfo & HITINFO_UNK1)
4259 data << uint32(0);
4260 data << float(0);
4261 data << float(0);
4262 data << float(0);
4263 data << float(0);
4264 data << float(0);
4265 data << float(0);
4266 data << float(0);
4267 data << float(0);
4268 for(uint8 i = 0; i < 5; ++i)
4270 data << float(0);
4271 data << float(0);
4273 data << uint32(0);
4276 SendMessageToSet( &data, true );
4279 void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit *target, uint8 SwingType, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount)
4281 sLog.outDebug("WORLD: Sending SMSG_ATTACKERSTATEUPDATE");
4283 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, (16+45)); // we guess size
4284 data << uint32(HitInfo); // flags
4285 data.append(GetPackGUID());
4286 data.append(target->GetPackGUID());
4287 data << uint32(Damage-AbsorbDamage-Resist-BlockedAmount);// damage
4288 data << uint32(0); // overkill value
4290 data << (uint8)SwingType; // count?
4292 // for(i = 0; i < SwingType; ++i)
4293 data << (uint32)damageSchoolMask;
4294 data << (float)(Damage-AbsorbDamage-Resist-BlockedAmount);
4295 data << (uint32)(Damage-AbsorbDamage-Resist-BlockedAmount);
4296 // end loop
4298 if(HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4300 // for(i = 0; i < SwingType; ++i)
4301 data << uint32(AbsorbDamage);
4302 // end loop
4305 if(HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4307 // for(i = 0; i < SwingType; ++i)
4308 data << uint32(Resist);
4309 // end loop
4312 data << (uint8)TargetState;
4313 data << (uint32)0;
4314 data << (uint32)0;
4316 if(HitInfo & HITINFO_BLOCK)
4318 data << uint32(BlockedAmount);
4321 if(HitInfo & HITINFO_UNK3)
4323 data << uint32(0);
4326 if(HitInfo & HITINFO_UNK1)
4328 data << uint32(0);
4329 data << float(0);
4330 data << float(0);
4331 data << float(0);
4332 data << float(0);
4333 data << float(0);
4334 data << float(0);
4335 data << float(0);
4336 data << float(0);
4337 for(uint8 i = 0; i < 5; ++i)
4339 data << float(0);
4340 data << float(0);
4342 data << uint32(0);
4345 SendMessageToSet( &data, true );
4348 bool Unit::HandleHasteAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
4350 SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto();
4352 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4353 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4355 uint32 triggered_spell_id = 0;
4356 Unit* target = pVictim;
4357 int32 basepoints0 = 0;
4359 switch(hasteSpell->SpellFamilyName)
4361 case SPELLFAMILY_ROGUE:
4363 switch(hasteSpell->Id)
4365 // Blade Flurry
4366 case 13877:
4367 case 33735:
4369 target = SelectNearbyTarget();
4370 if(!target)
4371 return false;
4372 basepoints0 = damage;
4373 triggered_spell_id = 22482;
4374 break;
4377 break;
4381 // processed charge only counting case
4382 if(!triggered_spell_id)
4383 return true;
4385 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
4387 if(!triggerEntry)
4389 sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",hasteSpell->Id,triggered_spell_id);
4390 return false;
4393 // default case
4394 if(!target || target!=this && !target->isAlive())
4395 return false;
4397 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
4398 return false;
4400 if(basepoints0)
4401 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
4402 else
4403 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
4405 if( cooldown && GetTypeId()==TYPEID_PLAYER )
4406 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
4408 return true;
4411 bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
4413 SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
4414 uint32 effIndex = triggeredByAura->GetEffIndex();
4415 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
4417 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4418 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4420 uint32 triggered_spell_id = 0;
4421 Unit* target = pVictim;
4422 int32 basepoints0 = 0;
4424 switch(dummySpell->SpellFamilyName)
4426 case SPELLFAMILY_GENERIC:
4428 switch (dummySpell->Id)
4430 // Eye for an Eye
4431 case 9799:
4432 case 25988:
4434 // return damage % to attacker but < 50% own total health
4435 basepoints0 = triggerAmount*int32(damage)/100;
4436 if(basepoints0 > GetMaxHealth()/2)
4437 basepoints0 = GetMaxHealth()/2;
4439 triggered_spell_id = 25997;
4440 break;
4442 // Sweeping Strikes
4443 case 12328:
4444 case 18765:
4445 case 35429:
4447 // prevent chain of triggered spell from same triggered spell
4448 if(procSpell && procSpell->Id==26654)
4449 return false;
4451 target = SelectNearbyTarget();
4452 if(!target)
4453 return false;
4455 triggered_spell_id = 26654;
4456 break;
4458 // Unstable Power
4459 case 24658:
4461 if (!procSpell || procSpell->Id == 24659)
4462 return false;
4463 // Need remove one 24659 aura
4464 RemoveSingleSpellAurasFromStack(24659);
4465 return true;
4467 // Restless Strength
4468 case 24661:
4470 // Need remove one 24662 aura
4471 RemoveSingleSpellAurasFromStack(24662);
4472 return true;
4474 // Adaptive Warding (Frostfire Regalia set)
4475 case 28764:
4477 if(!procSpell)
4478 return false;
4480 // find Mage Armor
4481 bool found = false;
4482 AuraList const& mRegenInterupt = GetAurasByType(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT);
4483 for(AuraList::const_iterator iter = mRegenInterupt.begin(); iter != mRegenInterupt.end(); ++iter)
4485 if(SpellEntry const* iterSpellProto = (*iter)->GetSpellProto())
4487 if(iterSpellProto->SpellFamilyName==SPELLFAMILY_MAGE && (iterSpellProto->SpellFamilyFlags & 0x10000000))
4489 found=true;
4490 break;
4494 if(!found)
4495 return false;
4497 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4499 case SPELL_SCHOOL_NORMAL:
4500 case SPELL_SCHOOL_HOLY:
4501 return false; // ignored
4502 case SPELL_SCHOOL_FIRE: triggered_spell_id = 28765; break;
4503 case SPELL_SCHOOL_NATURE: triggered_spell_id = 28768; break;
4504 case SPELL_SCHOOL_FROST: triggered_spell_id = 28766; break;
4505 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 28769; break;
4506 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 28770; break;
4507 default:
4508 return false;
4511 target = this;
4512 break;
4514 // Obsidian Armor (Justice Bearer`s Pauldrons shoulder)
4515 case 27539:
4517 if(!procSpell)
4518 return false;
4520 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4522 case SPELL_SCHOOL_NORMAL:
4523 return false; // ignore
4524 case SPELL_SCHOOL_HOLY: triggered_spell_id = 27536; break;
4525 case SPELL_SCHOOL_FIRE: triggered_spell_id = 27533; break;
4526 case SPELL_SCHOOL_NATURE: triggered_spell_id = 27538; break;
4527 case SPELL_SCHOOL_FROST: triggered_spell_id = 27534; break;
4528 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 27535; break;
4529 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 27540; break;
4530 default:
4531 return false;
4534 target = this;
4535 break;
4537 // Mana Leech (Passive) (Priest Pet Aura)
4538 case 28305:
4540 // Cast on owner
4541 target = GetOwner();
4542 if(!target)
4543 return false;
4545 triggered_spell_id = 34650;
4546 break;
4548 // Mark of Malice
4549 case 33493:
4551 // Cast finish spell at last charge
4552 if (triggeredByAura->GetAuraCharges() > 1)
4553 return false;
4555 target = this;
4556 triggered_spell_id = 33494;
4557 break;
4559 // Twisted Reflection (boss spell)
4560 case 21063:
4561 triggered_spell_id = 21064;
4562 break;
4563 // Vampiric Aura (boss spell)
4564 case 38196:
4566 basepoints0 = 3 * damage; // 300%
4567 if (basepoints0 < 0)
4568 return false;
4570 triggered_spell_id = 31285;
4571 target = this;
4572 break;
4574 // Aura of Madness (Darkmoon Card: Madness trinket)
4575 //=====================================================
4576 // 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior)
4577 // 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid)
4578 // 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid)
4579 // 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4580 // 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes)
4581 // 41005 Manic: +35 haste (spell, melee and ranged) (All classes)
4582 // 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter)
4583 // 41011 Martyr Complex: +35 stamina (All classes)
4584 // 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4585 // 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4586 case 39446:
4588 if(GetTypeId() != TYPEID_PLAYER)
4589 return false;
4591 // Select class defined buff
4592 switch (getClass())
4594 case CLASS_PALADIN: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4595 case CLASS_DRUID: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4597 uint32 RandomSpell[]={39511,40997,40998,40999,41002,41005,41009,41011,41409};
4598 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4599 break;
4601 case CLASS_ROGUE: // 39511,40997,40998,41002,41005,41011
4602 case CLASS_WARRIOR: // 39511,40997,40998,41002,41005,41011
4604 uint32 RandomSpell[]={39511,40997,40998,41002,41005,41011};
4605 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4606 break;
4608 case CLASS_PRIEST: // 40999,41002,41005,41009,41011,41406,41409
4609 case CLASS_SHAMAN: // 40999,41002,41005,41009,41011,41406,41409
4610 case CLASS_MAGE: // 40999,41002,41005,41009,41011,41406,41409
4611 case CLASS_WARLOCK: // 40999,41002,41005,41009,41011,41406,41409
4613 uint32 RandomSpell[]={40999,41002,41005,41009,41011,41406,41409};
4614 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4615 break;
4617 case CLASS_HUNTER: // 40997,40999,41002,41005,41009,41011,41406,41409
4619 uint32 RandomSpell[]={40997,40999,41002,41005,41009,41011,41406,41409};
4620 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4621 break;
4623 default:
4624 return false;
4627 target = this;
4628 if (roll_chance_i(10))
4629 ((Player*)this)->Say("This is Madness!", LANG_UNIVERSAL);
4630 break;
4633 // TODO: need find item for aura and triggered spells
4634 // Sunwell Exalted Caster Neck (??? neck)
4635 // cast ??? Light's Wrath if Exalted by Aldor
4636 // cast ??? Arcane Bolt if Exalted by Scryers*/
4637 case 46569:
4638 return false; // disable for while
4641 if(GetTypeId() != TYPEID_PLAYER)
4642 return false;
4644 // Get Aldor reputation rank
4645 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4647 target = this;
4648 triggered_spell_id = ???
4649 break;
4651 // Get Scryers reputation rank
4652 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4654 triggered_spell_id = ???
4655 break;
4657 return false;
4658 }/**/
4659 // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck)
4660 // cast 45479 Light's Wrath if Exalted by Aldor
4661 // cast 45429 Arcane Bolt if Exalted by Scryers
4662 case 45481:
4664 if(GetTypeId() != TYPEID_PLAYER)
4665 return false;
4667 // Get Aldor reputation rank
4668 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4670 target = this;
4671 triggered_spell_id = 45479;
4672 break;
4674 // Get Scryers reputation rank
4675 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4677 triggered_spell_id = 45429;
4678 break;
4680 return false;
4682 // Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck)
4683 // cast 45480 Light's Strength if Exalted by Aldor
4684 // cast 45428 Arcane Strike if Exalted by Scryers
4685 case 45482:
4687 if(GetTypeId() != TYPEID_PLAYER)
4688 return false;
4690 // Get Aldor reputation rank
4691 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4693 target = this;
4694 triggered_spell_id = 45480;
4695 break;
4697 // Get Scryers reputation rank
4698 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4700 triggered_spell_id = 45428;
4701 break;
4703 return false;
4705 // Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck)
4706 // cast 45431 Arcane Insight if Exalted by Aldor
4707 // cast 45432 Light's Ward if Exalted by Scryers
4708 case 45483:
4710 if(GetTypeId() != TYPEID_PLAYER)
4711 return false;
4713 // Get Aldor reputation rank
4714 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4716 target = this;
4717 triggered_spell_id = 45432;
4718 break;
4720 // Get Scryers reputation rank
4721 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4723 target = this;
4724 triggered_spell_id = 45431;
4725 break;
4727 return false;
4729 // Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck)
4730 // cast 45478 Light's Salvation if Exalted by Aldor
4731 // cast 45430 Arcane Surge if Exalted by Scryers
4732 case 45484:
4734 if(GetTypeId() != TYPEID_PLAYER)
4735 return false;
4737 // Get Aldor reputation rank
4738 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4740 target = this;
4741 triggered_spell_id = 45478;
4742 break;
4744 // Get Scryers reputation rank
4745 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4747 triggered_spell_id = 45430;
4748 break;
4750 return false;
4752 // Living Seed
4753 case 48504:
4755 triggered_spell_id = 48503;
4756 basepoints0 = triggerAmount;
4757 target = this;
4758 break;
4760 // Vampiric Touch (generic, used by some boss)
4761 case 52723:
4762 case 60501:
4764 triggered_spell_id = 52724;
4765 basepoints0 = damage / 2;
4766 target = this;
4767 break;
4769 // Divine purpose
4770 case 31871:
4771 case 31872:
4773 // Roll chane
4774 if (!roll_chance_i(triggerAmount))
4775 return false;
4777 // Remove any stun effect on target
4778 AuraMap& Auras = pVictim->GetAuras();
4779 for(AuraMap::iterator iter = Auras.begin(); iter != Auras.end();)
4781 SpellEntry const *spell = iter->second->GetSpellProto();
4782 if( spell->Mechanic == MECHANIC_STUN ||
4783 spell->EffectMechanic[iter->second->GetEffIndex()] == MECHANIC_STUN)
4785 pVictim->RemoveAurasDueToSpell(spell->Id);
4786 iter = Auras.begin();
4788 else
4789 ++iter;
4791 return true;
4794 break;
4796 case SPELLFAMILY_MAGE:
4798 // Magic Absorption
4799 if (dummySpell->SpellIconID == 459) // only this spell have SpellIconID == 459 and dummy aura
4801 if (getPowerType() != POWER_MANA)
4802 return false;
4804 // mana reward
4805 basepoints0 = (triggerAmount * GetMaxPower(POWER_MANA) / 100);
4806 target = this;
4807 triggered_spell_id = 29442;
4808 break;
4810 // Master of Elements
4811 if (dummySpell->SpellIconID == 1920)
4813 if(!procSpell)
4814 return false;
4816 // mana cost save
4817 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
4818 basepoints0 = cost * triggerAmount/100;
4819 if( basepoints0 <=0 )
4820 return false;
4822 target = this;
4823 triggered_spell_id = 29077;
4824 break;
4826 // Hot Streak
4827 if (dummySpell->SpellIconID == 2999)
4829 if (effIndex!=0)
4830 return true;
4831 Aura *counter = GetAura(triggeredByAura->GetId(), 1);
4832 if (!counter)
4833 return true;
4835 // Count spell criticals in a row in second aura
4836 Modifier *mod = counter->GetModifier();
4837 if (procEx & PROC_EX_CRITICAL_HIT)
4839 mod->m_amount *=2;
4840 if (mod->m_amount < 100) // not enough
4841 return true;
4842 // Crititcal counted -> roll chance
4843 if (roll_chance_i(triggerAmount))
4844 CastSpell(this, 48108, true, castItem, triggeredByAura);
4846 mod->m_amount = 25;
4847 return true;
4849 // Burnout
4850 if (dummySpell->SpellIconID == 2998)
4852 if(!procSpell)
4853 return false;
4855 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
4856 basepoints0 = cost * triggerAmount/100;
4857 if( basepoints0 <=0 )
4858 return false;
4859 triggered_spell_id = 44450;
4860 target = this;
4861 break;
4863 // Incanter's Regalia set (add trigger chance to Mana Shield)
4864 if (dummySpell->SpellFamilyFlags & 0x0000000000008000LL)
4866 if(GetTypeId() != TYPEID_PLAYER)
4867 return false;
4869 target = this;
4870 triggered_spell_id = 37436;
4871 break;
4873 switch(dummySpell->Id)
4875 // Ignite
4876 case 11119:
4877 case 11120:
4878 case 12846:
4879 case 12847:
4880 case 12848:
4882 switch (dummySpell->Id)
4884 case 11119: basepoints0 = int32(0.04f*damage); break;
4885 case 11120: basepoints0 = int32(0.08f*damage); break;
4886 case 12846: basepoints0 = int32(0.12f*damage); break;
4887 case 12847: basepoints0 = int32(0.16f*damage); break;
4888 case 12848: basepoints0 = int32(0.20f*damage); break;
4889 default:
4890 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (IG)",dummySpell->Id);
4891 return false;
4894 triggered_spell_id = 12654;
4895 break;
4897 // Combustion
4898 case 11129:
4900 //last charge and crit
4901 if (triggeredByAura->GetAuraCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT) )
4903 RemoveAurasDueToSpell(28682); //-> remove Combustion auras
4904 return true; // charge counting (will removed)
4907 CastSpell(this, 28682, true, castItem, triggeredByAura);
4908 return (procEx & PROC_EX_CRITICAL_HIT);// charge update only at crit hits, no hidden cooldowns
4911 break;
4913 case SPELLFAMILY_WARRIOR:
4915 // Retaliation
4916 if(dummySpell->SpellFamilyFlags==0x0000000800000000LL)
4918 // check attack comes not from behind
4919 if (!HasInArc(M_PI, pVictim))
4920 return false;
4922 triggered_spell_id = 22858;
4923 break;
4925 // Second Wind
4926 if (dummySpell->SpellIconID == 1697)
4928 // only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example)
4929 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
4930 return false;
4931 // Need stun or root mechanic
4932 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_STUN))))
4933 return false;
4935 switch (dummySpell->Id)
4937 case 29838: triggered_spell_id=29842; break;
4938 case 29834: triggered_spell_id=29841; break;
4939 case 42770: triggered_spell_id=42771; break;
4940 default:
4941 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)",dummySpell->Id);
4942 return false;
4945 target = this;
4946 break;
4948 // Damage Shield
4949 if (dummySpell->SpellIconID == 3214)
4951 triggered_spell_id = 59653;
4952 basepoints0 = GetShieldBlockValue() * triggerAmount / 100;
4953 break;
4955 break;
4957 case SPELLFAMILY_WARLOCK:
4959 // Seed of Corruption
4960 if (dummySpell->SpellFamilyFlags & 0x0000001000000000LL)
4962 Modifier* mod = triggeredByAura->GetModifier();
4963 // if damage is more than need or target die from damage deal finish spell
4964 if( mod->m_amount <= damage || GetHealth() <= damage )
4966 // remember guid before aura delete
4967 uint64 casterGuid = triggeredByAura->GetCasterGUID();
4969 // Remove aura (before cast for prevent infinite loop handlers)
4970 RemoveAurasDueToSpell(triggeredByAura->GetId());
4972 // Cast finish spell (triggeredByAura already not exist!)
4973 CastSpell(this, 27285, true, castItem, NULL, casterGuid);
4974 return true; // no hidden cooldown
4977 // Damage counting
4978 mod->m_amount-=damage;
4979 return true;
4981 // Seed of Corruption (Mobs cast) - no die req
4982 if (dummySpell->SpellFamilyFlags == 0x00LL && dummySpell->SpellIconID == 1932)
4984 Modifier* mod = triggeredByAura->GetModifier();
4985 // if damage is more than need deal finish spell
4986 if( mod->m_amount <= damage )
4988 // remember guid before aura delete
4989 uint64 casterGuid = triggeredByAura->GetCasterGUID();
4991 // Remove aura (before cast for prevent infinite loop handlers)
4992 RemoveAurasDueToSpell(triggeredByAura->GetId());
4994 // Cast finish spell (triggeredByAura already not exist!)
4995 CastSpell(this, 32865, true, castItem, NULL, casterGuid);
4996 return true; // no hidden cooldown
4998 // Damage counting
4999 mod->m_amount-=damage;
5000 return true;
5002 // Fel Synergy
5003 if (dummySpell->SpellIconID == 3222)
5005 target = GetPet();
5006 if (!target)
5007 return false;
5008 triggered_spell_id = 54181;
5009 basepoints0 = damage * triggerAmount / 100;
5010 break;
5012 switch(dummySpell->Id)
5014 // Nightfall
5015 case 18094:
5016 case 18095:
5018 target = this;
5019 triggered_spell_id = 17941;
5020 break;
5022 //Soul Leech
5023 case 30293:
5024 case 30295:
5025 case 30296:
5027 // health
5028 basepoints0 = int32(damage*triggerAmount/100);
5029 target = this;
5030 triggered_spell_id = 30294;
5031 break;
5033 // Shadowflame (Voidheart Raiment set bonus)
5034 case 37377:
5036 triggered_spell_id = 37379;
5037 break;
5039 // Pet Healing (Corruptor Raiment or Rift Stalker Armor)
5040 case 37381:
5042 target = GetPet();
5043 if(!target)
5044 return false;
5046 // heal amount
5047 basepoints0 = damage * triggerAmount/100;
5048 triggered_spell_id = 37382;
5049 break;
5051 // Shadowflame Hellfire (Voidheart Raiment set bonus)
5052 case 39437:
5054 triggered_spell_id = 37378;
5055 break;
5058 break;
5060 case SPELLFAMILY_PRIEST:
5062 // Vampiric Touch
5063 if( dummySpell->SpellFamilyFlags & 0x0000040000000000LL )
5065 if(!pVictim || !pVictim->isAlive())
5066 return false;
5068 // pVictim is caster of aura
5069 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5070 return false;
5072 // energize amount
5073 basepoints0 = triggerAmount*damage/100;
5074 pVictim->CastCustomSpell(pVictim,34919,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5075 return true; // no hidden cooldown
5077 // Divine Aegis
5078 if (dummySpell->SpellIconID == 2820)
5080 basepoints0 = damage * triggerAmount/100;
5081 triggered_spell_id = 47753;
5082 break;
5084 switch(dummySpell->Id)
5086 // Vampiric Embrace
5087 case 15286:
5089 if(!pVictim || !pVictim->isAlive())
5090 return false;
5092 // pVictim is caster of aura
5093 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5094 return false;
5096 // heal amount
5097 int32 team = triggerAmount*damage/500;
5098 int32 self = triggerAmount*damage/100 - team;
5099 pVictim->CastCustomSpell(pVictim,15290,&team,&self,NULL,true,castItem,triggeredByAura);
5100 return true; // no hidden cooldown
5102 // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen)
5103 case 40438:
5105 // Shadow Word: Pain
5106 if( procSpell->SpellFamilyFlags & 0x0000000000008000LL )
5107 triggered_spell_id = 40441;
5108 // Renew
5109 else if( procSpell->SpellFamilyFlags & 0x0000000000000010LL )
5110 triggered_spell_id = 40440;
5111 else
5112 return false;
5114 target = this;
5115 break;
5117 // Oracle Healing Bonus ("Garments of the Oracle" set)
5118 case 26169:
5120 // heal amount
5121 basepoints0 = int32(damage * 10/100);
5122 target = this;
5123 triggered_spell_id = 26170;
5124 break;
5126 // Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set
5127 case 39372:
5129 if(!procSpell || (GetSpellSchoolMask(procSpell) & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW))==0 )
5130 return false;
5132 // heal amount
5133 basepoints0 = damage * triggerAmount/100;
5134 target = this;
5135 triggered_spell_id = 39373;
5136 break;
5138 // Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus)
5139 case 28809:
5141 triggered_spell_id = 28810;
5142 break;
5144 // Glyph of Dispel Magic
5145 case 55677:
5147 if(!target->IsFriendlyTo(this))
5148 return false;
5150 basepoints0 = int32(target->GetMaxHealth() * triggerAmount / 100);
5151 triggered_spell_id = 56131;
5152 break;
5155 break;
5157 case SPELLFAMILY_DRUID:
5159 switch(dummySpell->Id)
5161 // Healing Touch (Dreamwalker Raiment set)
5162 case 28719:
5164 // mana back
5165 basepoints0 = int32(procSpell->manaCost * 30 / 100);
5166 target = this;
5167 triggered_spell_id = 28742;
5168 break;
5170 // Healing Touch Refund (Idol of Longevity trinket)
5171 case 28847:
5173 target = this;
5174 triggered_spell_id = 28848;
5175 break;
5177 // Mana Restore (Malorne Raiment set / Malorne Regalia set)
5178 case 37288:
5179 case 37295:
5181 target = this;
5182 triggered_spell_id = 37238;
5183 break;
5185 // Druid Tier 6 Trinket
5186 case 40442:
5188 float chance;
5190 // Starfire
5191 if( procSpell->SpellFamilyFlags & 0x0000000000000004LL )
5193 triggered_spell_id = 40445;
5194 chance = 25.f;
5196 // Rejuvenation
5197 else if( procSpell->SpellFamilyFlags & 0x0000000000000010LL )
5199 triggered_spell_id = 40446;
5200 chance = 25.f;
5202 // Mangle (cat/bear)
5203 else if( procSpell->SpellFamilyFlags & 0x0000044000000000LL )
5205 triggered_spell_id = 40452;
5206 chance = 40.f;
5208 else
5209 return false;
5211 if (!roll_chance_f(chance))
5212 return false;
5214 target = this;
5215 break;
5217 // Maim Interrupt
5218 case 44835:
5220 // Deadly Interrupt Effect
5221 triggered_spell_id = 32747;
5222 break;
5225 // Eclipse
5226 if (dummySpell->SpellIconID == 2856)
5228 if (!procSpell)
5229 return false;
5230 // Only 0 aura can proc
5231 if (effIndex!=0)
5232 return true;
5233 // Wrath crit
5234 if (procSpell->SpellFamilyFlags & 0x0000000000000001LL)
5236 if (!roll_chance_i(60))
5237 return false;
5238 triggered_spell_id = 48518;
5239 target = this;
5240 break;
5242 // Starfire crit
5243 if (procSpell->SpellFamilyFlags & 0x0000000000000004LL)
5245 triggered_spell_id = 48517;
5246 target = this;
5247 break;
5249 return false;
5251 // Living Seed
5252 else if (dummySpell->SpellIconID == 2860)
5254 triggered_spell_id = 48504;
5255 basepoints0 = triggerAmount * damage / 100;
5256 break;
5258 break;
5260 case SPELLFAMILY_ROGUE:
5262 switch(dummySpell->Id)
5264 // Deadly Throw Interrupt
5265 case 32748:
5267 // Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw
5268 if(this == pVictim)
5269 return false;
5271 triggered_spell_id = 32747;
5272 break;
5275 // Cut to the Chase
5276 if( dummySpell->SpellIconID == 2909 )
5278 // "refresh your Slice and Dice duration to its 5 combo point maximum"
5279 // lookup Slice and Dice
5280 AuraList const& sd = GetAurasByType(SPELL_AURA_MOD_HASTE);
5281 for(AuraList::const_iterator itr = sd.begin(); itr != sd.end(); ++itr)
5283 SpellEntry const *spellProto = (*itr)->GetSpellProto();
5284 if( spellProto->SpellFamilyName == SPELLFAMILY_ROGUE &&
5285 spellProto->SpellFamilyFlags & 0x0000000000040000LL)
5287 (*itr)->SetAuraMaxDuration(GetSpellMaxDuration(spellProto));
5288 (*itr)->RefreshAura();
5289 return true;
5292 return false;
5294 // Deadly Brew
5295 if( dummySpell->SpellIconID == 2963 )
5297 triggered_spell_id = 25809;
5298 break;
5300 // Quick Recovery
5301 if( dummySpell->SpellIconID == 2116 )
5303 if(!procSpell)
5304 return false;
5306 // energy cost save
5307 basepoints0 = procSpell->manaCost * triggerAmount/100;
5308 if(basepoints0 <= 0)
5309 return false;
5311 target = this;
5312 triggered_spell_id = 31663;
5313 break;
5315 break;
5317 case SPELLFAMILY_HUNTER:
5319 // Thrill of the Hunt
5320 if ( dummySpell->SpellIconID == 2236 )
5322 if(!procSpell)
5323 return false;
5325 // mana cost save
5326 int32 mana = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
5327 basepoints0 = mana * 40/100;
5328 if(basepoints0 <= 0)
5329 return false;
5331 target = this;
5332 triggered_spell_id = 34720;
5333 break;
5335 // Hunting Party
5336 if ( dummySpell->SpellIconID == 3406 )
5338 triggered_spell_id = 57669;
5339 target = this;
5340 break;
5342 // Lock and Load
5343 if ( dummySpell->SpellIconID == 3579 )
5345 // Proc only from periodic (from trap activation proc another aura of this spell)
5346 if (!(procFlag & PROC_FLAG_ON_DO_PERIODIC) || !roll_chance_i(triggerAmount))
5347 return false;
5348 triggered_spell_id = 56453;
5349 target = this;
5350 break;
5352 // Rapid Recuperation
5353 if ( dummySpell->SpellIconID == 3560 )
5355 // This effect only from Rapid Killing (mana regen)
5356 if (!(procSpell->SpellFamilyFlags & 0x0100000000000000LL))
5357 return false;
5358 triggered_spell_id = 56654;
5359 target = this;
5360 break;
5362 break;
5364 case SPELLFAMILY_PALADIN:
5366 // Seal of Righteousness - melee proc dummy (addition ${$MWS*(0.022*$AP+0.044*$SPH)} damage)
5367 if (dummySpell->SpellFamilyFlags&0x000000008000000LL && effIndex==0)
5369 triggered_spell_id = 25742;
5370 float ap = GetTotalAttackPowerValue(BASE_ATTACK);
5371 int32 holy = SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
5372 SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, pVictim);
5373 basepoints0 = GetAttackTime(BASE_ATTACK) * int32(ap*0.022f + 0.044f * holy) / 1000;
5374 break;
5376 // Sacred Shield
5377 if (dummySpell->SpellFamilyFlags&0x0008000000000000LL)
5379 triggered_spell_id = 58597;
5380 target = this;
5381 break;
5383 // Righteous Vengeance
5384 if (dummySpell->SpellIconID == 3025)
5386 // 4 damage tick
5387 basepoints0 = triggerAmount*damage/400;
5388 triggered_spell_id = 61840;
5389 break;
5391 // Sheath of Light
5392 if (dummySpell->SpellIconID == 3030)
5394 // 4 healing tick
5395 basepoints0 = triggerAmount*damage/400;
5396 triggered_spell_id = 54203;
5397 break;
5399 switch(dummySpell->Id)
5401 // Judgement of Light
5402 case 20185:
5404 // Get judgement caster
5405 Unit *caster = triggeredByAura->GetCaster();
5406 if (!caster)
5407 return false;
5408 float ap = caster->GetTotalAttackPowerValue(BASE_ATTACK);
5409 int32 holy = caster->SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
5410 caster->SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, this);
5411 basepoints0 = int32(ap*0.10f + 0.10f*holy);
5412 pVictim->CastCustomSpell(pVictim, 20267, &basepoints0, 0, 0, true, 0, triggeredByAura);
5413 return true;
5415 // Judgement of Wisdom
5416 case 20186:
5418 if (pVictim->getPowerType() == POWER_MANA)
5419 pVictim->CastSpell(pVictim, 20268, true, 0, triggeredByAura);
5420 return true;
5422 // Holy Power (Redemption Armor set)
5423 case 28789:
5425 if(!pVictim)
5426 return false;
5428 // Set class defined buff
5429 switch (pVictim->getClass())
5431 case CLASS_PALADIN:
5432 case CLASS_PRIEST:
5433 case CLASS_SHAMAN:
5434 case CLASS_DRUID:
5435 triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5436 break;
5437 case CLASS_MAGE:
5438 case CLASS_WARLOCK:
5439 triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5440 break;
5441 case CLASS_HUNTER:
5442 case CLASS_ROGUE:
5443 triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d.
5444 break;
5445 case CLASS_WARRIOR:
5446 triggered_spell_id = 28790; // Increases the friendly target's armor
5447 break;
5448 default:
5449 return false;
5451 break;
5453 // Seal of Vengeance (damage calc on apply aura)
5454 case 31801:
5456 if(effIndex != 0) // effect 1,2 used by seal unleashing code
5457 return false;
5459 triggered_spell_id = 31803;
5460 break;
5462 // Spiritual Attunement
5463 case 31785:
5464 case 33776:
5466 // if healed by another unit (pVictim)
5467 if(this == pVictim)
5468 return false;
5470 // heal amount
5471 basepoints0 = triggerAmount*damage/100;
5472 target = this;
5473 triggered_spell_id = 31786;
5474 break;
5476 // Seal of Blood do damage trigger
5477 case 31892:
5479 if (effIndex == 0) // 0 effect - is proc on enemy
5480 triggered_spell_id = 31893;
5481 else if (effIndex == 1) // 1 effect - is proc on self
5483 // add spell damage from prev effect (27%)
5484 damage += CalculateDamage(BASE_ATTACK, false) * 27 / 100;
5485 basepoints0 = triggerAmount * damage / 100;
5486 target = this;
5487 triggered_spell_id = 32221;
5489 else
5490 return true;
5491 break;
5493 // Seal of the Martyr do damage trigger
5494 case 53720:
5496 if (effIndex == 0) // 0 effect - is proc on enemy
5497 triggered_spell_id = 53719;
5498 else if (effIndex == 1) // 1 effect - is proc on self
5500 // add spell damage from prev effect (27%)
5501 damage += CalculateDamage(BASE_ATTACK, false) * 27 / 100;
5502 basepoints0 = triggerAmount * damage / 100;
5503 target = this;
5504 triggered_spell_id = 53718;
5506 else
5507 return true;
5508 break;
5510 // Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal)
5511 case 40470:
5513 if( !procSpell )
5514 return false;
5516 float chance;
5518 // Flash of light/Holy light
5519 if( procSpell->SpellFamilyFlags & 0x00000000C0000000LL)
5521 triggered_spell_id = 40471;
5522 chance = 15.f;
5524 // Judgement
5525 else if( procSpell->SpellFamilyFlags & 0x0000000000800000LL )
5527 triggered_spell_id = 40472;
5528 chance = 50.f;
5530 else
5531 return false;
5533 if (!roll_chance_f(chance))
5534 return false;
5536 break;
5538 // Glyph of Divinity
5539 case 54939:
5541 // Lookup base amount mana restore
5542 for (int i=0; i<3;i++)
5543 if (procSpell->Effect[i] == SPELL_EFFECT_ENERGIZE)
5545 int32 mana = procSpell->EffectBasePoints[i];
5546 CastCustomSpell(this, 54986, 0, &mana, 0, true, castItem, triggeredByAura);
5547 break;
5549 return true;
5551 // Glyph of Flash of Light
5552 case 54936:
5554 triggered_spell_id = 54957;
5555 basepoints0 = triggerAmount*damage/100;
5556 break;
5558 // Glyph of Holy Light
5559 case 54937:
5561 triggered_spell_id = 54968;
5562 basepoints0 = triggerAmount*damage/100;
5563 break;
5566 break;
5568 case SPELLFAMILY_SHAMAN:
5570 switch(dummySpell->Id)
5572 // Totemic Power (The Earthshatterer set)
5573 case 28823:
5575 if( !pVictim )
5576 return false;
5578 // Set class defined buff
5579 switch (pVictim->getClass())
5581 case CLASS_PALADIN:
5582 case CLASS_PRIEST:
5583 case CLASS_SHAMAN:
5584 case CLASS_DRUID:
5585 triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5586 break;
5587 case CLASS_MAGE:
5588 case CLASS_WARLOCK:
5589 triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5590 break;
5591 case CLASS_HUNTER:
5592 case CLASS_ROGUE:
5593 triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d.
5594 break;
5595 case CLASS_WARRIOR:
5596 triggered_spell_id = 28827; // Increases the friendly target's armor
5597 break;
5598 default:
5599 return false;
5601 break;
5603 // Lesser Healing Wave (Totem of Flowing Water Relic)
5604 case 28849:
5606 target = this;
5607 triggered_spell_id = 28850;
5608 break;
5610 // Windfury Weapon (Passive) 1-5 Ranks
5611 case 33757:
5613 if(GetTypeId()!=TYPEID_PLAYER)
5614 return false;
5616 if(!castItem || !castItem->IsEquipped())
5617 return false;
5619 // custom cooldown processing case
5620 if( cooldown && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
5621 return false;
5623 // Now amount of extra power stored in 1 effect of Enchant spell
5624 // Get it by item enchant id
5625 uint32 spellId;
5626 switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)))
5628 case 283: spellId = 8232; break; // 1 Rank
5629 case 284: spellId = 8235; break; // 2 Rank
5630 case 525: spellId = 10486; break; // 3 Rank
5631 case 1669:spellId = 16362; break; // 4 Rank
5632 case 2636:spellId = 25505; break; // 5 Rank
5633 case 3785:spellId = 58801; break; // 6 Rank
5634 case 3786:spellId = 58803; break; // 7 Rank
5635 case 3787:spellId = 58804; break; // 8 Rank
5636 default:
5638 sLog.outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)",
5639 castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)),dummySpell->Id);
5640 return false;
5644 SpellEntry const* windfurySpellEntry = sSpellStore.LookupEntry(spellId);
5645 if(!windfurySpellEntry)
5647 sLog.outError("Unit::HandleDummyAuraProc: non existed spell id: %u (Windfury)",spellId);
5648 return false;
5651 int32 extra_attack_power = CalculateSpellDamage(windfurySpellEntry, 1, windfurySpellEntry->EffectBasePoints[1], pVictim);
5653 // Off-Hand case
5654 if ( castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
5656 // Value gained from additional AP
5657 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(OFF_ATTACK)/1000/2);
5658 triggered_spell_id = 33750;
5660 // Main-Hand case
5661 else
5663 // Value gained from additional AP
5664 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(BASE_ATTACK)/1000);
5665 triggered_spell_id = 25504;
5668 // apply cooldown before cast to prevent processing itself
5669 if( cooldown )
5670 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
5672 // Attack Twice
5673 for ( uint32 i = 0; i<2; ++i )
5674 CastCustomSpell(pVictim,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5676 return true;
5678 // Shaman Tier 6 Trinket
5679 case 40463:
5681 if( !procSpell )
5682 return false;
5684 float chance;
5685 if (procSpell->SpellFamilyFlags & 0x0000000000000001LL)
5687 triggered_spell_id = 40465; // Lightning Bolt
5688 chance = 15.f;
5690 else if (procSpell->SpellFamilyFlags & 0x0000000000000080LL)
5692 triggered_spell_id = 40465; // Lesser Healing Wave
5693 chance = 10.f;
5695 else if (procSpell->SpellFamilyFlags & 0x0000001000000000LL)
5697 triggered_spell_id = 40466; // Stormstrike
5698 chance = 50.f;
5700 else
5701 return false;
5703 if (!roll_chance_f(chance))
5704 return false;
5706 target = this;
5707 break;
5709 // Glyph of Healing Wave
5710 case 55440:
5712 // Not proc from self heals
5713 if (this==pVictim)
5714 return false;
5715 basepoints0 = triggerAmount * damage / 100;
5716 target = this;
5717 triggered_spell_id = 55533;
5718 break;
5720 // Spirit Hunt
5721 case 58877:
5723 // Cast on owner
5724 target = GetOwner();
5725 if(!target)
5726 return false;
5727 basepoints0 = triggerAmount * damage / 100;
5728 triggered_spell_id = 58879;
5729 break;
5732 // Ancestral Awakening
5733 if (dummySpell->SpellIconID == 3065)
5735 // TODO: frite dummy fot triggered spell
5736 triggered_spell_id = 52759;
5737 basepoints0 = triggerAmount * damage / 100;
5738 target = this;
5739 break;
5741 // Earth Shield
5742 if(dummySpell->SpellFamilyFlags & 0x0000040000000000LL)
5744 basepoints0 = triggerAmount;
5745 target = this;
5746 triggered_spell_id = 379;
5747 break;
5749 // Improved Water Shield
5750 if (dummySpell->SpellIconID == 2287)
5752 // Lesser Healing Wave need aditional 60% roll
5753 if (procSpell->SpellFamilyFlags & 0x0000000000000080LL && !roll_chance_i(60))
5754 return false;
5755 // lookup water shield
5756 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
5757 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
5759 if( (*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
5760 (*itr)->GetSpellProto()->SpellFamilyFlags & 0x0000002000000000LL)
5762 uint32 spell = (*itr)->GetSpellProto()->EffectTriggerSpell[(*itr)->GetEffIndex()];
5763 CastSpell(this, spell, true, castItem, triggeredByAura);
5764 if ((*itr)->DropAuraCharge())
5765 RemoveAurasDueToSpell((*itr)->GetId());
5766 return true;
5769 return false;
5770 break;
5772 // Lightning Overload
5773 if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura
5775 if(!procSpell || GetTypeId() != TYPEID_PLAYER || !pVictim )
5776 return false;
5778 // custom cooldown processing case
5779 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
5780 return false;
5782 uint32 spellId = 0;
5783 // Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost
5784 switch (procSpell->Id)
5786 // Lightning Bolt
5787 case 403: spellId = 45284; break; // Rank 1
5788 case 529: spellId = 45286; break; // Rank 2
5789 case 548: spellId = 45287; break; // Rank 3
5790 case 915: spellId = 45288; break; // Rank 4
5791 case 943: spellId = 45289; break; // Rank 5
5792 case 6041: spellId = 45290; break; // Rank 6
5793 case 10391: spellId = 45291; break; // Rank 7
5794 case 10392: spellId = 45292; break; // Rank 8
5795 case 15207: spellId = 45293; break; // Rank 9
5796 case 15208: spellId = 45294; break; // Rank 10
5797 case 25448: spellId = 45295; break; // Rank 11
5798 case 25449: spellId = 45296; break; // Rank 12
5799 case 49237: spellId = 49239; break; // Rank 13
5800 case 49238: spellId = 49240; break; // Rank 14
5801 // Chain Lightning
5802 case 421: spellId = 45297; break; // Rank 1
5803 case 930: spellId = 45298; break; // Rank 2
5804 case 2860: spellId = 45299; break; // Rank 3
5805 case 10605: spellId = 45300; break; // Rank 4
5806 case 25439: spellId = 45301; break; // Rank 5
5807 case 25442: spellId = 45302; break; // Rank 6
5808 case 49268: spellId = 49270; break; // Rank 7
5809 case 49269: spellId = 49271; break; // Rank 8
5810 default:
5811 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (LO)", procSpell->Id);
5812 return false;
5814 // No thread generated mod
5815 // TODO: exist special flag in spell attributes for this, need found and use!
5816 SpellModifier *mod = new SpellModifier;
5817 mod->op = SPELLMOD_THREAT;
5818 mod->value = -100;
5819 mod->type = SPELLMOD_PCT;
5820 mod->spellId = dummySpell->Id;
5821 mod->mask = 0x0000000000000003LL;
5822 mod->mask2= 0LL;
5823 ((Player*)this)->AddSpellMod(mod, true);
5825 // Remove cooldown (Chain Lightning - have Category Recovery time)
5826 if (procSpell->SpellFamilyFlags & 0x0000000000000002LL)
5827 ((Player*)this)->RemoveSpellCooldown(spellId);
5829 CastSpell(pVictim, spellId, true, castItem, triggeredByAura);
5831 ((Player*)this)->AddSpellMod(mod, false);
5833 if( cooldown && GetTypeId()==TYPEID_PLAYER )
5834 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
5836 return true;
5838 // Static Shock
5839 if(dummySpell->SpellIconID == 3059)
5841 // lookup Lightning Shield
5842 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
5843 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
5845 if( (*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
5846 (*itr)->GetSpellProto()->SpellFamilyFlags & 0x0000000000000400LL)
5848 uint32 spell = 0;
5849 switch ((*itr)->GetId())
5851 case 324: spell = 26364; break;
5852 case 325: spell = 26365; break;
5853 case 905: spell = 26366; break;
5854 case 945: spell = 26367; break;
5855 case 8134: spell = 26369; break;
5856 case 10431: spell = 26370; break;
5857 case 10432: spell = 26363; break;
5858 case 25469: spell = 26371; break;
5859 case 25472: spell = 26372; break;
5860 case 49280: spell = 49278; break;
5861 case 49281: spell = 49279; break;
5862 default:
5863 return false;
5865 CastSpell(this, spell, true, castItem, triggeredByAura);
5866 if ((*itr)->DropAuraCharge())
5867 RemoveAurasDueToSpell((*itr)->GetId());
5868 return true;
5871 return false;
5872 break;
5874 break;
5876 case SPELLFAMILY_DEATHKNIGHT:
5878 // Blood Aura
5879 if (dummySpell->SpellIconID == 2636)
5881 if (GetTypeId() != TYPEID_PLAYER || !((Player*)this)->isHonorOrXPTarget(pVictim))
5882 return false;
5883 basepoints0 = triggerAmount * damage / 100;
5884 triggered_spell_id = 53168;
5885 break;
5887 // Butchery
5888 if (dummySpell->SpellIconID == 2664)
5890 basepoints0 = triggerAmount;
5891 triggered_spell_id = 50163;
5892 target = this;
5893 break;
5895 // Dancing Rune Weapon
5896 if (dummySpell->Id == 49028)
5898 // 1 dummy aura for dismiss rune blade
5899 if (effIndex!=2)
5900 return false;
5901 // TODO: wite script for this "fights on its own, doing the same attacks"
5902 // NOTE: Trigger here on every attack and spell cast
5903 return false;
5905 // Mark of Blood
5906 if (dummySpell->Id == 49005)
5908 // TODO: need more info (cooldowns/PPM)
5909 triggered_spell_id = 50424;
5910 break;
5912 // Vendetta
5913 if (dummySpell->SpellFamilyFlags & 0x0000000000010000LL)
5915 basepoints0 = triggerAmount * GetMaxHealth() / 100;
5916 triggered_spell_id = 50181;
5917 target = this;
5918 break;
5920 // Necrosis
5921 if (dummySpell->SpellIconID == 2709)
5923 basepoints0 = triggerAmount * damage / 100;
5924 triggered_spell_id = 51460;
5925 break;
5927 // Runic Power Back on Snare/Root
5928 if (dummySpell->Id == 61257)
5930 // only for spells and hit/crit (trigger start always) and not start from self casted spells
5931 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
5932 return false;
5933 // Need snare or root mechanic
5934 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_SNARE))))
5935 return false;
5936 triggered_spell_id = 61258;
5937 target = this;
5938 break;
5940 // Wandering Plague
5941 if (dummySpell->SpellIconID == 1614)
5943 if (!roll_chance_f(GetUnitCriticalChance(BASE_ATTACK, pVictim)))
5944 return false;
5945 basepoints0 = triggerAmount * damage / 100;
5946 triggered_spell_id = 50526;
5947 break;
5949 break;
5951 default:
5952 break;
5955 // processed charge only counting case
5956 if(!triggered_spell_id)
5957 return true;
5959 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
5961 if(!triggerEntry)
5963 sLog.outError("Unit::HandleDummyAuraProc: Spell %u have not existed triggered spell %u",dummySpell->Id,triggered_spell_id);
5964 return false;
5967 // default case
5968 if(!target || target!=this && !target->isAlive())
5969 return false;
5971 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
5972 return false;
5974 if(basepoints0)
5975 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5976 else
5977 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
5979 if( cooldown && GetTypeId()==TYPEID_PLAYER )
5980 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
5982 return true;
5985 bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown)
5987 // Get triggered aura spell info
5988 SpellEntry const* auraSpellInfo = triggeredByAura->GetSpellProto();
5990 // Basepoints of trigger aura
5991 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
5993 // Set trigger spell id, target, custom basepoints
5994 uint32 trigger_spell_id = auraSpellInfo->EffectTriggerSpell[triggeredByAura->GetEffIndex()];
5995 Unit* target = NULL;
5996 int32 basepoints0 = 0;
5998 if(triggeredByAura->GetModifier()->m_auraname == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE)
5999 basepoints0 = triggerAmount;
6001 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
6002 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
6004 // Try handle uncnown trigger spells
6005 if (sSpellStore.LookupEntry(trigger_spell_id)==NULL)
6007 switch (auraSpellInfo->SpellFamilyName)
6009 case SPELLFAMILY_GENERIC:
6010 //if (auraSpellInfo->Id==59532) // Abandon Passengers on Poly
6011 //if (auraSpellInfo->Id==54775) // Abandon Vehicle on Poly
6012 //if (auraSpellInfo->Id==34082) // Advantaged State (DND)
6013 if (auraSpellInfo->Id == 23780) // Aegis of Preservation (Aegis of Preservation trinket)
6014 trigger_spell_id = 23781;
6015 //else if (auraSpellInfo->Id==43504) // Alterac Valley OnKill Proc Aura
6016 //else if (auraSpellInfo->Id == 48876) // Beast's Mark
6018 // trigger_spell_id = 48877;
6020 //else if (auraSpellInfo->Id == 59237) // Beast's Mark
6022 // trigger_spell_id = 59233;
6024 //else if (auraSpellInfo->Id==46939) // Black Bow of the Betrayer
6026 // trigger_spell_id = 29471; // gain mana
6027 // 27526; // drain mana if possible
6029 //else if (auraSpellInfo->Id==50844) // Blood Mirror
6030 //else if (auraSpellInfo->Id==54476) // Blood Presence
6031 //else if (auraSpellInfo->Id==50689) // Blood Presence (Rank 1)
6032 //else if (auraSpellInfo->Id==37030) // Chaotic Temperament
6033 //else if (auraSpellInfo->Id==52856) // Charge
6034 else if (auraSpellInfo->Id==43820) // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket)
6036 // Pct value stored in dummy
6037 basepoints0 = pVictim->GetCreateHealth() * auraSpellInfo->EffectBasePoints[1] / 100;
6038 target = pVictim;
6039 break;
6041 //else if (auraSpellInfo->Id==41248) // Consuming Strikes
6042 // trigger_spell_id = 41249;
6043 //else if (auraSpellInfo->Id==45205) // Copy Offhand Weapon
6044 //else if (auraSpellInfo->Id==57594) // Copy Ranged Weapon
6045 //else if (auraSpellInfo->Id==41054) // Copy Weapon
6046 // trigger_spell_id = 41055;
6047 //else if (auraSpellInfo->Id==45343) // Dark Flame Aura
6048 //else if (auraSpellInfo->Id==47300) // Dark Flame Aura
6049 else if (auraSpellInfo->Id==57345) // Darkmoon Card: Greatness
6051 float stat = 0.0f;
6052 // strength
6053 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); }
6054 // agility
6055 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); }
6056 // intellect
6057 if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);}
6058 // spirit
6059 if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235;stat = GetStat(STAT_SPIRIT); }
6061 //else if (auraSpellInfo->Id==31255) // Deadly Swiftness (Rank 1)
6062 //else if (auraSpellInfo->Id==5301) // Defensive State (DND)
6063 //else if (auraSpellInfo->Id==13358) // Defensive State (DND)
6064 //else if (auraSpellInfo->Id==16092) // Defensive State (DND)
6065 //else if (auraSpellInfo->Id==24949) // Defensive State 2 (DND)
6066 //else if (auraSpellInfo->Id==40329) // Demo Shout Sensor
6067 else if (auraSpellInfo->Id == 33896) // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher)
6068 trigger_spell_id = 33898;
6069 //else if (auraSpellInfo->Id==18943) // Double Attack
6070 //else if (auraSpellInfo->Id==19194) // Double Attack
6071 //else if (auraSpellInfo->Id==19817) // Double Attack
6072 //else if (auraSpellInfo->Id==19818) // Double Attack
6073 //else if (auraSpellInfo->Id==22835) // Drunken Rage
6074 // trigger_spell_id = 14822;
6076 else if (auraSpellInfo->SpellIconID==191) // Elemental Response
6078 switch (auraSpellInfo->Id && auraSpellInfo->AttributesEx==0)
6080 case 34191:
6081 case 34329:
6082 case 34524:
6083 case 34582:
6084 case 36733:
6085 break;
6086 default:
6087 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Elemental Response",auraSpellInfo->Id);
6088 return false;
6090 //This generic aura self-triggers a different spell for each school of magic that lands on the wearer:
6091 switch (procSpell->School)
6093 case SPELL_SCHOOL_FIRE: trigger_spell_id = 34192; break;
6094 case SPELL_SCHOOL_FROST: trigger_spell_id = 34193; break;
6095 case SPELL_SCHOOL_ARCANE:trigger_spell_id = 34194; break;
6096 case SPELL_SCHOOL_NATURE:trigger_spell_id = 34195; break;
6097 case SPELL_SCHOOL_SHADOW:trigger_spell_id = 34196; break;
6098 case SPELL_SCHOOL_HOLY: trigger_spell_id = 34197; break;
6099 case SPELL_SCHOOL_NORMAL:trigger_spell_id = 34198; break;
6100 default:
6101 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u Elemental Response wrong school",auraSpellInfo->Id);
6102 return false;
6106 //else if (auraSpellInfo->Id==40364) // Entangling Roots Sensor
6107 //else if (auraSpellInfo->Id==33207) // Gossip NPC Periodic - Fidget
6108 //else if (auraSpellInfo->Id==50051) // Ethereal Pet Aura
6109 //else if (auraSpellInfo->Id==35321) // Gushing Wound
6110 //else if (auraSpellInfo->Id==38363) // Gushing Wound
6111 //else if (auraSpellInfo->Id==39215) // Gushing Wound
6112 //else if (auraSpellInfo->Id==44527) // Hate Monster (Spar Buddy) (30 sec)
6113 //else if (auraSpellInfo->Id==44819) // Hate Monster (Spar Buddy) (>30% Health)
6114 //else if (auraSpellInfo->Id==44526) // Hate Monster (Spar) (30 sec)
6115 //else if (auraSpellInfo->Id==44820) // Hate Monster (Spar) (<30%)
6116 //else if (auraSpellInfo->Id==49059) // Horde, Hate Monster (Spar Buddy) (>30% Health)
6117 //else if (auraSpellInfo->Id==40250) // Improved Duration
6118 //else if (auraSpellInfo->Id==59288) // Infra-Green Shield
6119 //else if (auraSpellInfo->Id==54072) // Knockback Ball Passive
6120 else if (auraSpellInfo->Id==27522 || auraSpellInfo->Id==40336)
6121 // Mana Drain Trigger
6123 // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target.
6124 if (this && this->isAlive())
6125 CastSpell(this, 29471, true, castItem, triggeredByAura);
6126 if (pVictim && pVictim->isAlive())
6127 CastSpell(pVictim, 27526, true, castItem, triggeredByAura);
6128 return true;
6130 //else if (auraSpellInfo->Id==55580) // Mana Link
6131 //else if (auraSpellInfo->Id==45903) // Offensive State
6132 //else if (auraSpellInfo->Id==44326) // Pure Energy Passive
6133 //else if (auraSpellInfo->Id==43453) // Rune Ward
6134 //else if (auraSpellInfo->Id== 7137) // Shadow Charge (Rank 1)
6135 //else if (auraSpellInfo->Id==36576) // Shaleskin (Shaleskin Flayer, Shaleskin Ripper) 30023 trigger
6136 //else if (auraSpellInfo->Id==34783) // Spell Reflection
6137 //else if (auraSpellInfo->Id==36096) // Spell Reflection
6138 //else if (auraSpellInfo->Id==57587) // Steal Ranged ()
6139 //else if (auraSpellInfo->Id==36207) // Steal Weapon
6140 //else if (auraSpellInfo->Id== 7377) // Take Immune Periodic Damage <Not Working>
6141 //else if (auraSpellInfo->Id==35205) // Vanish
6142 //else if (auraSpellInfo->Id==42730) // Woe Strike
6143 //else if (auraSpellInfo->Id==59735) // Woe Strike
6144 //else if (auraSpellInfo->Id==46146) // [PH] Ahune Spanky Hands
6145 break;
6146 case SPELLFAMILY_MAGE:
6147 if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed
6149 switch (auraSpellInfo->Id)
6151 case 31641: // Rank 1
6152 case 31642: // Rank 2
6153 trigger_spell_id = 31643;
6154 break;
6155 default:
6156 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blazing Speed",auraSpellInfo->Id);
6157 return false;
6160 break;
6161 case SPELLFAMILY_WARRIOR:
6162 if (auraSpellInfo->Id == 50421) // Scent of Blood
6163 trigger_spell_id = 50422;
6164 break;
6165 case SPELLFAMILY_WARLOCK:
6167 // Pyroclasm
6168 if (auraSpellInfo->SpellIconID == 1137)
6170 if(!pVictim || !pVictim->isAlive() || pVictim == this || procSpell == NULL)
6171 return false;
6172 // Calculate spell tick count for spells
6173 uint32 tick = 1; // Default tick = 1
6175 // Hellfire have 15 tick
6176 if (procSpell->SpellFamilyFlags&0x0000000000000040LL)
6177 tick = 15;
6178 // Rain of Fire have 4 tick
6179 else if (procSpell->SpellFamilyFlags&0x0000000000000020LL)
6180 tick = 4;
6181 else
6182 return false;
6184 // Calculate chance = baseChance / tick
6185 float chance = 0;
6186 switch (auraSpellInfo->Id)
6188 case 18096: chance = 13.0f / tick; break;
6189 case 18073: chance = 26.0f / tick; break;
6191 // Roll chance
6192 if (!roll_chance_f(chance))
6193 return false;
6195 trigger_spell_id = 18093;
6197 // Drain Soul
6198 else if (auraSpellInfo->SpellFamilyFlags & 0x0000000000004000LL)
6200 Unit::AuraList const& mAddFlatModifier = GetAurasByType(SPELL_AURA_ADD_FLAT_MODIFIER);
6201 for(Unit::AuraList::const_iterator i = mAddFlatModifier.begin(); i != mAddFlatModifier.end(); ++i)
6203 if ((*i)->GetModifier()->m_miscvalue == SPELLMOD_CHANCE_OF_SUCCESS && (*i)->GetSpellProto()->SpellIconID == 113)
6205 int32 value2 = CalculateSpellDamage((*i)->GetSpellProto(),2,(*i)->GetSpellProto()->EffectBasePoints[2],this);
6206 // Drain Soul
6207 CastCustomSpell(this, 18371, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
6208 break;
6211 // Not remove charge (aura removed on death in any cases)
6212 // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura
6213 return false;
6215 // Nether Protection
6216 else if (auraSpellInfo->SpellIconID == 1985)
6218 if (!procSpell)
6219 return false;
6220 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
6222 case SPELL_SCHOOL_NORMAL:
6223 case SPELL_SCHOOL_HOLY:
6224 return false; // ignore
6225 case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break;
6226 case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break;
6227 case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break;
6228 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break;
6229 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
6230 default:
6231 return false;
6234 break;
6236 case SPELLFAMILY_PRIEST:
6238 // Greater Heal Refund
6239 if (auraSpellInfo->Id==37594)
6240 trigger_spell_id = 37595;
6241 // Blessed Recovery
6242 else if (auraSpellInfo->SpellIconID == 1875)
6244 switch (auraSpellInfo->Id)
6246 case 27811: trigger_spell_id = 27813; break;
6247 case 27815: trigger_spell_id = 27817; break;
6248 case 27816: trigger_spell_id = 27818; break;
6249 default:
6250 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id);
6251 return false;
6253 basepoints0 = damage * triggerAmount / 100 / 3;
6254 target = this;
6256 break;
6258 case SPELLFAMILY_DRUID:
6260 // Druid Forms Trinket
6261 if (auraSpellInfo->Id==37336)
6263 switch(m_form)
6265 case FORM_NONE: trigger_spell_id = 37344;break;
6266 case FORM_CAT: trigger_spell_id = 37341;break;
6267 case FORM_BEAR:
6268 case FORM_DIREBEAR: trigger_spell_id = 37340;break;
6269 case FORM_TREE: trigger_spell_id = 37342;break;
6270 case FORM_MOONKIN: trigger_spell_id = 37343;break;
6271 default:
6272 return false;
6275 //else if (auraSpellInfo->Id==40363)// Entangling Roots ()
6276 // trigger_spell_id = ????;
6277 // Leader of the Pack
6278 else if (auraSpellInfo->Id == 24932)
6280 if (triggerAmount == 0)
6281 return false;
6282 basepoints0 = triggerAmount * GetMaxHealth() / 100;
6283 trigger_spell_id = 34299;
6285 break;
6287 case SPELLFAMILY_HUNTER:
6288 break;
6289 case SPELLFAMILY_PALADIN:
6292 // Blessed Life
6293 if (auraSpellInfo->SpellIconID == 2137)
6295 switch (auraSpellInfo->Id)
6297 case 31828: // Rank 1
6298 case 31829: // Rank 2
6299 case 31830: // Rank 3
6300 break;
6301 default:
6302 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blessed Life", auraSpellInfo->Id);
6303 return false;
6307 // Healing Discount
6308 if (auraSpellInfo->Id==37705)
6310 trigger_spell_id = 37706;
6311 target = this;
6313 // Soul Preserver
6314 if (auraSpellInfo->Id==60510)
6316 trigger_spell_id = 60515;
6317 target = this;
6319 // Illumination
6320 else if (auraSpellInfo->SpellIconID==241)
6322 if(!procSpell)
6323 return false;
6324 // procspell is triggered spell but we need mana cost of original casted spell
6325 uint32 originalSpellId = procSpell->Id;
6326 // Holy Shock heal
6327 if(procSpell->SpellFamilyFlags & 0x0001000000000000LL)
6329 switch(procSpell->Id)
6331 case 25914: originalSpellId = 20473; break;
6332 case 25913: originalSpellId = 20929; break;
6333 case 25903: originalSpellId = 20930; break;
6334 case 27175: originalSpellId = 27174; break;
6335 case 33074: originalSpellId = 33072; break;
6336 case 48820: originalSpellId = 48824; break;
6337 case 48821: originalSpellId = 48825; break;
6338 default:
6339 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in HShock",procSpell->Id);
6340 return false;
6343 SpellEntry const *originalSpell = sSpellStore.LookupEntry(originalSpellId);
6344 if(!originalSpell)
6346 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu",originalSpellId);
6347 return false;
6349 // percent stored in effect 1 (class scripts) base points
6350 int32 cost = originalSpell->manaCost + originalSpell->ManaCostPercentage * GetCreateMana() / 100;
6351 basepoints0 = cost*auraSpellInfo->CalculateSimpleValue(1)/100;
6352 trigger_spell_id = 20272;
6353 target = this;
6355 // Lightning Capacitor
6356 else if (auraSpellInfo->Id==37657)
6358 if(!pVictim || !pVictim->isAlive())
6359 return false;
6360 // stacking
6361 CastSpell(this, 37658, true, NULL, triggeredByAura);
6363 Aura * dummy = GetDummyAura(37658);
6364 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
6365 if(!dummy || dummy->GetStackAmount() < triggerAmount)
6366 return false;
6368 RemoveAurasDueToSpell(37658);
6369 trigger_spell_id = 37661;
6370 target = pVictim;
6372 // Thunder Capacitor
6373 else if (auraSpellInfo->Id == 54841)
6375 if(!pVictim || !pVictim->isAlive())
6376 return false;
6377 // stacking
6378 CastSpell(this, 54842, true, NULL, triggeredByAura);
6380 // counting
6381 Aura * dummy = GetDummyAura(54842);
6382 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
6383 if(!dummy || dummy->GetStackAmount() < triggerAmount)
6384 return false;
6386 RemoveAurasDueToSpell(54842);
6387 trigger_spell_id = 54843;
6388 target = pVictim;
6390 break;
6392 case SPELLFAMILY_SHAMAN:
6394 // Lightning Shield (overwrite non existing triggered spell call in spell.dbc
6395 if(auraSpellInfo->SpellFamilyFlags & 0x0000000000000400)
6397 switch(auraSpellInfo->Id)
6399 case 324: // Rank 1
6400 trigger_spell_id = 26364; break;
6401 case 325: // Rank 2
6402 trigger_spell_id = 26365; break;
6403 case 905: // Rank 3
6404 trigger_spell_id = 26366; break;
6405 case 945: // Rank 4
6406 trigger_spell_id = 26367; break;
6407 case 8134: // Rank 5
6408 trigger_spell_id = 26369; break;
6409 case 10431: // Rank 6
6410 trigger_spell_id = 26370; break;
6411 case 10432: // Rank 7
6412 trigger_spell_id = 26363; break;
6413 case 25469: // Rank 8
6414 trigger_spell_id = 26371; break;
6415 case 25472: // Rank 9
6416 trigger_spell_id = 26372; break;
6417 case 49280: // Rank 10
6418 trigger_spell_id = 49278; break;
6419 case 49281: // Rank 11
6420 trigger_spell_id = 49279; break;
6421 default:
6422 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in LShield", auraSpellInfo->Id);
6423 return false;
6426 // Lightning Shield (The Ten Storms set)
6427 else if (auraSpellInfo->Id == 23551)
6429 trigger_spell_id = 23552;
6430 target = pVictim;
6432 // Damage from Lightning Shield (The Ten Storms set)
6433 else if (auraSpellInfo->Id == 23552)
6434 trigger_spell_id = 27635;
6435 // Mana Surge (The Earthfury set)
6436 else if (auraSpellInfo->Id == 23572)
6438 if(!procSpell)
6439 return false;
6440 basepoints0 = procSpell->manaCost * 35 / 100;
6441 trigger_spell_id = 23571;
6442 target = this;
6444 // Nature's Guardian
6445 else if (auraSpellInfo->SpellIconID == 2013)
6447 // Check health condition - should drop to less 30% (damage deal after this!)
6448 if (!(10*(int32(GetHealth() - damage)) < 3 * GetMaxHealth()))
6449 return false;
6451 if(pVictim && pVictim->isAlive())
6452 pVictim->getThreatManager().modifyThreatPercent(this,-10);
6454 basepoints0 = triggerAmount * GetMaxHealth() / 100;
6455 trigger_spell_id = 31616;
6456 target = this;
6458 break;
6460 case SPELLFAMILY_DEATHKNIGHT:
6462 // Acclimation
6463 if (auraSpellInfo->SpellIconID == 1930)
6465 if (!procSpell)
6466 return false;
6467 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
6469 case SPELL_SCHOOL_NORMAL:
6470 return false; // ignore
6471 case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break;
6472 case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break;
6473 case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break;
6474 case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break;
6475 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break;
6476 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
6477 default:
6478 return false;
6481 // Blood Presence
6482 else if (auraSpellInfo->Id == 48266)
6484 if (GetTypeId() != TYPEID_PLAYER)
6485 return false;
6486 if (!((Player*)this)->isHonorOrXPTarget(pVictim))
6487 return false;
6488 trigger_spell_id = 50475;
6489 basepoints0 = damage * triggerAmount / 100;
6491 break;
6493 default:
6494 break;
6498 // All ok. Check current trigger spell
6499 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(trigger_spell_id);
6500 if ( triggerEntry == NULL )
6502 // Not cast unknown spell
6503 // sLog.outError("Unit::HandleProcTriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?",auraSpellInfo->Id,triggeredByAura->GetEffIndex());
6504 return false;
6507 // not allow proc extra attack spell at extra attack
6508 if( m_extraAttacks && IsSpellHaveEffect(triggerEntry, SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6509 return false;
6511 // Costum requirements (not listed in procEx) Warning! damage dealing after this
6512 // Custom triggered spells
6513 switch (auraSpellInfo->Id)
6515 // Persistent Shield (Scarab Brooch trinket)
6516 // This spell originally trigger 13567 - Dummy Trigger (vs dummy efect)
6517 case 26467:
6519 basepoints0 = damage * 15 / 100;
6520 target = pVictim;
6521 trigger_spell_id = 26470;
6522 break;
6524 // Cheat Death
6525 case 28845:
6527 // When your health drops below 20% ....
6528 if (GetHealth() - damage > GetMaxHealth() / 5 || GetHealth() < GetMaxHealth() / 5)
6529 return false;
6530 break;
6532 // Deadly Swiftness (Rank 1)
6533 case 31255:
6535 // whenever you deal damage to a target who is below 20% health.
6536 if (pVictim->GetHealth() > pVictim->GetMaxHealth() / 5)
6537 return false;
6539 target = this;
6540 trigger_spell_id = 22588;
6542 // Greater Heal Refund (Avatar Raiment set)
6543 case 37594:
6545 // Not give if target alredy have full health
6546 if (pVictim->GetHealth() == pVictim->GetMaxHealth())
6547 return false;
6548 // If your Greater Heal brings the target to full health, you gain $37595s1 mana.
6549 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
6550 return false;
6551 break;
6553 // Bonus Healing (Crystal Spire of Karabor mace)
6554 case 40971:
6556 // If your target is below $s1% health
6557 if (pVictim->GetHealth() > pVictim->GetMaxHealth() * triggerAmount / 100)
6558 return false;
6559 break;
6561 // Evasive Maneuvers (Commendation of Kael`thas trinket)
6562 case 45057:
6564 // reduce you below $s1% health
6565 if (GetHealth() - damage > GetMaxHealth() * triggerAmount / 100)
6566 return false;
6567 break;
6569 // Rapid Recuperation
6570 case 53228:
6571 case 53232:
6573 // This effect only from Rapid Fire (ability cast)
6574 if (!(procSpell->SpellFamilyFlags & 0x0000000000000020LL))
6575 return false;
6576 break;
6580 // Costum basepoints/target for exist spell
6581 // dummy basepoints or other customs
6582 switch(trigger_spell_id)
6584 // Cast positive spell on enemy target
6585 case 7099: // Curse of Mending
6586 case 39647: // Curse of Mending
6587 case 29494: // Temptation
6588 case 20233: // Improved Lay on Hands (cast on target)
6590 target = pVictim;
6591 break;
6593 // Combo points add triggers (need add combopoint only for main tatget, and after possible combopoints reset)
6594 case 15250: // Rogue Setup
6596 if(!pVictim || pVictim != getVictim()) // applied only for main target
6597 return false;
6598 break; // continue normal case
6600 // Finish movies that add combo
6601 case 14189: // Seal Fate (Netherblade set)
6602 case 14157: // Ruthlessness
6604 // Need add combopoint AFTER finish movie (or they dropped in finish phase)
6605 break;
6607 // Bloodthirst (($m/100)% of max health)
6608 case 23880:
6610 basepoints0 = int32(GetMaxHealth() * triggerAmount / 100);
6611 break;
6613 // Shamanistic Rage triggered spell
6614 case 30824:
6616 basepoints0 = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
6617 break;
6619 // Enlightenment (trigger only from mana cost spells)
6620 case 35095:
6622 if(!procSpell || procSpell->powerType!=POWER_MANA || procSpell->manaCost==0 && procSpell->ManaCostPercentage==0 && procSpell->manaCostPerlevel==0)
6623 return false;
6624 break;
6626 // Brain Freeze
6627 case 57761:
6629 if(!procSpell)
6630 return false;
6631 // For trigger from Blizzard need exist Improved Blizzard
6632 if (procSpell->SpellFamilyName==SPELLFAMILY_MAGE && procSpell->SpellFamilyFlags & 0x0000000000000080LL)
6634 bool found = false;
6635 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
6636 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
6638 int32 script = (*i)->GetModifier()->m_miscvalue;
6639 if(script==836 || script==988 || script==989)
6641 found=true;
6642 break;
6645 if(!found)
6646 return false;
6648 break;
6650 // Astral Shift
6651 case 52179:
6653 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
6654 return false;
6656 // Need stun, fear or silence mechanic
6657 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_SILENCE)|(1<<MECHANIC_STUN)|(1<<MECHANIC_FEAR))))
6658 return false;
6659 break;
6661 // Burning Determination
6662 case 54748:
6664 if(!procSpell)
6665 return false;
6666 // Need Interrupt or Silenced mechanic
6667 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_INTERRUPT)|(1<<MECHANIC_SILENCE))))
6668 return false;
6669 break;
6671 // Lock and Load
6672 case 56453:
6674 // Proc only from trap activation (from periodic proc another aura of this spell)
6675 if (!(procFlags & PROC_FLAG_ON_TRAP_ACTIVATION) || !roll_chance_i(triggerAmount))
6676 return false;
6677 break;
6681 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(trigger_spell_id))
6682 return false;
6684 // try detect target manually if not set
6685 if ( target == NULL )
6686 target = !(procFlags & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) && IsPositiveSpell(trigger_spell_id) ? this : pVictim;
6688 // default case
6689 if(!target || target!=this && !target->isAlive())
6690 return false;
6692 if(basepoints0)
6693 CastCustomSpell(target,trigger_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
6694 else
6695 CastSpell(target,trigger_spell_id,true,castItem,triggeredByAura);
6697 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6698 ((Player*)this)->AddSpellCooldown(trigger_spell_id,0,time(NULL) + cooldown);
6700 return true;
6703 bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, uint32 damage, Aura *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown)
6705 int32 scriptId = triggeredByAura->GetModifier()->m_miscvalue;
6707 if(!pVictim || !pVictim->isAlive())
6708 return false;
6710 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
6711 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
6713 uint32 triggered_spell_id = 0;
6715 switch(scriptId)
6717 case 836: // Improved Blizzard (Rank 1)
6719 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6720 return false;
6721 triggered_spell_id = 12484;
6722 break;
6724 case 988: // Improved Blizzard (Rank 2)
6726 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6727 return false;
6728 triggered_spell_id = 12485;
6729 break;
6731 case 989: // Improved Blizzard (Rank 3)
6733 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6734 return false;
6735 triggered_spell_id = 12486;
6736 break;
6738 case 4086: // Improved Mend Pet (Rank 1)
6739 case 4087: // Improved Mend Pet (Rank 2)
6741 int32 chance = triggeredByAura->GetSpellProto()->EffectBasePoints[triggeredByAura->GetEffIndex()];
6742 if(!roll_chance_i(chance))
6743 return false;
6745 triggered_spell_id = 24406;
6746 break;
6748 case 4533: // Dreamwalker Raiment 2 pieces bonus
6750 // Chance 50%
6751 if (!roll_chance_i(50))
6752 return false;
6754 switch (pVictim->getPowerType())
6756 case POWER_MANA: triggered_spell_id = 28722; break;
6757 case POWER_RAGE: triggered_spell_id = 28723; break;
6758 case POWER_ENERGY: triggered_spell_id = 28724; break;
6759 default:
6760 return false;
6762 break;
6764 case 4537: // Dreamwalker Raiment 6 pieces bonus
6765 triggered_spell_id = 28750; // Blessing of the Claw
6766 break;
6767 case 5497: // Improved Mana Gems (Serpent-Coil Braid)
6768 triggered_spell_id = 37445; // Mana Surge
6769 break;
6770 case 8152: // Serendipity
6772 // if heal your target over maximum health
6773 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
6774 return false;
6775 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
6776 int32 basepoints0 = cost * triggeredByAura->GetModifier()->m_amount/100;
6777 CastCustomSpell(this, 47762, &basepoints0, 0, 0, true, 0, triggeredByAura);
6778 return true;
6782 // not processed
6783 if(!triggered_spell_id)
6784 return false;
6786 // standard non-dummy case
6787 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
6789 if(!triggerEntry)
6791 sLog.outError("Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u",triggered_spell_id,scriptId);
6792 return false;
6795 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
6796 return false;
6798 CastSpell(pVictim, triggered_spell_id, true, castItem, triggeredByAura);
6800 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6801 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
6803 return true;
6806 void Unit::setPowerType(Powers new_powertype)
6808 SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype);
6810 if(GetTypeId() == TYPEID_PLAYER)
6812 if(((Player*)this)->GetGroup())
6813 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE);
6815 else if(((Creature*)this)->isPet())
6817 Pet *pet = ((Pet*)this);
6818 if(pet->isControlled())
6820 Unit *owner = GetOwner();
6821 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
6822 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE);
6826 switch(new_powertype)
6828 default:
6829 case POWER_MANA:
6830 break;
6831 case POWER_RAGE:
6832 SetMaxPower(POWER_RAGE,GetCreatePowers(POWER_RAGE));
6833 SetPower( POWER_RAGE,0);
6834 break;
6835 case POWER_FOCUS:
6836 SetMaxPower(POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
6837 SetPower( POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
6838 break;
6839 case POWER_ENERGY:
6840 SetMaxPower(POWER_ENERGY,GetCreatePowers(POWER_ENERGY));
6841 SetPower( POWER_ENERGY,0);
6842 break;
6843 case POWER_HAPPINESS:
6844 SetMaxPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
6845 SetPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
6846 break;
6850 FactionTemplateEntry const* Unit::getFactionTemplateEntry() const
6852 FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry(getFaction());
6853 if(!entry)
6855 static uint64 guid = 0; // prevent repeating spam same faction problem
6857 if(GetGUID() != guid)
6859 if(GetTypeId() == TYPEID_PLAYER)
6860 sLog.outError("Player %s have invalid faction (faction template id) #%u", ((Player*)this)->GetName(), getFaction());
6861 else
6862 sLog.outError("Creature (template id: %u) have invalid faction (faction template id) #%u", ((Creature*)this)->GetCreatureInfo()->Entry, getFaction());
6863 guid = GetGUID();
6866 return entry;
6869 bool Unit::IsHostileTo(Unit const* unit) const
6871 // always non-hostile to self
6872 if(unit==this)
6873 return false;
6875 // always non-hostile to GM in GM mode
6876 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
6877 return false;
6879 // always hostile to enemy
6880 if(getVictim()==unit || unit->getVictim()==this)
6881 return true;
6883 // test pet/charm masters instead pers/charmeds
6884 Unit const* testerOwner = GetCharmerOrOwner();
6885 Unit const* targetOwner = unit->GetCharmerOrOwner();
6887 // always hostile to owner's enemy
6888 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
6889 return true;
6891 // always hostile to enemy owner
6892 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
6893 return true;
6895 // always hostile to owner of owner's enemy
6896 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
6897 return true;
6899 Unit const* tester = testerOwner ? testerOwner : this;
6900 Unit const* target = targetOwner ? targetOwner : unit;
6902 // always non-hostile to target with common owner, or to owner/pet
6903 if(tester==target)
6904 return false;
6906 // special cases (Duel, etc)
6907 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
6909 Player const* pTester = (Player const*)tester;
6910 Player const* pTarget = (Player const*)target;
6912 // Duel
6913 if(pTester->duel && pTester->duel->opponent == pTarget && pTester->duel->startTime != 0)
6914 return true;
6916 // Group
6917 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
6918 return false;
6920 // Sanctuary
6921 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
6922 return false;
6924 // PvP FFA state
6925 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))
6926 return true;
6928 //= PvP states
6929 // Green/Blue (can't attack)
6930 if(pTester->GetTeam()==pTarget->GetTeam())
6931 return false;
6933 // Red (can attack) if true, Blue/Yellow (can't attack) in another case
6934 return pTester->IsPvP() && pTarget->IsPvP();
6937 // faction base cases
6938 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
6939 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
6940 if(!tester_faction || !target_faction)
6941 return false;
6943 if(target->isAttackingPlayer() && tester->IsContestedGuard())
6944 return true;
6946 // PvC forced reaction and reputation case
6947 if(tester->GetTypeId()==TYPEID_PLAYER)
6949 // forced reaction
6950 if(target_faction->faction)
6952 if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
6953 return *force <= REP_HOSTILE;
6955 // if faction have reputation then hostile state for tester at 100% dependent from at_war state
6956 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
6957 if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
6958 return (factionState->Flags & FACTION_FLAG_AT_WAR);
6961 // CvP forced reaction and reputation case
6962 else if(target->GetTypeId()==TYPEID_PLAYER)
6964 // forced reaction
6965 if(tester_faction->faction)
6967 if(ReputationRank const* force = ((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
6968 return *force <= REP_HOSTILE;
6970 // apply reputation state
6971 FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction);
6972 if(raw_tester_faction && raw_tester_faction->reputationListID >=0 )
6973 return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) <= REP_HOSTILE;
6977 // common faction based case (CvC,PvC,CvP)
6978 return tester_faction->IsHostileTo(*target_faction);
6981 bool Unit::IsFriendlyTo(Unit const* unit) const
6983 // always friendly to self
6984 if(unit==this)
6985 return true;
6987 // always friendly to GM in GM mode
6988 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
6989 return true;
6991 // always non-friendly to enemy
6992 if(getVictim()==unit || unit->getVictim()==this)
6993 return false;
6995 // test pet/charm masters instead pers/charmeds
6996 Unit const* testerOwner = GetCharmerOrOwner();
6997 Unit const* targetOwner = unit->GetCharmerOrOwner();
6999 // always non-friendly to owner's enemy
7000 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
7001 return false;
7003 // always non-friendly to enemy owner
7004 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
7005 return false;
7007 // always non-friendly to owner of owner's enemy
7008 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
7009 return false;
7011 Unit const* tester = testerOwner ? testerOwner : this;
7012 Unit const* target = targetOwner ? targetOwner : unit;
7014 // always friendly to target with common owner, or to owner/pet
7015 if(tester==target)
7016 return true;
7018 // special cases (Duel)
7019 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
7021 Player const* pTester = (Player const*)tester;
7022 Player const* pTarget = (Player const*)target;
7024 // Duel
7025 if(pTester->duel && pTester->duel->opponent == target && pTester->duel->startTime != 0)
7026 return false;
7028 // Group
7029 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
7030 return true;
7032 // Sanctuary
7033 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
7034 return true;
7036 // PvP FFA state
7037 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))
7038 return false;
7040 //= PvP states
7041 // Green/Blue (non-attackable)
7042 if(pTester->GetTeam()==pTarget->GetTeam())
7043 return true;
7045 // Blue (friendly/non-attackable) if not PVP, or Yellow/Red in another case (attackable)
7046 return !pTarget->IsPvP();
7049 // faction base cases
7050 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
7051 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
7052 if(!tester_faction || !target_faction)
7053 return false;
7055 if(target->isAttackingPlayer() && tester->IsContestedGuard())
7056 return false;
7058 // PvC forced reaction and reputation case
7059 if(tester->GetTypeId()==TYPEID_PLAYER)
7061 // forced reaction
7062 if(target_faction->faction)
7064 if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
7065 return *force >= REP_FRIENDLY;
7067 // if faction have reputation then friendly state for tester at 100% dependent from at_war state
7068 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
7069 if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
7070 return !(factionState->Flags & FACTION_FLAG_AT_WAR);
7073 // CvP forced reaction and reputation case
7074 else if(target->GetTypeId()==TYPEID_PLAYER)
7076 // forced reaction
7077 if(tester_faction->faction)
7079 if(ReputationRank const* force =((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
7080 return *force >= REP_FRIENDLY;
7082 // apply reputation state
7083 if(FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction))
7084 if(raw_tester_faction->reputationListID >=0 )
7085 return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) >= REP_FRIENDLY;
7089 // common faction based case (CvC,PvC,CvP)
7090 return tester_faction->IsFriendlyTo(*target_faction);
7093 bool Unit::IsHostileToPlayers() const
7095 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
7096 if(!my_faction || !my_faction->faction)
7097 return false;
7099 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
7100 if(raw_faction && raw_faction->reputationListID >=0 )
7101 return false;
7103 return my_faction->IsHostileToPlayers();
7106 bool Unit::IsNeutralToAll() const
7108 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
7109 if(!my_faction || !my_faction->faction)
7110 return true;
7112 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
7113 if(raw_faction && raw_faction->reputationListID >=0 )
7114 return false;
7116 return my_faction->IsNeutralToAll();
7119 bool Unit::Attack(Unit *victim, bool meleeAttack)
7121 if(!victim || victim == this)
7122 return false;
7124 // dead units can neither attack nor be attacked
7125 if(!isAlive() || !victim->isAlive())
7126 return false;
7128 // player cannot attack in mount state
7129 if(GetTypeId()==TYPEID_PLAYER && IsMounted())
7130 return false;
7132 // nobody can attack GM in GM-mode
7133 if(victim->GetTypeId()==TYPEID_PLAYER)
7135 if(((Player*)victim)->isGameMaster())
7136 return false;
7138 else
7140 if(((Creature*)victim)->IsInEvadeMode())
7141 return false;
7144 // remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack)
7145 if(HasAuraType(SPELL_AURA_MOD_UNATTACKABLE))
7146 RemoveSpellsCausingAura(SPELL_AURA_MOD_UNATTACKABLE);
7148 // in fighting already
7149 if (m_attacking)
7151 if (m_attacking == victim)
7153 // switch to melee attack from ranged/magic
7154 if( meleeAttack && !hasUnitState(UNIT_STAT_MELEE_ATTACKING) )
7156 addUnitState(UNIT_STAT_MELEE_ATTACKING);
7157 SendAttackStart(victim);
7158 return true;
7160 return false;
7163 // remove old target data
7164 AttackStop(true);
7166 // new battle
7167 else
7169 // set position before any AI calls/assistance
7170 if(GetTypeId()==TYPEID_UNIT)
7171 ((Creature*)this)->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ());
7174 //Set our target
7175 SetUInt64Value(UNIT_FIELD_TARGET, victim->GetGUID());
7177 if(meleeAttack)
7178 addUnitState(UNIT_STAT_MELEE_ATTACKING);
7180 m_attacking = victim;
7181 m_attacking->_addAttacker(this);
7183 if(GetTypeId()==TYPEID_UNIT)
7185 WorldPacket data(SMSG_AI_REACTION, 12);
7186 data << uint64(GetGUID());
7187 data << uint32(AI_REACTION_AGGRO); // Aggro sound
7188 ((WorldObject*)this)->SendMessageToSet(&data, true);
7190 ((Creature*)this)->CallAssistance();
7193 // delay offhand weapon attack to next attack time
7194 if(haveOffhandWeapon())
7195 resetAttackTimer(OFF_ATTACK);
7197 if(meleeAttack)
7198 SendAttackStart(victim);
7200 return true;
7203 bool Unit::AttackStop(bool targetSwitch /*=false*/)
7205 if (!m_attacking)
7206 return false;
7208 Unit* victim = m_attacking;
7210 m_attacking->_removeAttacker(this);
7211 m_attacking = NULL;
7213 //Clear our target
7214 SetUInt64Value(UNIT_FIELD_TARGET, 0);
7216 clearUnitState(UNIT_STAT_MELEE_ATTACKING);
7218 InterruptSpell(CURRENT_MELEE_SPELL);
7220 // reset only at real combat stop
7221 if(!targetSwitch && GetTypeId()==TYPEID_UNIT )
7222 ((Creature*)this)->SetNoCallAssistance(false);
7224 SendAttackStop(victim);
7226 return true;
7229 void Unit::CombatStop(bool includingCast)
7231 if (includingCast && IsNonMeleeSpellCasted(false))
7232 InterruptNonMeleeSpells(false);
7234 AttackStop();
7235 RemoveAllAttackers();
7236 if( GetTypeId()==TYPEID_PLAYER )
7237 ((Player*)this)->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel
7238 ClearInCombat();
7241 void Unit::CombatStopWithPets(bool includingCast)
7243 CombatStop(includingCast);
7244 if(Pet* pet = GetPet())
7245 pet->CombatStop(includingCast);
7246 if(Unit* charm = GetCharm())
7247 charm->CombatStop(includingCast);
7248 if(GetTypeId()==TYPEID_PLAYER)
7250 GuardianPetList const& guardians = ((Player*)this)->GetGuardians();
7251 for(GuardianPetList::const_iterator itr = guardians.begin(); itr != guardians.end(); ++itr)
7252 if(Unit* guardian = Unit::GetUnit(*this,*itr))
7253 guardian->CombatStop(includingCast);
7257 bool Unit::isAttackingPlayer() const
7259 if(hasUnitState(UNIT_STAT_ATTACK_PLAYER))
7260 return true;
7262 Pet* pet = GetPet();
7263 if(pet && pet->isAttackingPlayer())
7264 return true;
7266 Unit* charmed = GetCharm();
7267 if(charmed && charmed->isAttackingPlayer())
7268 return true;
7270 for (int8 i = 0; i < MAX_TOTEM; i++)
7272 if(m_TotemSlot[i])
7274 Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]);
7275 if(totem && totem->isAttackingPlayer())
7276 return true;
7280 return false;
7283 void Unit::RemoveAllAttackers()
7285 while (!m_attackers.empty())
7287 AttackerSet::iterator iter = m_attackers.begin();
7288 if(!(*iter)->AttackStop())
7290 sLog.outError("WORLD: Unit has an attacker that isn't attacking it!");
7291 m_attackers.erase(iter);
7296 void Unit::ModifyAuraState(AuraState flag, bool apply)
7298 if (apply)
7300 if (!HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)))
7302 SetFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
7303 if(GetTypeId() == TYPEID_PLAYER)
7305 const PlayerSpellMap& sp_list = ((Player*)this)->GetSpellMap();
7306 for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
7308 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
7309 SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first);
7310 if (!spellInfo || !IsPassiveSpell(itr->first)) continue;
7311 if (spellInfo->CasterAuraState == flag)
7312 CastSpell(this, itr->first, true, NULL);
7317 else
7319 if (HasFlag(UNIT_FIELD_AURASTATE,1<<(flag-1)))
7321 RemoveFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
7322 Unit::AuraMap& tAuras = GetAuras();
7323 for (Unit::AuraMap::iterator itr = tAuras.begin(); itr != tAuras.end();)
7325 SpellEntry const* spellProto = (*itr).second->GetSpellProto();
7326 if (spellProto->CasterAuraState == flag)
7328 // exceptions (applied at state but not removed at state change)
7329 // Rampage
7330 if(spellProto->SpellIconID==2006 && spellProto->SpellFamilyName==SPELLFAMILY_WARRIOR && spellProto->SpellFamilyFlags==0x100000)
7332 ++itr;
7333 continue;
7336 RemoveAura(itr);
7338 else
7339 ++itr;
7345 Unit *Unit::GetOwner() const
7347 uint64 ownerid = GetOwnerGUID();
7348 if(!ownerid)
7349 return NULL;
7350 return ObjectAccessor::GetUnit(*this, ownerid);
7353 Unit *Unit::GetCharmer() const
7355 if(uint64 charmerid = GetCharmerGUID())
7356 return ObjectAccessor::GetUnit(*this, charmerid);
7357 return NULL;
7360 Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself()
7362 uint64 guid = GetCharmerOrOwnerGUID();
7363 if(IS_PLAYER_GUID(guid))
7364 return ObjectAccessor::GetPlayer(*this, guid);
7366 return GetTypeId()==TYPEID_PLAYER ? (Player*)this : NULL;
7369 Pet* Unit::GetPet() const
7371 if(uint64 pet_guid = GetPetGUID())
7373 if(Pet* pet = ObjectAccessor::GetPet(pet_guid))
7374 return pet;
7376 sLog.outError("Unit::GetPet: Pet %u not exist.",GUID_LOPART(pet_guid));
7377 const_cast<Unit*>(this)->SetPet(0);
7380 return NULL;
7383 Unit* Unit::GetCharm() const
7385 if(uint64 charm_guid = GetCharmGUID())
7387 if(Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid))
7388 return pet;
7390 sLog.outError("Unit::GetCharm: Charmed creature %u not exist.",GUID_LOPART(charm_guid));
7391 const_cast<Unit*>(this)->SetCharm(NULL);
7394 return NULL;
7397 float Unit::GetCombatDistance( const Unit* target ) const
7399 float radius = target->GetFloatValue(UNIT_FIELD_COMBATREACH) + GetFloatValue(UNIT_FIELD_COMBATREACH);
7400 float dx = GetPositionX() - target->GetPositionX();
7401 float dy = GetPositionY() - target->GetPositionY();
7402 float dz = GetPositionZ() - target->GetPositionZ();
7403 float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - radius;
7404 return ( dist > 0 ? dist : 0);
7407 void Unit::SetPet(Pet* pet)
7409 SetUInt64Value(UNIT_FIELD_SUMMON, pet ? pet->GetGUID() : 0);
7411 // FIXME: hack, speed must be set only at follow
7412 if(pet)
7413 for(int i = 0; i < MAX_MOVE_TYPE; ++i)
7414 pet->SetSpeed(UnitMoveType(i), m_speed_rate[i], true);
7417 void Unit::SetCharm(Unit* pet)
7419 SetUInt64Value(UNIT_FIELD_CHARM, pet ? pet->GetGUID() : 0);
7421 if(GetTypeId() == TYPEID_PLAYER)
7422 ((Player*)this)->m_mover = pet ? pet : this;
7425 void Unit::UnsummonAllTotems()
7427 for (int8 i = 0; i < MAX_TOTEM; ++i)
7429 if(!m_TotemSlot[i])
7430 continue;
7432 Creature *OldTotem = GetMap()->GetCreature(m_TotemSlot[i]);
7433 if (OldTotem && OldTotem->isTotem())
7434 ((Totem*)OldTotem)->UnSummon();
7438 int32 Unit::DealHeal(Unit *pVictim, uint32 addhealth, SpellEntry const *spellProto, bool critical)
7440 int32 gain = pVictim->ModifyHealth(int32(addhealth));
7442 if (GetTypeId()==TYPEID_PLAYER)
7444 SendHealSpellLog(pVictim, spellProto->Id, addhealth, critical);
7446 if (BattleGround *bg = ((Player*)this)->GetBattleGround())
7447 bg->UpdatePlayerScore((Player*)this, SCORE_HEALING_DONE, gain);
7449 // use the actual gain, as the overheal shall not be counted, skip gain 0 (it ignored anyway in to criteria)
7450 if (gain)
7451 ((Player*)this)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE, gain, 0, pVictim);
7453 ((Player*)this)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED, addhealth);
7456 if (pVictim->GetTypeId()==TYPEID_PLAYER)
7458 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED, gain);
7459 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED, addhealth);
7462 return gain;
7465 Unit* Unit::SelectMagnetTarget(Unit *victim, SpellEntry const *spellInfo)
7467 if(!victim)
7468 return NULL;
7470 // Magic case
7471 if(spellInfo && (spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC))
7473 Unit::AuraList const& magnetAuras = victim->GetAurasByType(SPELL_AURA_SPELL_MAGNET);
7474 for(Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
7475 if(Unit* magnet = (*itr)->GetCaster())
7476 if(magnet->IsWithinLOSInMap(this) && magnet->isAlive())
7477 return magnet;
7479 // Melee && ranged case
7480 else
7482 AuraList const& hitTriggerAuras = victim->GetAurasByType(SPELL_AURA_ADD_CASTER_HIT_TRIGGER);
7483 for(AuraList::const_iterator i = hitTriggerAuras.begin(); i != hitTriggerAuras.end(); ++i)
7484 if(Unit* magnet = (*i)->GetCaster())
7485 if(magnet->isAlive() && magnet->IsWithinLOSInMap(this))
7486 if(roll_chance_i((*i)->GetModifier()->m_amount))
7487 return magnet;
7490 return victim;
7493 void Unit::SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, bool critical)
7495 // we guess size
7496 WorldPacket data(SMSG_SPELLHEALLOG, (8+8+4+4+1));
7497 data.append(pVictim->GetPackGUID());
7498 data.append(GetPackGUID());
7499 data << uint32(SpellID);
7500 data << uint32(Damage);
7501 data << uint32(0); // over healing?
7502 data << uint8(critical ? 1 : 0);
7503 data << uint8(0); // unused in client?
7504 SendMessageToSet(&data, true);
7507 void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
7509 WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1));
7510 data.append(pVictim->GetPackGUID());
7511 data.append(GetPackGUID());
7512 data << uint32(SpellID);
7513 data << uint32(powertype);
7514 data << uint32(Damage);
7515 SendMessageToSet(&data, true);
7518 uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack)
7520 if(!spellProto || !pVictim || damagetype==DIRECT_DAMAGE )
7521 return pdamage;
7523 // For totems get damage bonus from owner (statue isn't totem in fact)
7524 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
7526 if(Unit* owner = GetOwner())
7527 return owner->SpellDamageBonus(pVictim, spellProto, pdamage, damagetype);
7530 // Taken/Done total percent damage auras
7531 float DoneTotalMod = 1.0f;
7532 float TakenTotalMod = 1.0f;
7533 int32 DoneTotal = 0;
7534 int32 TakenTotal = 0;
7536 // ..done
7537 // Pet damage
7538 if( GetTypeId() == TYPEID_UNIT && !((Creature*)this)->isPet() )
7539 DoneTotalMod *= ((Creature*)this)->GetSpellDamageMod(((Creature*)this)->GetCreatureInfo()->rank);
7541 AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
7542 for(AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
7544 if( ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto)) &&
7545 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
7546 // -1 == any item class (not wand then)
7547 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
7548 // 0 == any inventory type (not wand then)
7550 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7554 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7555 // Add flat bonus from spell damage versus
7556 DoneTotal += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask);
7557 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
7558 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
7559 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7560 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7562 // done scripted mod (take it from owner)
7563 Unit *owner = GetOwner();
7564 if (!owner) owner = this;
7565 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7566 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7568 if (!(*i)->isAffectedOnSpell(spellProto))
7569 continue;
7570 switch((*i)->GetModifier()->m_miscvalue)
7572 case 4920: // Molten Fury
7573 case 4919:
7574 case 6917: // Death's Embrace
7575 case 6926:
7576 case 6928:
7578 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7579 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7580 break;
7582 // Soul Siphon
7583 case 4992:
7584 case 4993:
7586 // effect 1 m_amount
7587 int32 maxPercent = (*i)->GetModifier()->m_amount;
7588 // effect 0 m_amount
7589 int32 stepPercent = CalculateSpellDamage((*i)->GetSpellProto(), 0, (*i)->GetSpellProto()->EffectBasePoints[0], this);
7590 // count affliction effects and calc additional damage in percentage
7591 int32 modPercent = 0;
7592 AuraMap const& victimAuras = pVictim->GetAuras();
7593 for (AuraMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
7595 SpellEntry const* m_spell = itr->second->GetSpellProto();
7596 if (m_spell->SpellFamilyName != SPELLFAMILY_WARLOCK || !(m_spell->SpellFamilyFlags & 0x0004071B8044C402LL))
7597 continue;
7598 modPercent += stepPercent * itr->second->GetStackAmount();
7599 if (modPercent >= maxPercent)
7601 modPercent = maxPercent;
7602 break;
7605 DoneTotalMod *= (modPercent+100.0f)/100.0f;
7606 break;
7608 case 6916: // Death's Embrace
7609 case 6925:
7610 case 6927:
7611 if (HasAuraState(AURA_STATE_HEALTHLESS_20_PERCENT))
7612 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7613 break;
7614 case 5481: // Starfire Bonus
7616 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x0000000000200002LL))
7617 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7618 break;
7620 case 4418: // Increased Shock Damage
7621 case 4554: // Increased Lightning Damage
7622 case 4555: // Improved Moonfire
7623 case 5142: // Increased Lightning Damage
7624 case 5147: // Improved Consecration / Libram of Resurgence
7625 case 5148: // Idol of the Shooting Star
7626 case 6008: // Increased Lightning Damage / Totem of Hex
7628 DoneTotal+=(*i)->GetModifier()->m_amount;
7629 break;
7631 // Tundra Stalker
7632 // Merciless Combat
7633 case 7277:
7635 // Merciless Combat
7636 if ((*i)->GetSpellProto()->SpellIconID == 2656)
7638 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7639 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7641 else // Tundra Stalker
7643 if (pVictim->GetAura(SPELL_AURA_DUMMY, SPELLFAMILY_DEATHKNIGHT, 0x0400000000000000LL))
7644 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7645 break;
7647 break;
7649 case 7293: // Rage of Rivendare
7651 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0x0200000000000000LL))
7652 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7653 break;
7655 // Twisted Faith
7656 case 7377:
7658 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x0000000000008000LL, 0, GetGUID()))
7659 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7660 break;
7662 // Marked for Death
7663 case 7598:
7664 case 7599:
7665 case 7600:
7666 case 7601:
7667 case 7602:
7669 if (pVictim->GetAura(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, 0x0000000000000400LL))
7670 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7671 break;
7676 // Custom scripted damage
7677 // Ice Lance
7678 if (spellProto->SpellFamilyName == SPELLFAMILY_MAGE && spellProto->SpellIconID == 186)
7680 if (pVictim->isFrozen())
7681 DoneTotalMod *= 3.0f;
7684 // ..taken
7685 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
7686 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
7687 if( (*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto) )
7688 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7690 // .. taken pct: dummy auras
7691 if (pVictim->GetTypeId() == TYPEID_PLAYER)
7693 //Cheat Death
7694 if (Aura *dummy = pVictim->GetDummyAura(45182))
7696 float mod = -((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2*4;
7697 if (mod < dummy->GetModifier()->m_amount)
7698 mod = dummy->GetModifier()->m_amount;
7699 TakenTotalMod *= (mod+100.0f)/100.0f;
7703 // From caster spells
7704 AuraList const& mOwnerTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_FROM_CASTER);
7705 for(AuraList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i)
7706 if( (*i)->GetCasterGUID() == GetGUID() && (*i)->isAffectedOnSpell(spellProto))
7707 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7709 // Mod damage from spell mechanic
7710 uint32 mechanicMask = GetAllSpellMechanicMask(spellProto);
7711 if (mechanicMask)
7713 AuraList const& mDamageDoneMechanic = pVictim->GetAurasByType(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT);
7714 for(AuraList::const_iterator i = mDamageDoneMechanic.begin();i != mDamageDoneMechanic.end(); ++i)
7715 if(mechanicMask & uint32(1<<((*i)->GetModifier()->m_miscvalue)))
7716 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7719 // Taken/Done fixed damage bonus auras
7720 int32 DoneAdvertisedBenefit = SpellBaseDamageBonus(GetSpellSchoolMask(spellProto));
7721 int32 TakenAdvertisedBenefit = SpellBaseDamageBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
7723 // Pets just add their bonus damage to their spell damage
7724 // note that their spell damage is just gain of their own auras
7725 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
7726 DoneAdvertisedBenefit += ((Pet*)this)->GetBonusDamage();
7728 float LvlPenalty = CalculateLevelPenalty(spellProto);
7729 // Spellmod SpellDamage
7730 float SpellModSpellDamage = 100.0f;
7731 if(Player* modOwner = GetSpellModOwner())
7732 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_SPELL_BONUS_DAMAGE,SpellModSpellDamage);
7733 SpellModSpellDamage /= 100.0f;
7735 // Check for table values
7736 SpellBonusEntry const* bonus = spellmgr.GetSpellBonusData(spellProto->Id);
7737 if (bonus)
7739 float coeff;
7740 if (damagetype == DOT)
7741 coeff = bonus->dot_damage * LvlPenalty * stack;
7742 else
7743 coeff = bonus->direct_damage * LvlPenalty * stack;
7745 if (bonus->ap_bonus)
7746 DoneTotal += int32(bonus->ap_bonus * GetTotalAttackPowerValue(BASE_ATTACK) * stack);
7748 DoneTotal += int32(DoneAdvertisedBenefit * coeff * SpellModSpellDamage);
7749 TakenTotal += int32(TakenAdvertisedBenefit * coeff);
7751 // Default calculation
7752 else if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
7754 // Damage Done from spell damage bonus
7755 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
7756 // Damage over Time spells bonus calculation
7757 float DotFactor = 1.0f;
7758 if(damagetype == DOT)
7760 int32 DotDuration = GetSpellDuration(spellProto);
7761 // 200% limit
7762 if(DotDuration > 0)
7764 if(DotDuration > 30000) DotDuration = 30000;
7765 if(!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
7766 int x = 0;
7767 for(int j = 0; j < 3; j++)
7769 if( spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
7770 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
7771 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
7773 x = j;
7774 break;
7777 int32 DotTicks = 6;
7778 if(spellProto->EffectAmplitude[x] != 0)
7779 DotTicks = DotDuration / spellProto->EffectAmplitude[x];
7780 if(DotTicks)
7782 DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
7783 TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
7787 // Distribute Damage over multiple effects, reduce by AoE
7788 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
7789 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
7790 for(int j = 0; j < 3; ++j)
7792 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
7793 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
7795 CastingTime /= 2;
7796 break;
7799 DoneTotal += int32(DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * SpellModSpellDamage);
7800 TakenTotal+= int32(TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty);
7803 float tmpDamage = (pdamage + DoneTotal) * DoneTotalMod;
7804 // apply spellmod to Done damage (flat and pct)
7805 if(Player* modOwner = GetSpellModOwner())
7806 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
7808 tmpDamage = (tmpDamage + TakenTotal) * TakenTotalMod;
7810 return tmpDamage > 0 ? uint32(tmpDamage) : 0;
7813 int32 Unit::SpellBaseDamageBonus(SpellSchoolMask schoolMask)
7815 int32 DoneAdvertisedBenefit = 0;
7817 // ..done
7818 AuraList const& mDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
7819 for(AuraList::const_iterator i = mDamageDone.begin();i != mDamageDone.end(); ++i)
7820 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0 &&
7821 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
7822 // -1 == any item class (not wand then)
7823 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
7824 // 0 == any inventory type (not wand then)
7825 DoneAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7827 if (GetTypeId() == TYPEID_PLAYER)
7829 // Base value
7830 DoneAdvertisedBenefit +=((Player*)this)->GetBaseSpellDamageBonus();
7832 // Damage bonus from stats
7833 AuraList const& mDamageDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT);
7834 for(AuraList::const_iterator i = mDamageDoneOfStatPercent.begin();i != mDamageDoneOfStatPercent.end(); ++i)
7836 if((*i)->GetModifier()->m_miscvalue & schoolMask)
7838 // stat used stored in miscValueB for this aura
7839 Stats usedStat = Stats((*i)->GetMiscBValue());
7840 DoneAdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
7843 // ... and attack power
7844 AuraList const& mDamageDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER);
7845 for(AuraList::const_iterator i =mDamageDonebyAP.begin();i != mDamageDonebyAP.end(); ++i)
7846 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
7847 DoneAdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
7850 return DoneAdvertisedBenefit;
7853 int32 Unit::SpellBaseDamageBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
7855 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7857 int32 TakenAdvertisedBenefit = 0;
7858 // ..done (for creature type by mask) in taken
7859 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
7860 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
7861 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7862 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7864 // ..taken
7865 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
7866 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
7867 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
7868 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7870 return TakenAdvertisedBenefit;
7873 bool Unit::isSpellCrit(Unit *pVictim, SpellEntry const *spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType)
7875 // not critting spell
7876 if((spellProto->AttributesEx2 & SPELL_ATTR_EX2_CANT_CRIT))
7877 return false;
7879 float crit_chance = 0.0f;
7880 switch(spellProto->DmgClass)
7882 case SPELL_DAMAGE_CLASS_NONE:
7883 return false;
7884 case SPELL_DAMAGE_CLASS_MAGIC:
7886 if (schoolMask & SPELL_SCHOOL_MASK_NORMAL)
7887 crit_chance = 0.0f;
7888 // For other schools
7889 else if (GetTypeId() == TYPEID_PLAYER)
7890 crit_chance = GetFloatValue( PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask));
7891 else
7893 crit_chance = m_baseSpellCritChance;
7894 crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
7896 // taken
7897 if (pVictim)
7899 if (!IsPositiveSpell(spellProto->Id))
7901 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE
7902 crit_chance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask);
7903 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE
7904 crit_chance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
7905 // Modify by player victim resilience
7906 if (pVictim->GetTypeId() == TYPEID_PLAYER)
7907 crit_chance -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
7910 // scripted (increase crit chance ... against ... target by x%
7911 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7912 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7914 if (!((*i)->isAffectedOnSpell(spellProto)))
7915 continue;
7916 switch((*i)->GetModifier()->m_miscvalue)
7918 case 849: if (pVictim->isFrozen()) crit_chance+= 17.0f; break; //Shatter Rank 1
7919 case 910: if (pVictim->isFrozen()) crit_chance+= 34.0f; break; //Shatter Rank 2
7920 case 911: if (pVictim->isFrozen()) crit_chance+= 50.0f; break; //Shatter Rank 3
7921 case 7917: // Glyph of Shadowburn
7922 if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7923 crit_chance+=(*i)->GetModifier()->m_amount;
7924 break;
7925 case 7997: // Renewed Hope
7926 case 7998:
7927 if (pVictim->HasAura(6788))
7928 crit_chance+=(*i)->GetModifier()->m_amount;
7929 break;
7930 case 21: // Test of Faith
7931 case 6935:
7932 case 6918:
7933 if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
7934 crit_chance+=(*i)->GetModifier()->m_amount;
7935 break;
7936 default:
7937 break;
7940 // Custom crit by class
7941 switch(spellProto->SpellFamilyName)
7943 case SPELLFAMILY_PALADIN:
7944 // Sacred Shield
7945 if (spellProto->SpellFamilyFlags & 0x0000000040000000LL)
7947 Aura *aura = pVictim->GetDummyAura(58597);
7948 if (aura && aura->GetCasterGUID() == GetGUID())
7949 crit_chance+=aura->GetModifier()->m_amount;
7950 break;
7952 break;
7953 case SPELLFAMILY_SHAMAN:
7954 // Lava Burst
7955 if (spellProto->SpellFamilyFlags & 0x0000100000000000LL)
7957 if (Aura *flameShock = pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, 0x0000000010000000LL, 0, GetGUID()))
7959 // Consume shock aura if not have Glyph of Flame Shock
7960 if (!GetAura(55447, 0))
7961 pVictim->RemoveAurasByCasterSpell(flameShock->GetId(), GetGUID());
7962 return true;
7964 break;
7966 break;
7970 break;
7972 case SPELL_DAMAGE_CLASS_MELEE:
7973 case SPELL_DAMAGE_CLASS_RANGED:
7975 if (pVictim)
7977 crit_chance = GetUnitCriticalChance(attackType, pVictim);
7978 crit_chance+= GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
7980 break;
7982 default:
7983 return false;
7985 // percent done
7986 // only players use intelligence for critical chance computations
7987 if(Player* modOwner = GetSpellModOwner())
7988 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance);
7990 crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f;
7991 if (roll_chance_f(crit_chance))
7992 return true;
7993 return false;
7996 uint32 Unit::SpellCriticalDamageBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
7998 // Calculate critical bonus
7999 int32 crit_bonus;
8000 switch(spellProto->DmgClass)
8002 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
8003 case SPELL_DAMAGE_CLASS_RANGED:
8004 // TODO: write here full calculation for melee/ranged spells
8005 crit_bonus = damage;
8006 break;
8007 default:
8008 crit_bonus = damage / 2; // for spells is 50%
8009 break;
8012 // adds additional damage to crit_bonus (from talents)
8013 if(Player* modOwner = GetSpellModOwner())
8014 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
8016 if(pVictim)
8018 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8019 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
8022 if(crit_bonus > 0)
8023 damage += crit_bonus;
8025 return damage;
8028 uint32 Unit::SpellCriticalHealingBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
8030 // Calculate critical bonus
8031 int32 crit_bonus;
8032 switch(spellProto->DmgClass)
8034 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
8035 case SPELL_DAMAGE_CLASS_RANGED:
8036 // TODO: write here full calculation for melee/ranged spells
8037 crit_bonus = damage;
8038 break;
8039 default:
8040 crit_bonus = damage / 2; // for spells is 50%
8041 break;
8044 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplier(SPELL_AURA_MOD_CRITICAL_HEALING_BONUS));
8046 if(pVictim)
8048 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8049 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
8052 if(crit_bonus > 0)
8053 damage += crit_bonus;
8055 return damage;
8058 uint32 Unit::SpellHealingBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 healamount, DamageEffectType damagetype, uint32 stack)
8060 // No heal amount for this class spells
8061 if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE)
8062 return healamount;
8064 // For totems get healing bonus from owner (statue isn't totem in fact)
8065 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
8066 if(Unit* owner = GetOwner())
8067 return owner->SpellHealingBonus(pVictim, spellProto, healamount, damagetype, stack);
8069 // Healing Done
8070 // Taken/Done total percent damage auras
8071 float DoneTotalMod = 1.0f;
8072 float TakenTotalMod = 1.0f;
8073 int32 DoneTotal = 0;
8074 int32 TakenTotal = 0;
8076 // Healing done percent
8077 AuraList const& mHealingDonePct = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT);
8078 for(AuraList::const_iterator i = mHealingDonePct.begin();i != mHealingDonePct.end(); ++i)
8079 DoneTotalMod *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
8081 // done scripted mod (take it from owner)
8082 Unit *owner = GetOwner();
8083 if (!owner) owner = this;
8084 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8085 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
8087 if (!(*i)->isAffectedOnSpell(spellProto))
8088 continue;
8089 switch((*i)->GetModifier()->m_miscvalue)
8091 case 4415: // Increased Rejuvenation Healing
8092 case 4953:
8093 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
8094 DoneTotal+=(*i)->GetModifier()->m_amount;
8095 break;
8096 case 7997: // Renewed Hope
8097 case 7998:
8098 if (pVictim->HasAura(6788))
8099 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
8100 break;
8101 case 21: // Test of Faith
8102 case 6935:
8103 case 6918:
8104 if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
8105 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
8106 break;
8107 case 7798: // Glyph of Regrowth
8109 if (pVictim->GetAura(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, 0x0000000000000040LL))
8110 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8111 break;
8113 case 8477: // Nourish Heal Boost
8115 int32 stepPercent = (*i)->GetModifier()->m_amount;
8116 int32 modPercent = 0;
8117 AuraMap const& victimAuras = pVictim->GetAuras();
8118 for (AuraMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
8120 if (itr->second->GetCasterGUID()!=GetGUID())
8121 continue;
8122 SpellEntry const* m_spell = itr->second->GetSpellProto();
8123 if ( m_spell->SpellFamilyName != SPELLFAMILY_DRUID ||
8124 !(m_spell->SpellFamilyFlags & 0x0000001000000050LL))
8125 continue;
8126 modPercent += stepPercent * itr->second->GetStackAmount();
8128 DoneTotalMod *= (modPercent+100.0f)/100.0f;
8129 break;
8131 case 7871: // Glyph of Lesser Healing Wave
8133 if (pVictim->GetAura(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, 0x0000040000000000LL, 0, GetGUID()))
8134 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8135 break;
8137 default:
8138 break;
8142 // Taken/Done fixed damage bonus auras
8143 int32 DoneAdvertisedBenefit = SpellBaseHealingBonus(GetSpellSchoolMask(spellProto));
8144 int32 TakenAdvertisedBenefit = SpellBaseHealingBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
8146 float LvlPenalty = CalculateLevelPenalty(spellProto);
8147 // Spellmod SpellDamage
8148 float SpellModSpellDamage = 100.0f;
8149 if(Player* modOwner = GetSpellModOwner())
8150 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_SPELL_BONUS_DAMAGE, SpellModSpellDamage);
8151 SpellModSpellDamage /= 100.0f;
8153 // Check for table values
8154 SpellBonusEntry const* bonus = spellmgr.GetSpellBonusData(spellProto->Id);
8155 if (bonus)
8157 float coeff;
8158 if (damagetype == DOT)
8159 coeff = bonus->dot_damage * LvlPenalty * stack;
8160 else
8161 coeff = bonus->direct_damage * LvlPenalty * stack;
8163 if (bonus->ap_bonus)
8164 DoneTotal += int32(bonus->ap_bonus * GetTotalAttackPowerValue(BASE_ATTACK) * stack);
8166 DoneTotal += int32(DoneAdvertisedBenefit * coeff * SpellModSpellDamage);
8167 TakenTotal += int32(TakenAdvertisedBenefit * coeff);
8169 // Default calculation
8170 else if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
8172 // Damage Done from spell damage bonus
8173 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
8174 // Damage over Time spells bonus calculation
8175 float DotFactor = 1.0f;
8176 if(damagetype == DOT)
8178 int32 DotDuration = GetSpellDuration(spellProto);
8179 // 200% limit
8180 if(DotDuration > 0)
8182 if(DotDuration > 30000) DotDuration = 30000;
8183 if(!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
8184 int x = 0;
8185 for(int j = 0; j < 3; j++)
8187 if( spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
8188 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
8189 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
8191 x = j;
8192 break;
8195 int32 DotTicks = 6;
8196 if(spellProto->EffectAmplitude[x] != 0)
8197 DotTicks = DotDuration / spellProto->EffectAmplitude[x];
8198 if(DotTicks)
8200 DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
8201 TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
8205 // Distribute Damage over multiple effects, reduce by AoE
8206 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
8207 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
8208 for(int j = 0; j < 3; ++j)
8210 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
8211 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
8213 CastingTime /= 2;
8214 break;
8217 DoneTotal += int32(DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * SpellModSpellDamage * 1.88f);
8218 TakenTotal += int32(TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * 1.88f);
8221 // use float as more appropriate for negative values and percent applying
8222 float heal = (healamount + DoneTotal)*DoneTotalMod;
8223 // apply spellmod to Done amount
8224 if(Player* modOwner = GetSpellModOwner())
8225 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal);
8227 // Taken mods
8228 // Healing Wave cast
8229 if (spellProto->SpellFamilyName == SPELLFAMILY_SHAMAN && spellProto->SpellFamilyFlags & 0x0000000000000040LL)
8231 // Search for Healing Way on Victim
8232 Unit::AuraList const& auraDummy = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
8233 for(Unit::AuraList::const_iterator itr = auraDummy.begin(); itr!=auraDummy.end(); ++itr)
8234 if((*itr)->GetId() == 29203)
8235 TakenTotalMod *= ((*itr)->GetModifier()->m_amount+100.0f) / 100.0f;
8238 // Healing taken percent
8239 float minval = pVictim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
8240 if(minval)
8241 TakenTotalMod *= (100.0f + minval) / 100.0f;
8243 float maxval = pVictim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
8244 if(maxval)
8245 TakenTotalMod *= (100.0f + maxval) / 100.0f;
8247 AuraList const& mHealingGet= pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING_RECEIVED);
8248 for(AuraList::const_iterator i = mHealingGet.begin(); i != mHealingGet.end(); ++i)
8249 if ((*i)->isAffectedOnSpell(spellProto))
8250 TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
8252 heal = (heal + TakenTotal) * TakenTotalMod;
8254 return heal < 0 ? 0 : uint32(heal);
8257 int32 Unit::SpellBaseHealingBonus(SpellSchoolMask schoolMask)
8259 int32 AdvertisedBenefit = 0;
8261 AuraList const& mHealingDone = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE);
8262 for(AuraList::const_iterator i = mHealingDone.begin();i != mHealingDone.end(); ++i)
8263 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
8264 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
8266 // Healing bonus of spirit, intellect and strength
8267 if (GetTypeId() == TYPEID_PLAYER)
8269 // Base value
8270 AdvertisedBenefit +=((Player*)this)->GetBaseSpellHealingBonus();
8272 // Healing bonus from stats
8273 AuraList const& mHealingDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT);
8274 for(AuraList::const_iterator i = mHealingDoneOfStatPercent.begin();i != mHealingDoneOfStatPercent.end(); ++i)
8276 // stat used dependent from misc value (stat index)
8277 Stats usedStat = Stats((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()]);
8278 AdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
8281 // ... and attack power
8282 AuraList const& mHealingDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER);
8283 for(AuraList::const_iterator i = mHealingDonebyAP.begin();i != mHealingDonebyAP.end(); ++i)
8284 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
8285 AdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
8287 return AdvertisedBenefit;
8290 int32 Unit::SpellBaseHealingBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
8292 int32 AdvertisedBenefit = 0;
8293 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING);
8294 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
8295 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
8296 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
8297 return AdvertisedBenefit;
8300 bool Unit::IsImmunedToDamage(SpellSchoolMask shoolMask)
8302 //If m_immuneToSchool type contain this school type, IMMUNE damage.
8303 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
8304 for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
8305 if(itr->type & shoolMask)
8306 return true;
8308 //If m_immuneToDamage type contain magic, IMMUNE damage.
8309 SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
8310 for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
8311 if(itr->type & shoolMask)
8312 return true;
8314 return false;
8317 bool Unit::IsImmunedToSpell(SpellEntry const* spellInfo)
8319 if (!spellInfo)
8320 return false;
8322 //FIX ME this hack: don't get feared if stunned
8323 if (spellInfo->Mechanic == MECHANIC_FEAR )
8325 if ( hasUnitState(UNIT_STAT_STUNNED) )
8326 return true;
8329 //TODO add spellEffect immunity checks!, player with flag in bg is imune to imunity buffs from other friendly players!
8330 //SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_EFFECT];
8332 SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_DISPEL];
8333 for(SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr)
8334 if(itr->type == spellInfo->Dispel)
8335 return true;
8337 if( !(spellInfo->AttributesEx & SPELL_ATTR_EX_UNAFFECTED_BY_SCHOOL_IMMUNE) && // unaffected by school immunity
8338 !(spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)) // can remove immune (by dispell or immune it)
8340 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
8341 for(SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
8342 if( !(IsPositiveSpell(itr->spellId) && IsPositiveSpell(spellInfo->Id)) &&
8343 (itr->type & GetSpellSchoolMask(spellInfo)) )
8344 return true;
8347 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
8348 for(SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
8350 if(itr->type == spellInfo->Mechanic)
8352 return true;
8356 return false;
8359 bool Unit::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
8361 //If m_immuneToEffect type contain this effect type, IMMUNE effect.
8362 uint32 effect = spellInfo->Effect[index];
8363 SpellImmuneList const& effectList = m_spellImmune[IMMUNITY_EFFECT];
8364 for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr)
8365 if(itr->type == effect)
8366 return true;
8368 if(uint32 mechanic = spellInfo->EffectMechanic[index])
8370 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
8371 for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
8372 if(itr->type == mechanic)
8373 return true;
8376 if(uint32 aura = spellInfo->EffectApplyAuraName[index])
8378 SpellImmuneList const& list = m_spellImmune[IMMUNITY_STATE];
8379 for(SpellImmuneList::const_iterator itr = list.begin(); itr != list.end(); ++itr)
8380 if(itr->type == aura)
8381 return true;
8382 // Check for immune to application of harmful magical effects
8383 AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MOD_IMMUNE_AURA_APPLY_SCHOOL);
8384 for(AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
8385 if (spellInfo->Dispel == DISPEL_MAGIC && // Magic debuff
8386 ((*iter)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellInfo)) && // Check school
8387 !IsPositiveEffect(spellInfo->Id, index)) // Harmful
8388 return true;
8391 return false;
8394 bool Unit::IsDamageToThreatSpell(SpellEntry const * spellInfo) const
8396 if(!spellInfo)
8397 return false;
8399 uint32 family = spellInfo->SpellFamilyName;
8400 uint64 flags = spellInfo->SpellFamilyFlags;
8402 if((family == 5 && flags == 256) || //Searing Pain
8403 (family == 6 && flags == 8192) || //Mind Blast
8404 (family == 11 && flags == 1048576)) //Earth Shock
8405 return true;
8407 return false;
8410 void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage,WeaponAttackType attType, SpellEntry const *spellProto)
8412 if(!pVictim)
8413 return;
8415 if(*pdamage == 0)
8416 return;
8418 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8420 // Taken/Done fixed damage bonus auras
8421 int32 DoneFlatBenefit = 0;
8422 int32 TakenFlatBenefit = 0;
8424 // ..done (for creature type by mask) in taken
8425 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
8426 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
8427 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8428 DoneFlatBenefit += (*i)->GetModifier()->m_amount;
8430 // ..done
8431 // SPELL_AURA_MOD_DAMAGE_DONE included in weapon damage
8433 // ..done (base at attack power for marked target and base at attack power for creature type)
8434 int32 APbonus = 0;
8435 if(attType == RANGED_ATTACK)
8437 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS);
8439 // ..done (base at attack power and creature type)
8440 AuraList const& mCreatureAttackPower = GetAurasByType(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS);
8441 for(AuraList::const_iterator i = mCreatureAttackPower.begin();i != mCreatureAttackPower.end(); ++i)
8442 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8443 APbonus += (*i)->GetModifier()->m_amount;
8445 else
8447 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS);
8449 // ..done (base at attack power and creature type)
8450 AuraList const& mCreatureAttackPower = GetAurasByType(SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS);
8451 for(AuraList::const_iterator i = mCreatureAttackPower.begin();i != mCreatureAttackPower.end(); ++i)
8452 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8453 APbonus += (*i)->GetModifier()->m_amount;
8456 if (APbonus!=0) // Can be negative
8458 bool normalized = false;
8459 if(spellProto)
8461 for (uint8 i = 0; i<3;i++)
8463 if (spellProto->Effect[i] == SPELL_EFFECT_NORMALIZED_WEAPON_DMG)
8465 normalized = true;
8466 break;
8471 DoneFlatBenefit += int32(APbonus/14.0f * GetAPMultiplier(attType,normalized));
8474 // ..taken
8475 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
8476 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
8477 if((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask())
8478 TakenFlatBenefit += (*i)->GetModifier()->m_amount;
8480 if(attType!=RANGED_ATTACK)
8481 TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN);
8482 else
8483 TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN);
8485 // Done/Taken total percent damage auras
8486 float DoneTotalMod = 1.0f;
8487 float TakenTotalMod = 1.0f;
8489 // ..done
8490 // SPELL_AURA_MOD_DAMAGE_PERCENT_DONE included in weapon damage
8491 // SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT included in weapon damage
8493 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
8494 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
8495 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8496 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8498 // ..taken
8499 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
8500 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
8501 if((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask())
8502 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8504 // .. taken pct: dummy auras
8505 AuraList const& mDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
8506 for(AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
8508 switch((*i)->GetSpellProto()->SpellIconID)
8510 //Cheat Death
8511 case 2109:
8512 if((*i)->GetModifier()->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)
8514 if(pVictim->GetTypeId() != TYPEID_PLAYER)
8515 continue;
8516 float mod = ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f);
8517 if (mod < (*i)->GetModifier()->m_amount)
8518 mod = (*i)->GetModifier()->m_amount;
8519 TakenTotalMod *= (mod+100.0f)/100.0f;
8521 break;
8522 //Mangle
8523 case 2312:
8524 if(spellProto==NULL)
8525 break;
8526 // Should increase Shred (initial Damage of Lacerate and Rake handled in Spell::EffectSchoolDMG)
8527 if(spellProto->SpellFamilyName==SPELLFAMILY_DRUID && (spellProto->SpellFamilyFlags==0x00008000LL))
8528 TakenTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
8529 break;
8533 // .. taken pct: class scripts
8534 AuraList const& mclassScritAuras = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8535 for(AuraList::const_iterator i = mclassScritAuras.begin(); i != mclassScritAuras.end(); ++i)
8537 switch((*i)->GetMiscValue())
8539 case 6427: case 6428: // Dirty Deeds
8540 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
8542 Aura* eff0 = GetAura((*i)->GetId(),0);
8543 if(!eff0 || (*i)->GetEffIndex()!=1)
8545 sLog.outError("Spell structure of DD (%u) changed.",(*i)->GetId());
8546 continue;
8549 // effect 0 have expected value but in negative state
8550 TakenTotalMod *= (-eff0->GetModifier()->m_amount+100.0f)/100.0f;
8552 break;
8556 if(attType != RANGED_ATTACK)
8558 AuraList const& mModMeleeDamageTakenPercent = pVictim->GetAurasByType(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT);
8559 for(AuraList::const_iterator i = mModMeleeDamageTakenPercent.begin(); i != mModMeleeDamageTakenPercent.end(); ++i)
8560 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8562 else
8564 AuraList const& mModRangedDamageTakenPercent = pVictim->GetAurasByType(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT);
8565 for(AuraList::const_iterator i = mModRangedDamageTakenPercent.begin(); i != mModRangedDamageTakenPercent.end(); ++i)
8566 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8569 float tmpDamage = float(int32(*pdamage) + DoneFlatBenefit) * DoneTotalMod;
8571 // apply spellmod to Done damage
8572 if(spellProto)
8574 if(Player* modOwner = GetSpellModOwner())
8575 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, tmpDamage);
8578 tmpDamage = (tmpDamage + TakenFlatBenefit)*TakenTotalMod;
8580 // bonus result can be negative
8581 *pdamage = tmpDamage > 0 ? uint32(tmpDamage) : 0;
8584 void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply)
8586 if (apply)
8588 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(), next; itr != m_spellImmune[op].end(); itr = next)
8590 next = itr; ++next;
8591 if(itr->type == type)
8593 m_spellImmune[op].erase(itr);
8594 next = m_spellImmune[op].begin();
8597 SpellImmune Immune;
8598 Immune.spellId = spellId;
8599 Immune.type = type;
8600 m_spellImmune[op].push_back(Immune);
8602 else
8604 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(); itr != m_spellImmune[op].end(); ++itr)
8606 if(itr->spellId == spellId)
8608 m_spellImmune[op].erase(itr);
8609 break;
8616 void Unit::ApplySpellDispelImmunity(const SpellEntry * spellProto, DispelType type, bool apply)
8618 ApplySpellImmune(spellProto->Id,IMMUNITY_DISPEL, type, apply);
8620 if (apply && spellProto->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)
8621 RemoveAurasWithDispelType(type);
8624 float Unit::GetWeaponProcChance() const
8626 // normalized proc chance for weapon attack speed
8627 // (odd formula...)
8628 if(isAttackReady(BASE_ATTACK))
8629 return (GetAttackTime(BASE_ATTACK) * 1.8f / 1000.0f);
8630 else if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
8631 return (GetAttackTime(OFF_ATTACK) * 1.6f / 1000.0f);
8632 return 0;
8635 float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM) const
8637 // proc per minute chance calculation
8638 if (PPM <= 0) return 0.0f;
8639 uint32 result = uint32((WeaponSpeed * PPM) / 600.0f); // result is chance in percents (probability = Speed_in_sec * (PPM / 60))
8640 return result;
8643 void Unit::Mount(uint32 mount)
8645 if(!mount)
8646 return;
8648 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNTING);
8650 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount);
8652 SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
8654 // unsummon pet
8655 if(GetTypeId() == TYPEID_PLAYER)
8656 ((Player*)this)->UnsummonPetTemporaryIfAny();
8659 void Unit::Unmount()
8661 if(!IsMounted())
8662 return;
8664 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED);
8666 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
8667 RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
8669 // only resummon old pet if the player is already added to a map
8670 // this prevents adding a pet to a not created map which would otherwise cause a crash
8671 // (it could probably happen when logging in after a previous crash)
8672 if(GetTypeId() == TYPEID_PLAYER)
8673 ((Player*)this)->ResummonPetTemporaryUnSummonedIfAny();
8676 void Unit::SetInCombatWith(Unit* enemy)
8678 Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf();
8679 if(eOwner->IsPvP())
8681 SetInCombatState(true);
8682 return;
8685 //check for duel
8686 if(eOwner->GetTypeId() == TYPEID_PLAYER && ((Player*)eOwner)->duel)
8688 Unit const* myOwner = GetCharmerOrOwnerOrSelf();
8689 if(((Player const*)eOwner)->duel->opponent == myOwner)
8691 SetInCombatState(true);
8692 return;
8695 SetInCombatState(false);
8698 void Unit::SetInCombatState(bool PvP)
8700 // only alive units can be in combat
8701 if(!isAlive())
8702 return;
8704 if(PvP)
8705 m_CombatTimer = 5000;
8706 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
8708 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
8709 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
8712 void Unit::ClearInCombat()
8714 m_CombatTimer = 0;
8715 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
8717 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
8718 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
8720 // Player's state will be cleared in Player::UpdateContestedPvP
8721 if(GetTypeId()!=TYPEID_PLAYER)
8722 clearUnitState(UNIT_STAT_ATTACK_PLAYER);
8723 else
8724 ((Player*)this)->UpdatePotionCooldown();
8727 bool Unit::isTargetableForAttack() const
8729 if (GetTypeId()==TYPEID_PLAYER && ((Player *)this)->isGameMaster())
8730 return false;
8732 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE))
8733 return false;
8735 return isAlive() && !hasUnitState(UNIT_STAT_DIED)&& !isInFlight() /*&& !isStealth()*/;
8738 int32 Unit::ModifyHealth(int32 dVal)
8740 int32 gain = 0;
8742 if(dVal==0)
8743 return 0;
8745 int32 curHealth = (int32)GetHealth();
8747 int32 val = dVal + curHealth;
8748 if(val <= 0)
8750 SetHealth(0);
8751 return -curHealth;
8754 int32 maxHealth = (int32)GetMaxHealth();
8756 if(val < maxHealth)
8758 SetHealth(val);
8759 gain = val - curHealth;
8761 else if(curHealth != maxHealth)
8763 SetHealth(maxHealth);
8764 gain = maxHealth - curHealth;
8767 return gain;
8770 int32 Unit::ModifyPower(Powers power, int32 dVal)
8772 int32 gain = 0;
8774 if(dVal==0)
8775 return 0;
8777 int32 curPower = (int32)GetPower(power);
8779 int32 val = dVal + curPower;
8780 if(val <= 0)
8782 SetPower(power,0);
8783 return -curPower;
8786 int32 maxPower = (int32)GetMaxPower(power);
8788 if(val < maxPower)
8790 SetPower(power,val);
8791 gain = val - curPower;
8793 else if(curPower != maxPower)
8795 SetPower(power,maxPower);
8796 gain = maxPower - curPower;
8799 return gain;
8802 bool Unit::isVisibleForOrDetect(Unit const* u, bool detect, bool inVisibleList, bool is3dDistance) const
8804 if(!u)
8805 return false;
8807 // Always can see self
8808 if (u==this)
8809 return true;
8811 // player visible for other player if not logout and at same transport
8812 // including case when player is out of world
8813 bool at_same_transport =
8814 GetTypeId() == TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER &&
8815 !((Player*)this)->GetSession()->PlayerLogout() && !((Player*)u)->GetSession()->PlayerLogout() &&
8816 !((Player*)this)->GetSession()->PlayerLoading() && !((Player*)u)->GetSession()->PlayerLoading() &&
8817 ((Player*)this)->GetTransport() && ((Player*)this)->GetTransport() == ((Player*)u)->GetTransport();
8819 // not in world
8820 if(!at_same_transport && (!IsInWorld() || !u->IsInWorld()))
8821 return false;
8823 // forbidden to seen (at GM respawn command)
8824 if(m_Visibility==VISIBILITY_RESPAWN)
8825 return false;
8827 // always seen by owner
8828 if(GetCharmerOrOwnerGUID()==u->GetGUID())
8829 return true;
8831 // Grid dead/alive checks
8832 if( u->GetTypeId()==TYPEID_PLAYER)
8834 // non visible at grid for any stealth state
8835 if(!IsVisibleInGridForPlayer((Player *)u))
8836 return false;
8838 // if player is dead then he can't detect anyone in any cases
8839 if(!u->isAlive())
8840 detect = false;
8842 else
8844 // all dead creatures/players not visible for any creatures
8845 if(!u->isAlive() || !isAlive())
8846 return false;
8849 // different visible distance checks
8850 if(u->isInFlight()) // what see player in flight
8852 // use object grey distance for all (only see objects any way)
8853 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceInFlight()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
8854 return false;
8856 else if(!isAlive()) // distance for show body
8858 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForObject()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
8859 return false;
8861 else if(GetTypeId()==TYPEID_PLAYER) // distance for show player
8863 if(u->GetTypeId()==TYPEID_PLAYER)
8865 // Players far than max visible distance for player or not in our map are not visible too
8866 if (!at_same_transport && !IsWithinDistInMap(u,World::GetMaxVisibleDistanceForPlayer()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8867 return false;
8869 else
8871 // Units far than max visible distance for creature or not in our map are not visible too
8872 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForCreature()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8873 return false;
8876 else if(GetCharmerOrOwnerGUID()) // distance for show pet/charmed
8878 // Pet/charmed far than max visible distance for player or not in our map are not visible too
8879 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForPlayer()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8880 return false;
8882 else // distance for show creature
8884 // Units far than max visible distance for creature or not in our map are not visible too
8885 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForCreature()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8886 return false;
8889 // Visible units, always are visible for all units, except for units under invisibility and phases
8890 if (m_Visibility == VISIBILITY_ON && u->m_invisibilityMask==0 && InSamePhase(u))
8891 return true;
8893 // GMs see any players, not higher GMs and all units in any phase
8894 if (u->GetTypeId() == TYPEID_PLAYER && ((Player *)u)->isGameMaster())
8896 if(GetTypeId() == TYPEID_PLAYER)
8897 return ((Player *)this)->GetSession()->GetSecurity() <= ((Player *)u)->GetSession()->GetSecurity();
8898 else
8899 return true;
8902 // non faction visibility non-breakable for non-GMs
8903 if (m_Visibility == VISIBILITY_OFF)
8904 return false;
8906 // phased visibility (both must phased in same way)
8907 if(!InSamePhase(u))
8908 return false;
8910 // raw invisibility
8911 bool invisible = (m_invisibilityMask != 0 || u->m_invisibilityMask !=0);
8913 // detectable invisibility case
8914 if( invisible && (
8915 // Invisible units, always are visible for units under same invisibility type
8916 (m_invisibilityMask & u->m_invisibilityMask)!=0 ||
8917 // Invisible units, always are visible for unit that can detect this invisibility (have appropriate level for detect)
8918 u->canDetectInvisibilityOf(this) ||
8919 // Units that can detect invisibility always are visible for units that can be detected
8920 canDetectInvisibilityOf(u) ))
8922 invisible = false;
8925 // special cases for always overwrite invisibility/stealth
8926 if(invisible || m_Visibility == VISIBILITY_GROUP_STEALTH)
8928 // non-hostile case
8929 if (!u->IsHostileTo(this))
8931 // 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)
8932 if(GetTypeId()==TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER)
8934 if(((Player*)this)->IsGroupVisibleFor(((Player*)u)))
8935 return true;
8937 // else apply same rules as for hostile case (detecting check for stealth)
8940 // hostile case
8941 else
8943 // Hunter mark functionality
8944 AuraList const& auras = GetAurasByType(SPELL_AURA_MOD_STALKED);
8945 for(AuraList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
8946 if((*iter)->GetCasterGUID()==u->GetGUID())
8947 return true;
8949 // else apply detecting check for stealth
8952 // none other cases for detect invisibility, so invisible
8953 if(invisible)
8954 return false;
8956 // else apply stealth detecting check
8959 // unit got in stealth in this moment and must ignore old detected state
8960 if (m_Visibility == VISIBILITY_GROUP_NO_DETECT)
8961 return false;
8963 // GM invisibility checks early, invisibility if any detectable, so if not stealth then visible
8964 if (m_Visibility != VISIBILITY_GROUP_STEALTH)
8965 return true;
8967 // NOW ONLY STEALTH CASE
8969 // stealth and detected and visible for some seconds
8970 if (u->GetTypeId() == TYPEID_PLAYER && ((Player*)u)->m_DetectInvTimer > 300 && ((Player*)u)->HaveAtClient(this))
8971 return true;
8973 //if in non-detect mode then invisible for unit
8974 if (!detect)
8975 return false;
8977 // Special cases
8979 // If is attacked then stealth is lost, some creature can use stealth too
8980 if( !getAttackers().empty() )
8981 return true;
8983 // If there is collision rogue is seen regardless of level difference
8984 // TODO: check sizes in DB
8985 float distance = GetDistance(u);
8986 if (distance < 0.24f)
8987 return true;
8989 //If a mob or player is stunned he will not be able to detect stealth
8990 if (u->hasUnitState(UNIT_STAT_STUNNED) && (u != this))
8991 return false;
8993 // Creature can detect target only in aggro radius
8994 if(u->GetTypeId() != TYPEID_PLAYER)
8996 //Always invisible from back and out of aggro range
8997 bool isInFront = u->isInFront(this,((Creature const*)u)->GetAttackDistance(this));
8998 if(!isInFront)
8999 return false;
9001 else
9003 //Always invisible from back
9004 bool isInFront = u->isInFront(this,(GetTypeId()==TYPEID_PLAYER || GetCharmerOrOwnerGUID()) ? World::GetMaxVisibleDistanceForPlayer() : World::GetMaxVisibleDistanceForCreature());
9005 if(!isInFront)
9006 return false;
9009 // if doesn't have stealth detection (Shadow Sight), then check how stealthy the unit is, otherwise just check los
9010 if(!u->HasAuraType(SPELL_AURA_DETECT_STEALTH))
9012 //Calculation if target is in front
9014 //Visible distance based on stealth value (stealth rank 4 300MOD, 10.5 - 3 = 7.5)
9015 float visibleDistance = 10.5f - (GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH)/100.0f);
9017 //Visible distance is modified by
9018 //-Level Diff (every level diff = 1.0f in visible distance)
9019 visibleDistance += int32(u->getLevelForTarget(this)) - int32(getLevelForTarget(u));
9021 //This allows to check talent tree and will add addition stealth dependent on used points)
9022 int32 stealthMod = GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_LEVEL);
9023 if(stealthMod < 0)
9024 stealthMod = 0;
9026 //-Stealth Mod(positive like Master of Deception) and Stealth Detection(negative like paranoia)
9027 //based on wowwiki every 5 mod we have 1 more level diff in calculation
9028 visibleDistance += (int32(u->GetTotalAuraModifier(SPELL_AURA_MOD_DETECT)) - stealthMod)/5.0f;
9030 if(distance > visibleDistance)
9031 return false;
9034 // Now check is target visible with LoS
9035 float ox,oy,oz;
9036 u->GetPosition(ox,oy,oz);
9037 return IsWithinLOS(ox,oy,oz);
9040 void Unit::SetVisibility(UnitVisibility x)
9042 m_Visibility = x;
9044 if(IsInWorld())
9046 Map *m = GetMap();
9048 if(GetTypeId()==TYPEID_PLAYER)
9049 m->PlayerRelocation((Player*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
9050 else
9051 m->CreatureRelocation((Creature*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
9055 bool Unit::canDetectInvisibilityOf(Unit const* u) const
9057 if(uint32 mask = (m_detectInvisibilityMask & u->m_invisibilityMask))
9059 for(uint32 i = 0; i < 10; ++i)
9061 if(((1 << i) & mask)==0)
9062 continue;
9064 // find invisibility level
9065 uint32 invLevel = 0;
9066 Unit::AuraList const& iAuras = u->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY);
9067 for(Unit::AuraList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr)
9068 if(((*itr)->GetModifier()->m_miscvalue)==i && invLevel < (*itr)->GetModifier()->m_amount)
9069 invLevel = (*itr)->GetModifier()->m_amount;
9071 // find invisibility detect level
9072 uint32 detectLevel = 0;
9073 Unit::AuraList const& dAuras = GetAurasByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION);
9074 for(Unit::AuraList::const_iterator itr = dAuras.begin(); itr != dAuras.end(); ++itr)
9075 if(((*itr)->GetModifier()->m_miscvalue)==i && detectLevel < (*itr)->GetModifier()->m_amount)
9076 detectLevel = (*itr)->GetModifier()->m_amount;
9078 if(i==6 && GetTypeId()==TYPEID_PLAYER) // special drunk detection case
9080 detectLevel = ((Player*)this)->GetDrunkValue();
9083 if(invLevel <= detectLevel)
9084 return true;
9088 return false;
9091 void Unit::UpdateSpeed(UnitMoveType mtype, bool forced)
9093 int32 main_speed_mod = 0;
9094 float stack_bonus = 1.0f;
9095 float non_stack_bonus = 1.0f;
9097 switch(mtype)
9099 case MOVE_WALK:
9100 return;
9101 case MOVE_RUN:
9103 if (IsMounted()) // Use on mount auras
9105 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED);
9106 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS);
9107 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK))/100.0f;
9109 else
9111 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED);
9112 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS);
9113 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK))/100.0f;
9115 break;
9117 case MOVE_RUN_BACK:
9118 return;
9119 case MOVE_SWIM:
9121 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SWIM_SPEED);
9122 break;
9124 case MOVE_SWIM_BACK:
9125 return;
9126 case MOVE_FLIGHT:
9128 if (IsMounted()) // Use on mount auras
9129 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
9130 else // Use not mount (shapeshift for example) auras (should stack)
9131 main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_SPEED_FLIGHT);
9132 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_FLIGHT_SPEED_ALWAYS);
9133 non_stack_bonus = (100.0 + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK))/100.0f;
9134 break;
9136 case MOVE_FLIGHT_BACK:
9137 return;
9138 default:
9139 sLog.outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype);
9140 return;
9143 float bonus = non_stack_bonus > stack_bonus ? non_stack_bonus : stack_bonus;
9144 // now we ready for speed calculation
9145 float speed = main_speed_mod ? bonus*(100.0f + main_speed_mod)/100.0f : bonus;
9147 switch(mtype)
9149 case MOVE_RUN:
9150 case MOVE_SWIM:
9151 case MOVE_FLIGHT:
9153 // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need
9154 // TODO: possible affect only on MOVE_RUN
9155 if(int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED))
9157 // Use speed from aura
9158 float max_speed = normalization / baseMoveSpeed[mtype];
9159 if (speed > max_speed)
9160 speed = max_speed;
9162 break;
9164 default:
9165 break;
9168 // Apply strongest slow aura mod to speed
9169 int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED);
9170 if (slow)
9171 speed *=(100.0f + slow)/100.0f;
9172 SetSpeed(mtype, speed, forced);
9175 float Unit::GetSpeed( UnitMoveType mtype ) const
9177 return m_speed_rate[mtype]*baseMoveSpeed[mtype];
9180 void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced)
9182 if (rate < 0)
9183 rate = 0.0f;
9185 // Update speed only on change
9186 if (m_speed_rate[mtype] == rate)
9187 return;
9189 m_speed_rate[mtype] = rate;
9191 propagateSpeedChange();
9193 WorldPacket data;
9194 if(!forced)
9196 switch(mtype)
9198 case MOVE_WALK:
9199 data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9200 break;
9201 case MOVE_RUN:
9202 data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8+4+2+4+4+4+4+4+4+4);
9203 break;
9204 case MOVE_RUN_BACK:
9205 data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9206 break;
9207 case MOVE_SWIM:
9208 data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8+4+2+4+4+4+4+4+4+4);
9209 break;
9210 case MOVE_SWIM_BACK:
9211 data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9212 break;
9213 case MOVE_TURN_RATE:
9214 data.Initialize(MSG_MOVE_SET_TURN_RATE, 8+4+2+4+4+4+4+4+4+4);
9215 break;
9216 case MOVE_FLIGHT:
9217 data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8+4+2+4+4+4+4+4+4+4);
9218 break;
9219 case MOVE_FLIGHT_BACK:
9220 data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9221 break;
9222 case MOVE_PITCH_RATE:
9223 data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8+4+2+4+4+4+4+4+4+4);
9224 break;
9225 default:
9226 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
9227 return;
9230 data.append(GetPackGUID());
9231 data << uint32(0); // movement flags
9232 data << uint16(0); // unk flags
9233 data << uint32(getMSTime());
9234 data << float(GetPositionX());
9235 data << float(GetPositionY());
9236 data << float(GetPositionZ());
9237 data << float(GetOrientation());
9238 data << uint32(0); // fall time
9239 data << float(GetSpeed(mtype));
9240 SendMessageToSet( &data, true );
9242 else
9244 if(GetTypeId() == TYPEID_PLAYER)
9246 // register forced speed changes for WorldSession::HandleForceSpeedChangeAck
9247 // and do it only for real sent packets and use run for run/mounted as client expected
9248 ++((Player*)this)->m_forced_speed_changes[mtype];
9251 switch(mtype)
9253 case MOVE_WALK:
9254 data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE, 16);
9255 break;
9256 case MOVE_RUN:
9257 data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE, 17);
9258 break;
9259 case MOVE_RUN_BACK:
9260 data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE, 16);
9261 break;
9262 case MOVE_SWIM:
9263 data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE, 16);
9264 break;
9265 case MOVE_SWIM_BACK:
9266 data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, 16);
9267 break;
9268 case MOVE_TURN_RATE:
9269 data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE, 16);
9270 break;
9271 case MOVE_FLIGHT:
9272 data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE, 16);
9273 break;
9274 case MOVE_FLIGHT_BACK:
9275 data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, 16);
9276 break;
9277 case MOVE_PITCH_RATE:
9278 data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE, 16);
9279 break;
9280 default:
9281 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
9282 return;
9284 data.append(GetPackGUID());
9285 data << (uint32)0; // moveEvent, NUM_PMOVE_EVTS = 0x39
9286 if (mtype == MOVE_RUN)
9287 data << uint8(0); // new 2.1.0
9288 data << float(GetSpeed(mtype));
9289 SendMessageToSet( &data, true );
9291 if(Pet* pet = GetPet())
9292 pet->SetSpeed(MOVE_RUN, m_speed_rate[mtype],forced);
9295 void Unit::SetHover(bool on)
9297 if(on)
9298 CastSpell(this,11010,true);
9299 else
9300 RemoveAurasDueToSpell(11010);
9303 void Unit::setDeathState(DeathState s)
9305 if (s != ALIVE && s!= JUST_ALIVED)
9307 CombatStop();
9308 DeleteThreatList();
9309 ClearComboPointHolders(); // any combo points pointed to unit lost at it death
9311 if(IsNonMeleeSpellCasted(false))
9312 InterruptNonMeleeSpells(false);
9315 if (s == JUST_DIED)
9317 RemoveAllAurasOnDeath();
9318 UnsummonAllTotems();
9320 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false);
9321 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, false);
9322 // remove aurastates allowing special moves
9323 ClearAllReactives();
9324 ClearDiminishings();
9326 else if(s == JUST_ALIVED)
9328 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground)
9331 if (m_deathState != ALIVE && s == ALIVE)
9333 //_ApplyAllAuraMods();
9335 m_deathState = s;
9338 /*########################################
9339 ######## ########
9340 ######## AGGRO SYSTEM ########
9341 ######## ########
9342 ########################################*/
9343 bool Unit::CanHaveThreatList() const
9345 // only creatures can have threat list
9346 if( GetTypeId() != TYPEID_UNIT )
9347 return false;
9349 // only alive units can have threat list
9350 if( !isAlive() )
9351 return false;
9353 // totems can not have threat list
9354 if( ((Creature*)this)->isTotem() )
9355 return false;
9357 // vehicles can not have threat list
9358 if( ((Creature*)this)->isVehicle() )
9359 return false;
9361 // pets can not have a threat list, unless they are controlled by a creature
9362 if( ((Creature*)this)->isPet() && IS_PLAYER_GUID(((Pet*)this)->GetOwnerGUID()) )
9363 return false;
9365 return true;
9368 //======================================================================
9370 float Unit::ApplyTotalThreatModifier(float threat, SpellSchoolMask schoolMask)
9372 if(!HasAuraType(SPELL_AURA_MOD_THREAT))
9373 return threat;
9375 SpellSchools school = GetFirstSchoolInMask(schoolMask);
9377 return threat * m_threatModifier[school];
9380 //======================================================================
9382 void Unit::AddThreat(Unit* pVictim, float threat, SpellSchoolMask schoolMask, SpellEntry const *threatSpell)
9384 // Only mobs can manage threat lists
9385 if(CanHaveThreatList())
9386 m_ThreatManager.addThreat(pVictim, threat, schoolMask, threatSpell);
9389 //======================================================================
9391 void Unit::DeleteThreatList()
9393 m_ThreatManager.clearReferences();
9396 //======================================================================
9398 void Unit::TauntApply(Unit* taunter)
9400 assert(GetTypeId()== TYPEID_UNIT);
9402 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
9403 return;
9405 if(!CanHaveThreatList())
9406 return;
9408 Unit *target = getVictim();
9409 if(target && target == taunter)
9410 return;
9412 SetInFront(taunter);
9413 if (((Creature*)this)->AI())
9414 ((Creature*)this)->AI()->AttackStart(taunter);
9416 m_ThreatManager.tauntApply(taunter);
9419 //======================================================================
9421 void Unit::TauntFadeOut(Unit *taunter)
9423 assert(GetTypeId()== TYPEID_UNIT);
9425 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
9426 return;
9428 if(!CanHaveThreatList())
9429 return;
9431 Unit *target = getVictim();
9432 if(!target || target != taunter)
9433 return;
9435 if(m_ThreatManager.isThreatListEmpty())
9437 if(((Creature*)this)->AI())
9438 ((Creature*)this)->AI()->EnterEvadeMode();
9439 return;
9442 m_ThreatManager.tauntFadeOut(taunter);
9443 target = m_ThreatManager.getHostilTarget();
9445 if (target && target != taunter)
9447 SetInFront(target);
9448 if (((Creature*)this)->AI())
9449 ((Creature*)this)->AI()->AttackStart(target);
9453 //======================================================================
9455 bool Unit::SelectHostilTarget()
9457 //function provides main threat functionality
9458 //next-victim-selection algorithm and evade mode are called
9459 //threat list sorting etc.
9461 assert(GetTypeId()== TYPEID_UNIT);
9463 if (!this->isAlive())
9464 return false;
9465 //This function only useful once AI has been initialized
9466 if (!((Creature*)this)->AI())
9467 return false;
9469 Unit* target = NULL;
9471 // First checking if we have some taunt on us
9472 const AuraList& tauntAuras = GetAurasByType(SPELL_AURA_MOD_TAUNT);
9473 if ( !tauntAuras.empty() )
9475 Unit* caster;
9477 // The last taunt aura caster is alive an we are happy to attack him
9478 if ( (caster = tauntAuras.back()->GetCaster()) && caster->isAlive() )
9479 return true;
9480 else if (tauntAuras.size() > 1)
9482 // We do not have last taunt aura caster but we have more taunt auras,
9483 // so find first available target
9485 // Auras are pushed_back, last caster will be on the end
9486 AuraList::const_iterator aura = --tauntAuras.end();
9489 --aura;
9490 if ( (caster = (*aura)->GetCaster()) &&
9491 caster->IsInMap(this) && caster->isTargetableForAttack() && caster->isInAccessablePlaceFor((Creature*)this) )
9493 target = caster;
9494 break;
9496 }while (aura != tauntAuras.begin());
9500 if ( !target && !m_ThreatManager.isThreatListEmpty() )
9501 // No taunt aura or taunt aura caster is dead standart target selection
9502 target = m_ThreatManager.getHostilTarget();
9504 if(target)
9506 if(!hasUnitState(UNIT_STAT_STUNNED))
9507 SetInFront(target);
9508 ((Creature*)this)->AI()->AttackStart(target);
9509 return true;
9512 // no target but something prevent go to evade mode
9513 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_TAUNT) )
9514 return false;
9516 // last case when creature don't must go to evade mode:
9517 // it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list
9518 // for example at owner command to pet attack some far away creature
9519 // Note: creature not have targeted movement generator but have attacker in this case
9520 if( GetMotionMaster()->GetCurrentMovementGeneratorType() != TARGETED_MOTION_TYPE )
9522 for(AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr)
9524 if( (*itr)->IsInMap(this) && (*itr)->isTargetableForAttack() && (*itr)->isInAccessablePlaceFor((Creature*)this) )
9525 return false;
9529 // enter in evade mode in other case
9530 ((Creature*)this)->AI()->EnterEvadeMode();
9532 return false;
9535 //======================================================================
9536 //======================================================================
9537 //======================================================================
9539 int32 Unit::CalculateSpellDamage(SpellEntry const* spellProto, uint8 effect_index, int32 effBasePoints, Unit const* target)
9541 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
9543 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
9545 int32 level = int32(getLevel());
9546 if (level > (int32)spellProto->maxLevel && spellProto->maxLevel > 0)
9547 level = (int32)spellProto->maxLevel;
9548 else if (level < (int32)spellProto->baseLevel)
9549 level = (int32)spellProto->baseLevel;
9550 level-= (int32)spellProto->spellLevel;
9552 float basePointsPerLevel = spellProto->EffectRealPointsPerLevel[effect_index];
9553 float randomPointsPerLevel = spellProto->EffectDicePerLevel[effect_index];
9554 int32 basePoints = int32(effBasePoints + level * basePointsPerLevel);
9555 int32 randomPoints = int32(spellProto->EffectDieSides[effect_index] + level * randomPointsPerLevel);
9556 float comboDamage = spellProto->EffectPointsPerComboPoint[effect_index];
9558 // range can have possitive and negative values, so order its for irand
9559 int32 randvalue = int32(spellProto->EffectBaseDice[effect_index]) >= randomPoints
9560 ? irand(randomPoints, int32(spellProto->EffectBaseDice[effect_index]))
9561 : irand(int32(spellProto->EffectBaseDice[effect_index]), randomPoints);
9563 int32 value = basePoints + randvalue;
9564 //random damage
9565 if(comboDamage != 0 && unitPlayer && target && (target->GetGUID() == unitPlayer->GetComboTarget()))
9566 value += (int32)(comboDamage * comboPoints);
9568 if(Player* modOwner = GetSpellModOwner())
9570 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_ALL_EFFECTS, value);
9571 switch(effect_index)
9573 case 0:
9574 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT1, value);
9575 break;
9576 case 1:
9577 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT2, value);
9578 break;
9579 case 2:
9580 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT3, value);
9581 break;
9585 if(spellProto->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION && spellProto->spellLevel &&
9586 spellProto->Effect[effect_index] != SPELL_EFFECT_WEAPON_PERCENT_DAMAGE &&
9587 spellProto->Effect[effect_index] != SPELL_EFFECT_KNOCK_BACK)
9588 value = int32(value*0.25f*exp(getLevel()*(70-spellProto->spellLevel)/1000.0f));
9590 return value;
9593 int32 Unit::CalculateSpellDuration(SpellEntry const* spellProto, uint8 effect_index, Unit const* target)
9595 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
9597 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
9599 int32 minduration = GetSpellDuration(spellProto);
9600 int32 maxduration = GetSpellMaxDuration(spellProto);
9602 int32 duration;
9604 if( minduration != -1 && minduration != maxduration )
9605 duration = minduration + int32((maxduration - minduration) * comboPoints / 5);
9606 else
9607 duration = minduration;
9609 if (duration > 0)
9611 int32 mechanic = GetEffectMechanic(spellProto, effect_index);
9612 // Find total mod value (negative bonus)
9613 int32 durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD, mechanic);
9614 // Modify from SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL aura (stack always ?)
9615 durationMod_always+=target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL, spellProto->Dispel);
9616 // Find max mod (negative bonus)
9617 int32 durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK, mechanic);
9619 int32 durationMod = 0;
9620 // Select strongest negative mod
9621 if (durationMod_always > durationMod_not_stack)
9622 durationMod = durationMod_not_stack;
9623 else
9624 durationMod = durationMod_always;
9626 if (durationMod != 0)
9627 duration = int32(int64(duration) * (100+durationMod) /100);
9629 if (duration < 0) duration = 0;
9632 return duration;
9635 DiminishingLevels Unit::GetDiminishing(DiminishingGroup group)
9637 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9639 if(i->DRGroup != group)
9640 continue;
9642 if(!i->hitCount)
9643 return DIMINISHING_LEVEL_1;
9645 if(!i->hitTime)
9646 return DIMINISHING_LEVEL_1;
9648 // If last spell was casted more than 15 seconds ago - reset the count.
9649 if(i->stack==0 && getMSTimeDiff(i->hitTime,getMSTime()) > 15000)
9651 i->hitCount = DIMINISHING_LEVEL_1;
9652 return DIMINISHING_LEVEL_1;
9654 // or else increase the count.
9655 else
9657 return DiminishingLevels(i->hitCount);
9660 return DIMINISHING_LEVEL_1;
9663 void Unit::IncrDiminishing(DiminishingGroup group)
9665 // Checking for existing in the table
9666 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9668 if(i->DRGroup != group)
9669 continue;
9670 if(i->hitCount < DIMINISHING_LEVEL_IMMUNE)
9671 i->hitCount += 1;
9672 return;
9674 m_Diminishing.push_back(DiminishingReturn(group,getMSTime(),DIMINISHING_LEVEL_2));
9677 void Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration,Unit* caster,DiminishingLevels Level)
9679 if(duration == -1 || group == DIMINISHING_NONE || caster->IsFriendlyTo(this) )
9680 return;
9682 // Duration of crowd control abilities on pvp target is limited by 10 sec. (2.2.0)
9683 if(duration > 10000 && IsDiminishingReturnsGroupDurationLimited(group))
9685 // test pet/charm masters instead pets/charmeds
9686 Unit const* targetOwner = GetCharmerOrOwner();
9687 Unit const* casterOwner = caster->GetCharmerOrOwner();
9689 Unit const* target = targetOwner ? targetOwner : this;
9690 Unit const* source = casterOwner ? casterOwner : caster;
9692 if(target->GetTypeId() == TYPEID_PLAYER && source->GetTypeId() == TYPEID_PLAYER)
9693 duration = 10000;
9696 float mod = 1.0f;
9698 // Some diminishings applies to mobs too (for example, Stun)
9699 if((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER && GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL)
9701 DiminishingLevels diminish = Level;
9702 switch(diminish)
9704 case DIMINISHING_LEVEL_1: break;
9705 case DIMINISHING_LEVEL_2: mod = 0.5f; break;
9706 case DIMINISHING_LEVEL_3: mod = 0.25f; break;
9707 case DIMINISHING_LEVEL_IMMUNE: mod = 0.0f;break;
9708 default: break;
9712 duration = int32(duration * mod);
9715 void Unit::ApplyDiminishingAura( DiminishingGroup group, bool apply )
9717 // Checking for existing in the table
9718 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9720 if(i->DRGroup != group)
9721 continue;
9723 if(apply)
9724 i->stack += 1;
9725 else if(i->stack)
9727 i->stack -= 1;
9728 // Remember time after last aura from group removed
9729 if (i->stack == 0)
9730 i->hitTime = getMSTime();
9732 break;
9736 Unit* Unit::GetUnit(WorldObject& object, uint64 guid)
9738 return ObjectAccessor::GetUnit(object,guid);
9741 bool Unit::isVisibleForInState( Player const* u, bool inVisibleList ) const
9743 return isVisibleForOrDetect(u, false, inVisibleList, false);
9746 uint32 Unit::GetCreatureType() const
9748 if(GetTypeId() == TYPEID_PLAYER)
9750 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
9751 if(ssEntry && ssEntry->creatureType > 0)
9752 return ssEntry->creatureType;
9753 else
9754 return CREATURE_TYPE_HUMANOID;
9756 else
9757 return ((Creature*)this)->GetCreatureInfo()->type;
9760 /*#######################################
9761 ######## ########
9762 ######## STAT SYSTEM ########
9763 ######## ########
9764 #######################################*/
9766 bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply)
9768 if(unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
9770 sLog.outError("ERROR in HandleStatModifier(): non existed UnitMods or wrong UnitModifierType!");
9771 return false;
9774 float val = 1.0f;
9776 switch(modifierType)
9778 case BASE_VALUE:
9779 case TOTAL_VALUE:
9780 m_auraModifiersGroup[unitMod][modifierType] += apply ? amount : -amount;
9781 break;
9782 case BASE_PCT:
9783 case TOTAL_PCT:
9784 if(amount <= -100.0f) //small hack-fix for -100% modifiers
9785 amount = -200.0f;
9787 val = (100.0f + amount) / 100.0f;
9788 m_auraModifiersGroup[unitMod][modifierType] *= apply ? val : (1.0f/val);
9789 break;
9791 default:
9792 break;
9795 if(!CanModifyStats())
9796 return false;
9798 switch(unitMod)
9800 case UNIT_MOD_STAT_STRENGTH:
9801 case UNIT_MOD_STAT_AGILITY:
9802 case UNIT_MOD_STAT_STAMINA:
9803 case UNIT_MOD_STAT_INTELLECT:
9804 case UNIT_MOD_STAT_SPIRIT: UpdateStats(GetStatByAuraGroup(unitMod)); break;
9806 case UNIT_MOD_ARMOR: UpdateArmor(); break;
9807 case UNIT_MOD_HEALTH: UpdateMaxHealth(); break;
9809 case UNIT_MOD_MANA:
9810 case UNIT_MOD_RAGE:
9811 case UNIT_MOD_FOCUS:
9812 case UNIT_MOD_ENERGY:
9813 case UNIT_MOD_HAPPINESS:
9814 case UNIT_MOD_RUNE:
9815 case UNIT_MOD_RUNIC_POWER: UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); break;
9817 case UNIT_MOD_RESISTANCE_HOLY:
9818 case UNIT_MOD_RESISTANCE_FIRE:
9819 case UNIT_MOD_RESISTANCE_NATURE:
9820 case UNIT_MOD_RESISTANCE_FROST:
9821 case UNIT_MOD_RESISTANCE_SHADOW:
9822 case UNIT_MOD_RESISTANCE_ARCANE: UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); break;
9824 case UNIT_MOD_ATTACK_POWER: UpdateAttackPowerAndDamage(); break;
9825 case UNIT_MOD_ATTACK_POWER_RANGED: UpdateAttackPowerAndDamage(true); break;
9827 case UNIT_MOD_DAMAGE_MAINHAND: UpdateDamagePhysical(BASE_ATTACK); break;
9828 case UNIT_MOD_DAMAGE_OFFHAND: UpdateDamagePhysical(OFF_ATTACK); break;
9829 case UNIT_MOD_DAMAGE_RANGED: UpdateDamagePhysical(RANGED_ATTACK); break;
9831 default:
9832 break;
9835 return true;
9838 float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const
9840 if( unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
9842 sLog.outError("trial to access non existed modifier value from UnitMods!");
9843 return 0.0f;
9846 if(modifierType == TOTAL_PCT && m_auraModifiersGroup[unitMod][modifierType] <= 0.0f)
9847 return 0.0f;
9849 return m_auraModifiersGroup[unitMod][modifierType];
9852 float Unit::GetTotalStatValue(Stats stat) const
9854 UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat);
9856 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
9857 return 0.0f;
9859 // value = ((base_value * base_pct) + total_value) * total_pct
9860 float value = m_auraModifiersGroup[unitMod][BASE_VALUE] + GetCreateStat(stat);
9861 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
9862 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
9863 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
9865 return value;
9868 float Unit::GetTotalAuraModValue(UnitMods unitMod) const
9870 if(unitMod >= UNIT_MOD_END)
9872 sLog.outError("trial to access non existed UnitMods in GetTotalAuraModValue()!");
9873 return 0.0f;
9876 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
9877 return 0.0f;
9879 float value = m_auraModifiersGroup[unitMod][BASE_VALUE];
9880 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
9881 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
9882 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
9884 return value;
9887 SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const
9889 SpellSchools school = SPELL_SCHOOL_NORMAL;
9891 switch(unitMod)
9893 case UNIT_MOD_RESISTANCE_HOLY: school = SPELL_SCHOOL_HOLY; break;
9894 case UNIT_MOD_RESISTANCE_FIRE: school = SPELL_SCHOOL_FIRE; break;
9895 case UNIT_MOD_RESISTANCE_NATURE: school = SPELL_SCHOOL_NATURE; break;
9896 case UNIT_MOD_RESISTANCE_FROST: school = SPELL_SCHOOL_FROST; break;
9897 case UNIT_MOD_RESISTANCE_SHADOW: school = SPELL_SCHOOL_SHADOW; break;
9898 case UNIT_MOD_RESISTANCE_ARCANE: school = SPELL_SCHOOL_ARCANE; break;
9900 default:
9901 break;
9904 return school;
9907 Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const
9909 Stats stat = STAT_STRENGTH;
9911 switch(unitMod)
9913 case UNIT_MOD_STAT_STRENGTH: stat = STAT_STRENGTH; break;
9914 case UNIT_MOD_STAT_AGILITY: stat = STAT_AGILITY; break;
9915 case UNIT_MOD_STAT_STAMINA: stat = STAT_STAMINA; break;
9916 case UNIT_MOD_STAT_INTELLECT: stat = STAT_INTELLECT; break;
9917 case UNIT_MOD_STAT_SPIRIT: stat = STAT_SPIRIT; break;
9919 default:
9920 break;
9923 return stat;
9926 Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const
9928 switch(unitMod)
9930 case UNIT_MOD_MANA: return POWER_MANA;
9931 case UNIT_MOD_RAGE: return POWER_RAGE;
9932 case UNIT_MOD_FOCUS: return POWER_FOCUS;
9933 case UNIT_MOD_ENERGY: return POWER_ENERGY;
9934 case UNIT_MOD_HAPPINESS: return POWER_HAPPINESS;
9935 case UNIT_MOD_RUNE: return POWER_RUNE;
9936 case UNIT_MOD_RUNIC_POWER:return POWER_RUNIC_POWER;
9939 return POWER_MANA;
9942 float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const
9944 if (attType == RANGED_ATTACK)
9946 int32 ap = GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS);
9947 if (ap < 0)
9948 return 0.0f;
9949 return ap * (1.0f + GetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER));
9951 else
9953 int32 ap = GetInt32Value(UNIT_FIELD_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS);
9954 if (ap < 0)
9955 return 0.0f;
9956 return ap * (1.0f + GetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER));
9960 float Unit::GetWeaponDamageRange(WeaponAttackType attType ,WeaponDamageRange type) const
9962 if (attType == OFF_ATTACK && !haveOffhandWeapon())
9963 return 0.0f;
9965 return m_weaponDamage[attType][type];
9968 void Unit::SetLevel(uint32 lvl)
9970 SetUInt32Value(UNIT_FIELD_LEVEL, lvl);
9972 // group update
9973 if ((GetTypeId() == TYPEID_PLAYER) && ((Player*)this)->GetGroup())
9974 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL);
9977 void Unit::SetHealth(uint32 val)
9979 uint32 maxHealth = GetMaxHealth();
9980 if(maxHealth < val)
9981 val = maxHealth;
9983 SetUInt32Value(UNIT_FIELD_HEALTH, val);
9985 // group update
9986 if(GetTypeId() == TYPEID_PLAYER)
9988 if(((Player*)this)->GetGroup())
9989 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP);
9991 else if(((Creature*)this)->isPet())
9993 Pet *pet = ((Pet*)this);
9994 if(pet->isControlled())
9996 Unit *owner = GetOwner();
9997 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
9998 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP);
10003 void Unit::SetMaxHealth(uint32 val)
10005 uint32 health = GetHealth();
10006 SetUInt32Value(UNIT_FIELD_MAXHEALTH, val);
10008 // group update
10009 if(GetTypeId() == TYPEID_PLAYER)
10011 if(((Player*)this)->GetGroup())
10012 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP);
10014 else if(((Creature*)this)->isPet())
10016 Pet *pet = ((Pet*)this);
10017 if(pet->isControlled())
10019 Unit *owner = GetOwner();
10020 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10021 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP);
10025 if(val < health)
10026 SetHealth(val);
10029 void Unit::SetPower(Powers power, uint32 val)
10031 if(GetPower(power) == val)
10032 return;
10034 uint32 maxPower = GetMaxPower(power);
10035 if(maxPower < val)
10036 val = maxPower;
10038 SetStatInt32Value(UNIT_FIELD_POWER1 + power, val);
10040 WorldPacket data(SMSG_POWER_UPDATE);
10041 data.append(GetPackGUID());
10042 data << uint8(power);
10043 data << uint32(val);
10044 SendMessageToSet(&data, GetTypeId() == TYPEID_PLAYER ? true : false);
10046 // group update
10047 if(GetTypeId() == TYPEID_PLAYER)
10049 if(((Player*)this)->GetGroup())
10050 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
10052 else if(((Creature*)this)->isPet())
10054 Pet *pet = ((Pet*)this);
10055 if(pet->isControlled())
10057 Unit *owner = GetOwner();
10058 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10059 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
10062 // Update the pet's character sheet with happiness damage bonus
10063 if(pet->getPetType() == HUNTER_PET && power == POWER_HAPPINESS)
10065 pet->UpdateDamagePhysical(BASE_ATTACK);
10070 void Unit::SetMaxPower(Powers power, uint32 val)
10072 uint32 cur_power = GetPower(power);
10073 SetStatInt32Value(UNIT_FIELD_MAXPOWER1 + power, val);
10075 // group update
10076 if(GetTypeId() == TYPEID_PLAYER)
10078 if(((Player*)this)->GetGroup())
10079 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
10081 else if(((Creature*)this)->isPet())
10083 Pet *pet = ((Pet*)this);
10084 if(pet->isControlled())
10086 Unit *owner = GetOwner();
10087 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10088 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
10092 if(val < cur_power)
10093 SetPower(power, val);
10096 void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply)
10098 ApplyModUInt32Value(UNIT_FIELD_POWER1+power, val, apply);
10100 // group update
10101 if(GetTypeId() == TYPEID_PLAYER)
10103 if(((Player*)this)->GetGroup())
10104 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
10106 else if(((Creature*)this)->isPet())
10108 Pet *pet = ((Pet*)this);
10109 if(pet->isControlled())
10111 Unit *owner = GetOwner();
10112 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10113 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
10118 void Unit::ApplyMaxPowerMod(Powers power, uint32 val, bool apply)
10120 ApplyModUInt32Value(UNIT_FIELD_MAXPOWER1+power, val, apply);
10122 // group update
10123 if(GetTypeId() == TYPEID_PLAYER)
10125 if(((Player*)this)->GetGroup())
10126 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
10128 else if(((Creature*)this)->isPet())
10130 Pet *pet = ((Pet*)this);
10131 if(pet->isControlled())
10133 Unit *owner = GetOwner();
10134 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10135 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
10140 void Unit::ApplyAuraProcTriggerDamage( Aura* aura, bool apply )
10142 AuraList& tAuraProcTriggerDamage = m_modAuras[SPELL_AURA_PROC_TRIGGER_DAMAGE];
10143 if(apply)
10144 tAuraProcTriggerDamage.push_back(aura);
10145 else
10146 tAuraProcTriggerDamage.remove(aura);
10149 uint32 Unit::GetCreatePowers( Powers power ) const
10151 // POWER_FOCUS and POWER_HAPPINESS only have hunter pet
10152 switch(power)
10154 case POWER_MANA: return GetCreateMana();
10155 case POWER_RAGE: return 1000;
10156 case POWER_FOCUS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 100);
10157 case POWER_ENERGY: return 100;
10158 case POWER_HAPPINESS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 1050000);
10159 case POWER_RUNIC_POWER: return 1000;
10162 return 0;
10165 void Unit::AddToWorld()
10167 Object::AddToWorld();
10170 void Unit::RemoveFromWorld()
10172 // cleanup
10173 if(IsInWorld())
10175 RemoveNotOwnSingleTargetAuras();
10178 Object::RemoveFromWorld();
10181 void Unit::CleanupsBeforeDelete()
10183 if(m_uint32Values) // only for fully created object
10185 InterruptNonMeleeSpells(true);
10186 m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList
10187 CombatStop();
10188 ClearComboPointHolders();
10189 DeleteThreatList();
10190 getHostilRefManager().setOnlineOfflineState(false);
10191 RemoveAllAuras();
10192 RemoveAllGameObjects();
10193 RemoveAllDynObjects();
10194 GetMotionMaster()->Clear(false); // remove different non-standard movement generators.
10196 RemoveFromWorld();
10199 CharmInfo* Unit::InitCharmInfo(Unit *charm)
10201 if(!m_charmInfo)
10202 m_charmInfo = new CharmInfo(charm);
10203 return m_charmInfo;
10206 CharmInfo::CharmInfo(Unit* unit)
10207 : m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_reactState(REACT_PASSIVE), m_petnumber(0)
10209 for(int i =0; i<4; ++i)
10211 m_charmspells[i].spellId = 0;
10212 m_charmspells[i].active = ACT_DISABLED;
10216 void CharmInfo::InitPetActionBar()
10218 // the first 3 SpellOrActions are attack, follow and stay
10219 for(uint32 i = 0; i < 3; i++)
10221 PetActionBar[i].Type = ACT_COMMAND;
10222 PetActionBar[i].SpellOrAction = COMMAND_ATTACK - i;
10224 PetActionBar[i + 7].Type = ACT_REACTION;
10225 PetActionBar[i + 7].SpellOrAction = COMMAND_ATTACK - i;
10227 for(uint32 i=0; i < 4; i++)
10229 PetActionBar[i + 3].Type = ACT_DISABLED;
10230 PetActionBar[i + 3].SpellOrAction = 0;
10234 void CharmInfo::InitEmptyActionBar()
10236 for(uint32 x = 1; x < 10; ++x)
10238 PetActionBar[x].Type = ACT_PASSIVE;
10239 PetActionBar[x].SpellOrAction = 0;
10241 PetActionBar[0].Type = ACT_COMMAND;
10242 PetActionBar[0].SpellOrAction = COMMAND_ATTACK;
10245 void CharmInfo::InitPossessCreateSpells()
10247 InitEmptyActionBar(); //charm action bar
10249 if(m_unit->GetTypeId() == TYPEID_PLAYER) //possessed players don't have spells, keep the action bar empty
10250 return;
10252 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10254 if (IsPassiveSpell(((Creature*)m_unit)->m_spells[x]))
10255 m_unit->CastSpell(m_unit, ((Creature*)m_unit)->m_spells[x], true);
10256 else
10257 AddSpellToAB(0, ((Creature*)m_unit)->m_spells[x], ACT_PASSIVE);
10261 void CharmInfo::InitCharmCreateSpells()
10263 if(m_unit->GetTypeId() == TYPEID_PLAYER) //charmed players don't have spells
10265 InitEmptyActionBar();
10266 return;
10269 InitPetActionBar();
10271 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10273 uint32 spellId = ((Creature*)m_unit)->m_spells[x];
10274 m_charmspells[x].spellId = spellId;
10276 if(!spellId)
10277 continue;
10279 if (IsPassiveSpell(spellId))
10281 m_unit->CastSpell(m_unit, spellId, true);
10282 m_charmspells[x].active = ACT_PASSIVE;
10284 else
10286 ActiveStates newstate;
10287 bool onlyselfcast = true;
10288 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
10290 if(!spellInfo) onlyselfcast = false;
10291 for(uint32 i = 0;i<3 && onlyselfcast;++i) //non existent spell will not make any problems as onlyselfcast would be false -> break right away
10293 if(spellInfo->EffectImplicitTargetA[i] != TARGET_SELF && spellInfo->EffectImplicitTargetA[i] != 0)
10294 onlyselfcast = false;
10297 if(onlyselfcast || !IsPositiveSpell(spellId)) //only self cast and spells versus enemies are autocastable
10298 newstate = ACT_DISABLED;
10299 else
10300 newstate = ACT_PASSIVE;
10302 AddSpellToAB(0, spellId, newstate);
10307 bool CharmInfo::AddSpellToAB(uint32 oldid, uint32 newid, ActiveStates newstate)
10309 for(uint8 i = 0; i < 10; i++)
10311 if((PetActionBar[i].Type == ACT_DISABLED || PetActionBar[i].Type == ACT_ENABLED || PetActionBar[i].Type == ACT_PASSIVE) && PetActionBar[i].SpellOrAction == oldid)
10313 PetActionBar[i].SpellOrAction = newid;
10314 if(!oldid)
10316 if(newstate == ACT_DECIDE)
10317 PetActionBar[i].Type = ACT_DISABLED;
10318 else
10319 PetActionBar[i].Type = newstate;
10322 return true;
10325 return false;
10328 void CharmInfo::ToggleCreatureAutocast(uint32 spellid, bool apply)
10330 if(IsPassiveSpell(spellid))
10331 return;
10333 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10335 if(spellid == m_charmspells[x].spellId)
10337 m_charmspells[x].active = apply ? ACT_ENABLED : ACT_DISABLED;
10342 void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow)
10344 m_petnumber = petnumber;
10345 if(statwindow)
10346 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber);
10347 else
10348 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0);
10351 bool Unit::isFrozen() const
10353 return HasAuraState(AURA_STATE_FROZEN);
10356 struct ProcTriggeredData
10358 ProcTriggeredData(SpellProcEventEntry const * _spellProcEvent, Aura* _triggeredByAura)
10359 : spellProcEvent(_spellProcEvent), triggeredByAura(_triggeredByAura),
10360 triggeredByAura_SpellPair(Unit::spellEffectPair(triggeredByAura->GetId(),triggeredByAura->GetEffIndex()))
10362 SpellProcEventEntry const *spellProcEvent;
10363 Aura* triggeredByAura;
10364 Unit::spellEffectPair triggeredByAura_SpellPair;
10367 typedef std::list< ProcTriggeredData > ProcTriggeredList;
10368 typedef std::list< uint32> RemoveSpellList;
10370 // List of auras that CAN be trigger but may not exist in spell_proc_event
10371 // in most case need for drop charges
10372 // in some types of aura need do additional check
10373 // for example SPELL_AURA_MECHANIC_IMMUNITY - need check for mechanic
10374 bool InitTriggerAuraData()
10376 for (int i=0;i<TOTAL_AURAS;i++)
10378 isTriggerAura[i]=false;
10379 isNonTriggerAura[i] = false;
10381 isTriggerAura[SPELL_AURA_DUMMY] = true;
10382 isTriggerAura[SPELL_AURA_MOD_CONFUSE] = true;
10383 isTriggerAura[SPELL_AURA_MOD_THREAT] = true;
10384 isTriggerAura[SPELL_AURA_MOD_STUN] = true; // Aura not have charges but need remove him on trigger
10385 isTriggerAura[SPELL_AURA_MOD_DAMAGE_DONE] = true;
10386 isTriggerAura[SPELL_AURA_MOD_DAMAGE_TAKEN] = true;
10387 isTriggerAura[SPELL_AURA_MOD_RESISTANCE] = true;
10388 isTriggerAura[SPELL_AURA_MOD_ROOT] = true;
10389 isTriggerAura[SPELL_AURA_REFLECT_SPELLS] = true;
10390 isTriggerAura[SPELL_AURA_DAMAGE_IMMUNITY] = true;
10391 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL] = true;
10392 isTriggerAura[SPELL_AURA_PROC_TRIGGER_DAMAGE] = true;
10393 isTriggerAura[SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK] = true;
10394 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT] = true;
10395 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL] = true;
10396 isTriggerAura[SPELL_AURA_REFLECT_SPELLS_SCHOOL] = true;
10397 isTriggerAura[SPELL_AURA_MECHANIC_IMMUNITY] = true;
10398 isTriggerAura[SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN] = true;
10399 isTriggerAura[SPELL_AURA_SPELL_MAGNET] = true;
10400 isTriggerAura[SPELL_AURA_MOD_ATTACK_POWER] = true;
10401 isTriggerAura[SPELL_AURA_ADD_CASTER_HIT_TRIGGER] = true;
10402 isTriggerAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true;
10403 isTriggerAura[SPELL_AURA_MOD_MECHANIC_RESISTANCE] = true;
10404 isTriggerAura[SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS] = true;
10405 isTriggerAura[SPELL_AURA_MOD_HASTE] = true;
10406 isTriggerAura[SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE]=true;
10407 isTriggerAura[SPELL_AURA_PRAYER_OF_MENDING] = true;
10408 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE] = true;
10409 isTriggerAura[SPELL_AURA_MOD_DAMAGE_FROM_CASTER] = true;
10411 isNonTriggerAura[SPELL_AURA_MOD_POWER_REGEN]=true;
10412 isNonTriggerAura[SPELL_AURA_REDUCE_PUSHBACK]=true;
10414 return true;
10417 uint32 createProcExtendMask(SpellNonMeleeDamage *damageInfo, SpellMissInfo missCondition)
10419 uint32 procEx = PROC_EX_NONE;
10420 // Check victim state
10421 if (missCondition!=SPELL_MISS_NONE)
10422 switch (missCondition)
10424 case SPELL_MISS_MISS: procEx|=PROC_EX_MISS; break;
10425 case SPELL_MISS_RESIST: procEx|=PROC_EX_RESIST; break;
10426 case SPELL_MISS_DODGE: procEx|=PROC_EX_DODGE; break;
10427 case SPELL_MISS_PARRY: procEx|=PROC_EX_PARRY; break;
10428 case SPELL_MISS_BLOCK: procEx|=PROC_EX_BLOCK; break;
10429 case SPELL_MISS_EVADE: procEx|=PROC_EX_EVADE; break;
10430 case SPELL_MISS_IMMUNE: procEx|=PROC_EX_IMMUNE; break;
10431 case SPELL_MISS_IMMUNE2: procEx|=PROC_EX_IMMUNE; break;
10432 case SPELL_MISS_DEFLECT: procEx|=PROC_EX_DEFLECT;break;
10433 case SPELL_MISS_ABSORB: procEx|=PROC_EX_ABSORB; break;
10434 case SPELL_MISS_REFLECT: procEx|=PROC_EX_REFLECT;break;
10435 default:
10436 break;
10438 else
10440 // On block
10441 if (damageInfo->blocked)
10442 procEx|=PROC_EX_BLOCK;
10443 // On absorb
10444 if (damageInfo->absorb)
10445 procEx|=PROC_EX_ABSORB;
10446 // On crit
10447 if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT)
10448 procEx|=PROC_EX_CRITICAL_HIT;
10449 else
10450 procEx|=PROC_EX_NORMAL_HIT;
10452 return procEx;
10455 void Unit::ProcDamageAndSpellFor( bool isVictim, Unit * pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const * procSpell, uint32 damage )
10457 // For melee/ranged based attack need update skills and set some Aura states
10458 if (procFlag & MELEE_BASED_TRIGGER_MASK)
10460 // Update skills here for players
10461 if (GetTypeId() == TYPEID_PLAYER)
10463 // On melee based hit/miss/resist need update skill (for victim and attacker)
10464 if (procExtra&(PROC_EX_NORMAL_HIT|PROC_EX_MISS|PROC_EX_RESIST))
10466 if (pTarget->GetTypeId() != TYPEID_PLAYER && pTarget->GetCreatureType() != CREATURE_TYPE_CRITTER)
10467 ((Player*)this)->UpdateCombatSkills(pTarget, attType, isVictim);
10469 // Update defence if player is victim and parry/dodge/block
10470 if (isVictim && procExtra&(PROC_EX_DODGE|PROC_EX_PARRY|PROC_EX_BLOCK))
10471 ((Player*)this)->UpdateDefense();
10473 // If exist crit/parry/dodge/block need update aura state (for victim and attacker)
10474 if (procExtra & (PROC_EX_CRITICAL_HIT|PROC_EX_PARRY|PROC_EX_DODGE|PROC_EX_BLOCK))
10476 // for victim
10477 if (isVictim)
10479 // if victim and dodge attack
10480 if (procExtra&PROC_EX_DODGE)
10482 //Update AURA_STATE on dodge
10483 if (getClass() != CLASS_ROGUE) // skip Rogue Riposte
10485 ModifyAuraState(AURA_STATE_DEFENSE, true);
10486 StartReactiveTimer( REACTIVE_DEFENSE );
10489 // if victim and parry attack
10490 if (procExtra & PROC_EX_PARRY)
10492 // For Hunters only Counterattack (skip Mongoose bite)
10493 if (getClass() == CLASS_HUNTER)
10495 ModifyAuraState(AURA_STATE_HUNTER_PARRY, true);
10496 StartReactiveTimer( REACTIVE_HUNTER_PARRY );
10498 else
10500 ModifyAuraState(AURA_STATE_DEFENSE, true);
10501 StartReactiveTimer( REACTIVE_DEFENSE );
10504 // if and victim block attack
10505 if (procExtra & PROC_EX_BLOCK)
10507 ModifyAuraState(AURA_STATE_DEFENSE,true);
10508 StartReactiveTimer( REACTIVE_DEFENSE );
10511 else //For attacker
10513 // Overpower on victim dodge
10514 if (procExtra&PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR)
10516 ((Player*)this)->AddComboPoints(pTarget, 1);
10517 StartReactiveTimer( REACTIVE_OVERPOWER );
10523 RemoveSpellList removedSpells;
10524 ProcTriggeredList procTriggered;
10525 // Fill procTriggered list
10526 for(AuraMap::const_iterator itr = GetAuras().begin(); itr!= GetAuras().end(); ++itr)
10528 SpellProcEventEntry const* spellProcEvent = NULL;
10529 if(!IsTriggeredAtSpellProcEvent(pTarget, itr->second, procSpell, procFlag, procExtra, attType, isVictim, (damage > 0), spellProcEvent))
10530 continue;
10532 procTriggered.push_back( ProcTriggeredData(spellProcEvent, itr->second) );
10535 // Nothing found
10536 if (procTriggered.empty())
10537 return;
10539 // Handle effects proceed this time
10540 for(ProcTriggeredList::iterator i = procTriggered.begin(); i != procTriggered.end(); ++i)
10542 // Some auras can be deleted in function called in this loop (except first, ofc)
10543 // Until storing auars in std::multimap to hard check deleting by another way
10544 if(i != procTriggered.begin())
10546 bool found = false;
10547 AuraMap::const_iterator lower = GetAuras().lower_bound(i->triggeredByAura_SpellPair);
10548 AuraMap::const_iterator upper = GetAuras().upper_bound(i->triggeredByAura_SpellPair);
10549 for(AuraMap::const_iterator itr = lower; itr!= upper; ++itr)
10551 if(itr->second==i->triggeredByAura)
10553 found = true;
10554 break;
10557 if(!found)
10559 // 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);
10560 // sLog.outDebug("It can be deleted one from early proccesed auras:");
10561 // for(ProcTriggeredList::iterator i2 = procTriggered.begin(); i != i2; ++i2)
10562 // sLog.outDebug(" Spell aura %u (id:%u effect:%u)", i->triggeredByAura->GetModifier()->m_auraname,i2->triggeredByAura_SpellPair.first,i2->triggeredByAura_SpellPair.second);
10563 // sLog.outDebug(" <end of list>");
10564 continue;
10568 SpellProcEventEntry const *spellProcEvent = i->spellProcEvent;
10569 Aura *triggeredByAura = i->triggeredByAura;
10570 Modifier *auraModifier = triggeredByAura->GetModifier();
10571 SpellEntry const *spellInfo = triggeredByAura->GetSpellProto();
10572 uint32 effIndex = triggeredByAura->GetEffIndex();
10573 bool useCharges = triggeredByAura->GetAuraCharges() > 0;
10574 // For players set spell cooldown if need
10575 uint32 cooldown = 0;
10576 if (GetTypeId() == TYPEID_PLAYER && spellProcEvent && spellProcEvent->cooldown)
10577 cooldown = spellProcEvent->cooldown;
10579 switch(auraModifier->m_auraname)
10581 case SPELL_AURA_PROC_TRIGGER_SPELL:
10583 sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
10584 // Don`t drop charge or add cooldown for not started trigger
10585 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10586 continue;
10587 break;
10589 case SPELL_AURA_PROC_TRIGGER_DAMAGE:
10591 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());
10592 SpellNonMeleeDamage damageInfo(this, pTarget, spellInfo->Id, spellInfo->SchoolMask);
10593 CalculateSpellDamage(&damageInfo, auraModifier->m_amount, spellInfo);
10594 SendSpellNonMeleeDamageLog(&damageInfo);
10595 DealSpellDamage(&damageInfo, true);
10596 break;
10598 case SPELL_AURA_MANA_SHIELD:
10599 case SPELL_AURA_DUMMY:
10601 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());
10602 if (!HandleDummyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10603 continue;
10604 break;
10606 case SPELL_AURA_MOD_HASTE:
10608 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());
10609 if (!HandleHasteAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10610 continue;
10611 break;
10613 case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
10615 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());
10616 if (!HandleOverrideClassScriptAuraProc(pTarget, damage, triggeredByAura, procSpell, cooldown))
10617 continue;
10618 break;
10620 case SPELL_AURA_PRAYER_OF_MENDING:
10622 sLog.outDebug("ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
10623 (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
10625 HandleMeandingAuraProc(triggeredByAura);
10626 break;
10628 case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE:
10630 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());
10632 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10633 continue;
10634 break;
10636 case SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK:
10637 // Skip melee hits or instant cast spells
10638 if (procSpell == NULL || GetSpellCastTime(procSpell) == 0)
10639 continue;
10640 break;
10641 case SPELL_AURA_REFLECT_SPELLS_SCHOOL:
10642 // Skip Melee hits and spells ws wrong school
10643 if (procSpell == NULL || (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0)
10644 continue;
10645 break;
10646 case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT:
10647 case SPELL_AURA_MOD_POWER_COST_SCHOOL:
10648 // Skip melee hits and spells ws wrong school or zero cost
10649 if (procSpell == NULL ||
10650 (procSpell->manaCost == 0 && procSpell->ManaCostPercentage == 0) || // Cost check
10651 (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0) // School check
10652 continue;
10653 break;
10654 case SPELL_AURA_MECHANIC_IMMUNITY:
10655 // Compare mechanic
10656 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
10657 continue;
10658 break;
10659 case SPELL_AURA_MOD_MECHANIC_RESISTANCE:
10660 // Compare mechanic
10661 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
10662 continue;
10663 break;
10664 case SPELL_AURA_MOD_DAMAGE_FROM_CASTER:
10665 // Compare casters
10666 if (triggeredByAura->GetCasterGUID() != pTarget->GetGUID())
10667 continue;
10668 break;
10669 default:
10670 // nothing do, just charges counter
10671 break;
10673 // Remove charge (aura can be removed by triggers)
10674 if(useCharges)
10676 // need found aura on drop (can be dropped by triggers)
10677 AuraMap::const_iterator lower = GetAuras().lower_bound(i->triggeredByAura_SpellPair);
10678 AuraMap::const_iterator upper = GetAuras().upper_bound(i->triggeredByAura_SpellPair);
10679 for(AuraMap::const_iterator itr = lower; itr!= upper; ++itr)
10681 // If last charge dropped add spell to remove list
10682 if(itr->second == i->triggeredByAura && triggeredByAura->DropAuraCharge())
10684 removedSpells.push_back(triggeredByAura->GetId());
10685 break;
10690 if (!removedSpells.empty())
10692 // Sort spells and remove dublicates
10693 removedSpells.sort();
10694 removedSpells.unique();
10695 // Remove auras from removedAuras
10696 for(RemoveSpellList::const_iterator i = removedSpells.begin(); i != removedSpells.end();i++)
10697 RemoveAurasDueToSpell(*i);
10701 SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const
10703 return SPELL_SCHOOL_MASK_NORMAL;
10706 Player* Unit::GetSpellModOwner()
10708 if(GetTypeId()==TYPEID_PLAYER)
10709 return (Player*)this;
10710 if(((Creature*)this)->isPet() || ((Creature*)this)->isTotem())
10712 Unit* owner = GetOwner();
10713 if(owner && owner->GetTypeId()==TYPEID_PLAYER)
10714 return (Player*)owner;
10716 return NULL;
10719 ///----------Pet responses methods-----------------
10720 void Unit::SendPetCastFail(uint32 spellid, SpellCastResult msg)
10722 if(msg == SPELL_CAST_OK)
10723 return;
10725 Unit *owner = GetCharmerOrOwner();
10726 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10727 return;
10729 WorldPacket data(SMSG_PET_CAST_FAILED, (4+1));
10730 data << uint8(0); // cast count?
10731 data << uint32(spellid);
10732 data << uint8(msg);
10733 // uint32 for some reason
10734 // uint32 for some reason
10735 ((Player*)owner)->GetSession()->SendPacket(&data);
10738 void Unit::SendPetActionFeedback (uint8 msg)
10740 Unit* owner = GetOwner();
10741 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10742 return;
10744 WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1);
10745 data << uint8(msg);
10746 ((Player*)owner)->GetSession()->SendPacket(&data);
10749 void Unit::SendPetTalk (uint32 pettalk)
10751 Unit* owner = GetOwner();
10752 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10753 return;
10755 WorldPacket data(SMSG_PET_ACTION_SOUND, 8+4);
10756 data << uint64(GetGUID());
10757 data << uint32(pettalk);
10758 ((Player*)owner)->GetSession()->SendPacket(&data);
10761 void Unit::SendPetSpellCooldown (uint32 spellid, time_t cooltime)
10763 Unit* owner = GetOwner();
10764 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10765 return;
10767 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4+4);
10768 data << uint64(GetGUID());
10769 data << uint8(0x0); // flags (0x1, 0x2)
10770 data << uint32(spellid);
10771 data << uint32(cooltime);
10773 ((Player*)owner)->GetSession()->SendPacket(&data);
10776 void Unit::SendPetClearCooldown (uint32 spellid)
10778 Unit* owner = GetOwner();
10779 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10780 return;
10782 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
10783 data << uint32(spellid);
10784 data << uint64(GetGUID());
10785 ((Player*)owner)->GetSession()->SendPacket(&data);
10788 void Unit::SendPetAIReaction(uint64 guid)
10790 Unit* owner = GetOwner();
10791 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10792 return;
10794 WorldPacket data(SMSG_AI_REACTION, 12);
10795 data << uint64(guid) << uint32(00000002);
10796 ((Player*)owner)->GetSession()->SendPacket(&data);
10799 ///----------End of Pet responses methods----------
10801 void Unit::StopMoving()
10803 clearUnitState(UNIT_STAT_MOVING);
10805 // send explicit stop packet
10806 // rely on vmaps here because for example stormwind is in air
10807 //float z = MapManager::Instance().GetBaseMap(GetMapId())->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), true);
10808 //if (fabs(GetPositionZ() - z) < 2.0f)
10809 // Relocate(GetPositionX(), GetPositionY(), z);
10810 Relocate(GetPositionX(), GetPositionY(),GetPositionZ());
10812 SendMonsterMove(GetPositionX(), GetPositionY(), GetPositionZ(), 0, true, 0);
10814 // update position and orientation;
10815 WorldPacket data;
10816 BuildHeartBeatMsg(&data);
10817 SendMessageToSet(&data,false);
10820 void Unit::SetFeared(bool apply, uint64 casterGUID, uint32 spellID)
10822 if( apply )
10824 if(HasAuraType(SPELL_AURA_PREVENTS_FLEEING))
10825 return;
10827 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
10829 GetMotionMaster()->MovementExpired(false);
10830 CastStop(GetGUID()==casterGUID ? spellID : 0);
10832 Unit* caster = ObjectAccessor::GetUnit(*this,casterGUID);
10834 GetMotionMaster()->MoveFleeing(caster); // caster==NULL processed in MoveFleeing
10836 else
10838 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
10840 GetMotionMaster()->MovementExpired(false);
10842 if( GetTypeId() != TYPEID_PLAYER && isAlive() )
10844 // restore appropriate movement generator
10845 if(getVictim())
10846 GetMotionMaster()->MoveChase(getVictim());
10847 else
10848 GetMotionMaster()->Initialize();
10850 // attack caster if can
10851 Unit* caster = ObjectAccessor::GetObjectInWorld(casterGUID, (Unit*)NULL);
10852 if(caster && ((Creature*)this)->AI())
10853 ((Creature*)this)->AI()->AttackedBy(caster);
10857 if (GetTypeId() == TYPEID_PLAYER)
10858 ((Player*)this)->SetClientControl(this, !apply);
10861 void Unit::SetConfused(bool apply, uint64 casterGUID, uint32 spellID)
10863 if( apply )
10865 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
10867 CastStop(GetGUID()==casterGUID ? spellID : 0);
10869 GetMotionMaster()->MoveConfused();
10871 else
10873 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
10875 GetMotionMaster()->MovementExpired(false);
10877 if (GetTypeId() == TYPEID_UNIT)
10879 // if in combat restore movement generator
10880 if(getVictim())
10881 GetMotionMaster()->MoveChase(getVictim());
10885 if(GetTypeId() == TYPEID_PLAYER)
10886 ((Player*)this)->SetClientControl(this, !apply);
10889 bool Unit::IsSitState() const
10891 uint8 s = getStandState();
10892 return
10893 s == UNIT_STAND_STATE_SIT_CHAIR || s == UNIT_STAND_STATE_SIT_LOW_CHAIR ||
10894 s == UNIT_STAND_STATE_SIT_MEDIUM_CHAIR || s == UNIT_STAND_STATE_SIT_HIGH_CHAIR ||
10895 s == UNIT_STAND_STATE_SIT;
10898 bool Unit::IsStandState() const
10900 uint8 s = getStandState();
10901 return !IsSitState() && s != UNIT_STAND_STATE_SLEEP && s != UNIT_STAND_STATE_KNEEL;
10904 void Unit::SetStandState(uint8 state)
10906 SetByteValue(UNIT_FIELD_BYTES_1, 0, state);
10908 if (IsStandState())
10909 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED);
10911 if(GetTypeId()==TYPEID_PLAYER)
10913 WorldPacket data(SMSG_STANDSTATE_UPDATE, 1);
10914 data << (uint8)state;
10915 ((Player*)this)->GetSession()->SendPacket(&data);
10919 bool Unit::IsPolymorphed() const
10921 return GetSpellSpecific(getTransForm())==SPELL_MAGE_POLYMORPH;
10924 void Unit::SetDisplayId(uint32 modelId)
10926 SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId);
10928 if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
10930 Pet *pet = ((Pet*)this);
10931 if(!pet->isControlled())
10932 return;
10933 Unit *owner = GetOwner();
10934 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10935 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID);
10939 void Unit::ClearComboPointHolders()
10941 while(!m_ComboPointHolders.empty())
10943 uint32 lowguid = *m_ComboPointHolders.begin();
10945 Player* plr = objmgr.GetPlayer(MAKE_NEW_GUID(lowguid, 0, HIGHGUID_PLAYER));
10946 if(plr && plr->GetComboTarget()==GetGUID()) // recheck for safe
10947 plr->ClearComboPoints(); // remove also guid from m_ComboPointHolders;
10948 else
10949 m_ComboPointHolders.erase(lowguid); // or remove manually
10953 void Unit::ClearAllReactives()
10955 for(int i=0; i < MAX_REACTIVE; ++i)
10956 m_reactiveTimer[i] = 0;
10958 if (HasAuraState( AURA_STATE_DEFENSE))
10959 ModifyAuraState(AURA_STATE_DEFENSE, false);
10960 if (getClass() == CLASS_HUNTER && HasAuraState( AURA_STATE_HUNTER_PARRY))
10961 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
10962 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
10963 ((Player*)this)->ClearComboPoints();
10966 void Unit::UpdateReactives( uint32 p_time )
10968 for(int i = 0; i < MAX_REACTIVE; ++i)
10970 ReactiveType reactive = ReactiveType(i);
10972 if(!m_reactiveTimer[reactive])
10973 continue;
10975 if ( m_reactiveTimer[reactive] <= p_time)
10977 m_reactiveTimer[reactive] = 0;
10979 switch ( reactive )
10981 case REACTIVE_DEFENSE:
10982 if (HasAuraState(AURA_STATE_DEFENSE))
10983 ModifyAuraState(AURA_STATE_DEFENSE, false);
10984 break;
10985 case REACTIVE_HUNTER_PARRY:
10986 if ( getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
10987 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
10988 break;
10989 case REACTIVE_OVERPOWER:
10990 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
10991 ((Player*)this)->ClearComboPoints();
10992 break;
10993 default:
10994 break;
10997 else
10999 m_reactiveTimer[reactive] -= p_time;
11004 Unit* Unit::SelectNearbyTarget() const
11006 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
11007 Cell cell(p);
11008 cell.data.Part.reserved = ALL_DISTRICT;
11009 cell.SetNoCreate();
11011 std::list<Unit *> targets;
11014 MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, ATTACK_DISTANCE);
11015 MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> searcher(this, targets, u_check);
11017 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
11018 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
11020 CellLock<GridReadGuard> cell_lock(cell, p);
11021 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
11022 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
11025 // remove current target
11026 if(getVictim())
11027 targets.remove(getVictim());
11029 // remove not LoS targets
11030 for(std::list<Unit *>::iterator tIter = targets.begin(); tIter != targets.end();)
11032 if(!IsWithinLOSInMap(*tIter))
11034 std::list<Unit *>::iterator tIter2 = tIter;
11035 ++tIter;
11036 targets.erase(tIter2);
11038 else
11039 ++tIter;
11042 // no appropriate targets
11043 if(targets.empty())
11044 return NULL;
11046 // select random
11047 uint32 rIdx = urand(0,targets.size()-1);
11048 std::list<Unit *>::const_iterator tcIter = targets.begin();
11049 for(uint32 i = 0; i < rIdx; ++i)
11050 ++tcIter;
11052 return *tcIter;
11055 bool Unit::hasNegativeAuraWithInterruptFlag(uint32 flag)
11057 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); ++iter)
11059 if (!iter->second->IsPositive() && iter->second->GetSpellProto()->AuraInterruptFlags & flag)
11060 return true;
11062 return false;
11065 void Unit::ApplyAttackTimePercentMod( WeaponAttackType att,float val, bool apply )
11067 if(val > 0)
11069 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply);
11070 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,val,!apply);
11072 else
11074 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply);
11075 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,-val,apply);
11079 void Unit::ApplyCastTimePercentMod(float val, bool apply )
11081 if(val > 0)
11082 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,val,!apply);
11083 else
11084 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,-val,apply);
11087 uint32 Unit::GetCastingTimeForBonus( SpellEntry const *spellProto, DamageEffectType damagetype, uint32 CastingTime )
11089 // Not apply this to creature casted spells with casttime==0
11090 if(CastingTime==0 && GetTypeId()==TYPEID_UNIT && !((Creature*)this)->isPet())
11091 return 3500;
11093 if (CastingTime > 7000) CastingTime = 7000;
11094 if (CastingTime < 1500) CastingTime = 1500;
11096 if(damagetype == DOT && !IsChanneledSpell(spellProto))
11097 CastingTime = 3500;
11099 int32 overTime = 0;
11100 uint8 effects = 0;
11101 bool DirectDamage = false;
11102 bool AreaEffect = false;
11104 for ( uint32 i=0; i<3;i++)
11106 switch ( spellProto->Effect[i] )
11108 case SPELL_EFFECT_SCHOOL_DAMAGE:
11109 case SPELL_EFFECT_POWER_DRAIN:
11110 case SPELL_EFFECT_HEALTH_LEECH:
11111 case SPELL_EFFECT_ENVIRONMENTAL_DAMAGE:
11112 case SPELL_EFFECT_POWER_BURN:
11113 case SPELL_EFFECT_HEAL:
11114 DirectDamage = true;
11115 break;
11116 case SPELL_EFFECT_APPLY_AURA:
11117 switch ( spellProto->EffectApplyAuraName[i] )
11119 case SPELL_AURA_PERIODIC_DAMAGE:
11120 case SPELL_AURA_PERIODIC_HEAL:
11121 case SPELL_AURA_PERIODIC_LEECH:
11122 if ( GetSpellDuration(spellProto) )
11123 overTime = GetSpellDuration(spellProto);
11124 break;
11125 default:
11126 // -5% per additional effect
11127 ++effects;
11128 break;
11130 default:
11131 break;
11134 if(IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetA[i])) || IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetB[i])))
11135 AreaEffect = true;
11138 // Combined Spells with Both Over Time and Direct Damage
11139 if ( overTime > 0 && CastingTime > 0 && DirectDamage )
11141 // mainly for DoTs which are 3500 here otherwise
11142 uint32 OriginalCastTime = GetSpellCastTime(spellProto);
11143 if (OriginalCastTime > 7000) OriginalCastTime = 7000;
11144 if (OriginalCastTime < 1500) OriginalCastTime = 1500;
11145 // Portion to Over Time
11146 float PtOT = (overTime / 15000.f) / ((overTime / 15000.f) + (OriginalCastTime / 3500.f));
11148 if ( damagetype == DOT )
11149 CastingTime = uint32(CastingTime * PtOT);
11150 else if ( PtOT < 1.0f )
11151 CastingTime = uint32(CastingTime * (1 - PtOT));
11152 else
11153 CastingTime = 0;
11156 // Area Effect Spells receive only half of bonus
11157 if ( AreaEffect )
11158 CastingTime /= 2;
11160 // -5% of total per any additional effect
11161 for ( uint8 i=0; i<effects; ++i)
11163 if ( CastingTime > 175 )
11165 CastingTime -= 175;
11167 else
11169 CastingTime = 0;
11170 break;
11174 return CastingTime;
11177 void Unit::UpdateAuraForGroup(uint8 slot)
11179 if(GetTypeId() == TYPEID_PLAYER)
11181 Player* player = (Player*)this;
11182 if(player->GetGroup())
11184 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_AURAS);
11185 player->SetAuraUpdateMask(slot);
11188 else if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
11190 Pet *pet = ((Pet*)this);
11191 if(pet->isControlled())
11193 Unit *owner = GetOwner();
11194 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11196 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_AURAS);
11197 pet->SetAuraUpdateMask(slot);
11203 float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized)
11205 if (!normalized || GetTypeId() != TYPEID_PLAYER)
11206 return float(GetAttackTime(attType))/1000.0f;
11208 Item *Weapon = ((Player*)this)->GetWeaponForAttack(attType);
11209 if (!Weapon)
11210 return 2.4; // fist attack
11212 switch (Weapon->GetProto()->InventoryType)
11214 case INVTYPE_2HWEAPON:
11215 return 3.3;
11216 case INVTYPE_RANGED:
11217 case INVTYPE_RANGEDRIGHT:
11218 case INVTYPE_THROWN:
11219 return 2.8;
11220 case INVTYPE_WEAPON:
11221 case INVTYPE_WEAPONMAINHAND:
11222 case INVTYPE_WEAPONOFFHAND:
11223 default:
11224 return Weapon->GetProto()->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7 : 2.4;
11228 Aura* Unit::GetDummyAura( uint32 spell_id ) const
11230 Unit::AuraList const& mDummy = GetAurasByType(SPELL_AURA_DUMMY);
11231 for(Unit::AuraList::const_iterator itr = mDummy.begin(); itr != mDummy.end(); ++itr)
11232 if ((*itr)->GetId() == spell_id)
11233 return *itr;
11235 return NULL;
11238 bool Unit::IsUnderLastManaUseEffect() const
11240 return getMSTimeDiff(m_lastManaUse,getMSTime()) < 5000;
11243 void Unit::SetContestedPvP(Player *attackedPlayer)
11245 Player* player = GetCharmerOrOwnerPlayerOrPlayerItself();
11247 if(!player || attackedPlayer && (attackedPlayer == player || player->duel && player->duel->opponent == attackedPlayer))
11248 return;
11250 player->SetContestedPvPTimer(30000);
11251 if(!player->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
11253 player->addUnitState(UNIT_STAT_ATTACK_PLAYER);
11254 player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
11255 // call MoveInLineOfSight for nearby contested guards
11256 SetVisibility(GetVisibility());
11258 if(!hasUnitState(UNIT_STAT_ATTACK_PLAYER))
11260 addUnitState(UNIT_STAT_ATTACK_PLAYER);
11261 // call MoveInLineOfSight for nearby contested guards
11262 SetVisibility(GetVisibility());
11266 void Unit::AddPetAura(PetAura const* petSpell)
11268 m_petAuras.insert(petSpell);
11269 if(Pet* pet = GetPet())
11270 pet->CastPetAura(petSpell);
11273 void Unit::RemovePetAura(PetAura const* petSpell)
11275 m_petAuras.erase(petSpell);
11276 if(Pet* pet = GetPet())
11277 pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry()));
11280 Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget,uint32 spell_id)
11282 Pet* pet = new Pet(HUNTER_PET);
11284 if(!pet->CreateBaseAtCreature(creatureTarget))
11286 delete pet;
11287 return NULL;
11290 pet->SetOwnerGUID(GetGUID());
11291 pet->SetCreatorGUID(GetGUID());
11292 pet->SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, getFaction());
11293 pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id);
11295 if(GetTypeId()==TYPEID_PLAYER)
11296 pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
11298 uint32 level = (creatureTarget->getLevel() < (getLevel() - 5)) ? (getLevel() - 5) : creatureTarget->getLevel();
11300 if(!pet->InitStatsForLevel(level))
11302 sLog.outError("Pet::InitStatsForLevel() failed for creature (Entry: %u)!",creatureTarget->GetEntry());
11303 delete pet;
11304 return NULL;
11307 pet->GetCharmInfo()->SetPetNumber(objmgr.GeneratePetNumber(), true);
11308 // this enables pet details window (Shift+P)
11309 pet->AIM_Initialize();
11310 pet->InitPetCreateSpells();
11311 pet->InitTalentForLevel();
11312 pet->SetHealth(pet->GetMaxHealth());
11314 return pet;
11317 bool Unit::IsTriggeredAtSpellProcEvent(Unit *pVictim, Aura* aura, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const*& spellProcEvent )
11319 SpellEntry const* spellProto = aura->GetSpellProto ();
11321 // Get proc Event Entry
11322 spellProcEvent = spellmgr.GetSpellProcEvent(spellProto->Id);
11324 // Aura info stored here
11325 Modifier *mod = aura->GetModifier();
11326 // Skip this auras
11327 if (isNonTriggerAura[mod->m_auraname])
11328 return false;
11329 // If not trigger by default and spellProcEvent==NULL - skip
11330 if (!isTriggerAura[mod->m_auraname] && spellProcEvent==NULL)
11331 return false;
11333 // Get EventProcFlag
11334 uint32 EventProcFlag;
11335 if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags
11336 EventProcFlag = spellProcEvent->procFlags;
11337 else
11338 EventProcFlag = spellProto->procFlags; // else get from spell proto
11339 // Continue if no trigger exist
11340 if (!EventProcFlag)
11341 return false;
11343 // Check spellProcEvent data requirements
11344 if(!SpellMgr::IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active))
11345 return false;
11347 // In most cases req get honor or XP from kill
11348 if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER)
11350 bool allow = ((Player*)this)->isHonorOrXPTarget(pVictim);
11351 // Shadow Word: Death - can trigger from every kill
11352 if (aura->GetId() == 32409)
11353 allow = true;
11354 if (!allow)
11355 return false;
11357 // Aura added by spell can`t trogger from self (prevent drop charges/do triggers)
11358 // But except periodic triggers (can triggered from self)
11359 if(procSpell && procSpell->Id == spellProto->Id && !(spellProto->procFlags&PROC_FLAG_ON_TAKE_PERIODIC))
11360 return false;
11362 // Check if current equipment allows aura to proc
11363 if(!isVictim && GetTypeId() == TYPEID_PLAYER)
11365 if(spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
11367 Item *item = NULL;
11368 if(attType == BASE_ATTACK)
11369 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
11370 else if (attType == OFF_ATTACK)
11371 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
11372 else
11373 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
11375 if (!((Player*)this)->IsUseEquipedWeapon(attType==BASE_ATTACK))
11376 return false;
11378 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
11379 return false;
11381 else if(spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
11383 // Check if player is wearing shield
11384 Item *item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
11385 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
11386 return false;
11389 // Get chance from spell
11390 float chance = (float)spellProto->procChance;
11391 // If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance;
11392 if(spellProcEvent && spellProcEvent->customChance)
11393 chance = spellProcEvent->customChance;
11394 // If PPM exist calculate chance from PPM
11395 if(!isVictim && spellProcEvent && spellProcEvent->ppmRate != 0)
11397 uint32 WeaponSpeed = GetAttackTime(attType);
11398 chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate);
11400 // Apply chance modifer aura
11401 if(Player* modOwner = GetSpellModOwner())
11402 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
11404 return roll_chance_f(chance);
11407 bool Unit::HandleMeandingAuraProc( Aura* triggeredByAura )
11409 // aura can be deleted at casts
11410 SpellEntry const* spellProto = triggeredByAura->GetSpellProto();
11411 uint32 effIdx = triggeredByAura->GetEffIndex();
11412 int32 heal = triggeredByAura->GetModifier()->m_amount;
11413 uint64 caster_guid = triggeredByAura->GetCasterGUID();
11415 // jumps
11416 int32 jumps = triggeredByAura->GetAuraCharges()-1;
11418 // current aura expire
11419 triggeredByAura->SetAuraCharges(1); // will removed at next charges decrease
11421 // next target selection
11422 if(jumps > 0 && GetTypeId()==TYPEID_PLAYER && IS_PLAYER_GUID(caster_guid))
11424 float radius;
11425 if (spellProto->EffectRadiusIndex[effIdx])
11426 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
11427 else
11428 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
11430 if(Player* caster = ((Player*)triggeredByAura->GetCaster()))
11432 caster->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius,NULL);
11434 if(Player* target = ((Player*)this)->GetNextRandomRaidMember(radius))
11436 // aura will applied from caster, but spell casted from current aura holder
11437 SpellModifier *mod = new SpellModifier;
11438 mod->op = SPELLMOD_CHARGES;
11439 mod->value = jumps-5; // negative
11440 mod->type = SPELLMOD_FLAT;
11441 mod->spellId = spellProto->Id;
11442 mod->mask = spellProto->SpellFamilyFlags;
11443 mod->mask2 = spellProto->SpellFamilyFlags2;
11445 caster->AddSpellMod(mod, true);
11446 CastCustomSpell(target,spellProto->Id,&heal,NULL,NULL,true,NULL,triggeredByAura,caster->GetGUID());
11447 caster->AddSpellMod(mod, false);
11452 // heal
11453 CastCustomSpell(this,33110,&heal,NULL,NULL,true,NULL,NULL,caster_guid);
11454 return true;
11457 void Unit::RemoveAurasAtChanneledTarget(SpellEntry const* spellInfo)
11459 uint64 target_guid = GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT);
11461 if(!IS_UNIT_GUID(target_guid))
11462 return;
11464 Unit* target = ObjectAccessor::GetUnit(*this, target_guid);
11465 if(!target)
11466 return;
11468 for (AuraMap::iterator iter = target->GetAuras().begin(); iter != target->GetAuras().end(); )
11470 if (iter->second->GetId() == spellInfo->Id && iter->second->GetCasterGUID()==GetGUID())
11471 target->RemoveAura(iter);
11472 else
11473 ++iter;
11477 void Unit::SetPhaseMask(uint32 newPhaseMask, bool update)
11479 WorldObject::SetPhaseMask(newPhaseMask,update);
11481 if(IsInWorld())
11482 if(Pet* pet = GetPet())
11483 pet->SetPhaseMask(newPhaseMask,true);
11486 void Unit::NearTeleportTo( float x, float y, float z, float orientation, bool casting /*= false*/ )
11488 if(GetTypeId() == TYPEID_PLAYER)
11489 ((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));
11490 else
11492 GetMap()->CreatureRelocation((Creature*)this, x, y, z, orientation);
11494 WorldPacket data;
11495 // Work strange for many spells: triggered active mover set for targeted player to creature
11496 //BuildTeleportAckMsg(&data, x, y, z, orientation);
11497 BuildHeartBeatMsg(&data);
11498 SendMessageToSet(&data, false);